add the filename field
[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     }
833 } while (0)
834
835 @d t_close_out do { /* close the terminal */
836   (mp->close_file)(mp->term_out);
837   (mp->close_file)(mp->err_out);
838 } while (0)
839
840 @d t_close_in do { /* close the terminal */
841   (mp->close_file)(mp->term_in);
842 } while (0)
843
844 @<Option variables@>=
845 char *command_line;
846
847 @ @<Allocate or initialize ...@>=
848 mp->command_line = xstrdup(opt->command_line);
849
850 @ Sometimes it is necessary to synchronize the input/output mixture that
851 happens on the user's terminal, and three system-dependent
852 procedures are used for this
853 purpose. The first of these, |update_terminal|, is called when we want
854 to make sure that everything we have output to the terminal so far has
855 actually left the computer's internal buffers and been sent.
856 The second, |clear_terminal|, is called when we wish to cancel any
857 input that the user may have typed ahead (since we are about to
858 issue an unexpected error message). The third, |wake_up_terminal|,
859 is supposed to revive the terminal if the user has disabled it by
860 some instruction to the operating system.  The following macros show how
861 these operations can be specified:
862 @^system dependencies@>
863
864 @d update_terminal   (mp->flush_file)(mp->term_out) /* empty the terminal output buffer */
865 @d clear_terminal   do_nothing /* clear the terminal input buffer */
866 @d wake_up_terminal  (mp->flush_file)(mp->term_out) /* cancel the user's cancellation of output */
867
868 @ We need a special routine to read the first line of \MP\ input from
869 the user's terminal. This line is different because it is read before we
870 have opened the transcript file; there is sort of a ``chicken and
871 egg'' problem here. If the user types `\.{input cmr10}' on the first
872 line, or if some macro invoked by that line does such an \.{input},
873 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
874 commands are performed during the first line of terminal input, the transcript
875 file will acquire its default name `\.{mpout.log}'. (The transcript file
876 will not contain error messages generated by the first line before the
877 first \.{input} command.)
878
879 The first line is even more special. It's nice to let the user start
880 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
881 such a case, \MP\ will operate as if the first line of input were
882 `\.{cmr10}', i.e., the first line will consist of the remainder of the
883 command line, after the part that invoked \MP.
884
885 @ Different systems have different ways to get started. But regardless of
886 what conventions are adopted, the routine that initializes the terminal
887 should satisfy the following specifications:
888
889 \yskip\textindent{1)}It should open file |term_in| for input from the
890   terminal. (The file |term_out| will already be open for output to the
891   terminal.)
892
893 \textindent{2)}If the user has given a command line, this line should be
894   considered the first line of terminal input. Otherwise the
895   user should be prompted with `\.{**}', and the first line of input
896   should be whatever is typed in response.
897
898 \textindent{3)}The first line of input, which might or might not be a
899   command line, should appear in locations |first| to |last-1| of the
900   |buffer| array.
901
902 \textindent{4)}The global variable |loc| should be set so that the
903   character to be read next by \MP\ is in |buffer[loc]|. This
904   character should not be blank, and we should have |loc<last|.
905
906 \yskip\noindent(It may be necessary to prompt the user several times
907 before a non-blank line comes in. The prompt is `\.{**}' instead of the
908 later `\.*' because the meaning is slightly different: `\.{input}' need
909 not be typed immediately after~`\.{**}'.)
910
911 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
912
913 @ The following program does the required initialization
914 without retrieving a possible command line.
915 It should be clear how to modify this routine to deal with command lines,
916 if the system permits them.
917 @^system dependencies@>
918
919 @c 
920 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
921   t_open_in; 
922   if (mp->last!=0) {
923     loc = mp->first = 0;
924         return true;
925   }
926   while (1) { 
927     wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
928 @.**@>
929     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
930       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
931 @.End of file on the terminal@>
932       return false;
933     }
934     loc=mp->first;
935     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
936       incr(loc);
937     if ( loc<(int)mp->last ) { 
938       return true; /* return unless the line was all blank */
939     };
940     do_fprintf(mp->term_out,"Please type the name of your input file.\n");
941   }
942 }
943
944 @ @<Declarations@>=
945 boolean mp_init_terminal (MP mp) ;
946
947
948 @* \[4] String handling.
949 Symbolic token names and diagnostic messages are variable-length strings
950 of eight-bit characters. Many strings \MP\ uses are simply literals
951 in the compiled source, like the error messages and the names of the
952 internal parameters. Other strings are used or defined from the \MP\ input 
953 language, and these have to be interned.
954
955 \MP\ uses strings more extensively than \MF\ does, but the necessary
956 operations can still be handled with a fairly simple data structure.
957 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
958 of the strings, and the array |str_start| contains indices of the starting
959 points of each string. Strings are referred to by integer numbers, so that
960 string number |s| comprises the characters |str_pool[j]| for
961 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
962 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
963 location.  The first string number not currently in use is |str_ptr|
964 and |next_str[str_ptr]| begins a list of free string numbers.  String
965 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
966 string currently being constructed.
967
968 String numbers 0 to 255 are reserved for strings that correspond to single
969 ASCII characters. This is in accordance with the conventions of \.{WEB},
970 @.WEB@>
971 which converts single-character strings into the ASCII code number of the
972 single character involved, while it converts other strings into integers
973 and builds a string pool file. Thus, when the string constant \.{"."} appears
974 in the program below, \.{WEB} converts it into the integer 46, which is the
975 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
976 into some integer greater than~255. String number 46 will presumably be the
977 single character `\..'\thinspace; but some ASCII codes have no standard visible
978 representation, and \MP\ may need to be able to print an arbitrary
979 ASCII character, so the first 256 strings are used to specify exactly what
980 should be printed for each of the 256 possibilities.
981
982 @<Types...@>=
983 typedef int pool_pointer; /* for variables that point into |str_pool| */
984 typedef int str_number; /* for variables that point into |str_start| */
985
986 @ @<Glob...@>=
987 ASCII_code *str_pool; /* the characters */
988 pool_pointer *str_start; /* the starting pointers */
989 str_number *next_str; /* for linking strings in order */
990 pool_pointer pool_ptr; /* first unused position in |str_pool| */
991 str_number str_ptr; /* number of the current string being created */
992 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
993 str_number init_str_use; /* the initial number of strings in use */
994 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
995 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
996
997 @ @<Allocate or initialize ...@>=
998 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
999 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1000 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1001
1002 @ @<Dealloc variables@>=
1003 xfree(mp->str_pool);
1004 xfree(mp->str_start);
1005 xfree(mp->next_str);
1006
1007 @ Most printing is done from |char *|s, but sometimes not. Here are
1008 functions that convert an internal string into a |char *| for use
1009 by the printing routines, and vice versa.
1010
1011 @d str(A) mp_str(mp,A)
1012 @d rts(A) mp_rts(mp,A)
1013
1014 @<Internal ...@>=
1015 int mp_xstrcmp (const char *a, const char *b);
1016 char * mp_str (MP mp, str_number s);
1017
1018 @ @<Declarations@>=
1019 str_number mp_rts (MP mp, char *s);
1020 str_number mp_make_string (MP mp);
1021
1022 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1023 very good: it does not handle nesting over more than one level.
1024
1025 @c 
1026 int mp_xstrcmp (const char *a, const char *b) {
1027         if (a==NULL && b==NULL) 
1028           return 0;
1029     if (a==NULL)
1030       return -1;
1031     if (b==NULL)
1032       return 1;
1033     return strcmp(a,b);
1034 }
1035
1036 @ @c
1037 char * mp_str (MP mp, str_number ss) {
1038   char *s;
1039   int len;
1040   if (ss==mp->str_ptr) {
1041     return NULL;
1042   } else {
1043     len = length(ss);
1044     s = xmalloc(len+1,sizeof(char));
1045     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1046     s[len] = 0;
1047     return (char *)s;
1048   }
1049 }
1050 str_number mp_rts (MP mp, char *s) {
1051   int r; /* the new string */ 
1052   int old; /* a possible string in progress */
1053   int i=0;
1054   if (strlen(s)==0) {
1055     return 256;
1056   } else if (strlen(s)==1) {
1057     return s[0];
1058   } else {
1059    old=0;
1060    str_room((integer)strlen(s));
1061    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1062      old = mp_make_string(mp);
1063    while (*s) {
1064      append_char(*s);
1065      s++;
1066    }
1067    r = mp_make_string(mp);
1068    if (old!=0) {
1069       str_room(length(old));
1070       while (i<length(old)) {
1071         append_char((mp->str_start[old]+i));
1072       } 
1073       mp_flush_string(mp,old);
1074     }
1075     return r;
1076   }
1077 }
1078
1079 @ Except for |strs_used_up|, the following string statistics are only
1080 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1081 commented out:
1082
1083 @<Glob...@>=
1084 integer strs_used_up; /* strings in use or unused but not reclaimed */
1085 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1086 integer strs_in_use; /* total number of strings actually in use */
1087 integer max_pl_used; /* maximum |pool_in_use| so far */
1088 integer max_strs_used; /* maximum |strs_in_use| so far */
1089
1090 @ Several of the elementary string operations are performed using \.{WEB}
1091 macros instead of functions, because many of the
1092 operations are done quite frequently and we want to avoid the
1093 overhead of procedure calls. For example, here is
1094 a simple macro that computes the length of a string.
1095 @.WEB@>
1096
1097 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1098   number \# */
1099 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1100
1101 @ The length of the current string is called |cur_length|.  If we decide that
1102 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1103 |cur_length| becomes zero.
1104
1105 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1106 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1107
1108 @ Strings are created by appending character codes to |str_pool|.
1109 The |append_char| macro, defined here, does not check to see if the
1110 value of |pool_ptr| has gotten too high; this test is supposed to be
1111 made before |append_char| is used.
1112
1113 To test if there is room to append |l| more characters to |str_pool|,
1114 we shall write |str_room(l)|, which tries to make sure there is enough room
1115 by compacting the string pool if necessary.  If this does not work,
1116 |do_compaction| aborts \MP\ and gives an apologetic error message.
1117
1118 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1119 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1120 }
1121 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1122   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1123     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1124     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1125   }
1126
1127 @ The following routine is similar to |str_room(1)| but it uses the
1128 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1129 string space is exhausted.
1130
1131 @<Declare the procedure called |unit_str_room|@>=
1132 void mp_unit_str_room (MP mp);
1133
1134 @ @c
1135 void mp_unit_str_room (MP mp) { 
1136   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1137   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1138 }
1139
1140 @ \MP's string expressions are implemented in a brute-force way: Every
1141 new string or substring that is needed is simply copied into the string pool.
1142 Space is eventually reclaimed by a procedure called |do_compaction| with
1143 the aid of a simple system system of reference counts.
1144 @^reference counts@>
1145
1146 The number of references to string number |s| will be |str_ref[s]|. The
1147 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1148 positive number of references; such strings will never be recycled. If
1149 a string is ever referred to more than 126 times, simultaneously, we
1150 put it in this category. Hence a single byte suffices to store each |str_ref|.
1151
1152 @d max_str_ref 127 /* ``infinite'' number of references */
1153 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1154   }
1155
1156 @<Glob...@>=
1157 int *str_ref;
1158
1159 @ @<Allocate or initialize ...@>=
1160 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1161
1162 @ @<Dealloc variables@>=
1163 xfree(mp->str_ref);
1164
1165 @ Here's what we do when a string reference disappears:
1166
1167 @d delete_str_ref(A)  { 
1168     if ( mp->str_ref[(A)]<max_str_ref ) {
1169        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1170        else mp_flush_string(mp, (A));
1171     }
1172   }
1173
1174 @<Declare the procedure called |flush_string|@>=
1175 void mp_flush_string (MP mp,str_number s) ;
1176
1177
1178 @ We can't flush the first set of static strings at all, so there 
1179 is no point in trying
1180
1181 @c
1182 void mp_flush_string (MP mp,str_number s) { 
1183   if (length(s)>1) {
1184     mp->pool_in_use=mp->pool_in_use-length(s);
1185     decr(mp->strs_in_use);
1186     if ( mp->next_str[s]!=mp->str_ptr ) {
1187       mp->str_ref[s]=0;
1188     } else { 
1189       mp->str_ptr=s;
1190       decr(mp->strs_used_up);
1191     }
1192     mp->pool_ptr=mp->str_start[mp->str_ptr];
1193   }
1194 }
1195
1196 @ C literals cannot be simply added, they need to be set so they can't
1197 be flushed.
1198
1199 @d intern(A) mp_intern(mp,(A))
1200
1201 @c
1202 str_number mp_intern (MP mp, char *s) {
1203   str_number r ;
1204   r = rts(s);
1205   mp->str_ref[r] = max_str_ref;
1206   return r;
1207 }
1208
1209 @ @<Declarations@>=
1210 str_number mp_intern (MP mp, char *s);
1211
1212
1213 @ Once a sequence of characters has been appended to |str_pool|, it
1214 officially becomes a string when the function |make_string| is called.
1215 This function returns the identification number of the new string as its
1216 value.
1217
1218 When getting the next unused string number from the linked list, we pretend
1219 that
1220 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1221 are linked sequentially even though the |next_str| entries have not been
1222 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1223 |do_compaction| is responsible for making sure of this.
1224
1225 @<Declarations@>=
1226 @<Declare the procedure called |do_compaction|@>;
1227 @<Declare the procedure called |unit_str_room|@>;
1228 str_number mp_make_string (MP mp);
1229
1230 @ @c 
1231 str_number mp_make_string (MP mp) { /* current string enters the pool */
1232   str_number s; /* the new string */
1233 RESTART: 
1234   s=mp->str_ptr;
1235   mp->str_ptr=mp->next_str[s];
1236   if ( mp->str_ptr>mp->max_str_ptr ) {
1237     if ( mp->str_ptr==mp->max_strings ) { 
1238       mp->str_ptr=s;
1239       mp_do_compaction(mp, 0);
1240       goto RESTART;
1241     } else {
1242 #ifdef DEBUG 
1243       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1244 @:this can't happen s}{\quad \.s@>
1245 #endif
1246       mp->max_str_ptr=mp->str_ptr;
1247       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1248     }
1249   }
1250   mp->str_ref[s]=1;
1251   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1252   incr(mp->strs_used_up);
1253   incr(mp->strs_in_use);
1254   mp->pool_in_use=mp->pool_in_use+length(s);
1255   if ( mp->pool_in_use>mp->max_pl_used ) 
1256     mp->max_pl_used=mp->pool_in_use;
1257   if ( mp->strs_in_use>mp->max_strs_used ) 
1258     mp->max_strs_used=mp->strs_in_use;
1259   return s;
1260 }
1261
1262 @ The most interesting string operation is string pool compaction.  The idea
1263 is to recover unused space in the |str_pool| array by recopying the strings
1264 to close the gaps created when some strings become unused.  All string
1265 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1266 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1267 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1268 with |needed=mp->pool_size| supresses all overflow tests.
1269
1270 The compaction process starts with |last_fixed_str| because all lower numbered
1271 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1272
1273 @<Glob...@>=
1274 str_number last_fixed_str; /* last permanently allocated string */
1275 str_number fixed_str_use; /* number of permanently allocated strings */
1276
1277 @ @<Declare the procedure called |do_compaction|@>=
1278 void mp_do_compaction (MP mp, pool_pointer needed) ;
1279
1280 @ @c
1281 void mp_do_compaction (MP mp, pool_pointer needed) {
1282   str_number str_use; /* a count of strings in use */
1283   str_number r,s,t; /* strings being manipulated */
1284   pool_pointer p,q; /* destination and source for copying string characters */
1285   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1286   r=mp->last_fixed_str;
1287   s=mp->next_str[r];
1288   p=mp->str_start[s];
1289   while ( s!=mp->str_ptr ) { 
1290     while ( mp->str_ref[s]==0 ) {
1291       @<Advance |s| and add the old |s| to the list of free string numbers;
1292         then |break| if |s=str_ptr|@>;
1293     }
1294     r=s; s=mp->next_str[s];
1295     incr(str_use);
1296     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1297      after the end of the string@>;
1298   }
1299   @<Move the current string back so that it starts at |p|@>;
1300   if ( needed<mp->pool_size ) {
1301     @<Make sure that there is room for another string with |needed| characters@>;
1302   }
1303   @<Account for the compaction and make sure the statistics agree with the
1304      global versions@>;
1305   mp->strs_used_up=str_use;
1306 }
1307
1308 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1309 t=mp->next_str[mp->last_fixed_str];
1310 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1311   incr(mp->fixed_str_use);
1312   mp->last_fixed_str=t;
1313   t=mp->next_str[t];
1314 }
1315 str_use=mp->fixed_str_use
1316
1317 @ Because of the way |flush_string| has been written, it should never be
1318 necessary to |break| here.  The extra line of code seems worthwhile to
1319 preserve the generality of |do_compaction|.
1320
1321 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1322 {
1323 t=s;
1324 s=mp->next_str[s];
1325 mp->next_str[r]=s;
1326 mp->next_str[t]=mp->next_str[mp->str_ptr];
1327 mp->next_str[mp->str_ptr]=t;
1328 if ( s==mp->str_ptr ) break;
1329 }
1330
1331 @ The string currently starts at |str_start[r]| and ends just before
1332 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1333 to locate the next string.
1334
1335 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1336 q=mp->str_start[r];
1337 mp->str_start[r]=p;
1338 while ( q<mp->str_start[s] ) { 
1339   mp->str_pool[p]=mp->str_pool[q];
1340   incr(p); incr(q);
1341 }
1342
1343 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1344 we do this, anything between them should be moved.
1345
1346 @ @<Move the current string back so that it starts at |p|@>=
1347 q=mp->str_start[mp->str_ptr];
1348 mp->str_start[mp->str_ptr]=p;
1349 while ( q<mp->pool_ptr ) { 
1350   mp->str_pool[p]=mp->str_pool[q];
1351   incr(p); incr(q);
1352 }
1353 mp->pool_ptr=p
1354
1355 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1356
1357 @<Make sure that there is room for another string with |needed| char...@>=
1358 if ( str_use>=mp->max_strings-1 )
1359   mp_reallocate_strings (mp,str_use);
1360 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1361   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1362   mp->max_pool_ptr=mp->pool_ptr+needed;
1363 }
1364
1365 @ @<Declarations@>=
1366 void mp_reallocate_strings (MP mp, str_number str_use) ;
1367 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1368
1369 @ @c 
1370 void mp_reallocate_strings (MP mp, str_number str_use) { 
1371   while ( str_use>=mp->max_strings-1 ) {
1372     int l = mp->max_strings + (mp->max_strings>>2);
1373     XREALLOC (mp->str_ref,   l, int);
1374     XREALLOC (mp->str_start, l, pool_pointer);
1375     XREALLOC (mp->next_str,  l, str_number);
1376     mp->max_strings = l;
1377   }
1378 }
1379 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1380   while ( needed>mp->pool_size ) {
1381     int l = mp->pool_size + (mp->pool_size>>2);
1382         XREALLOC (mp->str_pool, l, ASCII_code);
1383     mp->pool_size = l;
1384   }
1385 }
1386
1387 @ @<Account for the compaction and make sure the statistics agree with...@>=
1388 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1389   mp_confusion(mp, "string");
1390 @:this can't happen string}{\quad string@>
1391 incr(mp->pact_count);
1392 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1393 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1394 #ifdef DEBUG
1395 s=mp->str_ptr; t=str_use;
1396 while ( s<=mp->max_str_ptr ){
1397   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1398   incr(t); s=mp->next_str[s];
1399 };
1400 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1401 #endif
1402
1403 @ A few more global variables are needed to keep track of statistics when
1404 |stat| $\ldots$ |tats| blocks are not commented out.
1405
1406 @<Glob...@>=
1407 integer pact_count; /* number of string pool compactions so far */
1408 integer pact_chars; /* total number of characters moved during compactions */
1409 integer pact_strs; /* total number of strings moved during compactions */
1410
1411 @ @<Initialize compaction statistics@>=
1412 mp->pact_count=0;
1413 mp->pact_chars=0;
1414 mp->pact_strs=0;
1415
1416 @ The following subroutine compares string |s| with another string of the
1417 same length that appears in |buffer| starting at position |k|;
1418 the result is |true| if and only if the strings are equal.
1419
1420 @c 
1421 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1422   /* test equality of strings */
1423   pool_pointer j; /* running index */
1424   j=mp->str_start[s];
1425   while ( j<str_stop(s) ) { 
1426     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1427       return false;
1428   }
1429   return true;
1430 }
1431
1432 @ Here is a similar routine, but it compares two strings in the string pool,
1433 and it does not assume that they have the same length. If the first string
1434 is lexicographically greater than, less than, or equal to the second,
1435 the result is respectively positive, negative, or zero.
1436
1437 @c 
1438 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1439   /* test equality of strings */
1440   pool_pointer j,k; /* running indices */
1441   integer ls,lt; /* lengths */
1442   integer l; /* length remaining to test */
1443   ls=length(s); lt=length(t);
1444   if ( ls<=lt ) l=ls; else l=lt;
1445   j=mp->str_start[s]; k=mp->str_start[t];
1446   while ( l-->0 ) { 
1447     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1448        return (mp->str_pool[j]-mp->str_pool[k]); 
1449     }
1450     incr(j); incr(k);
1451   }
1452   return (ls-lt);
1453 }
1454
1455 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1456 and |str_ptr| are computed by the \.{INIMP} program, based in part
1457 on the information that \.{WEB} has output while processing \MP.
1458 @.INIMP@>
1459 @^string pool@>
1460
1461 @c 
1462 void mp_get_strings_started (MP mp) { 
1463   /* initializes the string pool,
1464     but returns |false| if something goes wrong */
1465   int k; /* small indices or counters */
1466   str_number g; /* a new string */
1467   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1468   mp->str_start[0]=0;
1469   mp->next_str[0]=1;
1470   mp->pool_in_use=0; mp->strs_in_use=0;
1471   mp->max_pl_used=0; mp->max_strs_used=0;
1472   @<Initialize compaction statistics@>;
1473   mp->strs_used_up=0;
1474   @<Make the first 256 strings@>;
1475   g=mp_make_string(mp); /* string 256 == "" */
1476   mp->str_ref[g]=max_str_ref;
1477   mp->last_fixed_str=mp->str_ptr-1;
1478   mp->fixed_str_use=mp->str_ptr;
1479   return;
1480 }
1481
1482 @ @<Declarations@>=
1483 void mp_get_strings_started (MP mp);
1484
1485 @ The first 256 strings will consist of a single character only.
1486
1487 @<Make the first 256...@>=
1488 for (k=0;k<=255;k++) { 
1489   append_char(k);
1490   g=mp_make_string(mp); 
1491   mp->str_ref[g]=max_str_ref;
1492 }
1493
1494 @ The first 128 strings will contain 95 standard ASCII characters, and the
1495 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1496 unless a system-dependent change is made here. Installations that have
1497 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1498 would like string 032 to be printed as the single character 032 instead
1499 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1500 even people with an extended character set will want to represent string
1501 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1502 to produce visible strings instead of tabs or line-feeds or carriage-returns
1503 or bell-rings or characters that are treated anomalously in text files.
1504
1505 Unprintable characters of codes 128--255 are, similarly, rendered
1506 \.{\^\^80}--\.{\^\^ff}.
1507
1508 The boolean expression defined here should be |true| unless \MP\ internal
1509 code number~|k| corresponds to a non-troublesome visible symbol in the
1510 local character set.
1511 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1512 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1513 must be printable.
1514 @^character set dependencies@>
1515 @^system dependencies@>
1516
1517 @<Character |k| cannot be printed@>=
1518   (k<' ')||(k>'~')
1519
1520 @* \[5] On-line and off-line printing.
1521 Messages that are sent to a user's terminal and to the transcript-log file
1522 are produced by several `|print|' procedures. These procedures will
1523 direct their output to a variety of places, based on the setting of
1524 the global variable |selector|, which has the following possible
1525 values:
1526
1527 \yskip
1528 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1529   transcript file.
1530
1531 \hang |log_only|, prints only on the transcript file.
1532
1533 \hang |term_only|, prints only on the terminal.
1534
1535 \hang |no_print|, doesn't print at all. This is used only in rare cases
1536   before the transcript file is open.
1537
1538 \hang |pseudo|, puts output into a cyclic buffer that is used
1539   by the |show_context| routine; when we get to that routine we shall discuss
1540   the reasoning behind this curious mode.
1541
1542 \hang |new_string|, appends the output to the current string in the
1543   string pool.
1544
1545 \hang |>=write_file| prints on one of the files used for the \&{write}
1546 @:write_}{\&{write} primitive@>
1547   command.
1548
1549 \yskip
1550 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1551 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1552 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1553 relations are not used when |selector| could be |pseudo|, or |new_string|.
1554 We need not check for unprintable characters when |selector<pseudo|.
1555
1556 Three additional global variables, |tally|, |term_offset| and |file_offset|
1557 record the number of characters that have been printed
1558 since they were most recently cleared to zero. We use |tally| to record
1559 the length of (possibly very long) stretches of printing; |term_offset|,
1560 and |file_offset|, on the other hand, keep track of how many
1561 characters have appeared so far on the current line that has been output
1562 to the terminal, the transcript file, or the \ps\ output file, respectively.
1563
1564 @d new_string 0 /* printing is deflected to the string pool */
1565 @d pseudo 2 /* special |selector| setting for |show_context| */
1566 @d no_print 3 /* |selector| setting that makes data disappear */
1567 @d term_only 4 /* printing is destined for the terminal only */
1568 @d log_only 5 /* printing is destined for the transcript file only */
1569 @d term_and_log 6 /* normal |selector| setting */
1570 @d write_file 7 /* first write file selector */
1571
1572 @<Glob...@>=
1573 void * log_file; /* transcript of \MP\ session */
1574 void * ps_file; /* the generic font output goes here */
1575 unsigned int selector; /* where to print a message */
1576 unsigned char dig[23]; /* digits in a number being output */
1577 integer tally; /* the number of characters recently printed */
1578 unsigned int term_offset;
1579   /* the number of characters on the current terminal line */
1580 unsigned int file_offset;
1581   /* the number of characters on the current file line */
1582 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1583 integer trick_count; /* threshold for pseudoprinting, explained later */
1584 integer first_count; /* another variable for pseudoprinting */
1585
1586 @ @<Allocate or initialize ...@>=
1587 memset(mp->dig,0,23);
1588 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1589
1590 @ @<Dealloc variables@>=
1591 xfree(mp->trick_buf);
1592
1593 @ @<Initialize the output routines@>=
1594 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1595
1596 @ Macro abbreviations for output to the terminal and to the log file are
1597 defined here for convenience. Some systems need special conventions
1598 for terminal output, and it is possible to adhere to those conventions
1599 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1600 @^system dependencies@>
1601
1602 @d do_fprintf(f,b) (mp->write_ascii_file)(f,b)
1603 @d wterm(A)     do_fprintf(mp->term_out,(A))
1604 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->term_out,(char *)ss); }
1605 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1606 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1607 @d wlog(A)      do_fprintf(mp->log_file,(A))
1608 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->log_file,(char *)ss); }
1609 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1610 @d wlog_ln(A)   {wlog_cr; do_fprintf(mp->log_file,(A)); }
1611
1612
1613 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1614 use an array |wr_file| that will be declared later.
1615
1616 @d mp_print_text(A) mp_print_str(mp,text((A)))
1617
1618 @<Internal ...@>=
1619 void mp_print_ln (MP mp);
1620 void mp_print_visible_char (MP mp, ASCII_code s); 
1621 void mp_print_char (MP mp, ASCII_code k);
1622 void mp_print (MP mp, char *s);
1623 void mp_print_str (MP mp, str_number s);
1624 void mp_print_nl (MP mp, char *s);
1625 void mp_print_two (MP mp,scaled x, scaled y) ;
1626 void mp_print_scaled (MP mp,scaled s);
1627
1628 @ @<Basic print...@>=
1629 void mp_print_ln (MP mp) { /* prints an end-of-line */
1630  switch (mp->selector) {
1631   case term_and_log: 
1632     wterm_cr; wlog_cr;
1633     mp->term_offset=0;  mp->file_offset=0;
1634     break;
1635   case log_only: 
1636     wlog_cr; mp->file_offset=0;
1637     break;
1638   case term_only: 
1639     wterm_cr; mp->term_offset=0;
1640     break;
1641   case no_print:
1642   case pseudo: 
1643   case new_string: 
1644     break;
1645   default: 
1646     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1647   }
1648 } /* note that |tally| is not affected */
1649
1650 @ The |print_visible_char| procedure sends one character to the desired
1651 destination, using the |xchr| array to map it into an external character
1652 compatible with |input_ln|.  (It assumes that it is always called with
1653 a visible ASCII character.)  All printing comes through |print_ln| or
1654 |print_char|, which ultimately calls |print_visible_char|, hence these
1655 routines are the ones that limit lines to at most |max_print_line| characters.
1656 But we must make an exception for the \ps\ output file since it is not safe
1657 to cut up lines arbitrarily in \ps.
1658
1659 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1660 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1661 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1662
1663 @<Basic printing...@>=
1664 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1665   switch (mp->selector) {
1666   case term_and_log: 
1667     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1668     incr(mp->term_offset); incr(mp->file_offset);
1669     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1670        wterm_cr; mp->term_offset=0;
1671     };
1672     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1673        wlog_cr; mp->file_offset=0;
1674     };
1675     break;
1676   case log_only: 
1677     wlog_chr(xchr(s)); incr(mp->file_offset);
1678     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1679     break;
1680   case term_only: 
1681     wterm_chr(xchr(s)); incr(mp->term_offset);
1682     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1683     break;
1684   case no_print: 
1685     break;
1686   case pseudo: 
1687     if ( mp->tally<mp->trick_count ) 
1688       mp->trick_buf[mp->tally % mp->error_line]=s;
1689     break;
1690   case new_string: 
1691     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1692       mp_unit_str_room(mp);
1693       if ( mp->pool_ptr>=mp->pool_size ) 
1694         goto DONE; /* drop characters if string space is full */
1695     };
1696     append_char(s);
1697     break;
1698   default:
1699     { char ss[2]; ss[0] = xchr(s); ss[1]=0;
1700       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1701     }
1702   }
1703 DONE:
1704   incr(mp->tally);
1705 }
1706
1707 @ The |print_char| procedure sends one character to the desired destination.
1708 File names and string expressions might contain |ASCII_code| values that
1709 can't be printed using |print_visible_char|.  These characters will be
1710 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1711 (This procedure assumes that it is safe to bypass all checks for unprintable
1712 characters when |selector| is in the range |0..max_write_files-1|.
1713 The user might want to write unprintable characters.
1714
1715 @d print_lc_hex(A) do { l=(A);
1716     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1717   } while (0)
1718
1719 @<Basic printing...@>=
1720 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1721   int l; /* small index or counter */
1722   if ( mp->selector<pseudo || mp->selector>=write_file) {
1723     mp_print_visible_char(mp, k);
1724   } else if ( @<Character |k| cannot be printed@> ) { 
1725     mp_print(mp, "^^"); 
1726     if ( k<0100 ) { 
1727       mp_print_visible_char(mp, k+0100); 
1728     } else if ( k<0200 ) { 
1729       mp_print_visible_char(mp, k-0100); 
1730     } else { 
1731       print_lc_hex(k / 16);  
1732       print_lc_hex(k % 16); 
1733     }
1734   } else {
1735     mp_print_visible_char(mp, k);
1736   }
1737 };
1738
1739 @ An entire string is output by calling |print|. Note that if we are outputting
1740 the single standard ASCII character \.c, we could call |print("c")|, since
1741 |"c"=99| is the number of a single-character string, as explained above. But
1742 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1743 routine when it knows that this is safe. (The present implementation
1744 assumes that it is always safe to print a visible ASCII character.)
1745 @^system dependencies@>
1746
1747 @<Basic print...@>=
1748 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1749   unsigned int j = 0;
1750   while ( j<len ){ 
1751     mp_print_char(mp, ss[j]); incr(j);
1752   }
1753 }
1754
1755
1756 @<Basic print...@>=
1757 void mp_print (MP mp, char *ss) {
1758   mp_do_print(mp, ss, strlen(ss));
1759 }
1760 void mp_print_str (MP mp, str_number s) {
1761   pool_pointer j; /* current character code position */
1762   if ( (s<0)||(s>mp->max_str_ptr) ) {
1763      mp_do_print(mp,"???",3); /* this can't happen */
1764 @.???@>
1765   }
1766   j=mp->str_start[s];
1767   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1768 }
1769
1770
1771 @ Here is the very first thing that \MP\ prints: a headline that identifies
1772 the version number and base name. The |term_offset| variable is temporarily
1773 incorrect, but the discrepancy is not serious since we assume that the banner
1774 and mem identifier together will occupy at most |max_print_line|
1775 character positions.
1776
1777 @<Initialize the output...@>=
1778 wterm (banner);
1779 wterm (version_string);
1780 if (mp->mem_ident!=NULL) 
1781   mp_print(mp,mp->mem_ident); 
1782 mp_print_ln(mp);
1783 update_terminal;
1784
1785 @ The procedure |print_nl| is like |print|, but it makes sure that the
1786 string appears at the beginning of a new line.
1787
1788 @<Basic print...@>=
1789 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1790   switch(mp->selector) {
1791   case term_and_log: 
1792     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1793     break;
1794   case log_only: 
1795     if ( mp->file_offset>0 ) mp_print_ln(mp);
1796     break;
1797   case term_only: 
1798     if ( mp->term_offset>0 ) mp_print_ln(mp);
1799     break;
1800   case no_print:
1801   case pseudo:
1802   case new_string: 
1803         break;
1804   } /* there are no other cases */
1805   mp_print(mp, s);
1806 }
1807
1808 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1809
1810 @<Basic print...@>=
1811 void mp_print_the_digs (MP mp, eight_bits k) {
1812   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1813   while ( k>0 ){ 
1814     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1815   }
1816 };
1817
1818 @ The following procedure, which prints out the decimal representation of a
1819 given integer |n|, has been written carefully so that it works properly
1820 if |n=0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1821 to negative arguments, since such operations are not implemented consistently
1822 on all platforms.
1823
1824 @<Basic print...@>=
1825 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1826   integer m; /* used to negate |n| in possibly dangerous cases */
1827   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1828   if ( n<0 ) { 
1829     mp_print_char(mp, '-');
1830     if ( n>-100000000 ) {
1831           negate(n);
1832     } else  { 
1833           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1834       if ( m<10 ) {
1835         mp->dig[0]=m;
1836       } else { 
1837         mp->dig[0]=0; incr(n);
1838       }
1839     }
1840   }
1841   do {  
1842     mp->dig[k]=n % 10; n=n / 10; incr(k);
1843   } while (n!=0);
1844   mp_print_the_digs(mp, k);
1845 };
1846
1847 @ @<Internal ...@>=
1848 void mp_print_int (MP mp,integer n);
1849
1850 @ \MP\ also makes use of a trivial procedure to print two digits. The
1851 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1852
1853 @c 
1854 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1855   n=abs(n) % 100; 
1856   mp_print_char(mp, '0'+(n / 10));
1857   mp_print_char(mp, '0'+(n % 10));
1858 }
1859
1860
1861 @ @<Internal ...@>=
1862 void mp_print_dd (MP mp,integer n);
1863
1864 @ Here is a procedure that asks the user to type a line of input,
1865 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1866 The input is placed into locations |first| through |last-1| of the
1867 |buffer| array, and echoed on the transcript file if appropriate.
1868
1869 This procedure is never called when |interaction<mp_scroll_mode|.
1870
1871 @d prompt_input(A) do { 
1872     if (!mp->noninteractive) {
1873       wake_up_terminal; mp_print(mp, (A)); 
1874     }
1875     mp_term_input(mp);
1876   } while (0) /* prints a string and gets a line of input */
1877
1878 @c 
1879 void mp_term_input (MP mp) { /* gets a line from the terminal */
1880   size_t k; /* index into |buffer| */
1881   update_terminal; /* Now the user sees the prompt for sure */
1882   if (!mp_input_ln(mp, mp->term_in )) {
1883     if (!mp->noninteractive) {
1884           mp_fatal_error(mp, "End of file on the terminal!");
1885 @.End of file on the terminal@>
1886     } else { /* we are done with this input chunk */
1887           longjmp(mp->jump_buf,1);      
1888     }
1889   }
1890   if (!mp->noninteractive) {
1891     mp->term_offset=0; /* the user's line ended with \<\rm return> */
1892     decr(mp->selector); /* prepare to echo the input */
1893     if ( mp->last!=mp->first ) {
1894       for (k=mp->first;k<=mp->last-1;k++) {
1895         mp_print_char(mp, mp->buffer[k]);
1896       }
1897     }
1898     mp_print_ln(mp); 
1899     mp->buffer[mp->last]='%'; 
1900     incr(mp->selector); /* restore previous status */
1901   }
1902 }
1903
1904 @* \[6] Reporting errors.
1905 When something anomalous is detected, \MP\ typically does something like this:
1906 $$\vbox{\halign{#\hfil\cr
1907 |print_err("Something anomalous has been detected");|\cr
1908 |help3("This is the first line of my offer to help.")|\cr
1909 |("This is the second line. I'm trying to")|\cr
1910 |("explain the best way for you to proceed.");|\cr
1911 |error;|\cr}}$$
1912 A two-line help message would be given using |help2|, etc.; these informal
1913 helps should use simple vocabulary that complements the words used in the
1914 official error message that was printed. (Outside the U.S.A., the help
1915 messages should preferably be translated into the local vernacular. Each
1916 line of help is at most 60 characters long, in the present implementation,
1917 so that |max_print_line| will not be exceeded.)
1918
1919 The |print_err| procedure supplies a `\.!' before the official message,
1920 and makes sure that the terminal is awake if a stop is going to occur.
1921 The |error| procedure supplies a `\..' after the official message, then it
1922 shows the location of the error; and if |interaction=error_stop_mode|,
1923 it also enters into a dialog with the user, during which time the help
1924 message may be printed.
1925 @^system dependencies@>
1926
1927 @ The global variable |interaction| has four settings, representing increasing
1928 amounts of user interaction:
1929
1930 @<Exported types@>=
1931 enum mp_interaction_mode { 
1932  mp_unspecified_mode=0, /* extra value for command-line switch */
1933  mp_batch_mode, /* omits all stops and omits terminal output */
1934  mp_nonstop_mode, /* omits all stops */
1935  mp_scroll_mode, /* omits error stops */
1936  mp_error_stop_mode, /* stops at every opportunity to interact */
1937 };
1938
1939 @ @<Option variables@>=
1940 int interaction; /* current level of interaction */
1941 int noninteractive; /* do we have a terminal? */
1942
1943 @ Set it here so it can be overwritten by the commandline
1944
1945 @<Allocate or initialize ...@>=
1946 mp->interaction=opt->interaction;
1947 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1948   mp->interaction=mp_error_stop_mode;
1949 if (mp->interaction<mp_unspecified_mode) 
1950   mp->interaction=mp_batch_mode;
1951 mp->noninteractive=opt->noninteractive;
1952
1953
1954
1955 @d print_err(A) mp_print_err(mp,(A))
1956
1957 @<Internal ...@>=
1958 void mp_print_err(MP mp, char * A);
1959
1960 @ @c
1961 void mp_print_err(MP mp, char * A) { 
1962   if ( mp->interaction==mp_error_stop_mode ) 
1963     wake_up_terminal;
1964   mp_print_nl(mp, "! "); 
1965   mp_print(mp, A);
1966 @.!\relax@>
1967 }
1968
1969
1970 @ \MP\ is careful not to call |error| when the print |selector| setting
1971 might be unusual. The only possible values of |selector| at the time of
1972 error messages are
1973
1974 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1975   and |log_file| not yet open);
1976
1977 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1978
1979 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1980
1981 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1982
1983 @<Initialize the print |selector| based on |interaction|@>=
1984 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1985
1986 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1987 routine is active when |error| is called; this ensures that |get_next|
1988 will never be called recursively.
1989 @^recursion@>
1990
1991 The global variable |history| records the worst level of error that
1992 has been detected. It has four possible values: |spotless|, |warning_issued|,
1993 |error_message_issued|, and |fatal_error_stop|.
1994
1995 Another global variable, |error_count|, is increased by one when an
1996 |error| occurs without an interactive dialog, and it is reset to zero at
1997 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1998 that there is no point in continuing further.
1999
2000 @<Types...@>=
2001 enum mp_history_states {
2002   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2003   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2004   mp_error_message_issued, /* |history| value when |error| has been called */
2005   mp_fatal_error_stop, /* |history| value when termination was premature */
2006 };
2007
2008 @ @<Glob...@>=
2009 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2010 int history; /* has the source input been clean so far? */
2011 int error_count; /* the number of scrolled errors since the last statement ended */
2012
2013 @ The value of |history| is initially |fatal_error_stop|, but it will
2014 be changed to |spotless| if \MP\ survives the initialization process.
2015
2016 @<Allocate or ...@>=
2017 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2018
2019 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2020 error procedures near the beginning of the program. But the error procedures
2021 in turn use some other procedures, which need to be declared |forward|
2022 before we get to |error| itself.
2023
2024 It is possible for |error| to be called recursively if some error arises
2025 when |get_next| is being used to delete a token, and/or if some fatal error
2026 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2027 @^recursion@>
2028 is never more than two levels deep.
2029
2030 @<Declarations@>=
2031 void mp_get_next (MP mp);
2032 void mp_term_input (MP mp);
2033 void mp_show_context (MP mp);
2034 void mp_begin_file_reading (MP mp);
2035 void mp_open_log_file (MP mp);
2036 void mp_clear_for_error_prompt (MP mp);
2037 void mp_debug_help (MP mp);
2038 @<Declare the procedure called |flush_string|@>
2039
2040 @ @<Internal ...@>=
2041 void mp_normalize_selector (MP mp);
2042
2043 @ Individual lines of help are recorded in the array |help_line|, which
2044 contains entries in positions |0..(help_ptr-1)|. They should be printed
2045 in reverse order, i.e., with |help_line[0]| appearing last.
2046
2047 @d hlp1(A) mp->help_line[0]=(A); }
2048 @d hlp2(A) mp->help_line[1]=(A); hlp1
2049 @d hlp3(A) mp->help_line[2]=(A); hlp2
2050 @d hlp4(A) mp->help_line[3]=(A); hlp3
2051 @d hlp5(A) mp->help_line[4]=(A); hlp4
2052 @d hlp6(A) mp->help_line[5]=(A); hlp5
2053 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2054 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2055 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2056 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2057 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2058 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2059 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2060
2061 @<Glob...@>=
2062 char * help_line[6]; /* helps for the next |error| */
2063 unsigned int help_ptr; /* the number of help lines present */
2064 boolean use_err_help; /* should the |err_help| string be shown? */
2065 str_number err_help; /* a string set up by \&{errhelp} */
2066 str_number filename_template; /* a string set up by \&{filenametemplate} */
2067
2068 @ @<Allocate or ...@>=
2069 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2070
2071 @ The |jump_out| procedure just cuts across all active procedure levels and
2072 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2073 whole program. It is used when there is no recovery from a particular error.
2074
2075 The program uses a |jump_buf| to handle this, this is initialized at three
2076 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2077 of |mp_run|. Those are the only library enty points.
2078
2079 @^system dependencies@>
2080
2081 @<Glob...@>=
2082 jmp_buf jump_buf;
2083
2084 @ @<Install and test the non-local jump buffer@>=
2085 if (setjmp(mp->jump_buf) != 0) { return mp->history; }
2086
2087
2088 @ @<Setup the non-local jump buffer in |mp_new|@>=
2089 if (setjmp(mp->jump_buf) != 0) return NULL;
2090
2091 @ If the array of internals is still |NULL| when |jump_out| is called, a
2092 crash occured during initialization, and it is not safe to run the normal
2093 cleanup routine.
2094
2095 @<Error hand...@>=
2096 void mp_jump_out (MP mp) { 
2097   if(mp->internal!=NULL)
2098     mp_close_files_and_terminate(mp);
2099   longjmp(mp->jump_buf,1);
2100 }
2101
2102 @ Here now is the general |error| routine.
2103
2104 @<Error hand...@>=
2105 void mp_error (MP mp) { /* completes the job of error reporting */
2106   ASCII_code c; /* what the user types */
2107   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2108   pool_pointer j; /* character position being printed */
2109   if ( mp->history<mp_error_message_issued ) 
2110         mp->history=mp_error_message_issued;
2111   mp_print_char(mp, '.'); mp_show_context(mp);
2112   if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2113     @<Get user's advice and |return|@>;
2114   }
2115   incr(mp->error_count);
2116   if ( mp->error_count==100 ) { 
2117     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2118 @.That makes 100 errors...@>
2119     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2120   }
2121   @<Put help message on the transcript file@>;
2122 }
2123 void mp_warn (MP mp, char *msg) {
2124   int saved_selector = mp->selector;
2125   mp_normalize_selector(mp);
2126   mp_print_nl(mp,"Warning: ");
2127   mp_print(mp,msg);
2128   mp->selector = saved_selector;
2129 }
2130
2131 @ @<Exported function ...@>=
2132 void mp_error (MP mp);
2133 void mp_warn (MP mp, char *msg);
2134
2135
2136 @ @<Get user's advice...@>=
2137 while (1) { 
2138 CONTINUE:
2139   mp_clear_for_error_prompt(mp); prompt_input("? ");
2140 @.?\relax@>
2141   if ( mp->last==mp->first ) return;
2142   c=mp->buffer[mp->first];
2143   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2144   @<Interpret code |c| and |return| if done@>;
2145 }
2146
2147 @ It is desirable to provide an `\.E' option here that gives the user
2148 an easy way to return from \MP\ to the system editor, with the offending
2149 line ready to be edited. But such an extension requires some system
2150 wizardry, so the present implementation simply types out the name of the
2151 file that should be
2152 edited and the relevant line number.
2153 @^system dependencies@>
2154
2155 @<Exported types@>=
2156 typedef void (*mp_run_editor_command)(MP, char *, int);
2157
2158 @ @<Option variables@>=
2159 mp_run_editor_command run_editor;
2160
2161 @ @<Allocate or initialize ...@>=
2162 set_callback_option(run_editor);
2163
2164 @ @<Declarations@>=
2165 void mp_run_editor (MP mp, char *fname, int fline);
2166
2167 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2168     mp_print_nl(mp, "You want to edit file ");
2169 @.You want to edit file x@>
2170     mp_print(mp, fname);
2171     mp_print(mp, " at line "); 
2172     mp_print_int(mp, fline);
2173     mp->interaction=mp_scroll_mode; 
2174     mp_jump_out(mp);
2175 }
2176
2177
2178 There is a secret `\.D' option available when the debugging routines haven't
2179 been commented~out.
2180 @^debugging@>
2181
2182 @<Interpret code |c| and |return| if done@>=
2183 switch (c) {
2184 case '0': case '1': case '2': case '3': case '4':
2185 case '5': case '6': case '7': case '8': case '9': 
2186   if ( mp->deletions_allowed ) {
2187     @<Delete |c-"0"| tokens and |continue|@>;
2188   }
2189   break;
2190 #ifdef DEBUG
2191 case 'D': 
2192   mp_debug_help(mp); continue; 
2193   break;
2194 #endif
2195 case 'E': 
2196   if ( mp->file_ptr>0 ){ 
2197     (mp->run_editor)(mp, 
2198                      str(mp->input_stack[mp->file_ptr].name_field), 
2199                      mp_true_line(mp));
2200   }
2201   break;
2202 case 'H': 
2203   @<Print the help information and |continue|@>;
2204   break;
2205 case 'I':
2206   @<Introduce new material from the terminal and |return|@>;
2207   break;
2208 case 'Q': case 'R': case 'S':
2209   @<Change the interaction level and |return|@>;
2210   break;
2211 case 'X':
2212   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2213   break;
2214 default:
2215   break;
2216 }
2217 @<Print the menu of available options@>
2218
2219 @ @<Print the menu...@>=
2220
2221   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2222 @.Type <return> to proceed...@>
2223   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2224   mp_print_nl(mp, "I to insert something, ");
2225   if ( mp->file_ptr>0 ) 
2226     mp_print(mp, "E to edit your file,");
2227   if ( mp->deletions_allowed )
2228     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2229   mp_print_nl(mp, "H for help, X to quit.");
2230 }
2231
2232 @ Here the author of \MP\ apologizes for making use of the numerical
2233 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2234 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2235 @^Knuth, Donald Ervin@>
2236
2237 @<Change the interaction...@>=
2238
2239   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2240   mp_print(mp, "OK, entering ");
2241   switch (c) {
2242   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2243   case 'R': mp_print(mp, "nonstopmode"); break;
2244   case 'S': mp_print(mp, "scrollmode"); break;
2245   } /* there are no other cases */
2246   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2247 }
2248
2249 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2250 contain the material inserted by the user; otherwise another prompt will
2251 be given. In order to understand this part of the program fully, you need
2252 to be familiar with \MP's input stacks.
2253
2254 @<Introduce new material...@>=
2255
2256   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2257   if ( mp->last>mp->first+1 ) { 
2258     loc=mp->first+1; mp->buffer[mp->first]=' ';
2259   } else { 
2260    prompt_input("insert>"); loc=mp->first;
2261 @.insert>@>
2262   };
2263   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2264 }
2265
2266 @ We allow deletion of up to 99 tokens at a time.
2267
2268 @<Delete |c-"0"| tokens...@>=
2269
2270   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2271   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2272     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2273   else 
2274     c=c-'0';
2275   while ( c>0 ) { 
2276     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2277     @<Decrease the string reference count, if the current token is a string@>;
2278     decr(c);
2279   };
2280   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2281   help2("I have just deleted some text, as you asked.")
2282        ("You can now delete more, or insert, or whatever.");
2283   mp_show_context(mp); 
2284   goto CONTINUE;
2285 }
2286
2287 @ @<Print the help info...@>=
2288
2289   if ( mp->use_err_help ) { 
2290     @<Print the string |err_help|, possibly on several lines@>;
2291     mp->use_err_help=false;
2292   } else { 
2293     if ( mp->help_ptr==0 ) {
2294       help2("Sorry, I don't know how to help in this situation.")
2295            ("Maybe you should try asking a human?");
2296      }
2297     do { 
2298       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2299     } while (mp->help_ptr!=0);
2300   };
2301   help4("Sorry, I already gave what help I could...")
2302        ("Maybe you should try asking a human?")
2303        ("An error might have occurred before I noticed any problems.")
2304        ("``If all else fails, read the instructions.''");
2305   goto CONTINUE;
2306 }
2307
2308 @ @<Print the string |err_help|, possibly on several lines@>=
2309 j=mp->str_start[mp->err_help];
2310 while ( j<str_stop(mp->err_help) ) { 
2311   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2312   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2313   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2314   else  { incr(j); mp_print_char(mp, '%'); };
2315   incr(j);
2316 }
2317
2318 @ @<Put help message on the transcript file@>=
2319 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2320 if ( mp->use_err_help ) { 
2321   mp_print_nl(mp, "");
2322   @<Print the string |err_help|, possibly on several lines@>;
2323 } else { 
2324   while ( mp->help_ptr>0 ){ 
2325     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2326   };
2327 }
2328 mp_print_ln(mp);
2329 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2330 mp_print_ln(mp)
2331
2332 @ In anomalous cases, the print selector might be in an unknown state;
2333 the following subroutine is called to fix things just enough to keep
2334 running a bit longer.
2335
2336 @c 
2337 void mp_normalize_selector (MP mp) { 
2338   if ( mp->log_opened ) mp->selector=term_and_log;
2339   else mp->selector=term_only;
2340   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2341   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2342 }
2343
2344 @ The following procedure prints \MP's last words before dying.
2345
2346 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2347     mp->interaction=mp_scroll_mode; /* no more interaction */
2348   if ( mp->log_opened ) mp_error(mp);
2349   /*| if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); |*/
2350   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2351   }
2352
2353 @<Error hand...@>=
2354 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2355   mp_normalize_selector(mp);
2356   print_err("Emergency stop"); help1(s); succumb;
2357 @.Emergency stop@>
2358 }
2359
2360 @ @<Exported function ...@>=
2361 void mp_fatal_error (MP mp, char *s);
2362
2363
2364 @ Here is the most dreaded error message.
2365
2366 @<Error hand...@>=
2367 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2368   mp_normalize_selector(mp);
2369   print_err("MetaPost capacity exceeded, sorry [");
2370 @.MetaPost capacity exceeded ...@>
2371   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2372   help2("If you really absolutely need more capacity,")
2373        ("you can ask a wizard to enlarge me.");
2374   succumb;
2375 }
2376
2377 @ @<Internal library declarations@>=
2378 void mp_overflow (MP mp, char *s, integer n);
2379
2380 @ The program might sometime run completely amok, at which point there is
2381 no choice but to stop. If no previous error has been detected, that's bad
2382 news; a message is printed that is really intended for the \MP\
2383 maintenance person instead of the user (unless the user has been
2384 particularly diabolical).  The index entries for `this can't happen' may
2385 help to pinpoint the problem.
2386 @^dry rot@>
2387
2388 @<Internal library ...@>=
2389 void mp_confusion (MP mp,char *s);
2390
2391 @ @<Error hand...@>=
2392 void mp_confusion (MP mp,char *s) {
2393   /* consistency check violated; |s| tells where */
2394   mp_normalize_selector(mp);
2395   if ( mp->history<mp_error_message_issued ) { 
2396     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2397 @.This can't happen@>
2398     help1("I'm broken. Please show this to someone who can fix can fix");
2399   } else { 
2400     print_err("I can\'t go on meeting you like this");
2401 @.I can't go on...@>
2402     help2("One of your faux pas seems to have wounded me deeply...")
2403          ("in fact, I'm barely conscious. Please fix it and try again.");
2404   }
2405   succumb;
2406 }
2407
2408 @ Users occasionally want to interrupt \MP\ while it's running.
2409 If the runtime system allows this, one can implement
2410 a routine that sets the global variable |interrupt| to some nonzero value
2411 when such an interrupt is signaled. Otherwise there is probably at least
2412 a way to make |interrupt| nonzero using the C debugger.
2413 @^system dependencies@>
2414 @^debugging@>
2415
2416 @d check_interrupt { if ( mp->interrupt!=0 )
2417    mp_pause_for_instructions(mp); }
2418
2419 @<Global...@>=
2420 integer interrupt; /* should \MP\ pause for instructions? */
2421 boolean OK_to_interrupt; /* should interrupts be observed? */
2422
2423 @ @<Allocate or ...@>=
2424 mp->interrupt=0; mp->OK_to_interrupt=true;
2425
2426 @ When an interrupt has been detected, the program goes into its
2427 highest interaction level and lets the user have the full flexibility of
2428 the |error| routine.  \MP\ checks for interrupts only at times when it is
2429 safe to do this.
2430
2431 @c 
2432 void mp_pause_for_instructions (MP mp) { 
2433   if ( mp->OK_to_interrupt ) { 
2434     mp->interaction=mp_error_stop_mode;
2435     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2436       incr(mp->selector);
2437     print_err("Interruption");
2438 @.Interruption@>
2439     help3("You rang?")
2440          ("Try to insert some instructions for me (e.g.,`I show x'),")
2441          ("unless you just want to quit by typing `X'.");
2442     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2443     mp->interrupt=0;
2444   }
2445 }
2446
2447 @ Many of \MP's error messages state that a missing token has been
2448 inserted behind the scenes. We can save string space and program space
2449 by putting this common code into a subroutine.
2450
2451 @c 
2452 void mp_missing_err (MP mp, char *s) { 
2453   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2454 @.Missing...inserted@>
2455 }
2456
2457 @* \[7] Arithmetic with scaled numbers.
2458 The principal computations performed by \MP\ are done entirely in terms of
2459 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2460 program can be carried out in exactly the same way on a wide variety of
2461 computers, including some small ones.
2462 @^small computers@>
2463
2464 But C does not rigidly define the |/| operation in the case of negative
2465 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2466 computers and |-n| on others (is this true ?).  There are two principal
2467 types of arithmetic: ``translation-preserving,'' in which the identity
2468 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2469 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2470 different results, although the differences should be negligible when the
2471 language is being used properly.  The \TeX\ processor has been defined
2472 carefully so that both varieties of arithmetic will produce identical
2473 output, but it would be too inefficient to constrain \MP\ in a similar way.
2474
2475 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2476
2477 @ One of \MP's most common operations is the calculation of
2478 $\lfloor{a+b\over2}\rfloor$,
2479 the midpoint of two given integers |a| and~|b|. The most decent way to do
2480 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2481 to calculate `|(a+b)>>1|'.
2482
2483 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2484 in this program. If \MP\ is being implemented with languages that permit
2485 binary shifting, the |half| macro should be changed to make this operation
2486 as efficient as possible.  Since some systems have shift operators that can
2487 only be trusted to work on positive numbers, there is also a macro |halfp|
2488 that is used only when the quantity being halved is known to be positive
2489 or zero.
2490
2491 @d half(A) ((A) / 2)
2492 @d halfp(A) ((A) >> 1)
2493
2494 @ A single computation might use several subroutine calls, and it is
2495 desirable to avoid producing multiple error messages in case of arithmetic
2496 overflow. So the routines below set the global variable |arith_error| to |true|
2497 instead of reporting errors directly to the user.
2498
2499 @<Glob...@>=
2500 boolean arith_error; /* has arithmetic overflow occurred recently? */
2501
2502 @ @<Allocate or ...@>=
2503 mp->arith_error=false;
2504
2505 @ At crucial points the program will say |check_arith|, to test if
2506 an arithmetic error has been detected.
2507
2508 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2509
2510 @c 
2511 void mp_clear_arith (MP mp) { 
2512   print_err("Arithmetic overflow");
2513 @.Arithmetic overflow@>
2514   help4("Uh, oh. A little while ago one of the quantities that I was")
2515        ("computing got too large, so I'm afraid your answers will be")
2516        ("somewhat askew. You'll probably have to adopt different")
2517        ("tactics next time. But I shall try to carry on anyway.");
2518   mp_error(mp); 
2519   mp->arith_error=false;
2520 }
2521
2522 @ Addition is not always checked to make sure that it doesn't overflow,
2523 but in places where overflow isn't too unlikely the |slow_add| routine
2524 is used.
2525
2526 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2527   if ( x>=0 )  {
2528     if ( y<=el_gordo-x ) { 
2529       return x+y;
2530     } else  { 
2531       mp->arith_error=true; 
2532           return el_gordo;
2533     }
2534   } else  if ( -y<=el_gordo+x ) {
2535     return x+y;
2536   } else { 
2537     mp->arith_error=true; 
2538         return -el_gordo;
2539   }
2540 }
2541
2542 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2543 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2544 positions from the right end of a binary computer word.
2545
2546 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2547 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2548 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2549 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2550 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2551 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2552
2553 @<Types...@>=
2554 typedef integer scaled; /* this type is used for scaled integers */
2555 typedef unsigned char small_number; /* this type is self-explanatory */
2556
2557 @ The following function is used to create a scaled integer from a given decimal
2558 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2559 given in |dig[i]|, and the calculation produces a correctly rounded result.
2560
2561 @c 
2562 scaled mp_round_decimals (MP mp,small_number k) {
2563   /* converts a decimal fraction */
2564  integer a = 0; /* the accumulator */
2565  while ( k-->0 ) { 
2566     a=(a+mp->dig[k]*two) / 10;
2567   }
2568   return halfp(a+1);
2569 }
2570
2571 @ Conversely, here is a procedure analogous to |print_int|. If the output
2572 of this procedure is subsequently read by \MP\ and converted by the
2573 |round_decimals| routine above, it turns out that the original value will
2574 be reproduced exactly. A decimal point is printed only if the value is
2575 not an integer. If there is more than one way to print the result with
2576 the optimum number of digits following the decimal point, the closest
2577 possible value is given.
2578
2579 The invariant relation in the \&{repeat} loop is that a sequence of
2580 decimal digits yet to be printed will yield the original number if and only if
2581 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2582 We can stop if and only if $f=0$ satisfies this condition; the loop will
2583 terminate before $s$ can possibly become zero.
2584
2585 @<Basic printing...@>=
2586 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2587   scaled delta; /* amount of allowable inaccuracy */
2588   if ( s<0 ) { 
2589         mp_print_char(mp, '-'); 
2590     negate(s); /* print the sign, if negative */
2591   }
2592   mp_print_int(mp, s / unity); /* print the integer part */
2593   s=10*(s % unity)+5;
2594   if ( s!=5 ) { 
2595     delta=10; 
2596     mp_print_char(mp, '.');
2597     do {  
2598       if ( delta>unity )
2599         s=s+0100000-(delta / 2); /* round the final digit */
2600       mp_print_char(mp, '0'+(s / unity)); 
2601       s=10*(s % unity); 
2602       delta=delta*10;
2603     } while (s>delta);
2604   }
2605 }
2606
2607 @ We often want to print two scaled quantities in parentheses,
2608 separated by a comma.
2609
2610 @<Basic printing...@>=
2611 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2612   mp_print_char(mp, '('); 
2613   mp_print_scaled(mp, x); 
2614   mp_print_char(mp, ','); 
2615   mp_print_scaled(mp, y);
2616   mp_print_char(mp, ')');
2617 }
2618
2619 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2620 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2621 arithmetic with 28~significant bits of precision. A |fraction| denotes
2622 a scaled integer whose binary point is assumed to be 28 bit positions
2623 from the right.
2624
2625 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2626 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2627 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2628 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2629 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2630
2631 @<Types...@>=
2632 typedef integer fraction; /* this type is used for scaled fractions */
2633
2634 @ In fact, the two sorts of scaling discussed above aren't quite
2635 sufficient; \MP\ has yet another, used internally to keep track of angles
2636 in units of $2^{-20}$ degrees.
2637
2638 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2639 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2640 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2641 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2642
2643 @<Types...@>=
2644 typedef integer angle; /* this type is used for scaled angles */
2645
2646 @ The |make_fraction| routine produces the |fraction| equivalent of
2647 |p/q|, given integers |p| and~|q|; it computes the integer
2648 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2649 positive. If |p| and |q| are both of the same scaled type |t|,
2650 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2651 and it's also possible to use the subroutine ``backwards,'' using
2652 the relation |make_fraction(t,fraction)=t| between scaled types.
2653
2654 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2655 sets |arith_error:=true|. Most of \MP's internal computations have
2656 been designed to avoid this sort of error.
2657
2658 If this subroutine were programmed in assembly language on a typical
2659 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2660 double-precision product can often be input to a fixed-point division
2661 instruction. But when we are restricted to int-eger arithmetic it
2662 is necessary either to resort to multiple-precision maneuvering
2663 or to use a simple but slow iteration. The multiple-precision technique
2664 would be about three times faster than the code adopted here, but it
2665 would be comparatively long and tricky, involving about sixteen
2666 additional multiplications and divisions.
2667
2668 This operation is part of \MP's ``inner loop''; indeed, it will
2669 consume nearly 10\pct! of the running time (exclusive of input and output)
2670 if the code below is left unchanged. A machine-dependent recoding
2671 will therefore make \MP\ run faster. The present implementation
2672 is highly portable, but slow; it avoids multiplication and division
2673 except in the initial stage. System wizards should be careful to
2674 replace it with a routine that is guaranteed to produce identical
2675 results in all cases.
2676 @^system dependencies@>
2677
2678 As noted below, a few more routines should also be replaced by machine-dependent
2679 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2680 such changes aren't advisable; simplicity and robustness are
2681 preferable to trickery, unless the cost is too high.
2682 @^inner loop@>
2683
2684 @<Internal ...@>=
2685 fraction mp_make_fraction (MP mp,integer p, integer q);
2686 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2687
2688 @ If FIXPT is not defined, we need these preprocessor values
2689
2690 @d ELGORDO  0x7fffffff
2691 @d TWEXP31  2147483648.0
2692 @d TWEXP28  268435456.0
2693 @d TWEXP16 65536.0
2694 @d TWEXP_16 (1.0/65536.0)
2695 @d TWEXP_28 (1.0/268435456.0)
2696
2697
2698 @c 
2699 fraction mp_make_fraction (MP mp,integer p, integer q) {
2700 #ifdef FIXPT
2701   integer f; /* the fraction bits, with a leading 1 bit */
2702   integer n; /* the integer part of $\vert p/q\vert$ */
2703   integer be_careful; /* disables certain compiler optimizations */
2704   boolean negative = false; /* should the result be negated? */
2705   if ( p<0 ) {
2706     negate(p); negative=true;
2707   }
2708   if ( q<=0 ) { 
2709 #ifdef DEBUG
2710     if ( q==0 ) mp_confusion(mp, '/');
2711 #endif
2712 @:this can't happen /}{\quad \./@>
2713     negate(q); negative = ! negative;
2714   };
2715   n=p / q; p=p % q;
2716   if ( n>=8 ){ 
2717     mp->arith_error=true;
2718     return ( negative ? -el_gordo : el_gordo);
2719   } else { 
2720     n=(n-1)*fraction_one;
2721     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2722     return (negative ? (-(f+n)) : (f+n));
2723   }
2724 #else /* FIXPT */
2725     register double d;
2726         register integer i;
2727 #ifdef DEBUG
2728         if (q==0) mp_confusion(mp,'/'); 
2729 #endif /* DEBUG */
2730         d = TWEXP28 * (double)p /(double)q;
2731         if ((p^q) >= 0) {
2732                 d += 0.5;
2733                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2734                 i = (integer) d;
2735                 if (d==i && ( ((q>0 ? -q : q)&077777)
2736                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2737         } else {
2738                 d -= 0.5;
2739                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2740                 i = (integer) d;
2741                 if (d==i && ( ((q>0 ? q : -q)&077777)
2742                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2743         }
2744         return i;
2745 #endif /* FIXPT */
2746 }
2747
2748 @ The |repeat| loop here preserves the following invariant relations
2749 between |f|, |p|, and~|q|:
2750 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2751 $p_0$ is the original value of~$p$.
2752
2753 Notice that the computation specifies
2754 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2755 Let us hope that optimizing compilers do not miss this point; a
2756 special variable |be_careful| is used to emphasize the necessary
2757 order of computation. Optimizing compilers should keep |be_careful|
2758 in a register, not store it in memory.
2759 @^inner loop@>
2760
2761 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2762 {
2763   f=1;
2764   do {  
2765     be_careful=p-q; p=be_careful+p;
2766     if ( p>=0 ) { 
2767       f=f+f+1;
2768     } else  { 
2769       f+=f; p=p+q;
2770     }
2771   } while (f<fraction_one);
2772   be_careful=p-q;
2773   if ( be_careful+p>=0 ) incr(f);
2774 }
2775
2776 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2777 given integer~|q| by a fraction~|f|. When the operands are positive, it
2778 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2779 of |q| and~|f|.
2780
2781 This routine is even more ``inner loopy'' than |make_fraction|;
2782 the present implementation consumes almost 20\pct! of \MP's computation
2783 time during typical jobs, so a machine-language substitute is advisable.
2784 @^inner loop@> @^system dependencies@>
2785
2786 @<Declarations@>=
2787 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2788
2789 @ @c 
2790 #ifdef FIXPT
2791 integer mp_take_fraction (MP mp,integer q, fraction f) {
2792   integer p; /* the fraction so far */
2793   boolean negative; /* should the result be negated? */
2794   integer n; /* additional multiple of $q$ */
2795   integer be_careful; /* disables certain compiler optimizations */
2796   @<Reduce to the case that |f>=0| and |q>0|@>;
2797   if ( f<fraction_one ) { 
2798     n=0;
2799   } else { 
2800     n=f / fraction_one; f=f % fraction_one;
2801     if ( q<=el_gordo / n ) { 
2802       n=n*q ; 
2803     } else { 
2804       mp->arith_error=true; n=el_gordo;
2805     }
2806   }
2807   f=f+fraction_one;
2808   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2809   be_careful=n-el_gordo;
2810   if ( be_careful+p>0 ){ 
2811     mp->arith_error=true; n=el_gordo-p;
2812   }
2813   if ( negative ) 
2814         return (-(n+p));
2815   else 
2816     return (n+p);
2817 #else /* FIXPT */
2818 integer mp_take_fraction (MP mp,integer p, fraction q) {
2819     register double d;
2820         register integer i;
2821         d = (double)p * (double)q * TWEXP_28;
2822         if ((p^q) >= 0) {
2823                 d += 0.5;
2824                 if (d>=TWEXP31) {
2825                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2826                                 mp->arith_error = true;
2827                         return ELGORDO;
2828                 }
2829                 i = (integer) d;
2830                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2831         } else {
2832                 d -= 0.5;
2833                 if (d<= -TWEXP31) {
2834                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2835                                 mp->arith_error = true;
2836                         return -ELGORDO;
2837                 }
2838                 i = (integer) d;
2839                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2840         }
2841         return i;
2842 #endif /* FIXPT */
2843 }
2844
2845 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2846 if ( f>=0 ) {
2847   negative=false;
2848 } else { 
2849   negate( f); negative=true;
2850 }
2851 if ( q<0 ) { 
2852   negate(q); negative=! negative;
2853 }
2854
2855 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2856 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2857 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2858 @^inner loop@>
2859
2860 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2861 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2862 if ( q<fraction_four ) {
2863   do {  
2864     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2865     f=halfp(f);
2866   } while (f!=1);
2867 } else  {
2868   do {  
2869     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2870     f=halfp(f);
2871   } while (f!=1);
2872 }
2873
2874
2875 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2876 analogous to |take_fraction| but with a different scaling.
2877 Given positive operands, |take_scaled|
2878 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2879
2880 Once again it is a good idea to use a machine-language replacement if
2881 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2882 when the Computer Modern fonts are being generated.
2883 @^inner loop@>
2884
2885 @c 
2886 #ifdef FIXPT
2887 integer mp_take_scaled (MP mp,integer q, scaled f) {
2888   integer p; /* the fraction so far */
2889   boolean negative; /* should the result be negated? */
2890   integer n; /* additional multiple of $q$ */
2891   integer be_careful; /* disables certain compiler optimizations */
2892   @<Reduce to the case that |f>=0| and |q>0|@>;
2893   if ( f<unity ) { 
2894     n=0;
2895   } else  { 
2896     n=f / unity; f=f % unity;
2897     if ( q<=el_gordo / n ) {
2898       n=n*q;
2899     } else  { 
2900       mp->arith_error=true; n=el_gordo;
2901     }
2902   }
2903   f=f+unity;
2904   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2905   be_careful=n-el_gordo;
2906   if ( be_careful+p>0 ) { 
2907     mp->arith_error=true; n=el_gordo-p;
2908   }
2909   return ( negative ?(-(n+p)) :(n+p));
2910 #else /* FIXPT */
2911 integer mp_take_scaled (MP mp,integer p, scaled q) {
2912     register double d;
2913         register integer i;
2914         d = (double)p * (double)q * TWEXP_16;
2915         if ((p^q) >= 0) {
2916                 d += 0.5;
2917                 if (d>=TWEXP31) {
2918                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2919                                 mp->arith_error = true;
2920                         return ELGORDO;
2921                 }
2922                 i = (integer) d;
2923                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2924         } else {
2925                 d -= 0.5;
2926                 if (d<= -TWEXP31) {
2927                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2928                                 mp->arith_error = true;
2929                         return -ELGORDO;
2930                 }
2931                 i = (integer) d;
2932                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2933         }
2934         return i;
2935 #endif /* FIXPT */
2936 }
2937
2938 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2939 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2940 @^inner loop@>
2941 if ( q<fraction_four ) {
2942   do {  
2943     p = (odd(f) ? halfp(p+q) : halfp(p));
2944     f=halfp(f);
2945   } while (f!=1);
2946 } else {
2947   do {  
2948     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2949     f=halfp(f);
2950   } while (f!=1);
2951 }
2952
2953 @ For completeness, there's also |make_scaled|, which computes a
2954 quotient as a |scaled| number instead of as a |fraction|.
2955 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2956 operands are positive. \ (This procedure is not used especially often,
2957 so it is not part of \MP's inner loop.)
2958
2959 @<Internal library ...@>=
2960 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2961
2962 @ @c 
2963 scaled mp_make_scaled (MP mp,integer p, integer q) {
2964 #ifdef FIXPT 
2965   integer f; /* the fraction bits, with a leading 1 bit */
2966   integer n; /* the integer part of $\vert p/q\vert$ */
2967   boolean negative; /* should the result be negated? */
2968   integer be_careful; /* disables certain compiler optimizations */
2969   if ( p>=0 ) negative=false;
2970   else  { negate(p); negative=true; };
2971   if ( q<=0 ) { 
2972 #ifdef DEBUG 
2973     if ( q==0 ) mp_confusion(mp, "/");
2974 @:this can't happen /}{\quad \./@>
2975 #endif
2976     negate(q); negative=! negative;
2977   }
2978   n=p / q; p=p % q;
2979   if ( n>=0100000 ) { 
2980     mp->arith_error=true;
2981     return (negative ? (-el_gordo) : el_gordo);
2982   } else  { 
2983     n=(n-1)*unity;
2984     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2985     return ( negative ? (-(f+n)) :(f+n));
2986   }
2987 #else /* FIXPT */
2988     register double d;
2989         register integer i;
2990 #ifdef DEBUG
2991         if (q==0) mp_confusion(mp,"/"); 
2992 #endif /* DEBUG */
2993         d = TWEXP16 * (double)p /(double)q;
2994         if ((p^q) >= 0) {
2995                 d += 0.5;
2996                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2997                 i = (integer) d;
2998                 if (d==i && ( ((q>0 ? -q : q)&077777)
2999                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3000         } else {
3001                 d -= 0.5;
3002                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3003                 i = (integer) d;
3004                 if (d==i && ( ((q>0 ? q : -q)&077777)
3005                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3006         }
3007         return i;
3008 #endif /* FIXPT */
3009 }
3010
3011 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3012 f=1;
3013 do {  
3014   be_careful=p-q; p=be_careful+p;
3015   if ( p>=0 ) f=f+f+1;
3016   else  { f+=f; p=p+q; };
3017 } while (f<unity);
3018 be_careful=p-q;
3019 if ( be_careful+p>=0 ) incr(f)
3020
3021 @ Here is a typical example of how the routines above can be used.
3022 It computes the function
3023 $${1\over3\tau}f(\theta,\phi)=
3024 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3025  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3026 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3027 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3028 fudge factor for placing the first control point of a curve that starts
3029 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3030 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3031
3032 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3033 (It's a sum of eight terms whose absolute values can be bounded using
3034 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3035 is positive; and since the tension $\tau$ is constrained to be at least
3036 $3\over4$, the numerator is less than $16\over3$. The denominator is
3037 nonnegative and at most~6.  Hence the fixed-point calculations below
3038 are guaranteed to stay within the bounds of a 32-bit computer word.
3039
3040 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3041 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3042 $\sin\phi$, and $\cos\phi$, respectively.
3043
3044 @c 
3045 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3046                       fraction cf, scaled t) {
3047   integer acc,num,denom; /* registers for intermediate calculations */
3048   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3049   acc=mp_take_fraction(mp, acc,ct-cf);
3050   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3051                    /* $2^{28}\sqrt2\approx379625062.497$ */
3052   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3053                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3054                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3055   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3056   /* |make_scaled(fraction,scaled)=fraction| */
3057   if ( num / 4>=denom ) 
3058     return fraction_four;
3059   else 
3060     return mp_make_fraction(mp, num, denom);
3061 }
3062
3063 @ The following somewhat different subroutine tests rigorously if $ab$ is
3064 greater than, equal to, or less than~$cd$,
3065 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3066 The result is $+1$, 0, or~$-1$ in the three respective cases.
3067
3068 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3069
3070 @c 
3071 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3072   integer q,r; /* temporary registers */
3073   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3074   while (1) { 
3075     q = a / d; r = c / b;
3076     if ( q!=r )
3077       return ( q>r ? 1 : -1);
3078     q = a % d; r = c % b;
3079     if ( r==0 )
3080       return (q ? 1 : 0);
3081     if ( q==0 ) return -1;
3082     a=b; b=q; c=d; d=r;
3083   } /* now |a>d>0| and |c>b>0| */
3084 }
3085
3086 @ @<Reduce to the case that |a...@>=
3087 if ( a<0 ) { negate(a); negate(b);  };
3088 if ( c<0 ) { negate(c); negate(d);  };
3089 if ( d<=0 ) { 
3090   if ( b>=0 ) {
3091     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3092     else return 1;
3093   }
3094   if ( d==0 )
3095     return ( a==0 ? 0 : -1);
3096   q=a; a=c; c=q; q=-b; b=-d; d=q;
3097 } else if ( b<=0 ) { 
3098   if ( b<0 ) if ( a>0 ) return -1;
3099   return (c==0 ? 0 : -1);
3100 }
3101
3102 @ We conclude this set of elementary routines with some simple rounding
3103 and truncation operations.
3104
3105 @<Internal library declarations@>=
3106 #define mp_floor_scaled(M,i) ((i)&(-65536))
3107 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3108 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3109
3110
3111 @* \[8] Algebraic and transcendental functions.
3112 \MP\ computes all of the necessary special functions from scratch, without
3113 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3114
3115 @ To get the square root of a |scaled| number |x|, we want to calculate
3116 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3117 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3118 determines $s$ by an iterative method that maintains the invariant
3119 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3120 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3121 might, however, be zero at the start of the first iteration.
3122
3123 @<Declarations@>=
3124 scaled mp_square_rt (MP mp,scaled x) ;
3125
3126 @ @c 
3127 scaled mp_square_rt (MP mp,scaled x) {
3128   small_number k; /* iteration control counter */
3129   integer y,q; /* registers for intermediate calculations */
3130   if ( x<=0 ) { 
3131     @<Handle square root of zero or negative argument@>;
3132   } else { 
3133     k=23; q=2;
3134     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3135       decr(k); x=x+x+x+x;
3136     }
3137     if ( x<fraction_four ) y=0;
3138     else  { x=x-fraction_four; y=1; };
3139     do {  
3140       @<Decrease |k| by 1, maintaining the invariant
3141       relations between |x|, |y|, and~|q|@>;
3142     } while (k!=0);
3143     return (halfp(q));
3144   }
3145 }
3146
3147 @ @<Handle square root of zero...@>=
3148
3149   if ( x<0 ) { 
3150     print_err("Square root of ");
3151 @.Square root...replaced by 0@>
3152     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3153     help2("Since I don't take square roots of negative numbers,")
3154          ("I'm zeroing this one. Proceed, with fingers crossed.");
3155     mp_error(mp);
3156   };
3157   return 0;
3158 }
3159
3160 @ @<Decrease |k| by 1, maintaining...@>=
3161 x+=x; y+=y;
3162 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3163   x=x-fraction_four; incr(y);
3164 };
3165 x+=x; y=y+y-q; q+=q;
3166 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3167 if ( y>q ){ y=y-q; q=q+2; }
3168 else if ( y<=0 )  { q=q-2; y=y+q;  };
3169 decr(k)
3170
3171 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3172 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3173 @^Moler, Cleve Barry@>
3174 @^Morrison, Donald Ross@>
3175 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3176 in such a way that their Pythagorean sum remains invariant, while the
3177 smaller argument decreases.
3178
3179 @<Internal library ...@>=
3180 integer mp_pyth_add (MP mp,integer a, integer b);
3181
3182
3183 @ @c 
3184 integer mp_pyth_add (MP mp,integer a, integer b) {
3185   fraction r; /* register used to transform |a| and |b| */
3186   boolean big; /* is the result dangerously near $2^{31}$? */
3187   a=abs(a); b=abs(b);
3188   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3189   if ( b>0 ) {
3190     if ( a<fraction_two ) {
3191       big=false;
3192     } else { 
3193       a=a / 4; b=b / 4; big=true;
3194     }; /* we reduced the precision to avoid arithmetic overflow */
3195     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3196     if ( big ) {
3197       if ( a<fraction_two ) {
3198         a=a+a+a+a;
3199       } else  { 
3200         mp->arith_error=true; a=el_gordo;
3201       };
3202     }
3203   }
3204   return a;
3205 }
3206
3207 @ The key idea here is to reflect the vector $(a,b)$ about the
3208 line through $(a,b/2)$.
3209
3210 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3211 while (1) {  
3212   r=mp_make_fraction(mp, b,a);
3213   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3214   if ( r==0 ) break;
3215   r=mp_make_fraction(mp, r,fraction_four+r);
3216   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3217 }
3218
3219
3220 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3221 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3222
3223 @c 
3224 integer mp_pyth_sub (MP mp,integer a, integer b) {
3225   fraction r; /* register used to transform |a| and |b| */
3226   boolean big; /* is the input dangerously near $2^{31}$? */
3227   a=abs(a); b=abs(b);
3228   if ( a<=b ) {
3229     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3230   } else { 
3231     if ( a<fraction_four ) {
3232       big=false;
3233     } else  { 
3234       a=halfp(a); b=halfp(b); big=true;
3235     }
3236     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3237     if ( big ) double(a);
3238   }
3239   return a;
3240 }
3241
3242 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3243 while (1) { 
3244   r=mp_make_fraction(mp, b,a);
3245   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3246   if ( r==0 ) break;
3247   r=mp_make_fraction(mp, r,fraction_four-r);
3248   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3249 }
3250
3251 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3252
3253   if ( a<b ){ 
3254     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3255     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3256     mp_print(mp, " has been replaced by 0");
3257 @.Pythagorean...@>
3258     help2("Since I don't take square roots of negative numbers,")
3259          ("I'm zeroing this one. Proceed, with fingers crossed.");
3260     mp_error(mp);
3261   }
3262   a=0;
3263 }
3264
3265 @ The subroutines for logarithm and exponential involve two tables.
3266 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3267 a bit more calculation, which the author claims to have done correctly:
3268 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3269 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3270 nearest integer.
3271
3272 @d two_to_the(A) (1<<(A))
3273
3274 @<Constants ...@>=
3275 static const integer spec_log[29] = { 0, /* special logarithms */
3276 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3277 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3278 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3279
3280 @ @<Local variables for initialization@>=
3281 integer k; /* all-purpose loop index */
3282
3283
3284 @ Here is the routine that calculates $2^8$ times the natural logarithm
3285 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3286 when |x| is a given positive integer.
3287
3288 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3289 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3290 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3291 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3292 during the calculation, and sixteen auxiliary bits to extend |y| are
3293 kept in~|z| during the initial argument reduction. (We add
3294 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3295 not become negative; also, the actual amount subtracted from~|y| is~96,
3296 not~100, because we want to add~4 for rounding before the final division by~8.)
3297
3298 @c 
3299 scaled mp_m_log (MP mp,scaled x) {
3300   integer y,z; /* auxiliary registers */
3301   integer k; /* iteration counter */
3302   if ( x<=0 ) {
3303      @<Handle non-positive logarithm@>;
3304   } else  { 
3305     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3306     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3307     while ( x<fraction_four ) {
3308        double(x); y-=93032639; z-=48782;
3309     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3310     y=y+(z / unity); k=2;
3311     while ( x>fraction_four+4 ) {
3312       @<Increase |k| until |x| can be multiplied by a
3313         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3314     }
3315     return (y / 8);
3316   }
3317 }
3318
3319 @ @<Increase |k| until |x| can...@>=
3320
3321   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3322   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3323   y+=spec_log[k]; x-=z;
3324 }
3325
3326 @ @<Handle non-positive logarithm@>=
3327
3328   print_err("Logarithm of ");
3329 @.Logarithm...replaced by 0@>
3330   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3331   help2("Since I don't take logs of non-positive numbers,")
3332        ("I'm zeroing this one. Proceed, with fingers crossed.");
3333   mp_error(mp); 
3334   return 0;
3335 }
3336
3337 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3338 when |x| is |scaled|. The result is an integer approximation to
3339 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3340
3341 @c 
3342 scaled mp_m_exp (MP mp,scaled x) {
3343   small_number k; /* loop control index */
3344   integer y,z; /* auxiliary registers */
3345   if ( x>174436200 ) {
3346     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3347     mp->arith_error=true; 
3348     return el_gordo;
3349   } else if ( x<-197694359 ) {
3350         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3351     return 0;
3352   } else { 
3353     if ( x<=0 ) { 
3354        z=-8*x; y=04000000; /* $y=2^{20}$ */
3355     } else { 
3356       if ( x<=127919879 ) { 
3357         z=1023359037-8*x;
3358         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3359       } else {
3360        z=8*(174436200-x); /* |z| is always nonnegative */
3361       }
3362       y=el_gordo;
3363     };
3364     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3365     if ( x<=127919879 ) 
3366        return ((y+8) / 16);
3367      else 
3368        return y;
3369   }
3370 }
3371
3372 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3373 to multiplying |y| by $1-2^{-k}$.
3374
3375 A subtle point (which had to be checked) was that if $x=127919879$, the
3376 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3377 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3378 and by~16 when |k=27|.
3379
3380 @<Multiply |y| by...@>=
3381 k=1;
3382 while ( z>0 ) { 
3383   while ( z>=spec_log[k] ) { 
3384     z-=spec_log[k];
3385     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3386   }
3387   incr(k);
3388 }
3389
3390 @ The trigonometric subroutines use an auxiliary table such that
3391 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3392 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3393
3394 @<Constants ...@>=
3395 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3396 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3397 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3398
3399 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3400 returns the |angle| whose tangent points in the direction $(x,y)$.
3401 This subroutine first determines the correct octant, then solves the
3402 problem for |0<=y<=x|, then converts the result appropriately to
3403 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3404 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3405 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3406
3407 The octants are represented in a ``Gray code,'' since that turns out
3408 to be computationally simplest.
3409
3410 @d negate_x 1
3411 @d negate_y 2
3412 @d switch_x_and_y 4
3413 @d first_octant 1
3414 @d second_octant (first_octant+switch_x_and_y)
3415 @d third_octant (first_octant+switch_x_and_y+negate_x)
3416 @d fourth_octant (first_octant+negate_x)
3417 @d fifth_octant (first_octant+negate_x+negate_y)
3418 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3419 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3420 @d eighth_octant (first_octant+negate_y)
3421
3422 @c 
3423 angle mp_n_arg (MP mp,integer x, integer y) {
3424   angle z; /* auxiliary register */
3425   integer t; /* temporary storage */
3426   small_number k; /* loop counter */
3427   int octant; /* octant code */
3428   if ( x>=0 ) {
3429     octant=first_octant;
3430   } else { 
3431     negate(x); octant=first_octant+negate_x;
3432   }
3433   if ( y<0 ) { 
3434     negate(y); octant=octant+negate_y;
3435   }
3436   if ( x<y ) { 
3437     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3438   }
3439   if ( x==0 ) { 
3440     @<Handle undefined arg@>; 
3441   } else { 
3442     @<Set variable |z| to the arg of $(x,y)$@>;
3443     @<Return an appropriate answer based on |z| and |octant|@>;
3444   }
3445 }
3446
3447 @ @<Handle undefined arg@>=
3448
3449   print_err("angle(0,0) is taken as zero");
3450 @.angle(0,0)...zero@>
3451   help2("The `angle' between two identical points is undefined.")
3452        ("I'm zeroing this one. Proceed, with fingers crossed.");
3453   mp_error(mp); 
3454   return 0;
3455 }
3456
3457 @ @<Return an appropriate answer...@>=
3458 switch (octant) {
3459 case first_octant: return z;
3460 case second_octant: return (ninety_deg-z);
3461 case third_octant: return (ninety_deg+z);
3462 case fourth_octant: return (one_eighty_deg-z);
3463 case fifth_octant: return (z-one_eighty_deg);
3464 case sixth_octant: return (-z-ninety_deg);
3465 case seventh_octant: return (z-ninety_deg);
3466 case eighth_octant: return (-z);
3467 }; /* there are no other cases */
3468 return 0
3469
3470 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3471 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3472 will be made.
3473
3474 @<Set variable |z| to the arg...@>=
3475 while ( x>=fraction_two ) { 
3476   x=halfp(x); y=halfp(y);
3477 }
3478 z=0;
3479 if ( y>0 ) { 
3480  while ( x<fraction_one ) { 
3481     x+=x; y+=y; 
3482  };
3483  @<Increase |z| to the arg of $(x,y)$@>;
3484 }
3485
3486 @ During the calculations of this section, variables |x| and~|y|
3487 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3488 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3489 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3490 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3491 coordinates whose angle has decreased by~$\phi$; in the special case
3492 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3493 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3494 @^Meggitt, John E.@>
3495 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3496
3497 The initial value of |x| will be multiplied by at most
3498 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3499 there is no chance of integer overflow.
3500
3501 @<Increase |z|...@>=
3502 k=0;
3503 do {  
3504   y+=y; incr(k);
3505   if ( y>x ){ 
3506     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3507   };
3508 } while (k!=15);
3509 do {  
3510   y+=y; incr(k);
3511   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3512 } while (k!=26)
3513
3514 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3515 and cosine of that angle. The results of this routine are
3516 stored in global integer variables |n_sin| and |n_cos|.
3517
3518 @<Glob...@>=
3519 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3520
3521 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3522 the purpose of |n_sin_cos(z)| is to set
3523 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3524 for some rather large number~|r|. The maximum of |x| and |y|
3525 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3526 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3527
3528 @c 
3529 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3530                                        and cosine */ 
3531   small_number k; /* loop control variable */
3532   int q; /* specifies the quadrant */
3533   fraction r; /* magnitude of |(x,y)| */
3534   integer x,y,t; /* temporary registers */
3535   while ( z<0 ) z=z+three_sixty_deg;
3536   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3537   q=z / forty_five_deg; z=z % forty_five_deg;
3538   x=fraction_one; y=x;
3539   if ( ! odd(q) ) z=forty_five_deg-z;
3540   @<Subtract angle |z| from |(x,y)|@>;
3541   @<Convert |(x,y)| to the octant determined by~|q|@>;
3542   r=mp_pyth_add(mp, x,y); 
3543   mp->n_cos=mp_make_fraction(mp, x,r); 
3544   mp->n_sin=mp_make_fraction(mp, y,r);
3545 }
3546
3547 @ In this case the octants are numbered sequentially.
3548
3549 @<Convert |(x,...@>=
3550 switch (q) {
3551 case 0: break;
3552 case 1: t=x; x=y; y=t; break;
3553 case 2: t=x; x=-y; y=t; break;
3554 case 3: negate(x); break;
3555 case 4: negate(x); negate(y); break;
3556 case 5: t=x; x=-y; y=-t; break;
3557 case 6: t=x; x=y; y=-t; break;
3558 case 7: negate(y); break;
3559 } /* there are no other cases */
3560
3561 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3562 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3563 that this loop is guaranteed to terminate before the (nonexistent) value
3564 |spec_atan[27]| would be required.
3565
3566 @<Subtract angle |z|...@>=
3567 k=1;
3568 while ( z>0 ){ 
3569   if ( z>=spec_atan[k] ) { 
3570     z=z-spec_atan[k]; t=x;
3571     x=t+y / two_to_the(k);
3572     y=y-t / two_to_the(k);
3573   }
3574   incr(k);
3575 }
3576 if ( y<0 ) y=0 /* this precaution may never be needed */
3577
3578 @ And now let's complete our collection of numeric utility routines
3579 by considering random number generation.
3580 \MP\ generates pseudo-random numbers with the additive scheme recommended
3581 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3582 results are random fractions between 0 and |fraction_one-1|, inclusive.
3583
3584 There's an auxiliary array |randoms| that contains 55 pseudo-random
3585 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3586 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3587 The global variable |j_random| tells which element has most recently
3588 been consumed.
3589 The global variable |random_seed| was introduced in version 0.9,
3590 for the sole reason of stressing the fact that the initial value of the
3591 random seed is system-dependant. The initialization code below will initialize
3592 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3593 is not good enough on modern fast machines that are capable of running
3594 multiple MetaPost processes within the same second.
3595 @^system dependencies@>
3596
3597 @<Glob...@>=
3598 fraction randoms[55]; /* the last 55 random values generated */
3599 int j_random; /* the number of unused |randoms| */
3600
3601 @ @<Option variables@>=
3602 int random_seed; /* the default random seed */
3603
3604 @ @<Allocate or initialize ...@>=
3605 mp->random_seed = (scaled)opt->random_seed;
3606
3607 @ To consume a random fraction, the program below will say `|next_random|'
3608 and then it will fetch |randoms[j_random]|.
3609
3610 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3611   else decr(mp->j_random); }
3612
3613 @c 
3614 void mp_new_randoms (MP mp) {
3615   int k; /* index into |randoms| */
3616   fraction x; /* accumulator */
3617   for (k=0;k<=23;k++) { 
3618    x=mp->randoms[k]-mp->randoms[k+31];
3619     if ( x<0 ) x=x+fraction_one;
3620     mp->randoms[k]=x;
3621   }
3622   for (k=24;k<= 54;k++){ 
3623     x=mp->randoms[k]-mp->randoms[k-24];
3624     if ( x<0 ) x=x+fraction_one;
3625     mp->randoms[k]=x;
3626   }
3627   mp->j_random=54;
3628 }
3629
3630 @ @<Declarations@>=
3631 void mp_init_randoms (MP mp,scaled seed);
3632
3633 @ To initialize the |randoms| table, we call the following routine.
3634
3635 @c 
3636 void mp_init_randoms (MP mp,scaled seed) {
3637   fraction j,jj,k; /* more or less random integers */
3638   int i; /* index into |randoms| */
3639   j=abs(seed);
3640   while ( j>=fraction_one ) j=halfp(j);
3641   k=1;
3642   for (i=0;i<=54;i++ ){ 
3643     jj=k; k=j-k; j=jj;
3644     if ( k<0 ) k=k+fraction_one;
3645     mp->randoms[(i*21)% 55]=j;
3646   }
3647   mp_new_randoms(mp); 
3648   mp_new_randoms(mp); 
3649   mp_new_randoms(mp); /* ``warm up'' the array */
3650 }
3651
3652 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3653 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3654
3655 Note that the call of |take_fraction| will produce the values 0 and~|x|
3656 with about half the probability that it will produce any other particular
3657 values between 0 and~|x|, because it rounds its answers.
3658
3659 @c 
3660 scaled mp_unif_rand (MP mp,scaled x) {
3661   scaled y; /* trial value */
3662   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3663   if ( y==abs(x) ) return 0;
3664   else if ( x>0 ) return y;
3665   else return (-y);
3666 }
3667
3668 @ Finally, a normal deviate with mean zero and unit standard deviation
3669 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3670 {\sl The Art of Computer Programming\/}).
3671
3672 @c 
3673 scaled mp_norm_rand (MP mp) {
3674   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3675   do { 
3676     do {  
3677       next_random;
3678       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3679       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3680       next_random; u=mp->randoms[mp->j_random];
3681     } while (abs(x)>=u);
3682     x=mp_make_fraction(mp, x,u);
3683     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3684   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3685   return x;
3686 }
3687
3688 @* \[9] Packed data.
3689 In order to make efficient use of storage space, \MP\ bases its major data
3690 structures on a |memory_word|, which contains either a (signed) integer,
3691 possibly scaled, or a small number of fields that are one half or one
3692 quarter of the size used for storing integers.
3693
3694 If |x| is a variable of type |memory_word|, it contains up to four
3695 fields that can be referred to as follows:
3696 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3697 |x|&.|int|&(an |integer|)\cr
3698 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3699 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3700 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3701   field)\cr
3702 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3703   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3704 This is somewhat cumbersome to write, and not very readable either, but
3705 macros will be used to make the notation shorter and more transparent.
3706 The code below gives a formal definition of |memory_word| and
3707 its subsidiary types, using packed variant records. \MP\ makes no
3708 assumptions about the relative positions of the fields within a word.
3709
3710 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3711 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3712
3713 @ Here are the inequalities that the quarterword and halfword values
3714 must satisfy (or rather, the inequalities that they mustn't satisfy):
3715
3716 @<Check the ``constant''...@>=
3717 if (mp->ini_version) {
3718   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3719 } else {
3720   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3721 }
3722 if ( max_quarterword<255 ) mp->bad=9;
3723 if ( max_halfword<65535 ) mp->bad=10;
3724 if ( max_quarterword>max_halfword ) mp->bad=11;
3725 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3726 if ( mp->max_strings>max_halfword ) mp->bad=13;
3727
3728 @ The macros |qi| and |qo| are used for input to and output 
3729 from quarterwords. These are legacy macros.
3730 @^system dependencies@>
3731
3732 @d qo(A) (A) /* to read eight bits from a quarterword */
3733 @d qi(A) (A) /* to store eight bits in a quarterword */
3734
3735 @ The reader should study the following definitions closely:
3736 @^system dependencies@>
3737
3738 @d sc cint /* |scaled| data is equivalent to |integer| */
3739
3740 @<Types...@>=
3741 typedef short quarterword; /* 1/4 of a word */
3742 typedef int halfword; /* 1/2 of a word */
3743 typedef union {
3744   struct {
3745     halfword RH, LH;
3746   } v;
3747   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3748     halfword junk;
3749     quarterword B0, B1;
3750   } u;
3751 } two_halves;
3752 typedef struct {
3753   struct {
3754     quarterword B2, B3, B0, B1;
3755   } u;
3756 } four_quarters;
3757 typedef union {
3758   two_halves hh;
3759   integer cint;
3760   four_quarters qqqq;
3761 } memory_word;
3762 #define b0 u.B0
3763 #define b1 u.B1
3764 #define b2 u.B2
3765 #define b3 u.B3
3766 #define rh v.RH
3767 #define lh v.LH
3768
3769 @ When debugging, we may want to print a |memory_word| without knowing
3770 what type it is; so we print it in all modes.
3771 @^debugging@>
3772
3773 @c 
3774 void mp_print_word (MP mp,memory_word w) {
3775   /* prints |w| in all ways */
3776   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3777   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3778   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3779   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3780   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3781   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3782   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3783   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3784   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3785   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3786   mp_print_int(mp, w.qqqq.b3);
3787 }
3788
3789
3790 @* \[10] Dynamic memory allocation.
3791
3792 The \MP\ system does nearly all of its own memory allocation, so that it
3793 can readily be transported into environments that do not have automatic
3794 facilities for strings, garbage collection, etc., and so that it can be in
3795 control of what error messages the user receives. The dynamic storage
3796 requirements of \MP\ are handled by providing a large array |mem| in
3797 which consecutive blocks of words are used as nodes by the \MP\ routines.
3798
3799 Pointer variables are indices into this array, or into another array
3800 called |eqtb| that will be explained later. A pointer variable might
3801 also be a special flag that lies outside the bounds of |mem|, so we
3802 allow pointers to assume any |halfword| value. The minimum memory
3803 index represents a null pointer.
3804
3805 @d null 0 /* the null pointer */
3806 @d mp_void (null+1) /* a null pointer different from |null| */
3807
3808
3809 @<Types...@>=
3810 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3811
3812 @ The |mem| array is divided into two regions that are allocated separately,
3813 but the dividing line between these two regions is not fixed; they grow
3814 together until finding their ``natural'' size in a particular job.
3815 Locations less than or equal to |lo_mem_max| are used for storing
3816 variable-length records consisting of two or more words each. This region
3817 is maintained using an algorithm similar to the one described in exercise
3818 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3819 appears in the allocated nodes; the program is responsible for knowing the
3820 relevant size when a node is freed. Locations greater than or equal to
3821 |hi_mem_min| are used for storing one-word records; a conventional
3822 \.{AVAIL} stack is used for allocation in this region.
3823
3824 Locations of |mem| between |0| and |mem_top| may be dumped as part
3825 of preloaded format files, by the \.{INIMP} preprocessor.
3826 @.INIMP@>
3827 Production versions of \MP\ may extend the memory at the top end in order to
3828 provide more space; these locations, between |mem_top| and |mem_max|,
3829 are always used for single-word nodes.
3830
3831 The key pointers that govern |mem| allocation have a prescribed order:
3832 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3833
3834 @<Glob...@>=
3835 memory_word *mem; /* the big dynamic storage area */
3836 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3837 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3838
3839
3840
3841 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3842 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3843 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3844 @d xstrdup(A)  mp_xstrdup(mp,A)
3845 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3846
3847 @<Declare helpers@>=
3848 void mp_xfree (void *x);
3849 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3850 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3851 char *mp_xstrdup(MP mp, const char *s);
3852
3853 @ The |max_size_test| guards against overflow, on the assumption that
3854 |size_t| is at least 31bits wide.
3855
3856 @d max_size_test 0x7FFFFFFF
3857
3858 @c
3859 void mp_xfree (void *x) {
3860   if (x!=NULL) free(x);
3861 }
3862 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3863   void *w ; 
3864   if ((max_size_test/size)<nmem) {
3865     do_fprintf(mp->err_out,"Memory size overflow!\n");
3866     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3867   }
3868   w = realloc (p,(nmem*size));
3869   if (w==NULL) {
3870     do_fprintf(mp->err_out,"Out of memory!\n");
3871     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3872   }
3873   return w;
3874 }
3875 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3876   void *w;
3877   if ((max_size_test/size)<nmem) {
3878     do_fprintf(mp->err_out,"Memory size overflow!\n");
3879     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3880   }
3881   w = malloc (nmem*size);
3882   if (w==NULL) {
3883     do_fprintf(mp->err_out,"Out of memory!\n");
3884     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3885   }
3886   return w;
3887 }
3888 char *mp_xstrdup(MP mp, const char *s) {
3889   char *w; 
3890   if (s==NULL)
3891     return NULL;
3892   w = strdup(s);
3893   if (w==NULL) {
3894     do_fprintf(mp->err_out,"Out of memory!\n");
3895     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3896   }
3897   return w;
3898 }
3899
3900
3901
3902 @<Allocate or initialize ...@>=
3903 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3904 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3905
3906 @ @<Dealloc variables@>=
3907 xfree(mp->mem);
3908
3909 @ Users who wish to study the memory requirements of particular applications can
3910 can use optional special features that keep track of current and
3911 maximum memory usage. When code between the delimiters |stat| $\ldots$
3912 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3913 report these statistics when |mp_tracing_stats| is positive.
3914
3915 @<Glob...@>=
3916 integer var_used; integer dyn_used; /* how much memory is in use */
3917
3918 @ Let's consider the one-word memory region first, since it's the
3919 simplest. The pointer variable |mem_end| holds the highest-numbered location
3920 of |mem| that has ever been used. The free locations of |mem| that
3921 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3922 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3923 and |rh| fields of |mem[p]| when it is of this type. The single-word
3924 free locations form a linked list
3925 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3926 terminated by |null|.
3927
3928 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3929 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3930
3931 @<Glob...@>=
3932 pointer avail; /* head of the list of available one-word nodes */
3933 pointer mem_end; /* the last one-word node used in |mem| */
3934
3935 @ If one-word memory is exhausted, it might mean that the user has forgotten
3936 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3937 later that try to help pinpoint the trouble.
3938
3939 @c 
3940 @<Declare the procedure called |show_token_list|@>;
3941 @<Declare the procedure called |runaway|@>
3942
3943 @ The function |get_avail| returns a pointer to a new one-word node whose
3944 |link| field is null. However, \MP\ will halt if there is no more room left.
3945 @^inner loop@>
3946
3947 @c 
3948 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3949   pointer p; /* the new node being got */
3950   p=mp->avail; /* get top location in the |avail| stack */
3951   if ( p!=null ) {
3952     mp->avail=link(mp->avail); /* and pop it off */
3953   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3954     incr(mp->mem_end); p=mp->mem_end;
3955   } else { 
3956     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3957     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3958       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3959       mp_overflow(mp, "main memory size",mp->mem_max);
3960       /* quit; all one-word nodes are busy */
3961 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3962     }
3963   }
3964   link(p)=null; /* provide an oft-desired initialization of the new node */
3965   incr(mp->dyn_used);/* maintain statistics */
3966   return p;
3967 };
3968
3969 @ Conversely, a one-word node is recycled by calling |free_avail|.
3970
3971 @d free_avail(A)  /* single-word node liberation */
3972   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3973
3974 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3975 overhead at the expense of extra programming. This macro is used in
3976 the places that would otherwise account for the most calls of |get_avail|.
3977 @^inner loop@>
3978
3979 @d fast_get_avail(A) { 
3980   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3981   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3982   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3983   }
3984
3985 @ The available-space list that keeps track of the variable-size portion
3986 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3987 pointed to by the roving pointer |rover|.
3988
3989 Each empty node has size 2 or more; the first word contains the special
3990 value |max_halfword| in its |link| field and the size in its |info| field;
3991 the second word contains the two pointers for double linking.
3992
3993 Each nonempty node also has size 2 or more. Its first word is of type
3994 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3995 Otherwise there is complete flexibility with respect to the contents
3996 of its other fields and its other words.
3997
3998 (We require |mem_max<max_halfword| because terrible things can happen
3999 when |max_halfword| appears in the |link| field of a nonempty node.)
4000
4001 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4002 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4003 @d node_size   info /* the size field in empty variable-size nodes */
4004 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4005 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4006
4007 @<Glob...@>=
4008 pointer rover; /* points to some node in the list of empties */
4009
4010 @ A call to |get_node| with argument |s| returns a pointer to a new node
4011 of size~|s|, which must be 2~or more. The |link| field of the first word
4012 of this new node is set to null. An overflow stop occurs if no suitable
4013 space exists.
4014
4015 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4016 areas and returns the value |max_halfword|.
4017
4018 @<Internal library declarations@>=
4019 pointer mp_get_node (MP mp,integer s) ;
4020
4021 @ @c 
4022 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4023   pointer p; /* the node currently under inspection */
4024   pointer q;  /* the node physically after node |p| */
4025   integer r; /* the newly allocated node, or a candidate for this honor */
4026   integer t,tt; /* temporary registers */
4027 @^inner loop@>
4028  RESTART: 
4029   p=mp->rover; /* start at some free node in the ring */
4030   do {  
4031     @<Try to allocate within node |p| and its physical successors,
4032      and |goto found| if allocation was possible@>;
4033     if (rlink(p)==null || rlink(p)==p) {
4034       print_err("Free list garbled");
4035       help3("I found an entry in the list of free nodes that links")
4036        ("badly. I will try to ignore the broken link, but something")
4037        ("is seriously amiss. It is wise to warn the maintainers.")
4038           mp_error(mp);
4039       rlink(p)=mp->rover;
4040     }
4041         p=rlink(p); /* move to the next node in the ring */
4042   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4043   if ( s==010000000000 ) { 
4044     return max_halfword;
4045   };
4046   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4047     if ( mp->lo_mem_max+2<=max_halfword ) {
4048       @<Grow more variable-size memory and |goto restart|@>;
4049     }
4050   }
4051   mp_overflow(mp, "main memory size",mp->mem_max);
4052   /* sorry, nothing satisfactory is left */
4053 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4054 FOUND: 
4055   link(r)=null; /* this node is now nonempty */
4056   mp->var_used+=s; /* maintain usage statistics */
4057   return r;
4058 }
4059
4060 @ The lower part of |mem| grows by 1000 words at a time, unless
4061 we are very close to going under. When it grows, we simply link
4062 a new node into the available-space list. This method of controlled
4063 growth helps to keep the |mem| usage consecutive when \MP\ is
4064 implemented on ``virtual memory'' systems.
4065 @^virtual memory@>
4066
4067 @<Grow more variable-size memory and |goto restart|@>=
4068
4069   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4070     t=mp->lo_mem_max+1000;
4071   } else {
4072     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4073     /* |lo_mem_max+2<=t<hi_mem_min| */
4074   }
4075   if ( t>max_halfword ) t=max_halfword;
4076   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4077   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4078   node_size(q)=t-mp->lo_mem_max;
4079   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4080   mp->rover=q; 
4081   goto RESTART;
4082 }
4083
4084 @ @<Try to allocate...@>=
4085 q=p+node_size(p); /* find the physical successor */
4086 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4087   t=rlink(q); tt=llink(q);
4088 @^inner loop@>
4089   if ( q==mp->rover ) mp->rover=t;
4090   llink(t)=tt; rlink(tt)=t;
4091   q=q+node_size(q);
4092 }
4093 r=q-s;
4094 if ( r>p+1 ) {
4095   @<Allocate from the top of node |p| and |goto found|@>;
4096 }
4097 if ( r==p ) { 
4098   if ( rlink(p)!=p ) {
4099     @<Allocate entire node |p| and |goto found|@>;
4100   }
4101 }
4102 node_size(p)=q-p /* reset the size in case it grew */
4103
4104 @ @<Allocate from the top...@>=
4105
4106   node_size(p)=r-p; /* store the remaining size */
4107   mp->rover=p; /* start searching here next time */
4108   goto FOUND;
4109 }
4110
4111 @ Here we delete node |p| from the ring, and let |rover| rove around.
4112
4113 @<Allocate entire...@>=
4114
4115   mp->rover=rlink(p); t=llink(p);
4116   llink(mp->rover)=t; rlink(t)=mp->rover;
4117   goto FOUND;
4118 }
4119
4120 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4121 the operation |free_node(p,s)| will make its words available, by inserting
4122 |p| as a new empty node just before where |rover| now points.
4123
4124 @<Internal library declarations@>=
4125 void mp_free_node (MP mp, pointer p, halfword s) ;
4126
4127 @ @c 
4128 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4129   liberation */
4130   pointer q; /* |llink(rover)| */
4131   node_size(p)=s; link(p)=empty_flag;
4132 @^inner loop@>
4133   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4134   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4135   mp->var_used-=s; /* maintain statistics */
4136 }
4137
4138 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4139 available space list. The list is probably very short at such times, so a
4140 simple insertion sort is used. The smallest available location will be
4141 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4142
4143 @c 
4144 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4145   by location */
4146   pointer p,q,r; /* indices into |mem| */
4147   pointer old_rover; /* initial |rover| setting */
4148   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4149   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4150   while ( p!=old_rover ) {
4151     @<Sort |p| into the list starting at |rover|
4152      and advance |p| to |rlink(p)|@>;
4153   }
4154   p=mp->rover;
4155   while ( rlink(p)!=max_halfword ) { 
4156     llink(rlink(p))=p; p=rlink(p);
4157   };
4158   rlink(p)=mp->rover; llink(mp->rover)=p;
4159 }
4160
4161 @ The following |while| loop is guaranteed to
4162 terminate, since the list that starts at
4163 |rover| ends with |max_halfword| during the sorting procedure.
4164
4165 @<Sort |p|...@>=
4166 if ( p<mp->rover ) { 
4167   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4168 } else  { 
4169   q=mp->rover;
4170   while ( rlink(q)<p ) q=rlink(q);
4171   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4172 }
4173
4174 @* \[11] Memory layout.
4175 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4176 more efficient than dynamic allocation when we can get away with it. For
4177 example, locations |0| to |1| are always used to store a
4178 two-word dummy token whose second word is zero.
4179 The following macro definitions accomplish the static allocation by giving
4180 symbolic names to the fixed positions. Static variable-size nodes appear
4181 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4182 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4183
4184 @d null_dash (2) /* the first two words are reserved for a null value */
4185 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4186 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4187 @d temp_val (zero_val+2) /* two words for a temporary value node */
4188 @d end_attr temp_val /* we use |end_attr+2| only */
4189 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4190 @d test_pen (inf_val+2)
4191   /* nine words for a pen used when testing the turning number */
4192 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4193 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4194   allocated word in the variable-size |mem| */
4195 @#
4196 @d sentinel mp->mem_top /* end of sorted lists */
4197 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4198 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4199 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4200 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4201   the one-word |mem| */
4202
4203 @ The following code gets the dynamic part of |mem| off to a good start,
4204 when \MP\ is initializing itself the slow way.
4205
4206 @<Initialize table entries (done by \.{INIMP} only)@>=
4207 @^data structure assumptions@>
4208 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4209 link(mp->rover)=empty_flag;
4210 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4211 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4212 mp->lo_mem_max=mp->rover+1000; 
4213 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4214 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4215   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4216 }
4217 mp->avail=null; mp->mem_end=mp->mem_top;
4218 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4219 mp->var_used=lo_mem_stat_max+1; 
4220 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4221 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4222
4223 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4224 nodes that starts at a given position, until coming to |sentinel| or a
4225 pointer that is not in the one-word region. Another procedure,
4226 |flush_node_list|, frees an entire linked list of one-word and two-word
4227 nodes, until coming to a |null| pointer.
4228 @^inner loop@>
4229
4230 @c 
4231 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4232   pointer q,r; /* list traversers */
4233   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4234     r=p;
4235     do {  
4236       q=r; r=link(r); 
4237       decr(mp->dyn_used);
4238       if ( r<mp->hi_mem_min ) break;
4239     } while (r!=sentinel);
4240   /* now |q| is the last node on the list */
4241     link(q)=mp->avail; mp->avail=p;
4242   }
4243 }
4244 @#
4245 void mp_flush_node_list (MP mp,pointer p) {
4246   pointer q; /* the node being recycled */
4247   while ( p!=null ){ 
4248     q=p; p=link(p);
4249     if ( q<mp->hi_mem_min ) 
4250       mp_free_node(mp, q,2);
4251     else 
4252       free_avail(q);
4253   }
4254 }
4255
4256 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4257 For example, some pointers might be wrong, or some ``dead'' nodes might not
4258 have been freed when the last reference to them disappeared. Procedures
4259 |check_mem| and |search_mem| are available to help diagnose such
4260 problems. These procedures make use of two arrays called |free| and
4261 |was_free| that are present only if \MP's debugging routines have
4262 been included. (You may want to decrease the size of |mem| while you
4263 @^debugging@>
4264 are debugging.)
4265
4266 Because |boolean|s are typedef-d as ints, it is better to use
4267 unsigned chars here.
4268
4269 @<Glob...@>=
4270 unsigned char *free; /* free cells */
4271 unsigned char *was_free; /* previously free cells */
4272 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4273   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4274 boolean panicking; /* do we want to check memory constantly? */
4275
4276 @ @<Allocate or initialize ...@>=
4277 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4278 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4279
4280 @ @<Dealloc variables@>=
4281 xfree(mp->free);
4282 xfree(mp->was_free);
4283
4284 @ @<Allocate or ...@>=
4285 mp->was_mem_end=0; /* indicate that everything was previously free */
4286 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4287 mp->panicking=false;
4288
4289 @ @<Declare |mp_reallocate| functions@>=
4290 void mp_reallocate_memory(MP mp, int l) ;
4291
4292 @ @c
4293 void mp_reallocate_memory(MP mp, int l) {
4294    XREALLOC(mp->free,     l, unsigned char);
4295    XREALLOC(mp->was_free, l, unsigned char);
4296    if (mp->mem) {
4297          int newarea = l-mp->mem_max;
4298      XREALLOC(mp->mem,      l, memory_word);
4299      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4300    } else {
4301      XREALLOC(mp->mem,      l, memory_word);
4302      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4303    }
4304    mp->mem_max = l;
4305    if (mp->ini_version) 
4306      mp->mem_top = l;
4307 }
4308
4309
4310
4311 @ Procedure |check_mem| makes sure that the available space lists of
4312 |mem| are well formed, and it optionally prints out all locations
4313 that are reserved now but were free the last time this procedure was called.
4314
4315 @c 
4316 void mp_check_mem (MP mp,boolean print_locs ) {
4317   pointer p,q,r; /* current locations of interest in |mem| */
4318   boolean clobbered; /* is something amiss? */
4319   for (p=0;p<=mp->lo_mem_max;p++) {
4320     mp->free[p]=false; /* you can probably do this faster */
4321   }
4322   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4323     mp->free[p]=false; /* ditto */
4324   }
4325   @<Check single-word |avail| list@>;
4326   @<Check variable-size |avail| list@>;
4327   @<Check flags of unavailable nodes@>;
4328   @<Check the list of linear dependencies@>;
4329   if ( print_locs ) {
4330     @<Print newly busy locations@>;
4331   }
4332   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4333   mp->was_mem_end=mp->mem_end; 
4334   mp->was_lo_max=mp->lo_mem_max; 
4335   mp->was_hi_min=mp->hi_mem_min;
4336 }
4337
4338 @ @<Check single-word...@>=
4339 p=mp->avail; q=null; clobbered=false;
4340 while ( p!=null ) { 
4341   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4342   else if ( mp->free[p] ) clobbered=true;
4343   if ( clobbered ) { 
4344     mp_print_nl(mp, "AVAIL list clobbered at ");
4345 @.AVAIL list clobbered...@>
4346     mp_print_int(mp, q); break;
4347   }
4348   mp->free[p]=true; q=p; p=link(q);
4349 }
4350
4351 @ @<Check variable-size...@>=
4352 p=mp->rover; q=null; clobbered=false;
4353 do {  
4354   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4355   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4356   else if (  !(is_empty(p))||(node_size(p)<2)||
4357    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4358   if ( clobbered ) { 
4359     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4360 @.Double-AVAIL list clobbered...@>
4361     mp_print_int(mp, q); break;
4362   }
4363   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4364     if ( mp->free[q] ) { 
4365       mp_print_nl(mp, "Doubly free location at ");
4366 @.Doubly free location...@>
4367       mp_print_int(mp, q); break;
4368     }
4369     mp->free[q]=true;
4370   }
4371   q=p; p=rlink(p);
4372 } while (p!=mp->rover)
4373
4374
4375 @ @<Check flags...@>=
4376 p=0;
4377 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4378   if ( is_empty(p) ) {
4379     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4380 @.Bad flag...@>
4381   }
4382   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4383   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4384 }
4385
4386 @ @<Print newly busy...@>=
4387
4388   @<Do intialization required before printing new busy locations@>;
4389   mp_print_nl(mp, "New busy locs:");
4390 @.New busy locs@>
4391   for (p=0;p<= mp->lo_mem_max;p++ ) {
4392     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4393       @<Indicate that |p| is a new busy location@>;
4394     }
4395   }
4396   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4397     if ( ! mp->free[p] &&
4398         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4399       @<Indicate that |p| is a new busy location@>;
4400     }
4401   }
4402   @<Finish printing new busy locations@>;
4403 }
4404
4405 @ There might be many new busy locations so we are careful to print contiguous
4406 blocks compactly.  During this operation |q| is the last new busy location and
4407 |r| is the start of the block containing |q|.
4408
4409 @<Indicate that |p| is a new busy location@>=
4410
4411   if ( p>q+1 ) { 
4412     if ( q>r ) { 
4413       mp_print(mp, ".."); mp_print_int(mp, q);
4414     }
4415     mp_print_char(mp, ' '); mp_print_int(mp, p);
4416     r=p;
4417   }
4418   q=p;
4419 }
4420
4421 @ @<Do intialization required before printing new busy locations@>=
4422 q=mp->mem_max; r=mp->mem_max
4423
4424 @ @<Finish printing new busy locations@>=
4425 if ( q>r ) { 
4426   mp_print(mp, ".."); mp_print_int(mp, q);
4427 }
4428
4429 @ The |search_mem| procedure attempts to answer the question ``Who points
4430 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4431 that might not be of type |two_halves|. Strictly speaking, this is
4432 undefined, and it can lead to ``false drops'' (words that seem to
4433 point to |p| purely by coincidence). But for debugging purposes, we want
4434 to rule out the places that do {\sl not\/} point to |p|, so a few false
4435 drops are tolerable.
4436
4437 @c
4438 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4439   integer q; /* current position being searched */
4440   for (q=0;q<=mp->lo_mem_max;q++) { 
4441     if ( link(q)==p ){ 
4442       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4443     }
4444     if ( info(q)==p ) { 
4445       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4446     }
4447   }
4448   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4449     if ( link(q)==p ) {
4450       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4451     }
4452     if ( info(q)==p ) {
4453       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4454     }
4455   }
4456   @<Search |eqtb| for equivalents equal to |p|@>;
4457 }
4458
4459 @* \[12] The command codes.
4460 Before we can go much further, we need to define symbolic names for the internal
4461 code numbers that represent the various commands obeyed by \MP. These codes
4462 are somewhat arbitrary, but not completely so. For example,
4463 some codes have been made adjacent so that |case| statements in the
4464 program need not consider cases that are widely spaced, or so that |case|
4465 statements can be replaced by |if| statements. A command can begin an
4466 expression if and only if its code lies between |min_primary_command| and
4467 |max_primary_command|, inclusive. The first token of a statement that doesn't
4468 begin with an expression has a command code between |min_command| and
4469 |max_statement_command|, inclusive. Anything less than |min_command| is
4470 eliminated during macro expansions, and anything no more than |max_pre_command|
4471 is eliminated when expanding \TeX\ material.  Ranges such as
4472 |min_secondary_command..max_secondary_command| are used when parsing
4473 expressions, but the relative ordering within such a range is generally not
4474 critical.
4475
4476 The ordering of the highest-numbered commands
4477 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4478 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4479 for the smallest two commands.  The ordering is also important in the ranges
4480 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4481
4482 At any rate, here is the list, for future reference.
4483
4484 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4485 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4486 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4487 @d max_pre_command mpx_break
4488 @d if_test 4 /* conditional text (\&{if}) */
4489 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4490 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4491 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4492 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4493 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4494 @d relax 10 /* do nothing (\.{\char`\\}) */
4495 @d scan_tokens 11 /* put a string into the input buffer */
4496 @d expand_after 12 /* look ahead one token */
4497 @d defined_macro 13 /* a macro defined by the user */
4498 @d min_command (defined_macro+1)
4499 @d save_command 14 /* save a list of tokens (\&{save}) */
4500 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4501 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4502 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4503 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4504 @d ship_out_command 19 /* output a character (\&{shipout}) */
4505 @d add_to_command 20 /* add to edges (\&{addto}) */
4506 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4507 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4508 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4509 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4510 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4511 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4512 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4513 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4514 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4515 @d special_command 30 /* output special info (\&{special})
4516                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4517 @d write_command 31 /* write text to a file (\&{write}) */
4518 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4519 @d max_statement_command type_name
4520 @d min_primary_command type_name
4521 @d left_delimiter 33 /* the left delimiter of a matching pair */
4522 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4523 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4524 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4525 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4526 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4527 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4528 @d capsule_token 40 /* a value that has been put into a token list */
4529 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4530 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4531 @d min_suffix_token internal_quantity
4532 @d tag_token 43 /* a symbolic token without a primitive meaning */
4533 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4534 @d max_suffix_token numeric_token
4535 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4536 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4537 @d min_tertiary_command plus_or_minus
4538 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4539 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4540 @d max_tertiary_command tertiary_binary
4541 @d left_brace 48 /* the operator `\.{\char`\{}' */
4542 @d min_expression_command left_brace
4543 @d path_join 49 /* the operator `\.{..}' */
4544 @d ampersand 50 /* the operator `\.\&' */
4545 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4546 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4547 @d equals 53 /* the operator `\.=' */
4548 @d max_expression_command equals
4549 @d and_command 54 /* the operator `\&{and}' */
4550 @d min_secondary_command and_command
4551 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4552 @d slash 56 /* the operator `\./' */
4553 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4554 @d max_secondary_command secondary_binary
4555 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4556 @d controls 59 /* specify control points explicitly (\&{controls}) */
4557 @d tension 60 /* specify tension between knots (\&{tension}) */
4558 @d at_least 61 /* bounded tension value (\&{atleast}) */
4559 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4560 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4561 @d right_delimiter 64 /* the right delimiter of a matching pair */
4562 @d left_bracket 65 /* the operator `\.[' */
4563 @d right_bracket 66 /* the operator `\.]' */
4564 @d right_brace 67 /* the operator `\.{\char`\}}' */
4565 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4566 @d thing_to_add 69
4567   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4568 @d of_token 70 /* the operator `\&{of}' */
4569 @d to_token 71 /* the operator `\&{to}' */
4570 @d step_token 72 /* the operator `\&{step}' */
4571 @d until_token 73 /* the operator `\&{until}' */
4572 @d within_token 74 /* the operator `\&{within}' */
4573 @d lig_kern_token 75
4574   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4575 @d assignment 76 /* the operator `\.{:=}' */
4576 @d skip_to 77 /* the operation `\&{skipto}' */
4577 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4578 @d double_colon 79 /* the operator `\.{::}' */
4579 @d colon 80 /* the operator `\.:' */
4580 @#
4581 @d comma 81 /* the operator `\.,', must be |colon+1| */
4582 @d end_of_statement (mp->cur_cmd>comma)
4583 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4584 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4585 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4586 @d max_command_code stop
4587 @d outer_tag (max_command_code+1) /* protection code added to command code */
4588
4589 @<Types...@>=
4590 typedef int command_code;
4591
4592 @ Variables and capsules in \MP\ have a variety of ``types,''
4593 distinguished by the code numbers defined here. These numbers are also
4594 not completely arbitrary.  Things that get expanded must have types
4595 |>mp_independent|; a type remaining after expansion is numeric if and only if
4596 its code number is at least |numeric_type|; objects containing numeric
4597 parts must have types between |transform_type| and |pair_type|;
4598 all other types must be smaller than |transform_type|; and among the types
4599 that are not unknown or vacuous, the smallest two must be |boolean_type|
4600 and |string_type| in that order.
4601  
4602 @d undefined 0 /* no type has been declared */
4603 @d unknown_tag 1 /* this constant is added to certain type codes below */
4604 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4605   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4606
4607 @<Types...@>=
4608 enum mp_variable_type {
4609 mp_vacuous=1, /* no expression was present */
4610 mp_boolean_type, /* \&{boolean} with a known value */
4611 mp_unknown_boolean,
4612 mp_string_type, /* \&{string} with a known value */
4613 mp_unknown_string,
4614 mp_pen_type, /* \&{pen} with a known value */
4615 mp_unknown_pen,
4616 mp_path_type, /* \&{path} with a known value */
4617 mp_unknown_path,
4618 mp_picture_type, /* \&{picture} with a known value */
4619 mp_unknown_picture,
4620 mp_transform_type, /* \&{transform} variable or capsule */
4621 mp_color_type, /* \&{color} variable or capsule */
4622 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4623 mp_pair_type, /* \&{pair} variable or capsule */
4624 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4625 mp_known, /* \&{numeric} with a known value */
4626 mp_dependent, /* a linear combination with |fraction| coefficients */
4627 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4628 mp_independent, /* \&{numeric} with unknown value */
4629 mp_token_list, /* variable name or suffix argument or text argument */
4630 mp_structured, /* variable with subscripts and attributes */
4631 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4632 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4633 } ;
4634
4635 @ @<Declarations@>=
4636 void mp_print_type (MP mp,small_number t) ;
4637
4638 @ @<Basic printing procedures@>=
4639 void mp_print_type (MP mp,small_number t) { 
4640   switch (t) {
4641   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4642   case mp_boolean_type:mp_print(mp, "boolean"); break;
4643   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4644   case mp_string_type:mp_print(mp, "string"); break;
4645   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4646   case mp_pen_type:mp_print(mp, "pen"); break;
4647   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4648   case mp_path_type:mp_print(mp, "path"); break;
4649   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4650   case mp_picture_type:mp_print(mp, "picture"); break;
4651   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4652   case mp_transform_type:mp_print(mp, "transform"); break;
4653   case mp_color_type:mp_print(mp, "color"); break;
4654   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4655   case mp_pair_type:mp_print(mp, "pair"); break;
4656   case mp_known:mp_print(mp, "known numeric"); break;
4657   case mp_dependent:mp_print(mp, "dependent"); break;
4658   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4659   case mp_numeric_type:mp_print(mp, "numeric"); break;
4660   case mp_independent:mp_print(mp, "independent"); break;
4661   case mp_token_list:mp_print(mp, "token list"); break;
4662   case mp_structured:mp_print(mp, "mp_structured"); break;
4663   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4664   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4665   default: mp_print(mp, "undefined"); break;
4666   }
4667 }
4668
4669 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4670 as well as a |type|. The possibilities for |name_type| are defined
4671 here; they will be explained in more detail later.
4672
4673 @<Types...@>=
4674 enum mp_name_type {
4675  mp_root=0, /* |name_type| at the top level of a variable */
4676  mp_saved_root, /* same, when the variable has been saved */
4677  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4678  mp_subscr, /* |name_type| in a subscript node */
4679  mp_attr, /* |name_type| in an attribute node */
4680  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4681  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4682  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4683  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4684  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4685  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4686  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4687  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4688  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4689  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4690  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4691  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4692  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4693  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4694  mp_capsule, /* |name_type| in stashed-away subexpressions */
4695  mp_token  /* |name_type| in a numeric token or string token */
4696 };
4697
4698 @ Primitive operations that produce values have a secondary identification
4699 code in addition to their command code; it's something like genera and species.
4700 For example, `\.*' has the command code |primary_binary|, and its
4701 secondary identification is |times|. The secondary codes start at 30 so that
4702 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4703 are used as operators as well as type identifications.  The relative values
4704 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4705 and |filled_op..bounded_op|.  The restrictions are that
4706 |and_op-false_code=or_op-true_code|, that the ordering of
4707 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4708 and the ordering of |filled_op..bounded_op| must match that of the code
4709 values they test for.
4710
4711 @d true_code 30 /* operation code for \.{true} */
4712 @d false_code 31 /* operation code for \.{false} */
4713 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4714 @d null_pen_code 33 /* operation code for \.{nullpen} */
4715 @d job_name_op 34 /* operation code for \.{jobname} */
4716 @d read_string_op 35 /* operation code for \.{readstring} */
4717 @d pen_circle 36 /* operation code for \.{pencircle} */
4718 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4719 @d read_from_op 38 /* operation code for \.{readfrom} */
4720 @d close_from_op 39 /* operation code for \.{closefrom} */
4721 @d odd_op 40 /* operation code for \.{odd} */
4722 @d known_op 41 /* operation code for \.{known} */
4723 @d unknown_op 42 /* operation code for \.{unknown} */
4724 @d not_op 43 /* operation code for \.{not} */
4725 @d decimal 44 /* operation code for \.{decimal} */
4726 @d reverse 45 /* operation code for \.{reverse} */
4727 @d make_path_op 46 /* operation code for \.{makepath} */
4728 @d make_pen_op 47 /* operation code for \.{makepen} */
4729 @d oct_op 48 /* operation code for \.{oct} */
4730 @d hex_op 49 /* operation code for \.{hex} */
4731 @d ASCII_op 50 /* operation code for \.{ASCII} */
4732 @d char_op 51 /* operation code for \.{char} */
4733 @d length_op 52 /* operation code for \.{length} */
4734 @d turning_op 53 /* operation code for \.{turningnumber} */
4735 @d color_model_part 54 /* operation code for \.{colormodel} */
4736 @d x_part 55 /* operation code for \.{xpart} */
4737 @d y_part 56 /* operation code for \.{ypart} */
4738 @d xx_part 57 /* operation code for \.{xxpart} */
4739 @d xy_part 58 /* operation code for \.{xypart} */
4740 @d yx_part 59 /* operation code for \.{yxpart} */
4741 @d yy_part 60 /* operation code for \.{yypart} */
4742 @d red_part 61 /* operation code for \.{redpart} */
4743 @d green_part 62 /* operation code for \.{greenpart} */
4744 @d blue_part 63 /* operation code for \.{bluepart} */
4745 @d cyan_part 64 /* operation code for \.{cyanpart} */
4746 @d magenta_part 65 /* operation code for \.{magentapart} */
4747 @d yellow_part 66 /* operation code for \.{yellowpart} */
4748 @d black_part 67 /* operation code for \.{blackpart} */
4749 @d grey_part 68 /* operation code for \.{greypart} */
4750 @d font_part 69 /* operation code for \.{fontpart} */
4751 @d text_part 70 /* operation code for \.{textpart} */
4752 @d path_part 71 /* operation code for \.{pathpart} */
4753 @d pen_part 72 /* operation code for \.{penpart} */
4754 @d dash_part 73 /* operation code for \.{dashpart} */
4755 @d sqrt_op 74 /* operation code for \.{sqrt} */
4756 @d m_exp_op 75 /* operation code for \.{mexp} */
4757 @d m_log_op 76 /* operation code for \.{mlog} */
4758 @d sin_d_op 77 /* operation code for \.{sind} */
4759 @d cos_d_op 78 /* operation code for \.{cosd} */
4760 @d floor_op 79 /* operation code for \.{floor} */
4761 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4762 @d char_exists_op 81 /* operation code for \.{charexists} */
4763 @d font_size 82 /* operation code for \.{fontsize} */
4764 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4765 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4766 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4767 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4768 @d arc_length 87 /* operation code for \.{arclength} */
4769 @d angle_op 88 /* operation code for \.{angle} */
4770 @d cycle_op 89 /* operation code for \.{cycle} */
4771 @d filled_op 90 /* operation code for \.{filled} */
4772 @d stroked_op 91 /* operation code for \.{stroked} */
4773 @d textual_op 92 /* operation code for \.{textual} */
4774 @d clipped_op 93 /* operation code for \.{clipped} */
4775 @d bounded_op 94 /* operation code for \.{bounded} */
4776 @d plus 95 /* operation code for \.+ */
4777 @d minus 96 /* operation code for \.- */
4778 @d times 97 /* operation code for \.* */
4779 @d over 98 /* operation code for \./ */
4780 @d pythag_add 99 /* operation code for \.{++} */
4781 @d pythag_sub 100 /* operation code for \.{+-+} */
4782 @d or_op 101 /* operation code for \.{or} */
4783 @d and_op 102 /* operation code for \.{and} */
4784 @d less_than 103 /* operation code for \.< */
4785 @d less_or_equal 104 /* operation code for \.{<=} */
4786 @d greater_than 105 /* operation code for \.> */
4787 @d greater_or_equal 106 /* operation code for \.{>=} */
4788 @d equal_to 107 /* operation code for \.= */
4789 @d unequal_to 108 /* operation code for \.{<>} */
4790 @d concatenate 109 /* operation code for \.\& */
4791 @d rotated_by 110 /* operation code for \.{rotated} */
4792 @d slanted_by 111 /* operation code for \.{slanted} */
4793 @d scaled_by 112 /* operation code for \.{scaled} */
4794 @d shifted_by 113 /* operation code for \.{shifted} */
4795 @d transformed_by 114 /* operation code for \.{transformed} */
4796 @d x_scaled 115 /* operation code for \.{xscaled} */
4797 @d y_scaled 116 /* operation code for \.{yscaled} */
4798 @d z_scaled 117 /* operation code for \.{zscaled} */
4799 @d in_font 118 /* operation code for \.{infont} */
4800 @d intersect 119 /* operation code for \.{intersectiontimes} */
4801 @d double_dot 120 /* operation code for improper \.{..} */
4802 @d substring_of 121 /* operation code for \.{substring} */
4803 @d min_of substring_of
4804 @d subpath_of 122 /* operation code for \.{subpath} */
4805 @d direction_time_of 123 /* operation code for \.{directiontime} */
4806 @d point_of 124 /* operation code for \.{point} */
4807 @d precontrol_of 125 /* operation code for \.{precontrol} */
4808 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4809 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4810 @d arc_time_of 128 /* operation code for \.{arctime} */
4811 @d mp_version 129 /* operation code for \.{mpversion} */
4812 @d envelope_of 130 /* operation code for \.{envelope} */
4813
4814 @c void mp_print_op (MP mp,quarterword c) { 
4815   if (c<=mp_numeric_type ) {
4816     mp_print_type(mp, c);
4817   } else {
4818     switch (c) {
4819     case true_code:mp_print(mp, "true"); break;
4820     case false_code:mp_print(mp, "false"); break;
4821     case null_picture_code:mp_print(mp, "nullpicture"); break;
4822     case null_pen_code:mp_print(mp, "nullpen"); break;
4823     case job_name_op:mp_print(mp, "jobname"); break;
4824     case read_string_op:mp_print(mp, "readstring"); break;
4825     case pen_circle:mp_print(mp, "pencircle"); break;
4826     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4827     case read_from_op:mp_print(mp, "readfrom"); break;
4828     case close_from_op:mp_print(mp, "closefrom"); break;
4829     case odd_op:mp_print(mp, "odd"); break;
4830     case known_op:mp_print(mp, "known"); break;
4831     case unknown_op:mp_print(mp, "unknown"); break;
4832     case not_op:mp_print(mp, "not"); break;
4833     case decimal:mp_print(mp, "decimal"); break;
4834     case reverse:mp_print(mp, "reverse"); break;
4835     case make_path_op:mp_print(mp, "makepath"); break;
4836     case make_pen_op:mp_print(mp, "makepen"); break;
4837     case oct_op:mp_print(mp, "oct"); break;
4838     case hex_op:mp_print(mp, "hex"); break;
4839     case ASCII_op:mp_print(mp, "ASCII"); break;
4840     case char_op:mp_print(mp, "char"); break;
4841     case length_op:mp_print(mp, "length"); break;
4842     case turning_op:mp_print(mp, "turningnumber"); break;
4843     case x_part:mp_print(mp, "xpart"); break;
4844     case y_part:mp_print(mp, "ypart"); break;
4845     case xx_part:mp_print(mp, "xxpart"); break;
4846     case xy_part:mp_print(mp, "xypart"); break;
4847     case yx_part:mp_print(mp, "yxpart"); break;
4848     case yy_part:mp_print(mp, "yypart"); break;
4849     case red_part:mp_print(mp, "redpart"); break;
4850     case green_part:mp_print(mp, "greenpart"); break;
4851     case blue_part:mp_print(mp, "bluepart"); break;
4852     case cyan_part:mp_print(mp, "cyanpart"); break;
4853     case magenta_part:mp_print(mp, "magentapart"); break;
4854     case yellow_part:mp_print(mp, "yellowpart"); break;
4855     case black_part:mp_print(mp, "blackpart"); break;
4856     case grey_part:mp_print(mp, "greypart"); break;
4857     case color_model_part:mp_print(mp, "colormodel"); break;
4858     case font_part:mp_print(mp, "fontpart"); break;
4859     case text_part:mp_print(mp, "textpart"); break;
4860     case path_part:mp_print(mp, "pathpart"); break;
4861     case pen_part:mp_print(mp, "penpart"); break;
4862     case dash_part:mp_print(mp, "dashpart"); break;
4863     case sqrt_op:mp_print(mp, "sqrt"); break;
4864     case m_exp_op:mp_print(mp, "mexp"); break;
4865     case m_log_op:mp_print(mp, "mlog"); break;
4866     case sin_d_op:mp_print(mp, "sind"); break;
4867     case cos_d_op:mp_print(mp, "cosd"); break;
4868     case floor_op:mp_print(mp, "floor"); break;
4869     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4870     case char_exists_op:mp_print(mp, "charexists"); break;
4871     case font_size:mp_print(mp, "fontsize"); break;
4872     case ll_corner_op:mp_print(mp, "llcorner"); break;
4873     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4874     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4875     case ur_corner_op:mp_print(mp, "urcorner"); break;
4876     case arc_length:mp_print(mp, "arclength"); break;
4877     case angle_op:mp_print(mp, "angle"); break;
4878     case cycle_op:mp_print(mp, "cycle"); break;
4879     case filled_op:mp_print(mp, "filled"); break;
4880     case stroked_op:mp_print(mp, "stroked"); break;
4881     case textual_op:mp_print(mp, "textual"); break;
4882     case clipped_op:mp_print(mp, "clipped"); break;
4883     case bounded_op:mp_print(mp, "bounded"); break;
4884     case plus:mp_print_char(mp, '+'); break;
4885     case minus:mp_print_char(mp, '-'); break;
4886     case times:mp_print_char(mp, '*'); break;
4887     case over:mp_print_char(mp, '/'); break;
4888     case pythag_add:mp_print(mp, "++"); break;
4889     case pythag_sub:mp_print(mp, "+-+"); break;
4890     case or_op:mp_print(mp, "or"); break;
4891     case and_op:mp_print(mp, "and"); break;
4892     case less_than:mp_print_char(mp, '<'); break;
4893     case less_or_equal:mp_print(mp, "<="); break;
4894     case greater_than:mp_print_char(mp, '>'); break;
4895     case greater_or_equal:mp_print(mp, ">="); break;
4896     case equal_to:mp_print_char(mp, '='); break;
4897     case unequal_to:mp_print(mp, "<>"); break;
4898     case concatenate:mp_print(mp, "&"); break;
4899     case rotated_by:mp_print(mp, "rotated"); break;
4900     case slanted_by:mp_print(mp, "slanted"); break;
4901     case scaled_by:mp_print(mp, "scaled"); break;
4902     case shifted_by:mp_print(mp, "shifted"); break;
4903     case transformed_by:mp_print(mp, "transformed"); break;
4904     case x_scaled:mp_print(mp, "xscaled"); break;
4905     case y_scaled:mp_print(mp, "yscaled"); break;
4906     case z_scaled:mp_print(mp, "zscaled"); break;
4907     case in_font:mp_print(mp, "infont"); break;
4908     case intersect:mp_print(mp, "intersectiontimes"); break;
4909     case substring_of:mp_print(mp, "substring"); break;
4910     case subpath_of:mp_print(mp, "subpath"); break;
4911     case direction_time_of:mp_print(mp, "directiontime"); break;
4912     case point_of:mp_print(mp, "point"); break;
4913     case precontrol_of:mp_print(mp, "precontrol"); break;
4914     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4915     case pen_offset_of:mp_print(mp, "penoffset"); break;
4916     case arc_time_of:mp_print(mp, "arctime"); break;
4917     case mp_version:mp_print(mp, "mpversion"); break;
4918     case envelope_of:mp_print(mp, "envelope"); break;
4919     default: mp_print(mp, ".."); break;
4920     }
4921   }
4922 }
4923
4924 @ \MP\ also has a bunch of internal parameters that a user might want to
4925 fuss with. Every such parameter has an identifying code number, defined here.
4926
4927 @<Types...@>=
4928 enum mp_given_internal {
4929   mp_tracing_titles=1, /* show titles online when they appear */
4930   mp_tracing_equations, /* show each variable when it becomes known */
4931   mp_tracing_capsules, /* show capsules too */
4932   mp_tracing_choices, /* show the control points chosen for paths */
4933   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4934   mp_tracing_commands, /* show commands and operations before they are performed */
4935   mp_tracing_restores, /* show when a variable or internal is restored */
4936   mp_tracing_macros, /* show macros before they are expanded */
4937   mp_tracing_output, /* show digitized edges as they are output */
4938   mp_tracing_stats, /* show memory usage at end of job */
4939   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4940   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4941   mp_year, /* the current year (e.g., 1984) */
4942   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4943   mp_day, /* the current day of the month */
4944   mp_time, /* the number of minutes past midnight when this job started */
4945   mp_char_code, /* the number of the next character to be output */
4946   mp_char_ext, /* the extension code of the next character to be output */
4947   mp_char_wd, /* the width of the next character to be output */
4948   mp_char_ht, /* the height of the next character to be output */
4949   mp_char_dp, /* the depth of the next character to be output */
4950   mp_char_ic, /* the italic correction of the next character to be output */
4951   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4952   mp_pausing, /* positive to display lines on the terminal before they are read */
4953   mp_showstopping, /* positive to stop after each \&{show} command */
4954   mp_fontmaking, /* positive if font metric output is to be produced */
4955   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4956   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4957   mp_miterlimit, /* controls miter length as in \ps */
4958   mp_warning_check, /* controls error message when variable value is large */
4959   mp_boundary_char, /* the right boundary character for ligatures */
4960   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4961   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4962   mp_default_color_model, /* the default color model for unspecified items */
4963   mp_restore_clip_color,
4964   mp_procset, /* wether or not create PostScript command shortcuts */
4965   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
4966 };
4967
4968 @
4969
4970 @d max_given_internal mp_gtroffmode
4971
4972 @<Glob...@>=
4973 scaled *internal;  /* the values of internal quantities */
4974 char **int_name;  /* their names */
4975 int int_ptr;  /* the maximum internal quantity defined so far */
4976 int max_internal; /* current maximum number of internal quantities */
4977
4978 @ @<Option variables@>=
4979 int troff_mode; 
4980
4981 @ @<Allocate or initialize ...@>=
4982 mp->max_internal=2*max_given_internal;
4983 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4984 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4985 mp->troff_mode=(opt->troff_mode>0 ? true : false);
4986
4987 @ @<Exported function ...@>=
4988 int mp_troff_mode(MP mp);
4989
4990 @ @c
4991 int mp_troff_mode(MP mp) { return mp->troff_mode; }
4992
4993 @ @<Set initial ...@>=
4994 for (k=0;k<= mp->max_internal; k++ ) { 
4995    mp->internal[k]=0; 
4996    mp->int_name[k]=NULL; 
4997 }
4998 mp->int_ptr=max_given_internal;
4999
5000 @ The symbolic names for internal quantities are put into \MP's hash table
5001 by using a routine called |primitive|, which will be defined later. Let us
5002 enter them now, so that we don't have to list all those names again
5003 anywhere else.
5004
5005 @<Put each of \MP's primitives into the hash table@>=
5006 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5007 @:tracingtitles_}{\&{tracingtitles} primitive@>
5008 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5009 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5010 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5011 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5012 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5013 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5014 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5015 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5016 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5017 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5018 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5019 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5020 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5021 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5022 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5023 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5024 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5025 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5026 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5027 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5028 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5029 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5030 mp_primitive(mp, "year",internal_quantity,mp_year);
5031 @:mp_year_}{\&{year} primitive@>
5032 mp_primitive(mp, "month",internal_quantity,mp_month);
5033 @:mp_month_}{\&{month} primitive@>
5034 mp_primitive(mp, "day",internal_quantity,mp_day);
5035 @:mp_day_}{\&{day} primitive@>
5036 mp_primitive(mp, "time",internal_quantity,mp_time);
5037 @:time_}{\&{time} primitive@>
5038 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5039 @:mp_char_code_}{\&{charcode} primitive@>
5040 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5041 @:mp_char_ext_}{\&{charext} primitive@>
5042 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5043 @:mp_char_wd_}{\&{charwd} primitive@>
5044 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5045 @:mp_char_ht_}{\&{charht} primitive@>
5046 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5047 @:mp_char_dp_}{\&{chardp} primitive@>
5048 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5049 @:mp_char_ic_}{\&{charic} primitive@>
5050 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5051 @:mp_design_size_}{\&{designsize} primitive@>
5052 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5053 @:mp_pausing_}{\&{pausing} primitive@>
5054 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5055 @:mp_showstopping_}{\&{showstopping} primitive@>
5056 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5057 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5058 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5059 @:mp_linejoin_}{\&{linejoin} primitive@>
5060 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5061 @:mp_linecap_}{\&{linecap} primitive@>
5062 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5063 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5064 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5065 @:mp_warning_check_}{\&{warningcheck} primitive@>
5066 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5067 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5068 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5069 @:mp_prologues_}{\&{prologues} primitive@>
5070 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5071 @:mp_true_corners_}{\&{truecorners} primitive@>
5072 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5073 @:mp_procset_}{\&{mpprocset} primitive@>
5074 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5075 @:troffmode_}{\&{troffmode} primitive@>
5076 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5077 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5078 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5079 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5080
5081 @ Colors can be specified in four color models. In the special
5082 case of |no_model|, MetaPost does not output any color operator to
5083 the postscript output.
5084
5085 Note: these values are passed directly on to |with_option|. This only
5086 works because the other possible values passed to |with_option| are
5087 8 and 10 respectively (from |with_pen| and |with_picture|).
5088
5089 There is a first state, that is only used for |gs_colormodel|. It flags
5090 the fact that there has not been any kind of color specification by
5091 the user so far in the game.
5092
5093 @<Types...@>=
5094 enum mp_color_model {
5095   mp_no_model=1,
5096   mp_grey_model=3,
5097   mp_rgb_model=5,
5098   mp_cmyk_model=7,
5099   mp_uninitialized_model=9,
5100 };
5101
5102
5103 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5104 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5105 mp->internal[mp_restore_clip_color]=unity;
5106
5107 @ Well, we do have to list the names one more time, for use in symbolic
5108 printouts.
5109
5110 @<Initialize table...@>=
5111 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5112 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5113 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5114 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5115 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5116 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5117 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5118 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5119 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5120 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5121 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5122 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5123 mp->int_name[mp_year]=xstrdup("year");
5124 mp->int_name[mp_month]=xstrdup("month");
5125 mp->int_name[mp_day]=xstrdup("day");
5126 mp->int_name[mp_time]=xstrdup("time");
5127 mp->int_name[mp_char_code]=xstrdup("charcode");
5128 mp->int_name[mp_char_ext]=xstrdup("charext");
5129 mp->int_name[mp_char_wd]=xstrdup("charwd");
5130 mp->int_name[mp_char_ht]=xstrdup("charht");
5131 mp->int_name[mp_char_dp]=xstrdup("chardp");
5132 mp->int_name[mp_char_ic]=xstrdup("charic");
5133 mp->int_name[mp_design_size]=xstrdup("designsize");
5134 mp->int_name[mp_pausing]=xstrdup("pausing");
5135 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5136 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5137 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5138 mp->int_name[mp_linecap]=xstrdup("linecap");
5139 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5140 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5141 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5142 mp->int_name[mp_prologues]=xstrdup("prologues");
5143 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5144 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5145 mp->int_name[mp_procset]=xstrdup("mpprocset");
5146 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5147 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5148
5149 @ The following procedure, which is called just before \MP\ initializes its
5150 input and output, establishes the initial values of the date and time.
5151 @^system dependencies@>
5152
5153 Note that the values are |scaled| integers. Hence \MP\ can no longer
5154 be used after the year 32767.
5155
5156 @c 
5157 void mp_fix_date_and_time (MP mp) { 
5158   time_t clock = time ((time_t *) 0);
5159   struct tm *tmptr = localtime (&clock);
5160   mp->internal[mp_time]=
5161       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5162   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5163   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5164   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5165 }
5166
5167 @ @<Declarations@>=
5168 void mp_fix_date_and_time (MP mp) ;
5169
5170 @ \MP\ is occasionally supposed to print diagnostic information that
5171 goes only into the transcript file, unless |mp_tracing_online| is positive.
5172 Now that we have defined |mp_tracing_online| we can define
5173 two routines that adjust the destination of print commands:
5174
5175 @<Declarations@>=
5176 void mp_begin_diagnostic (MP mp) ;
5177 void mp_end_diagnostic (MP mp,boolean blank_line);
5178 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5179
5180 @ @<Basic printing...@>=
5181 @<Declare a function called |true_line|@>;
5182 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5183   mp->old_setting=mp->selector;
5184   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5185     decr(mp->selector);
5186     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5187   }
5188 }
5189 @#
5190 void mp_end_diagnostic (MP mp,boolean blank_line) {
5191   /* restore proper conditions after tracing */
5192   mp_print_nl(mp, "");
5193   if ( blank_line ) mp_print_ln(mp);
5194   mp->selector=mp->old_setting;
5195 }
5196
5197
5198
5199 @<Glob...@>=
5200 unsigned int old_setting;
5201
5202 @ We will occasionally use |begin_diagnostic| in connection with line-number
5203 printing, as follows. (The parameter |s| is typically |"Path"| or
5204 |"Cycle spec"|, etc.)
5205
5206 @<Basic printing...@>=
5207 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5208   mp_begin_diagnostic(mp);
5209   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5210   mp_print(mp, " at line "); 
5211   mp_print_int(mp, mp_true_line(mp));
5212   mp_print(mp, t); mp_print_char(mp, ':');
5213 }
5214
5215 @ The 256 |ASCII_code| characters are grouped into classes by means of
5216 the |char_class| table. Individual class numbers have no semantic
5217 or syntactic significance, except in a few instances defined here.
5218 There's also |max_class|, which can be used as a basis for additional
5219 class numbers in nonstandard extensions of \MP.
5220
5221 @d digit_class 0 /* the class number of \.{0123456789} */
5222 @d period_class 1 /* the class number of `\..' */
5223 @d space_class 2 /* the class number of spaces and nonstandard characters */
5224 @d percent_class 3 /* the class number of `\.\%' */
5225 @d string_class 4 /* the class number of `\."' */
5226 @d right_paren_class 8 /* the class number of `\.)' */
5227 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5228 @d letter_class 9 /* letters and the underline character */
5229 @d left_bracket_class 17 /* `\.[' */
5230 @d right_bracket_class 18 /* `\.]' */
5231 @d invalid_class 20 /* bad character in the input */
5232 @d max_class 20 /* the largest class number */
5233
5234 @<Glob...@>=
5235 int char_class[256]; /* the class numbers */
5236
5237 @ If changes are made to accommodate non-ASCII character sets, they should
5238 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5239 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5240 @^system dependencies@>
5241
5242 @<Set initial ...@>=
5243 for (k='0';k<='9';k++) 
5244   mp->char_class[k]=digit_class;
5245 mp->char_class['.']=period_class;
5246 mp->char_class[' ']=space_class;
5247 mp->char_class['%']=percent_class;
5248 mp->char_class['"']=string_class;
5249 mp->char_class[',']=5;
5250 mp->char_class[';']=6;
5251 mp->char_class['(']=7;
5252 mp->char_class[')']=right_paren_class;
5253 for (k='A';k<= 'Z';k++ )
5254   mp->char_class[k]=letter_class;
5255 for (k='a';k<='z';k++) 
5256   mp->char_class[k]=letter_class;
5257 mp->char_class['_']=letter_class;
5258 mp->char_class['<']=10;
5259 mp->char_class['=']=10;
5260 mp->char_class['>']=10;
5261 mp->char_class[':']=10;
5262 mp->char_class['|']=10;
5263 mp->char_class['`']=11;
5264 mp->char_class['\'']=11;
5265 mp->char_class['+']=12;
5266 mp->char_class['-']=12;
5267 mp->char_class['/']=13;
5268 mp->char_class['*']=13;
5269 mp->char_class['\\']=13;
5270 mp->char_class['!']=14;
5271 mp->char_class['?']=14;
5272 mp->char_class['#']=15;
5273 mp->char_class['&']=15;
5274 mp->char_class['@@']=15;
5275 mp->char_class['$']=15;
5276 mp->char_class['^']=16;
5277 mp->char_class['~']=16;
5278 mp->char_class['[']=left_bracket_class;
5279 mp->char_class[']']=right_bracket_class;
5280 mp->char_class['{']=19;
5281 mp->char_class['}']=19;
5282 for (k=0;k<' ';k++)
5283   mp->char_class[k]=invalid_class;
5284 mp->char_class['\t']=space_class;
5285 mp->char_class['\f']=space_class;
5286 for (k=127;k<=255;k++)
5287   mp->char_class[k]=invalid_class;
5288
5289 @* \[13] The hash table.
5290 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5291 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5292 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5293 table, it is never removed.
5294
5295 The actual sequence of characters forming a symbolic token is
5296 stored in the |str_pool| array together with all the other strings. An
5297 auxiliary array |hash| consists of items with two halfword fields per
5298 word. The first of these, called |next(p)|, points to the next identifier
5299 belonging to the same coalesced list as the identifier corresponding to~|p|;
5300 and the other, called |text(p)|, points to the |str_start| entry for
5301 |p|'s identifier. If position~|p| of the hash table is empty, we have
5302 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5303 hash list, we have |next(p)=0|.
5304
5305 An auxiliary pointer variable called |hash_used| is maintained in such a
5306 way that all locations |p>=hash_used| are nonempty. The global variable
5307 |st_count| tells how many symbolic tokens have been defined, if statistics
5308 are being kept.
5309
5310 The first 256 locations of |hash| are reserved for symbols of length one.
5311
5312 There's a parallel array called |eqtb| that contains the current equivalent
5313 values of each symbolic token. The entries of this array consist of
5314 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5315 piece of information that qualifies the |eq_type|).
5316
5317 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5318 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5319 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5320 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5321 @d hash_base 257 /* hashing actually starts here */
5322 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5323
5324 @<Glob...@>=
5325 pointer hash_used; /* allocation pointer for |hash| */
5326 integer st_count; /* total number of known identifiers */
5327
5328 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5329 since they are used in error recovery.
5330
5331 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5332 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5333 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5334 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5335 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5336 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5337 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5338 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5339 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5340 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5341 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5342 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5343 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5344 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5345 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5346 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5347 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5348
5349 @<Glob...@>=
5350 two_halves *hash; /* the hash table */
5351 two_halves *eqtb; /* the equivalents */
5352
5353 @ @<Allocate or initialize ...@>=
5354 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5355 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5356
5357 @ @<Dealloc variables@>=
5358 xfree(mp->hash);
5359 xfree(mp->eqtb);
5360
5361 @ @<Set init...@>=
5362 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5363 for (k=2;k<=hash_end;k++)  { 
5364   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5365 }
5366
5367 @ @<Initialize table entries...@>=
5368 mp->hash_used=frozen_inaccessible; /* nothing is used */
5369 mp->st_count=0;
5370 text(frozen_bad_vardef)=intern("a bad variable");
5371 text(frozen_etex)=intern("etex");
5372 text(frozen_mpx_break)=intern("mpxbreak");
5373 text(frozen_fi)=intern("fi");
5374 text(frozen_end_group)=intern("endgroup");
5375 text(frozen_end_def)=intern("enddef");
5376 text(frozen_end_for)=intern("endfor");
5377 text(frozen_semicolon)=intern(";");
5378 text(frozen_colon)=intern(":");
5379 text(frozen_slash)=intern("/");
5380 text(frozen_left_bracket)=intern("[");
5381 text(frozen_right_delimiter)=intern(")");
5382 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5383 eq_type(frozen_right_delimiter)=right_delimiter;
5384
5385 @ @<Check the ``constant'' values...@>=
5386 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5387
5388 @ Here is the subroutine that searches the hash table for an identifier
5389 that matches a given string of length~|l| appearing in |buffer[j..
5390 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5391 will always be found, and the corresponding hash table address
5392 will be returned.
5393
5394 @c 
5395 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5396   integer h; /* hash code */
5397   pointer p; /* index in |hash| array */
5398   pointer k; /* index in |buffer| array */
5399   if (l==1) {
5400     @<Treat special case of length 1 and |break|@>;
5401   }
5402   @<Compute the hash code |h|@>;
5403   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5404   while (true)  { 
5405         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5406       break;
5407     if ( next(p)==0 ) {
5408       @<Insert a new symbolic token after |p|, then
5409         make |p| point to it and |break|@>;
5410     }
5411     p=next(p);
5412   }
5413   return p;
5414 };
5415
5416 @ @<Treat special case of length 1...@>=
5417  p=mp->buffer[j]+1; text(p)=p-1; return p;
5418
5419
5420 @ @<Insert a new symbolic...@>=
5421 {
5422 if ( text(p)>0 ) { 
5423   do {  
5424     if ( hash_is_full )
5425       mp_overflow(mp, "hash size",mp->hash_size);
5426 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5427     decr(mp->hash_used);
5428   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5429   next(p)=mp->hash_used; 
5430   p=mp->hash_used;
5431 }
5432 str_room(l);
5433 for (k=j;k<=j+l-1;k++) {
5434   append_char(mp->buffer[k]);
5435 }
5436 text(p)=mp_make_string(mp); 
5437 mp->str_ref[text(p)]=max_str_ref;
5438 incr(mp->st_count);
5439 break;
5440 }
5441
5442
5443 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5444 should be a prime number.  The theory of hashing tells us to expect fewer
5445 than two table probes, on the average, when the search is successful.
5446 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5447 @^Vitter, Jeffrey Scott@>
5448
5449 @<Compute the hash code |h|@>=
5450 h=mp->buffer[j];
5451 for (k=j+1;k<=j+l-1;k++){ 
5452   h=h+h+mp->buffer[k];
5453   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5454 }
5455
5456 @ @<Search |eqtb| for equivalents equal to |p|@>=
5457 for (q=1;q<=hash_end;q++) { 
5458   if ( equiv(q)==p ) { 
5459     mp_print_nl(mp, "EQUIV("); 
5460     mp_print_int(mp, q); 
5461     mp_print_char(mp, ')');
5462   }
5463 }
5464
5465 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5466 table, together with their command code (which will be the |eq_type|)
5467 and an operand (which will be the |equiv|). The |primitive| procedure
5468 does this, in a way that no \MP\ user can. The global value |cur_sym|
5469 contains the new |eqtb| pointer after |primitive| has acted.
5470
5471 @c 
5472 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5473   pool_pointer k; /* index into |str_pool| */
5474   small_number j; /* index into |buffer| */
5475   small_number l; /* length of the string */
5476   str_number s;
5477   s = intern(ss);
5478   k=mp->str_start[s]; l=str_stop(s)-k;
5479   /* we will move |s| into the (empty) |buffer| */
5480   for (j=0;j<=l-1;j++) {
5481     mp->buffer[j]=mp->str_pool[k+j];
5482   }
5483   mp->cur_sym=mp_id_lookup(mp, 0,l);
5484   if ( s>=256 ) { /* we don't want to have the string twice */
5485     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5486   };
5487   eq_type(mp->cur_sym)=c; 
5488   equiv(mp->cur_sym)=o;
5489 }
5490
5491
5492 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5493 by their |eq_type| alone. These primitives are loaded into the hash table
5494 as follows:
5495
5496 @<Put each of \MP's primitives into the hash table@>=
5497 mp_primitive(mp, "..",path_join,0);
5498 @:.._}{\.{..} primitive@>
5499 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5500 @:[ }{\.{[} primitive@>
5501 mp_primitive(mp, "]",right_bracket,0);
5502 @:] }{\.{]} primitive@>
5503 mp_primitive(mp, "}",right_brace,0);
5504 @:]]}{\.{\char`\}} primitive@>
5505 mp_primitive(mp, "{",left_brace,0);
5506 @:][}{\.{\char`\{} primitive@>
5507 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5508 @:: }{\.{:} primitive@>
5509 mp_primitive(mp, "::",double_colon,0);
5510 @::: }{\.{::} primitive@>
5511 mp_primitive(mp, "||:",bchar_label,0);
5512 @:::: }{\.{\char'174\char'174:} primitive@>
5513 mp_primitive(mp, ":=",assignment,0);
5514 @::=_}{\.{:=} primitive@>
5515 mp_primitive(mp, ",",comma,0);
5516 @:, }{\., primitive@>
5517 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5518 @:; }{\.; primitive@>
5519 mp_primitive(mp, "\\",relax,0);
5520 @:]]\\}{\.{\char`\\} primitive@>
5521 @#
5522 mp_primitive(mp, "addto",add_to_command,0);
5523 @:add_to_}{\&{addto} primitive@>
5524 mp_primitive(mp, "atleast",at_least,0);
5525 @:at_least_}{\&{atleast} primitive@>
5526 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5527 @:begin_group_}{\&{begingroup} primitive@>
5528 mp_primitive(mp, "controls",controls,0);
5529 @:controls_}{\&{controls} primitive@>
5530 mp_primitive(mp, "curl",curl_command,0);
5531 @:curl_}{\&{curl} primitive@>
5532 mp_primitive(mp, "delimiters",delimiters,0);
5533 @:delimiters_}{\&{delimiters} primitive@>
5534 mp_primitive(mp, "endgroup",end_group,0);
5535  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5536 @:endgroup_}{\&{endgroup} primitive@>
5537 mp_primitive(mp, "everyjob",every_job_command,0);
5538 @:every_job_}{\&{everyjob} primitive@>
5539 mp_primitive(mp, "exitif",exit_test,0);
5540 @:exit_if_}{\&{exitif} primitive@>
5541 mp_primitive(mp, "expandafter",expand_after,0);
5542 @:expand_after_}{\&{expandafter} primitive@>
5543 mp_primitive(mp, "interim",interim_command,0);
5544 @:interim_}{\&{interim} primitive@>
5545 mp_primitive(mp, "let",let_command,0);
5546 @:let_}{\&{let} primitive@>
5547 mp_primitive(mp, "newinternal",new_internal,0);
5548 @:new_internal_}{\&{newinternal} primitive@>
5549 mp_primitive(mp, "of",of_token,0);
5550 @:of_}{\&{of} primitive@>
5551 mp_primitive(mp, "randomseed",mp_random_seed,0);
5552 @:mp_random_seed_}{\&{randomseed} primitive@>
5553 mp_primitive(mp, "save",save_command,0);
5554 @:save_}{\&{save} primitive@>
5555 mp_primitive(mp, "scantokens",scan_tokens,0);
5556 @:scan_tokens_}{\&{scantokens} primitive@>
5557 mp_primitive(mp, "shipout",ship_out_command,0);
5558 @:ship_out_}{\&{shipout} primitive@>
5559 mp_primitive(mp, "skipto",skip_to,0);
5560 @:skip_to_}{\&{skipto} primitive@>
5561 mp_primitive(mp, "special",special_command,0);
5562 @:special}{\&{special} primitive@>
5563 mp_primitive(mp, "fontmapfile",special_command,1);
5564 @:fontmapfile}{\&{fontmapfile} primitive@>
5565 mp_primitive(mp, "fontmapline",special_command,2);
5566 @:fontmapline}{\&{fontmapline} primitive@>
5567 mp_primitive(mp, "step",step_token,0);
5568 @:step_}{\&{step} primitive@>
5569 mp_primitive(mp, "str",str_op,0);
5570 @:str_}{\&{str} primitive@>
5571 mp_primitive(mp, "tension",tension,0);
5572 @:tension_}{\&{tension} primitive@>
5573 mp_primitive(mp, "to",to_token,0);
5574 @:to_}{\&{to} primitive@>
5575 mp_primitive(mp, "until",until_token,0);
5576 @:until_}{\&{until} primitive@>
5577 mp_primitive(mp, "within",within_token,0);
5578 @:within_}{\&{within} primitive@>
5579 mp_primitive(mp, "write",write_command,0);
5580 @:write_}{\&{write} primitive@>
5581
5582 @ Each primitive has a corresponding inverse, so that it is possible to
5583 display the cryptic numeric contents of |eqtb| in symbolic form.
5584 Every call of |primitive| in this program is therefore accompanied by some
5585 straightforward code that forms part of the |print_cmd_mod| routine
5586 explained below.
5587
5588 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5589 case add_to_command:mp_print(mp, "addto"); break;
5590 case assignment:mp_print(mp, ":="); break;
5591 case at_least:mp_print(mp, "atleast"); break;
5592 case bchar_label:mp_print(mp, "||:"); break;
5593 case begin_group:mp_print(mp, "begingroup"); break;
5594 case colon:mp_print(mp, ":"); break;
5595 case comma:mp_print(mp, ","); break;
5596 case controls:mp_print(mp, "controls"); break;
5597 case curl_command:mp_print(mp, "curl"); break;
5598 case delimiters:mp_print(mp, "delimiters"); break;
5599 case double_colon:mp_print(mp, "::"); break;
5600 case end_group:mp_print(mp, "endgroup"); break;
5601 case every_job_command:mp_print(mp, "everyjob"); break;
5602 case exit_test:mp_print(mp, "exitif"); break;
5603 case expand_after:mp_print(mp, "expandafter"); break;
5604 case interim_command:mp_print(mp, "interim"); break;
5605 case left_brace:mp_print(mp, "{"); break;
5606 case left_bracket:mp_print(mp, "["); break;
5607 case let_command:mp_print(mp, "let"); break;
5608 case new_internal:mp_print(mp, "newinternal"); break;
5609 case of_token:mp_print(mp, "of"); break;
5610 case path_join:mp_print(mp, ".."); break;
5611 case mp_random_seed:mp_print(mp, "randomseed"); break;
5612 case relax:mp_print_char(mp, '\\'); break;
5613 case right_brace:mp_print(mp, "}"); break;
5614 case right_bracket:mp_print(mp, "]"); break;
5615 case save_command:mp_print(mp, "save"); break;
5616 case scan_tokens:mp_print(mp, "scantokens"); break;
5617 case semicolon:mp_print(mp, ";"); break;
5618 case ship_out_command:mp_print(mp, "shipout"); break;
5619 case skip_to:mp_print(mp, "skipto"); break;
5620 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5621                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5622                  mp_print(mp, "special"); break;
5623 case step_token:mp_print(mp, "step"); break;
5624 case str_op:mp_print(mp, "str"); break;
5625 case tension:mp_print(mp, "tension"); break;
5626 case to_token:mp_print(mp, "to"); break;
5627 case until_token:mp_print(mp, "until"); break;
5628 case within_token:mp_print(mp, "within"); break;
5629 case write_command:mp_print(mp, "write"); break;
5630
5631 @ We will deal with the other primitives later, at some point in the program
5632 where their |eq_type| and |equiv| values are more meaningful.  For example,
5633 the primitives for macro definitions will be loaded when we consider the
5634 routines that define macros.
5635 It is easy to find where each particular
5636 primitive was treated by looking in the index at the end; for example, the
5637 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5638
5639 @* \[14] Token lists.
5640 A \MP\ token is either symbolic or numeric or a string, or it denotes
5641 a macro parameter or capsule; so there are five corresponding ways to encode it
5642 @^token@>
5643 internally: (1)~A symbolic token whose hash code is~|p|
5644 is represented by the number |p|, in the |info| field of a single-word
5645 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5646 represented in a two-word node of~|mem|; the |type| field is |known|,
5647 the |name_type| field is |token|, and the |value| field holds~|v|.
5648 The fact that this token appears in a two-word node rather than a
5649 one-word node is, of course, clear from the node address.
5650 (3)~A string token is also represented in a two-word node; the |type|
5651 field is |mp_string_type|, the |name_type| field is |token|, and the
5652 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5653 |name_type=capsule|, and their |type| and |value| fields represent
5654 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5655 are like symbolic tokens in that they appear in |info| fields of
5656 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5657 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5658 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5659 Actual values of these parameters are kept in a separate stack, as we will
5660 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5661 of course, chosen so that there will be no confusion between symbolic
5662 tokens and parameters of various types.
5663
5664 Note that
5665 the `\\{type}' field of a node has nothing to do with ``type'' in a
5666 printer's sense. It's curious that the same word is used in such different ways.
5667
5668 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5669 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5670 @d token_node_size 2 /* the number of words in a large token node */
5671 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5672 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5673 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5674 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5675 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5676
5677 @<Check the ``constant''...@>=
5678 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5679
5680 @ We have set aside a two word node beginning at |null| so that we can have
5681 |value(null)=0|.  We will make use of this coincidence later.
5682
5683 @<Initialize table entries...@>=
5684 link(null)=null; value(null)=0;
5685
5686 @ A numeric token is created by the following trivial routine.
5687
5688 @c 
5689 pointer mp_new_num_tok (MP mp,scaled v) {
5690   pointer p; /* the new node */
5691   p=mp_get_node(mp, token_node_size); value(p)=v;
5692   type(p)=mp_known; name_type(p)=mp_token; 
5693   return p;
5694 }
5695
5696 @ A token list is a singly linked list of nodes in |mem|, where
5697 each node contains a token and a link.  Here's a subroutine that gets rid
5698 of a token list when it is no longer needed.
5699
5700 @c void mp_flush_token_list (MP mp,pointer p) {
5701   pointer q; /* the node being recycled */
5702   while ( p!=null ) { 
5703     q=p; p=link(p);
5704     if ( q>=mp->hi_mem_min ) {
5705      free_avail(q);
5706     } else { 
5707       switch (type(q)) {
5708       case mp_vacuous: case mp_boolean_type: case mp_known:
5709         break;
5710       case mp_string_type:
5711         delete_str_ref(value(q));
5712         break;
5713       case unknown_types: case mp_pen_type: case mp_path_type: 
5714       case mp_picture_type: case mp_pair_type: case mp_color_type:
5715       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5716       case mp_proto_dependent: case mp_independent:
5717         mp_recycle_value(mp,q);
5718         break;
5719       default: mp_confusion(mp, "token");
5720 @:this can't happen token}{\quad token@>
5721       }
5722       mp_free_node(mp, q,token_node_size);
5723     }
5724   }
5725 }
5726
5727 @ The procedure |show_token_list|, which prints a symbolic form of
5728 the token list that starts at a given node |p|, illustrates these
5729 conventions. The token list being displayed should not begin with a reference
5730 count. However, the procedure is intended to be fairly robust, so that if the
5731 memory links are awry or if |p| is not really a pointer to a token list,
5732 almost nothing catastrophic can happen.
5733
5734 An additional parameter |q| is also given; this parameter is either null
5735 or it points to a node in the token list where a certain magic computation
5736 takes place that will be explained later. (Basically, |q| is non-null when
5737 we are printing the two-line context information at the time of an error
5738 message; |q| marks the place corresponding to where the second line
5739 should begin.)
5740
5741 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5742 of printing exceeds a given limit~|l|; the length of printing upon entry is
5743 assumed to be a given amount called |null_tally|. (Note that
5744 |show_token_list| sometimes uses itself recursively to print
5745 variable names within a capsule.)
5746 @^recursion@>
5747
5748 Unusual entries are printed in the form of all-caps tokens
5749 preceded by a space, e.g., `\.{\char`\ BAD}'.
5750
5751 @<Declare the procedure called |show_token_list|@>=
5752 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5753                          integer null_tally) ;
5754
5755 @ @c
5756 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5757                          integer null_tally) {
5758   small_number class,c; /* the |char_class| of previous and new tokens */
5759   integer r,v; /* temporary registers */
5760   class=percent_class;
5761   mp->tally=null_tally;
5762   while ( (p!=null) && (mp->tally<l) ) { 
5763     if ( p==q ) 
5764       @<Do magic computation@>;
5765     @<Display token |p| and set |c| to its class;
5766       but |return| if there are problems@>;
5767     class=c; p=link(p);
5768   }
5769   if ( p!=null ) 
5770      mp_print(mp, " ETC.");
5771 @.ETC@>
5772   return;
5773 };
5774
5775 @ @<Display token |p| and set |c| to its class...@>=
5776 c=letter_class; /* the default */
5777 if ( (p<0)||(p>mp->mem_end) ) { 
5778   mp_print(mp, " CLOBBERED"); return;
5779 @.CLOBBERED@>
5780 }
5781 if ( p<mp->hi_mem_min ) { 
5782   @<Display two-word token@>;
5783 } else { 
5784   r=info(p);
5785   if ( r>=expr_base ) {
5786      @<Display a parameter token@>;
5787   } else {
5788     if ( r<1 ) {
5789       if ( r==0 ) { 
5790         @<Display a collective subscript@>
5791       } else {
5792         mp_print(mp, " IMPOSSIBLE");
5793 @.IMPOSSIBLE@>
5794       }
5795     } else { 
5796       r=text(r);
5797       if ( (r<0)||(r>mp->max_str_ptr) ) {
5798         mp_print(mp, " NONEXISTENT");
5799 @.NONEXISTENT@>
5800       } else {
5801        @<Print string |r| as a symbolic token
5802         and set |c| to its class@>;
5803       }
5804     }
5805   }
5806 }
5807
5808 @ @<Display two-word token@>=
5809 if ( name_type(p)==mp_token ) {
5810   if ( type(p)==mp_known ) {
5811     @<Display a numeric token@>;
5812   } else if ( type(p)!=mp_string_type ) {
5813     mp_print(mp, " BAD");
5814 @.BAD@>
5815   } else { 
5816     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5817     c=string_class;
5818   }
5819 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5820   mp_print(mp, " BAD");
5821 } else { 
5822   mp_print_capsule(mp,p); c=right_paren_class;
5823 }
5824
5825 @ @<Display a numeric token@>=
5826 if ( class==digit_class ) 
5827   mp_print_char(mp, ' ');
5828 v=value(p);
5829 if ( v<0 ){ 
5830   if ( class==left_bracket_class ) 
5831     mp_print_char(mp, ' ');
5832   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5833   c=right_bracket_class;
5834 } else { 
5835   mp_print_scaled(mp, v); c=digit_class;
5836 }
5837
5838
5839 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5840 But we will see later (in the |print_variable_name| routine) that
5841 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5842
5843 @<Display a collective subscript@>=
5844 {
5845 if ( class==left_bracket_class ) 
5846   mp_print_char(mp, ' ');
5847 mp_print(mp, "[]"); c=right_bracket_class;
5848 }
5849
5850 @ @<Display a parameter token@>=
5851 {
5852 if ( r<suffix_base ) { 
5853   mp_print(mp, "(EXPR"); r=r-(expr_base);
5854 @.EXPR@>
5855 } else if ( r<text_base ) { 
5856   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5857 @.SUFFIX@>
5858 } else { 
5859   mp_print(mp, "(TEXT"); r=r-(text_base);
5860 @.TEXT@>
5861 }
5862 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5863 }
5864
5865
5866 @ @<Print string |r| as a symbolic token...@>=
5867
5868 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5869 if ( c==class ) {
5870   switch (c) {
5871   case letter_class:mp_print_char(mp, '.'); break;
5872   case isolated_classes: break;
5873   default: mp_print_char(mp, ' '); break;
5874   }
5875 }
5876 mp_print_str(mp, r);
5877 }
5878
5879 @ @<Declarations@>=
5880 void mp_print_capsule (MP mp, pointer p);
5881
5882 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5883 void mp_print_capsule (MP mp, pointer p) { 
5884   mp_print_char(mp, '('); mp_print_exp(mp,p,0); mp_print_char(mp, ')');
5885 }
5886
5887 @ Macro definitions are kept in \MP's memory in the form of token lists
5888 that have a few extra one-word nodes at the beginning.
5889
5890 The first node contains a reference count that is used to tell when the
5891 list is no longer needed. To emphasize the fact that a reference count is
5892 present, we shall refer to the |info| field of this special node as the
5893 |ref_count| field.
5894 @^reference counts@>
5895
5896 The next node or nodes after the reference count serve to describe the
5897 formal parameters. They either contain a code word that specifies all
5898 of the parameters, or they contain zero or more parameter tokens followed
5899 by the code `|general_macro|'.
5900
5901 @d ref_count info
5902   /* reference count preceding a macro definition or picture header */
5903 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5904 @d general_macro 0 /* preface to a macro defined with a parameter list */
5905 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5906 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5907 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5908 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5909 @d of_macro 5 /* preface to a macro with
5910   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5911 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5912 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5913
5914 @c 
5915 void mp_delete_mac_ref (MP mp,pointer p) {
5916   /* |p| points to the reference count of a macro list that is
5917     losing one reference */
5918   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5919   else decr(ref_count(p));
5920 }
5921
5922 @ The following subroutine displays a macro, given a pointer to its
5923 reference count.
5924
5925 @c 
5926 @<Declare the procedure called |print_cmd_mod|@>;
5927 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5928   pointer r; /* temporary storage */
5929   p=link(p); /* bypass the reference count */
5930   while ( info(p)>text_macro ){ 
5931     r=link(p); link(p)=null;
5932     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5933     if ( l>0 ) l=l-mp->tally; else return;
5934   } /* control printing of `\.{ETC.}' */
5935 @.ETC@>
5936   mp->tally=0;
5937   switch(info(p)) {
5938   case general_macro:mp_print(mp, "->"); break;
5939 @.->@>
5940   case primary_macro: case secondary_macro: case tertiary_macro:
5941     mp_print_char(mp, '<');
5942     mp_print_cmd_mod(mp, param_type,info(p)); 
5943     mp_print(mp, ">->");
5944     break;
5945   case expr_macro:mp_print(mp, "<expr>->"); break;
5946   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5947   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5948   case text_macro:mp_print(mp, "<text>->"); break;
5949   } /* there are no other cases */
5950   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5951 }
5952
5953 @* \[15] Data structures for variables.
5954 The variables of \MP\ programs can be simple, like `\.x', or they can
5955 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5956 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5957 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5958 things are represented inside of the computer.
5959
5960 Each variable value occupies two consecutive words, either in a two-word
5961 node called a value node, or as a two-word subfield of a larger node.  One
5962 of those two words is called the |value| field; it is an integer,
5963 containing either a |scaled| numeric value or the representation of some
5964 other type of quantity. (It might also be subdivided into halfwords, in
5965 which case it is referred to by other names instead of |value|.) The other
5966 word is broken into subfields called |type|, |name_type|, and |link|.  The
5967 |type| field is a quarterword that specifies the variable's type, and
5968 |name_type| is a quarterword from which \MP\ can reconstruct the
5969 variable's name (sometimes by using the |link| field as well).  Thus, only
5970 1.25 words are actually devoted to the value itself; the other
5971 three-quarters of a word are overhead, but they aren't wasted because they
5972 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5973
5974 In this section we shall be concerned only with the structural aspects of
5975 variables, not their values. Later parts of the program will change the
5976 |type| and |value| fields, but we shall treat those fields as black boxes
5977 whose contents should not be touched.
5978
5979 However, if the |type| field is |mp_structured|, there is no |value| field,
5980 and the second word is broken into two pointer fields called |attr_head|
5981 and |subscr_head|. Those fields point to additional nodes that
5982 contain structural information, as we shall see.
5983
5984 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5985 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5986 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5987 @d value_node_size 2 /* the number of words in a value node */
5988
5989 @ An attribute node is three words long. Two of these words contain |type|
5990 and |value| fields as described above, and the third word contains
5991 additional information:  There is an |attr_loc| field, which contains the
5992 hash address of the token that names this attribute; and there's also a
5993 |parent| field, which points to the value node of |mp_structured| type at the
5994 next higher level (i.e., at the level to which this attribute is
5995 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
5996 |link| field points to the next attribute with the same parent; these are
5997 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
5998 final attribute node links to the constant |end_attr|, whose |attr_loc|
5999 field is greater than any legal hash address. The |attr_head| in the
6000 parent points to a node whose |name_type| is |mp_structured_root|; this
6001 node represents the null attribute, i.e., the variable that is relevant
6002 when no attributes are attached to the parent. The |attr_head| node is either
6003 a value node, a subscript node, or an attribute node, depending on what
6004 the parent would be if it were not structured; but the subscript and
6005 attribute fields are ignored, so it effectively contains only the data of
6006 a value node. The |link| field in this special node points to an attribute
6007 node whose |attr_loc| field is zero; the latter node represents a collective
6008 subscript `\.{[]}' attached to the parent, and its |link| field points to
6009 the first non-special attribute node (or to |end_attr| if there are none).
6010
6011 A subscript node likewise occupies three words, with |type| and |value| fields
6012 plus extra information; its |name_type| is |subscr|. In this case the
6013 third word is called the |subscript| field, which is a |scaled| integer.
6014 The |link| field points to the subscript node with the next larger
6015 subscript, if any; otherwise the |link| points to the attribute node
6016 for collective subscripts at this level. We have seen that the latter node
6017 contains an upward pointer, so that the parent can be deduced.
6018
6019 The |name_type| in a parent-less value node is |root|, and the |link|
6020 is the hash address of the token that names this value.
6021
6022 In other words, variables have a hierarchical structure that includes
6023 enough threads running around so that the program is able to move easily
6024 between siblings, parents, and children. An example should be helpful:
6025 (The reader is advised to draw a picture while reading the following
6026 description, since that will help to firm up the ideas.)
6027 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6028 and `\.{x20b}' have been mentioned in a user's program, where
6029 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6030 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6031 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6032 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6033 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6034 node and |r| to a subscript node. (Are you still following this? Use
6035 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6036 |type(q)| and |value(q)|; furthermore
6037 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6038 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6039 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6040 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6041 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6042 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6043 |name_type(qq)=mp_structured_root|, and
6044 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6045 an attribute node representing `\.{x[][]}', which has never yet
6046 occurred; its |type| field is |undefined|, and its |value| field is
6047 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6048 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6049 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6050 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6051 (Maybe colored lines will help untangle your picture.)
6052  Node |r| is a subscript node with |type| and |value|
6053 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6054 and |link(r)=r1| is another subscript node. To complete the picture,
6055 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6056 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6057 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6058 and we finish things off with three more nodes
6059 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6060 with a larger sheet of paper.) The value of variable \.{x20b}
6061 appears in node~|qqq2|, as you can well imagine.
6062
6063 If the example in the previous paragraph doesn't make things crystal
6064 clear, a glance at some of the simpler subroutines below will reveal how
6065 things work out in practice.
6066
6067 The only really unusual thing about these conventions is the use of
6068 collective subscript attributes. The idea is to avoid repeating a lot of
6069 type information when many elements of an array are identical macros
6070 (for which distinct values need not be stored) or when they don't have
6071 all of the possible attributes. Branches of the structure below collective
6072 subscript attributes do not carry actual values except for macro identifiers;
6073 branches of the structure below subscript nodes do not carry significant
6074 information in their collective subscript attributes.
6075
6076 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6077 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6078 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6079 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6080 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6081 @d attr_node_size 3 /* the number of words in an attribute node */
6082 @d subscr_node_size 3 /* the number of words in a subscript node */
6083 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6084
6085 @<Initialize table...@>=
6086 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6087
6088 @ Variables of type \&{pair} will have values that point to four-word
6089 nodes containing two numeric values. The first of these values has
6090 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6091 the |link| in the first points back to the node whose |value| points
6092 to this four-word node.
6093
6094 Variables of type \&{transform} are similar, but in this case their
6095 |value| points to a 12-word node containing six values, identified by
6096 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6097 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6098 Finally, variables of type \&{color} have 3~values in 6~words
6099 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6100
6101 When an entire structured variable is saved, the |root| indication
6102 is temporarily replaced by |saved_root|.
6103
6104 Some variables have no name; they just are used for temporary storage
6105 while expressions are being evaluated. We call them {\sl capsules}.
6106
6107 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6108 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6109 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6110 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6111 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6112 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6113 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6114 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6115 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6116 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6117 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6118 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6119 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6120 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6121 @#
6122 @d pair_node_size 4 /* the number of words in a pair node */
6123 @d transform_node_size 12 /* the number of words in a transform node */
6124 @d color_node_size 6 /* the number of words in a color node */
6125 @d cmykcolor_node_size 8 /* the number of words in a color node */
6126
6127 @<Glob...@>=
6128 small_number big_node_size[mp_pair_type+1];
6129 small_number sector0[mp_pair_type+1];
6130 small_number sector_offset[mp_black_part_sector+1];
6131
6132 @ The |sector0| array gives for each big node type, |name_type| values
6133 for its first subfield; the |sector_offset| array gives for each
6134 |name_type| value, the offset from the first subfield in words;
6135 and the |big_node_size| array gives the size in words for each type of
6136 big node.
6137
6138 @<Set init...@>=
6139 mp->big_node_size[mp_transform_type]=transform_node_size;
6140 mp->big_node_size[mp_pair_type]=pair_node_size;
6141 mp->big_node_size[mp_color_type]=color_node_size;
6142 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6143 mp->sector0[mp_transform_type]=mp_x_part_sector;
6144 mp->sector0[mp_pair_type]=mp_x_part_sector;
6145 mp->sector0[mp_color_type]=mp_red_part_sector;
6146 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6147 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6148   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6149 }
6150 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6151   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6152 }
6153 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6154   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6155 }
6156
6157 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6158 procedure call |init_big_node(p)| will allocate a pair or transform node
6159 for~|p|.  The individual parts of such nodes are initially of type
6160 |mp_independent|.
6161
6162 @c 
6163 void mp_init_big_node (MP mp,pointer p) {
6164   pointer q; /* the new node */
6165   small_number s; /* its size */
6166   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6167   do {  
6168     s=s-2; 
6169     @<Make variable |q+s| newly independent@>;
6170     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6171     link(q+s)=null;
6172   } while (s!=0);
6173   link(q)=p; value(p)=q;
6174 }
6175
6176 @ The |id_transform| function creates a capsule for the
6177 identity transformation.
6178
6179 @c 
6180 pointer mp_id_transform (MP mp) {
6181   pointer p,q,r; /* list manipulation registers */
6182   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6183   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6184   r=q+transform_node_size;
6185   do {  
6186     r=r-2;
6187     type(r)=mp_known; value(r)=0;
6188   } while (r!=q);
6189   value(xx_part_loc(q))=unity; 
6190   value(yy_part_loc(q))=unity;
6191   return p;
6192 }
6193
6194 @ Tokens are of type |tag_token| when they first appear, but they point
6195 to |null| until they are first used as the root of a variable.
6196 The following subroutine establishes the root node on such grand occasions.
6197
6198 @c 
6199 void mp_new_root (MP mp,pointer x) {
6200   pointer p; /* the new node */
6201   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6202   link(p)=x; equiv(x)=p;
6203 }
6204
6205 @ These conventions for variable representation are illustrated by the
6206 |print_variable_name| routine, which displays the full name of a
6207 variable given only a pointer to its two-word value packet.
6208
6209 @<Declarations@>=
6210 void mp_print_variable_name (MP mp, pointer p);
6211
6212 @ @c 
6213 void mp_print_variable_name (MP mp, pointer p) {
6214   pointer q; /* a token list that will name the variable's suffix */
6215   pointer r; /* temporary for token list creation */
6216   while ( name_type(p)>=mp_x_part_sector ) {
6217     @<Preface the output with a part specifier; |return| in the
6218       case of a capsule@>;
6219   }
6220   q=null;
6221   while ( name_type(p)>mp_saved_root ) {
6222     @<Ascend one level, pushing a token onto list |q|
6223      and replacing |p| by its parent@>;
6224   }
6225   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6226   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6227 @.SAVED@>
6228   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6229   mp_flush_token_list(mp, r);
6230 }
6231
6232 @ @<Ascend one level, pushing a token onto list |q|...@>=
6233
6234   if ( name_type(p)==mp_subscr ) { 
6235     r=mp_new_num_tok(mp, subscript(p));
6236     do {  
6237       p=link(p);
6238     } while (name_type(p)!=mp_attr);
6239   } else if ( name_type(p)==mp_structured_root ) {
6240     p=link(p); goto FOUND;
6241   } else { 
6242     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6243 @:this can't happen var}{\quad var@>
6244     r=mp_get_avail(mp); info(r)=attr_loc(p);
6245   }
6246   link(r)=q; q=r;
6247 FOUND:  
6248   p=parent(p);
6249 }
6250
6251 @ @<Preface the output with a part specifier...@>=
6252 { switch (name_type(p)) {
6253   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6254   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6255   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6256   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6257   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6258   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6259   case mp_red_part_sector: mp_print(mp, "red"); break;
6260   case mp_green_part_sector: mp_print(mp, "green"); break;
6261   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6262   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6263   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6264   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6265   case mp_black_part_sector: mp_print(mp, "black"); break;
6266   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6267   case mp_capsule: 
6268     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6269     break;
6270 @.CAPSULE@>
6271   } /* there are no other cases */
6272   mp_print(mp, "part "); 
6273   p=link(p-mp->sector_offset[name_type(p)]);
6274 }
6275
6276 @ The |interesting| function returns |true| if a given variable is not
6277 in a capsule, or if the user wants to trace capsules.
6278
6279 @c 
6280 boolean mp_interesting (MP mp,pointer p) {
6281   small_number t; /* a |name_type| */
6282   if ( mp->internal[mp_tracing_capsules]>0 ) {
6283     return true;
6284   } else { 
6285     t=name_type(p);
6286     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6287       t=name_type(link(p-mp->sector_offset[t]));
6288     return (t!=mp_capsule);
6289   }
6290 }
6291
6292 @ Now here is a subroutine that converts an unstructured type into an
6293 equivalent structured type, by inserting a |mp_structured| node that is
6294 capable of growing. This operation is done only when |name_type(p)=root|,
6295 |subscr|, or |attr|.
6296
6297 The procedure returns a pointer to the new node that has taken node~|p|'s
6298 place in the structure. Node~|p| itself does not move, nor are its
6299 |value| or |type| fields changed in any way.
6300
6301 @c 
6302 pointer mp_new_structure (MP mp,pointer p) {
6303   pointer q,r=0; /* list manipulation registers */
6304   switch (name_type(p)) {
6305   case mp_root: 
6306     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6307     break;
6308   case mp_subscr: 
6309     @<Link a new subscript node |r| in place of node |p|@>;
6310     break;
6311   case mp_attr: 
6312     @<Link a new attribute node |r| in place of node |p|@>;
6313     break;
6314   default: 
6315     mp_confusion(mp, "struct");
6316 @:this can't happen struct}{\quad struct@>
6317     break;
6318   }
6319   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6320   attr_head(r)=p; name_type(p)=mp_structured_root;
6321   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6322   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6323   attr_loc(q)=collective_subscript; 
6324   return r;
6325 };
6326
6327 @ @<Link a new subscript node |r| in place of node |p|@>=
6328
6329   q=p;
6330   do {  
6331     q=link(q);
6332   } while (name_type(q)!=mp_attr);
6333   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6334   do {  
6335     q=r; r=link(r);
6336   } while (r!=p);
6337   r=mp_get_node(mp, subscr_node_size);
6338   link(q)=r; subscript(r)=subscript(p);
6339 }
6340
6341 @ If the attribute is |collective_subscript|, there are two pointers to
6342 node~|p|, so we must change both of them.
6343
6344 @<Link a new attribute node |r| in place of node |p|@>=
6345
6346   q=parent(p); r=attr_head(q);
6347   do {  
6348     q=r; r=link(r);
6349   } while (r!=p);
6350   r=mp_get_node(mp, attr_node_size); link(q)=r;
6351   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6352   if ( attr_loc(p)==collective_subscript ) { 
6353     q=subscr_head_loc(parent(p));
6354     while ( link(q)!=p ) q=link(q);
6355     link(q)=r;
6356   }
6357 }
6358
6359 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6360 list of suffixes; it returns a pointer to the corresponding two-word
6361 value. For example, if |t| points to token \.x followed by a numeric
6362 token containing the value~7, |find_variable| finds where the value of
6363 \.{x7} is stored in memory. This may seem a simple task, and it
6364 usually is, except when \.{x7} has never been referenced before.
6365 Indeed, \.x may never have even been subscripted before; complexities
6366 arise with respect to updating the collective subscript information.
6367
6368 If a macro type is detected anywhere along path~|t|, or if the first
6369 item on |t| isn't a |tag_token|, the value |null| is returned.
6370 Otherwise |p| will be a non-null pointer to a node such that
6371 |undefined<type(p)<mp_structured|.
6372
6373 @d abort_find { return null; }
6374
6375 @c 
6376 pointer mp_find_variable (MP mp,pointer t) {
6377   pointer p,q,r,s; /* nodes in the ``value'' line */
6378   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6379   integer n; /* subscript or attribute */
6380   memory_word save_word; /* temporary storage for a word of |mem| */
6381 @^inner loop@>
6382   p=info(t); t=link(t);
6383   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6384   if ( equiv(p)==null ) mp_new_root(mp, p);
6385   p=equiv(p); pp=p;
6386   while ( t!=null ) { 
6387     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6388     if ( t<mp->hi_mem_min ) {
6389       @<Descend one level for the subscript |value(t)|@>
6390     } else {
6391       @<Descend one level for the attribute |info(t)|@>;
6392     }
6393     t=link(t);
6394   }
6395   if ( type(pp)>=mp_structured ) {
6396     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6397   }
6398   if ( type(p)==mp_structured ) p=attr_head(p);
6399   if ( type(p)==undefined ) { 
6400     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6401     type(p)=type(pp); value(p)=null;
6402   };
6403   return p;
6404 }
6405
6406 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6407 |pp|~stays in the collective line while |p|~goes through actual subscript
6408 values.
6409
6410 @<Make sure that both nodes |p| and |pp|...@>=
6411 if ( type(pp)!=mp_structured ) { 
6412   if ( type(pp)>mp_structured ) abort_find;
6413   ss=mp_new_structure(mp, pp);
6414   if ( p==pp ) p=ss;
6415   pp=ss;
6416 }; /* now |type(pp)=mp_structured| */
6417 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6418   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6419
6420 @ We want this part of the program to be reasonably fast, in case there are
6421 @^inner loop@>
6422 lots of subscripts at the same level of the data structure. Therefore
6423 we store an ``infinite'' value in the word that appears at the end of the
6424 subscript list, even though that word isn't part of a subscript node.
6425
6426 @<Descend one level for the subscript |value(t)|@>=
6427
6428   n=value(t);
6429   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6430   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6431   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6432   do {  
6433     r=s; s=link(s);
6434   } while (n>subscript(s));
6435   if ( n==subscript(s) ) {
6436     p=s;
6437   } else { 
6438     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6439     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6440   }
6441   mp->mem[subscript_loc(q)]=save_word;
6442 }
6443
6444 @ @<Descend one level for the attribute |info(t)|@>=
6445
6446   n=info(t);
6447   ss=attr_head(pp);
6448   do {  
6449     rr=ss; ss=link(ss);
6450   } while (n>attr_loc(ss));
6451   if ( n<attr_loc(ss) ) { 
6452     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6453     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6454     parent(qq)=pp; ss=qq;
6455   }
6456   if ( p==pp ) { 
6457     p=ss; pp=ss;
6458   } else { 
6459     pp=ss; s=attr_head(p);
6460     do {  
6461       r=s; s=link(s);
6462     } while (n>attr_loc(s));
6463     if ( n==attr_loc(s) ) {
6464       p=s;
6465     } else { 
6466       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6467       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6468       parent(q)=p; p=q;
6469     }
6470   }
6471 }
6472
6473 @ Variables lose their former values when they appear in a type declaration,
6474 or when they are defined to be macros or \&{let} equal to something else.
6475 A subroutine will be defined later that recycles the storage associated
6476 with any particular |type| or |value|; our goal now is to study a higher
6477 level process called |flush_variable|, which selectively frees parts of a
6478 variable structure.
6479
6480 This routine has some complexity because of examples such as
6481 `\hbox{\tt numeric x[]a[]b}'
6482 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6483 `\hbox{\tt vardef x[]a[]=...}'
6484 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6485 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6486 to handle such examples is to use recursion; so that's what we~do.
6487 @^recursion@>
6488
6489 Parameter |p| points to the root information of the variable;
6490 parameter |t| points to a list of one-word nodes that represent
6491 suffixes, with |info=collective_subscript| for subscripts.
6492
6493 @<Declarations@>=
6494 @<Declare subroutines for printing expressions@>
6495 @<Declare basic dependency-list subroutines@>
6496 @<Declare the recycling subroutines@>
6497 void mp_flush_cur_exp (MP mp,scaled v) ;
6498 @<Declare the procedure called |flush_below_variable|@>
6499
6500 @ @c 
6501 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6502   pointer q,r; /* list manipulation */
6503   halfword n; /* attribute to match */
6504   while ( t!=null ) { 
6505     if ( type(p)!=mp_structured ) return;
6506     n=info(t); t=link(t);
6507     if ( n==collective_subscript ) { 
6508       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6509       while ( name_type(q)==mp_subscr ){ 
6510         mp_flush_variable(mp, q,t,discard_suffixes);
6511         if ( t==null ) {
6512           if ( type(q)==mp_structured ) r=q;
6513           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6514         } else {
6515           r=q;
6516         }
6517         q=link(r);
6518       }
6519     }
6520     p=attr_head(p);
6521     do {  
6522       r=p; p=link(p);
6523     } while (attr_loc(p)<n);
6524     if ( attr_loc(p)!=n ) return;
6525   }
6526   if ( discard_suffixes ) {
6527     mp_flush_below_variable(mp, p);
6528   } else { 
6529     if ( type(p)==mp_structured ) p=attr_head(p);
6530     mp_recycle_value(mp, p);
6531   }
6532 }
6533
6534 @ The next procedure is simpler; it wipes out everything but |p| itself,
6535 which becomes undefined.
6536
6537 @<Declare the procedure called |flush_below_variable|@>=
6538 void mp_flush_below_variable (MP mp, pointer p);
6539
6540 @ @c
6541 void mp_flush_below_variable (MP mp,pointer p) {
6542    pointer q,r; /* list manipulation registers */
6543   if ( type(p)!=mp_structured ) {
6544     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6545   } else { 
6546     q=subscr_head(p);
6547     while ( name_type(q)==mp_subscr ) { 
6548       mp_flush_below_variable(mp, q); r=q; q=link(q);
6549       mp_free_node(mp, r,subscr_node_size);
6550     }
6551     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6552     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6553     else mp_free_node(mp, r,subscr_node_size);
6554     /* we assume that |subscr_node_size=attr_node_size| */
6555     do {  
6556       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6557     } while (q!=end_attr);
6558     type(p)=undefined;
6559   }
6560 }
6561
6562 @ Just before assigning a new value to a variable, we will recycle the
6563 old value and make the old value undefined. The |und_type| routine
6564 determines what type of undefined value should be given, based on
6565 the current type before recycling.
6566
6567 @c 
6568 small_number mp_und_type (MP mp,pointer p) { 
6569   switch (type(p)) {
6570   case undefined: case mp_vacuous:
6571     return undefined;
6572   case mp_boolean_type: case mp_unknown_boolean:
6573     return mp_unknown_boolean;
6574   case mp_string_type: case mp_unknown_string:
6575     return mp_unknown_string;
6576   case mp_pen_type: case mp_unknown_pen:
6577     return mp_unknown_pen;
6578   case mp_path_type: case mp_unknown_path:
6579     return mp_unknown_path;
6580   case mp_picture_type: case mp_unknown_picture:
6581     return mp_unknown_picture;
6582   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6583   case mp_pair_type: case mp_numeric_type: 
6584     return type(p);
6585   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6586     return mp_numeric_type;
6587   } /* there are no other cases */
6588   return 0;
6589 }
6590
6591 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6592 of a symbolic token. It must remove any variable structure or macro
6593 definition that is currently attached to that symbol. If the |saving|
6594 parameter is true, a subsidiary structure is saved instead of destroyed.
6595
6596 @c 
6597 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6598   pointer q; /* |equiv(p)| */
6599   q=equiv(p);
6600   switch (eq_type(p) % outer_tag)  {
6601   case defined_macro:
6602   case secondary_primary_macro:
6603   case tertiary_secondary_macro:
6604   case expression_tertiary_macro: 
6605     if ( ! saving ) mp_delete_mac_ref(mp, q);
6606     break;
6607   case tag_token:
6608     if ( q!=null ) {
6609       if ( saving ) {
6610         name_type(q)=mp_saved_root;
6611       } else { 
6612         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6613       }
6614     }
6615     break;
6616   default:
6617     break;
6618   }
6619   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6620 };
6621
6622 @* \[16] Saving and restoring equivalents.
6623 The nested structure given by \&{begingroup} and \&{endgroup}
6624 allows |eqtb| entries to be saved and restored, so that temporary changes
6625 can be made without difficulty.  When the user requests a current value to
6626 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6627 \&{endgroup} ultimately causes the old values to be removed from the save
6628 stack and put back in their former places.
6629
6630 The save stack is a linked list containing three kinds of entries,
6631 distinguished by their |info| fields. If |p| points to a saved item,
6632 then
6633
6634 \smallskip\hang
6635 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6636 such an item to the save stack and each \&{endgroup} cuts back the stack
6637 until the most recent such entry has been removed.
6638
6639 \smallskip\hang
6640 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6641 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6642 commands or suitable \&{interim} commands.
6643
6644 \smallskip\hang
6645 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6646 integer to be restored to internal parameter number~|q|. Such entries
6647 are generated by \&{interim} commands.
6648
6649 \smallskip\noindent
6650 The global variable |save_ptr| points to the top item on the save stack.
6651
6652 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6653 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6654 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6655   link((A))=mp->save_ptr; mp->save_ptr=(A);
6656   }
6657
6658 @<Glob...@>=
6659 pointer save_ptr; /* the most recently saved item */
6660
6661 @ @<Set init...@>=mp->save_ptr=null;
6662
6663 @ The |save_variable| routine is given a hash address |q|; it salts this
6664 address in the save stack, together with its current equivalent,
6665 then makes token~|q| behave as though it were brand new.
6666
6667 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6668 things from the stack when the program is not inside a group, so there's
6669 no point in wasting the space.
6670
6671 @c void mp_save_variable (MP mp,pointer q) {
6672   pointer p; /* temporary register */
6673   if ( mp->save_ptr!=null ){ 
6674     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6675     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6676   }
6677   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6678 }
6679
6680 @ Similarly, |save_internal| is given the location |q| of an internal
6681 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6682 third kind.
6683
6684 @c void mp_save_internal (MP mp,halfword q) {
6685   pointer p; /* new item for the save stack */
6686   if ( mp->save_ptr!=null ){ 
6687      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6688     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6689   }
6690 }
6691
6692 @ At the end of a group, the |unsave| routine restores all of the saved
6693 equivalents in reverse order. This routine will be called only when there
6694 is at least one boundary item on the save stack.
6695
6696 @c 
6697 void mp_unsave (MP mp) {
6698   pointer q; /* index to saved item */
6699   pointer p; /* temporary register */
6700   while ( info(mp->save_ptr)!=0 ) {
6701     q=info(mp->save_ptr);
6702     if ( q>hash_end ) {
6703       if ( mp->internal[mp_tracing_restores]>0 ) {
6704         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6705         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6706         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6707         mp_end_diagnostic(mp, false);
6708       }
6709       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6710     } else { 
6711       if ( mp->internal[mp_tracing_restores]>0 ) {
6712         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6713         mp_print_text(q); mp_print_char(mp, '}');
6714         mp_end_diagnostic(mp, false);
6715       }
6716       mp_clear_symbol(mp, q,false);
6717       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6718       if ( eq_type(q) % outer_tag==tag_token ) {
6719         p=equiv(q);
6720         if ( p!=null ) name_type(p)=mp_root;
6721       }
6722     }
6723     p=link(mp->save_ptr); 
6724     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6725   }
6726   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6727 }
6728
6729 @* \[17] Data structures for paths.
6730 When a \MP\ user specifies a path, \MP\ will create a list of knots
6731 and control points for the associated cubic spline curves. If the
6732 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6733 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6734 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6735 @:Bezier}{B\'ezier, Pierre Etienne@>
6736 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6737 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6738 for |0<=t<=1|.
6739
6740 There is a 8-word node for each knot $z_k$, containing one word of
6741 control information and six words for the |x| and |y| coordinates of
6742 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6743 |left_type| and |right_type| fields, which each occupy a quarter of
6744 the first word in the node; they specify properties of the curve as it
6745 enters and leaves the knot. There's also a halfword |link| field,
6746 which points to the following knot, and a final supplementary word (of
6747 which only a quarter is used).
6748
6749 If the path is a closed contour, knots 0 and |n| are identical;
6750 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6751 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6752 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6753 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6754
6755 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6756 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6757 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6758 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6759 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6760 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6761 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6762 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6763 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6764 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6765 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6766 @d left_coord(A)   mp->mem[(A)+2].sc
6767   /* coordinate of previous control point given |x_loc| or |y_loc| */
6768 @d right_coord(A)   mp->mem[(A)+4].sc
6769   /* coordinate of next control point given |x_loc| or |y_loc| */
6770 @d knot_node_size 8 /* number of words in a knot node */
6771
6772 @<Types...@>=
6773 enum mp_knot_type {
6774  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6775  mp_explicit, /* |left_type| or |right_type| when control points are known */
6776  mp_given, /* |left_type| or |right_type| when a direction is given */
6777  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6778  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6779  mp_end_cycle
6780 } ;
6781
6782 @ Before the B\'ezier control points have been calculated, the memory
6783 space they will ultimately occupy is taken up by information that can be
6784 used to compute them. There are four cases:
6785
6786 \yskip
6787 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6788 the knot in the same direction it entered; \MP\ will figure out a
6789 suitable direction.
6790
6791 \yskip
6792 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6793 knot in a direction depending on the angle at which it enters the next
6794 knot and on the curl parameter stored in |right_curl|.
6795
6796 \yskip
6797 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6798 knot in a nonzero direction stored as an |angle| in |right_given|.
6799
6800 \yskip
6801 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6802 point for leaving this knot has already been computed; it is in the
6803 |right_x| and |right_y| fields.
6804
6805 \yskip\noindent
6806 The rules for |left_type| are similar, but they refer to the curve entering
6807 the knot, and to \\{left} fields instead of \\{right} fields.
6808
6809 Non-|explicit| control points will be chosen based on ``tension'' parameters
6810 in the |left_tension| and |right_tension| fields. The
6811 `\&{atleast}' option is represented by negative tension values.
6812 @:at_least_}{\&{atleast} primitive@>
6813
6814 For example, the \MP\ path specification
6815 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6816   3 and 4..p},$$
6817 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6818 by the six knots
6819 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6820 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6821 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6822 \noalign{\yskip}
6823 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6824 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6825 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6826 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6827 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6828 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6829 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6830 Of course, this example is more complicated than anything a normal user
6831 would ever write.
6832
6833 These types must satisfy certain restrictions because of the form of \MP's
6834 path syntax:
6835 (i)~|open| type never appears in the same node together with |endpoint|,
6836 |given|, or |curl|.
6837 (ii)~The |right_type| of a node is |explicit| if and only if the
6838 |left_type| of the following node is |explicit|.
6839 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6840
6841 @d left_curl left_x /* curl information when entering this knot */
6842 @d left_given left_x /* given direction when entering this knot */
6843 @d left_tension left_y /* tension information when entering this knot */
6844 @d right_curl right_x /* curl information when leaving this knot */
6845 @d right_given right_x /* given direction when leaving this knot */
6846 @d right_tension right_y /* tension information when leaving this knot */
6847
6848 @ Knots can be user-supplied, or they can be created by program code,
6849 like the |split_cubic| function, or |copy_path|. The distinction is
6850 needed for the cleanup routine that runs after |split_cubic|, because
6851 it should only delete knots it has previously inserted, and never
6852 anything that was user-supplied. In order to be able to differentiate
6853 one knot from another, we will set |originator(p):=mp_metapost_user| when
6854 it appeared in the actual metapost program, and
6855 |originator(p):=mp_program_code| in all other cases.
6856
6857 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6858
6859 @<Types...@>=
6860 enum {
6861   mp_program_code=0, /* not created by a user */
6862   mp_metapost_user, /* created by a user */
6863 };
6864
6865 @ Here is a routine that prints a given knot list
6866 in symbolic form. It illustrates the conventions discussed above,
6867 and checks for anomalies that might arise while \MP\ is being debugged.
6868
6869 @<Declare subroutines for printing expressions@>=
6870 void mp_pr_path (MP mp,pointer h);
6871
6872 @ @c
6873 void mp_pr_path (MP mp,pointer h) {
6874   pointer p,q; /* for list traversal */
6875   p=h;
6876   do {  
6877     q=link(p);
6878     if ( (p==null)||(q==null) ) { 
6879       mp_print_nl(mp, "???"); return; /* this won't happen */
6880 @.???@>
6881     }
6882     @<Print information for adjacent knots |p| and |q|@>;
6883   DONE1:
6884     p=q;
6885     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6886       @<Print two dots, followed by |given| or |curl| if present@>;
6887     }
6888   } while (p!=h);
6889   if ( left_type(h)!=mp_endpoint ) 
6890     mp_print(mp, "cycle");
6891 }
6892
6893 @ @<Print information for adjacent knots...@>=
6894 mp_print_two(mp, x_coord(p),y_coord(p));
6895 switch (right_type(p)) {
6896 case mp_endpoint: 
6897   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6898 @.open?@>
6899   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6900   goto DONE1;
6901   break;
6902 case mp_explicit: 
6903   @<Print control points between |p| and |q|, then |goto done1|@>;
6904   break;
6905 case mp_open: 
6906   @<Print information for a curve that begins |open|@>;
6907   break;
6908 case mp_curl:
6909 case mp_given: 
6910   @<Print information for a curve that begins |curl| or |given|@>;
6911   break;
6912 default:
6913   mp_print(mp, "???"); /* can't happen */
6914 @.???@>
6915   break;
6916 }
6917 if ( left_type(q)<=mp_explicit ) {
6918   mp_print(mp, "..control?"); /* can't happen */
6919 @.control?@>
6920 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6921   @<Print tension between |p| and |q|@>;
6922 }
6923
6924 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6925 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6926
6927 @<Print two dots...@>=
6928
6929   mp_print_nl(mp, " ..");
6930   if ( left_type(p)==mp_given ) { 
6931     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6932     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6933     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6934   } else if ( left_type(p)==mp_curl ){ 
6935     mp_print(mp, "{curl "); 
6936     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6937   }
6938 }
6939
6940 @ @<Print tension between |p| and |q|@>=
6941
6942   mp_print(mp, "..tension ");
6943   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6944   mp_print_scaled(mp, abs(right_tension(p)));
6945   if ( right_tension(p)!=left_tension(q) ){ 
6946     mp_print(mp, " and ");
6947     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6948     mp_print_scaled(mp, abs(left_tension(q)));
6949   }
6950 }
6951
6952 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6953
6954   mp_print(mp, "..controls "); 
6955   mp_print_two(mp, right_x(p),right_y(p)); 
6956   mp_print(mp, " and ");
6957   if ( left_type(q)!=mp_explicit ) { 
6958     mp_print(mp, "??"); /* can't happen */
6959 @.??@>
6960   } else {
6961     mp_print_two(mp, left_x(q),left_y(q));
6962   }
6963   goto DONE1;
6964 }
6965
6966 @ @<Print information for a curve that begins |open|@>=
6967 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
6968   mp_print(mp, "{open?}"); /* can't happen */
6969 @.open?@>
6970 }
6971
6972 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6973 \MP's default curl is present.
6974
6975 The code here uses the fact that |left_curl==left_given| and
6976 |right_curl==right_given|.
6977
6978 @<Print information for a curve that begins |curl|...@>=
6979
6980   if ( left_type(p)==mp_open )  
6981     mp_print(mp, "??"); /* can't happen */
6982 @.??@>
6983   if ( right_type(p)==mp_curl ) { 
6984     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6985   } else { 
6986     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6987     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6988     mp_print_scaled(mp, mp->n_sin);
6989   }
6990   mp_print_char(mp, '}');
6991 }
6992
6993 @ It is convenient to have another version of |pr_path| that prints the path
6994 as a diagnostic message.
6995
6996 @<Declare subroutines for printing expressions@>=
6997 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
6998   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
6999 @.Path at line...@>
7000   mp_pr_path(mp, h);
7001   mp_end_diagnostic(mp, true);
7002 }
7003
7004 @ If we want to duplicate a knot node, we can say |copy_knot|:
7005
7006 @c 
7007 pointer mp_copy_knot (MP mp,pointer p) {
7008   pointer q; /* the copy */
7009   int k; /* runs through the words of a knot node */
7010   q=mp_get_node(mp, knot_node_size);
7011   for (k=0;k<knot_node_size;k++) {
7012     mp->mem[q+k]=mp->mem[p+k];
7013   }
7014   originator(q)=originator(p);
7015   return q;
7016 }
7017
7018 @ The |copy_path| routine makes a clone of a given path.
7019
7020 @c 
7021 pointer mp_copy_path (MP mp, pointer p) {
7022   pointer q,pp,qq; /* for list manipulation */
7023   q=mp_copy_knot(mp, p);
7024   qq=q; pp=link(p);
7025   while ( pp!=p ) { 
7026     link(qq)=mp_copy_knot(mp, pp);
7027     qq=link(qq);
7028     pp=link(pp);
7029   }
7030   link(qq)=q;
7031   return q;
7032 }
7033
7034
7035 @ Just before |ship_out|, knot lists are exported for printing.
7036
7037 The |gr_XXXX| macros are defined in |mppsout.h|.
7038
7039 @c 
7040 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7041   struct mp_knot *q; /* the copy */
7042   if (p==null)
7043      return NULL;
7044   q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7045   memset(q,0,sizeof (struct mp_knot));
7046   gr_left_type(q)  = left_type(p);
7047   gr_right_type(q) = right_type(p);
7048   gr_x_coord(q)    = x_coord(p);
7049   gr_y_coord(q)    = y_coord(p);
7050   gr_left_x(q)     = left_x(p);
7051   gr_left_y(q)     = left_y(p);
7052   gr_right_x(q)    = right_x(p);
7053   gr_right_y(q)    = right_y(p);
7054   gr_originator(q) = originator(p);
7055   return q;
7056 }
7057
7058 @ The |export_knot_list| routine therefore also makes a clone 
7059 of a given path.
7060
7061 @c 
7062 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7063   struct mp_knot *q, *qq; /* for list manipulation */
7064   pointer pp; /* for list manipulation */
7065   if (p==null)
7066      return NULL;
7067   q=mp_export_knot(mp, p);
7068   qq=q; pp=link(p);
7069   while ( pp!=p ) { 
7070     gr_next_knot(qq)=mp_export_knot(mp, pp);
7071     qq=gr_next_knot(qq);
7072     pp=link(pp);
7073   }
7074   gr_next_knot(qq)=q;
7075   return q;
7076 }
7077
7078
7079 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7080 returns a pointer to the first node of the copy, if the path is a cycle,
7081 but to the final node of a non-cyclic copy. The global
7082 variable |path_tail| will point to the final node of the original path;
7083 this trick makes it easier to implement `\&{doublepath}'.
7084
7085 All node types are assumed to be |endpoint| or |explicit| only.
7086
7087 @c 
7088 pointer mp_htap_ypoc (MP mp,pointer p) {
7089   pointer q,pp,qq,rr; /* for list manipulation */
7090   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7091   qq=q; pp=p;
7092   while (1) { 
7093     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7094     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7095     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7096     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7097     originator(qq)=originator(pp);
7098     if ( link(pp)==p ) { 
7099       link(q)=qq; mp->path_tail=pp; return q;
7100     }
7101     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7102   }
7103 }
7104
7105 @ @<Glob...@>=
7106 pointer path_tail; /* the node that links to the beginning of a path */
7107
7108 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7109 calling the following subroutine.
7110
7111 @<Declare the recycling subroutines@>=
7112 void mp_toss_knot_list (MP mp,pointer p) ;
7113
7114 @ @c
7115 void mp_toss_knot_list (MP mp,pointer p) {
7116   pointer q; /* the node being freed */
7117   pointer r; /* the next node */
7118   q=p;
7119   do {  
7120     r=link(q); 
7121     mp_free_node(mp, q,knot_node_size); q=r;
7122   } while (q!=p);
7123 }
7124
7125 @* \[18] Choosing control points.
7126 Now we must actually delve into one of \MP's more difficult routines,
7127 the |make_choices| procedure that chooses angles and control points for
7128 the splines of a curve when the user has not specified them explicitly.
7129 The parameter to |make_choices| points to a list of knots and
7130 path information, as described above.
7131
7132 A path decomposes into independent segments at ``breakpoint'' knots,
7133 which are knots whose left and right angles are both prespecified in
7134 some way (i.e., their |left_type| and |right_type| aren't both open).
7135
7136 @c 
7137 @<Declare the procedure called |solve_choices|@>;
7138 void mp_make_choices (MP mp,pointer knots) {
7139   pointer h; /* the first breakpoint */
7140   pointer p,q; /* consecutive breakpoints being processed */
7141   @<Other local variables for |make_choices|@>;
7142   check_arith; /* make sure that |arith_error=false| */
7143   if ( mp->internal[mp_tracing_choices]>0 )
7144     mp_print_path(mp, knots,", before choices",true);
7145   @<If consecutive knots are equal, join them explicitly@>;
7146   @<Find the first breakpoint, |h|, on the path;
7147     insert an artificial breakpoint if the path is an unbroken cycle@>;
7148   p=h;
7149   do {  
7150     @<Fill in the control points between |p| and the next breakpoint,
7151       then advance |p| to that breakpoint@>;
7152   } while (p!=h);
7153   if ( mp->internal[mp_tracing_choices]>0 )
7154     mp_print_path(mp, knots,", after choices",true);
7155   if ( mp->arith_error ) {
7156     @<Report an unexpected problem during the choice-making@>;
7157   }
7158 }
7159
7160 @ @<Report an unexpected problem during the choice...@>=
7161
7162   print_err("Some number got too big");
7163 @.Some number got too big@>
7164   help2("The path that I just computed is out of range.")
7165        ("So it will probably look funny. Proceed, for a laugh.");
7166   mp_put_get_error(mp); mp->arith_error=false;
7167 }
7168
7169 @ Two knots in a row with the same coordinates will always be joined
7170 by an explicit ``curve'' whose control points are identical with the
7171 knots.
7172
7173 @<If consecutive knots are equal, join them explicitly@>=
7174 p=knots;
7175 do {  
7176   q=link(p);
7177   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7178     right_type(p)=mp_explicit;
7179     if ( left_type(p)==mp_open ) { 
7180       left_type(p)=mp_curl; left_curl(p)=unity;
7181     }
7182     left_type(q)=mp_explicit;
7183     if ( right_type(q)==mp_open ) { 
7184       right_type(q)=mp_curl; right_curl(q)=unity;
7185     }
7186     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7187     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7188   }
7189   p=q;
7190 } while (p!=knots)
7191
7192 @ If there are no breakpoints, it is necessary to compute the direction
7193 angles around an entire cycle. In this case the |left_type| of the first
7194 node is temporarily changed to |end_cycle|.
7195
7196 @<Find the first breakpoint, |h|, on the path...@>=
7197 h=knots;
7198 while (1) { 
7199   if ( left_type(h)!=mp_open ) break;
7200   if ( right_type(h)!=mp_open ) break;
7201   h=link(h);
7202   if ( h==knots ) { 
7203     left_type(h)=mp_end_cycle; break;
7204   }
7205 }
7206
7207 @ If |right_type(p)<given| and |q=link(p)|, we must have
7208 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7209
7210 @<Fill in the control points between |p| and the next breakpoint...@>=
7211 q=link(p);
7212 if ( right_type(p)>=mp_given ) { 
7213   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7214   @<Fill in the control information between
7215     consecutive breakpoints |p| and |q|@>;
7216 } else if ( right_type(p)==mp_endpoint ) {
7217   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7218 }
7219 p=q
7220
7221 @ This step makes it possible to transform an explicitly computed path without
7222 checking the |left_type| and |right_type| fields.
7223
7224 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7225
7226   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7227   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7228 }
7229
7230 @ Before we can go further into the way choices are made, we need to
7231 consider the underlying theory. The basic ideas implemented in |make_choices|
7232 are due to John Hobby, who introduced the notion of ``mock curvature''
7233 @^Hobby, John Douglas@>
7234 at a knot. Angles are chosen so that they preserve mock curvature when
7235 a knot is passed, and this has been found to produce excellent results.
7236
7237 It is convenient to introduce some notations that simplify the necessary
7238 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7239 between knots |k| and |k+1|; and let
7240 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7241 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7242 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7243 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7244 $$\eqalign{z_k^+&=z_k+
7245   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7246  z\k^-&=z\k-
7247   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7248 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7249 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7250 corresponding ``offset angles.'' These angles satisfy the condition
7251 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7252 whenever the curve leaves an intermediate knot~|k| in the direction that
7253 it enters.
7254
7255 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7256 the curve at its beginning and ending points. This means that
7257 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7258 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7259 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7260 z\k^-,z\k^{\phantom+};t)$
7261 has curvature
7262 @^curvature@>
7263 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7264 \qquad{\rm and}\qquad
7265 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7266 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7267 @^mock curvature@>
7268 approximation to this true curvature that arises in the limit for
7269 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7270 The standard velocity function satisfies
7271 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7272 hence the mock curvatures are respectively
7273 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7274 \qquad{\rm and}\qquad
7275 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7276
7277 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7278 determines $\phi_k$ when $\theta_k$ is known, so the task of
7279 angle selection is essentially to choose appropriate values for each
7280 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7281 from $(**)$, we obtain a system of linear equations of the form
7282 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7283 where
7284 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7285 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7286 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7287 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7288 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7289 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7290 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7291 hence they have a unique solution. Moreover, in most cases the tensions
7292 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7293 solution numerically stable, and there is an exponential damping
7294 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7295 a factor of~$O(2^{-j})$.
7296
7297 @ However, we still must consider the angles at the starting and ending
7298 knots of a non-cyclic path. These angles might be given explicitly, or
7299 they might be specified implicitly in terms of an amount of ``curl.''
7300
7301 Let's assume that angles need to be determined for a non-cyclic path
7302 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7303 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7304 have been given for $0<k<n$, and it will be convenient to introduce
7305 equations of the same form for $k=0$ and $k=n$, where
7306 $$A_0=B_0=C_n=D_n=0.$$
7307 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7308 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7309 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7310 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7311 mock curvature at $z_1$; i.e.,
7312 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7313 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7314 This equation simplifies to
7315 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7316  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7317  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7318 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7319 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7320 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7321 hence the linear equations remain nonsingular.
7322
7323 Similar considerations apply at the right end, when the final angle $\phi_n$
7324 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7325 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7326 or we have
7327 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7328 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7329   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7330
7331 When |make_choices| chooses angles, it must compute the coefficients of
7332 these linear equations, then solve the equations. To compute the coefficients,
7333 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7334 When the equations are solved, the chosen directions $\theta_k$ are put
7335 back into the form of control points by essentially computing sines and
7336 cosines.
7337
7338 @ OK, we are ready to make the hard choices of |make_choices|.
7339 Most of the work is relegated to an auxiliary procedure
7340 called |solve_choices|, which has been introduced to keep
7341 |make_choices| from being extremely long.
7342
7343 @<Fill in the control information between...@>=
7344 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7345   set $n$ to the length of the path@>;
7346 @<Remove |open| types at the breakpoints@>;
7347 mp_solve_choices(mp, p,q,n)
7348
7349 @ It's convenient to precompute quantities that will be needed several
7350 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7351 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7352 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7353 and $z\k-z_k$ will be stored in |psi[k]|.
7354
7355 @<Glob...@>=
7356 int path_size; /* maximum number of knots between breakpoints of a path */
7357 scaled *delta_x;
7358 scaled *delta_y;
7359 scaled *delta; /* knot differences */
7360 angle  *psi; /* turning angles */
7361
7362 @ @<Allocate or initialize ...@>=
7363 mp->delta_x = NULL;
7364 mp->delta_y = NULL;
7365 mp->delta = NULL;
7366 mp->psi = NULL;
7367
7368 @ @<Dealloc variables@>=
7369 xfree(mp->delta_x);
7370 xfree(mp->delta_y);
7371 xfree(mp->delta);
7372 xfree(mp->psi);
7373
7374 @ @<Other local variables for |make_choices|@>=
7375   int k,n; /* current and final knot numbers */
7376   pointer s,t; /* registers for list traversal */
7377   scaled delx,dely; /* directions where |open| meets |explicit| */
7378   fraction sine,cosine; /* trig functions of various angles */
7379
7380 @ @<Calculate the turning angles...@>=
7381 {
7382 RESTART:
7383   k=0; s=p; n=mp->path_size;
7384   do {  
7385     t=link(s);
7386     mp->delta_x[k]=x_coord(t)-x_coord(s);
7387     mp->delta_y[k]=y_coord(t)-y_coord(s);
7388     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7389     if ( k>0 ) { 
7390       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7391       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7392       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7393         mp_take_fraction(mp, mp->delta_y[k],sine),
7394         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7395           mp_take_fraction(mp, mp->delta_x[k],sine));
7396     }
7397     incr(k); s=t;
7398     if ( k==mp->path_size ) {
7399       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7400       goto RESTART; /* retry, loop size has changed */
7401     }
7402     if ( s==q ) n=k;
7403   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7404   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7405 }
7406
7407 @ When we get to this point of the code, |right_type(p)| is either
7408 |given| or |curl| or |open|. If it is |open|, we must have
7409 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7410 case, the |open| type is converted to |given|; however, if the
7411 velocity coming into this knot is zero, the |open| type is
7412 converted to a |curl|, since we don't know the incoming direction.
7413
7414 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7415 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7416
7417 @<Remove |open| types at the breakpoints@>=
7418 if ( left_type(q)==mp_open ) { 
7419   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7420   if ( (delx==0)&&(dely==0) ) { 
7421     left_type(q)=mp_curl; left_curl(q)=unity;
7422   } else { 
7423     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7424   }
7425 }
7426 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7427   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7428   if ( (delx==0)&&(dely==0) ) { 
7429     right_type(p)=mp_curl; right_curl(p)=unity;
7430   } else { 
7431     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7432   }
7433 }
7434
7435 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7436 and exactly one of the breakpoints involves a curl. The simplest case occurs
7437 when |n=1| and there is a curl at both breakpoints; then we simply draw
7438 a straight line.
7439
7440 But before coding up the simple cases, we might as well face the general case,
7441 since we must deal with it sooner or later, and since the general case
7442 is likely to give some insight into the way simple cases can be handled best.
7443
7444 When there is no cycle, the linear equations to be solved form a tridiagonal
7445 system, and we can apply the standard technique of Gaussian elimination
7446 to convert that system to a sequence of equations of the form
7447 $$\theta_0+u_0\theta_1=v_0,\quad
7448 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7449 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7450 \theta_n=v_n.$$
7451 It is possible to do this diagonalization while generating the equations.
7452 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7453 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7454
7455 The procedure is slightly more complex when there is a cycle, but the
7456 basic idea will be nearly the same. In the cyclic case the right-hand
7457 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7458 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7459 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7460 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7461 eliminate the $w$'s from the system, after which the solution can be
7462 obtained as before.
7463
7464 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7465 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7466 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7467 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7468
7469 @<Glob...@>=
7470 angle *theta; /* values of $\theta_k$ */
7471 fraction *uu; /* values of $u_k$ */
7472 angle *vv; /* values of $v_k$ */
7473 fraction *ww; /* values of $w_k$ */
7474
7475 @ @<Allocate or initialize ...@>=
7476 mp->theta = NULL;
7477 mp->uu = NULL;
7478 mp->vv = NULL;
7479 mp->ww = NULL;
7480
7481 @ @<Dealloc variables@>=
7482 xfree(mp->theta);
7483 xfree(mp->uu);
7484 xfree(mp->vv);
7485 xfree(mp->ww);
7486
7487 @ @<Declare |mp_reallocate| functions@>=
7488 void mp_reallocate_paths (MP mp, int l);
7489
7490 @ @c
7491 void mp_reallocate_paths (MP mp, int l) {
7492   XREALLOC (mp->delta_x, l, scaled);
7493   XREALLOC (mp->delta_y, l, scaled);
7494   XREALLOC (mp->delta,   l, scaled);
7495   XREALLOC (mp->psi,     l, angle);
7496   XREALLOC (mp->theta,   l, angle);
7497   XREALLOC (mp->uu,      l, fraction);
7498   XREALLOC (mp->vv,      l, angle);
7499   XREALLOC (mp->ww,      l, fraction);
7500   mp->path_size = l;
7501 }
7502
7503 @ Our immediate problem is to get the ball rolling by setting up the
7504 first equation or by realizing that no equations are needed, and to fit
7505 this initialization into a framework suitable for the overall computation.
7506
7507 @<Declare the procedure called |solve_choices|@>=
7508 @<Declare subroutines needed by |solve_choices|@>;
7509 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7510   int k; /* current knot number */
7511   pointer r,s,t; /* registers for list traversal */
7512   @<Other local variables for |solve_choices|@>;
7513   k=0; s=p; r=0;
7514   while (1) { 
7515     t=link(s);
7516     if ( k==0 ) {
7517       @<Get the linear equations started; or |return|
7518         with the control points in place, if linear equations
7519         needn't be solved@>
7520     } else  { 
7521       switch (left_type(s)) {
7522       case mp_end_cycle: case mp_open:
7523         @<Set up equation to match mock curvatures
7524           at $z_k$; then |goto found| with $\theta_n$
7525           adjusted to equal $\theta_0$, if a cycle has ended@>;
7526         break;
7527       case mp_curl:
7528         @<Set up equation for a curl at $\theta_n$
7529           and |goto found|@>;
7530         break;
7531       case mp_given:
7532         @<Calculate the given value of $\theta_n$
7533           and |goto found|@>;
7534         break;
7535       } /* there are no other cases */
7536     }
7537     r=s; s=t; incr(k);
7538   }
7539 FOUND:
7540   @<Finish choosing angles and assigning control points@>;
7541 }
7542
7543 @ On the first time through the loop, we have |k=0| and |r| is not yet
7544 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7545
7546 @<Get the linear equations started...@>=
7547 switch (right_type(s)) {
7548 case mp_given: 
7549   if ( left_type(t)==mp_given ) {
7550     @<Reduce to simple case of two givens  and |return|@>
7551   } else {
7552     @<Set up the equation for a given value of $\theta_0$@>;
7553   }
7554   break;
7555 case mp_curl: 
7556   if ( left_type(t)==mp_curl ) {
7557     @<Reduce to simple case of straight line and |return|@>
7558   } else {
7559     @<Set up the equation for a curl at $\theta_0$@>;
7560   }
7561   break;
7562 case mp_open: 
7563   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7564   /* this begins a cycle */
7565   break;
7566 } /* there are no other cases */
7567
7568 @ The general equation that specifies equality of mock curvature at $z_k$ is
7569 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7570 as derived above. We want to combine this with the already-derived equation
7571 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7572 a new equation
7573 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7574 equation
7575 $$(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}
7576     -A_kw_{k-1}\theta_0$$
7577 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7578 fixed-point arithmetic, avoiding the chance of overflow while retaining
7579 suitable precision.
7580
7581 The calculations will be performed in several registers that
7582 provide temporary storage for intermediate quantities.
7583
7584 @<Other local variables for |solve_choices|@>=
7585 fraction aa,bb,cc,ff,acc; /* temporary registers */
7586 scaled dd,ee; /* likewise, but |scaled| */
7587 scaled lt,rt; /* tension values */
7588
7589 @ @<Set up equation to match mock curvatures...@>=
7590 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7591     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7592     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7593   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7594   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7595   @<Calculate the values of $v_k$ and $w_k$@>;
7596   if ( left_type(s)==mp_end_cycle ) {
7597     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7598   }
7599 }
7600
7601 @ Since tension values are never less than 3/4, the values |aa| and
7602 |bb| computed here are never more than 4/5.
7603
7604 @<Calculate the values $\\{aa}=...@>=
7605 if ( abs(right_tension(r))==unity) { 
7606   aa=fraction_half; dd=2*mp->delta[k];
7607 } else { 
7608   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7609   dd=mp_take_fraction(mp, mp->delta[k],
7610     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7611 }
7612 if ( abs(left_tension(t))==unity ){ 
7613   bb=fraction_half; ee=2*mp->delta[k-1];
7614 } else { 
7615   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7616   ee=mp_take_fraction(mp, mp->delta[k-1],
7617     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7618 }
7619 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7620
7621 @ The ratio to be calculated in this step can be written in the form
7622 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7623   \\{cc}\cdot\\{dd},$$
7624 because of the quantities just calculated. The values of |dd| and |ee|
7625 will not be needed after this step has been performed.
7626
7627 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7628 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7629 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7630   if ( lt<rt ) { 
7631     ff=mp_make_fraction(mp, lt,rt);
7632     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7633     dd=mp_take_fraction(mp, dd,ff);
7634   } else { 
7635     ff=mp_make_fraction(mp, rt,lt);
7636     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7637     ee=mp_take_fraction(mp, ee,ff);
7638   }
7639 }
7640 ff=mp_make_fraction(mp, ee,ee+dd)
7641
7642 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7643 equation was specified by a curl. In that case we must use a special
7644 method of computation to prevent overflow.
7645
7646 Fortunately, the calculations turn out to be even simpler in this ``hard''
7647 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7648 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7649
7650 @<Calculate the values of $v_k$ and $w_k$@>=
7651 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7652 if ( right_type(r)==mp_curl ) { 
7653   mp->ww[k]=0;
7654   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7655 } else { 
7656   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7657     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7658   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7659   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7660   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7661   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7662   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7663 }
7664
7665 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7666 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7667 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7668 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7669 were no cycle.
7670
7671 The idea in the following code is to observe that
7672 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7673 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7674   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7675 so we can solve for $\theta_n=\theta_0$.
7676
7677 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7678
7679 aa=0; bb=fraction_one; /* we have |k=n| */
7680 do {  decr(k);
7681 if ( k==0 ) k=n;
7682   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7683   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7684 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7685 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7686 mp->theta[n]=aa; mp->vv[0]=aa;
7687 for (k=1;k<=n-1;k++) {
7688   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7689 }
7690 goto FOUND;
7691 }
7692
7693 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7694   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7695
7696 @<Calculate the given value of $\theta_n$...@>=
7697
7698   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7699   reduce_angle(mp->theta[n]);
7700   goto FOUND;
7701 }
7702
7703 @ @<Set up the equation for a given value of $\theta_0$@>=
7704
7705   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7706   reduce_angle(mp->vv[0]);
7707   mp->uu[0]=0; mp->ww[0]=0;
7708 }
7709
7710 @ @<Set up the equation for a curl at $\theta_0$@>=
7711 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7712   if ( (rt==unity)&&(lt==unity) )
7713     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7714   else 
7715     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7716   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7717 }
7718
7719 @ @<Set up equation for a curl at $\theta_n$...@>=
7720 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7721   if ( (rt==unity)&&(lt==unity) )
7722     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7723   else 
7724     ff=mp_curl_ratio(mp, cc,lt,rt);
7725   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7726     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7727   goto FOUND;
7728 }
7729
7730 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7731 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7732 a somewhat tedious program to calculate
7733 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7734   \alpha^3\gamma+(3-\beta)\beta^2},$$
7735 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7736 is necessary only if the curl and tension are both large.)
7737 The values of $\alpha$ and $\beta$ will be at most~4/3.
7738
7739 @<Declare subroutines needed by |solve_choices|@>=
7740 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7741                         scaled b_tension) {
7742   fraction alpha,beta,num,denom,ff; /* registers */
7743   alpha=mp_make_fraction(mp, unity,a_tension);
7744   beta=mp_make_fraction(mp, unity,b_tension);
7745   if ( alpha<=beta ) {
7746     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7747     gamma=mp_take_fraction(mp, gamma,ff);
7748     beta=beta / 010000; /* convert |fraction| to |scaled| */
7749     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7750     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7751   } else { 
7752     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7753     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7754     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7755       /* $1365\approx 2^{12}/3$ */
7756     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7757   }
7758   if ( num>=denom+denom+denom+denom ) return fraction_four;
7759   else return mp_make_fraction(mp, num,denom);
7760 }
7761
7762 @ We're in the home stretch now.
7763
7764 @<Finish choosing angles and assigning control points@>=
7765 for (k=n-1;k>=0;k--) {
7766   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7767 }
7768 s=p; k=0;
7769 do {  
7770   t=link(s);
7771   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7772   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7773   mp_set_controls(mp, s,t,k);
7774   incr(k); s=t;
7775 } while (k!=n)
7776
7777 @ The |set_controls| routine actually puts the control points into
7778 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7779 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7780 $\cos\phi$ needed in this calculation.
7781
7782 @<Glob...@>=
7783 fraction st;
7784 fraction ct;
7785 fraction sf;
7786 fraction cf; /* sines and cosines */
7787
7788 @ @<Declare subroutines needed by |solve_choices|@>=
7789 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7790   fraction rr,ss; /* velocities, divided by thrice the tension */
7791   scaled lt,rt; /* tensions */
7792   fraction sine; /* $\sin(\theta+\phi)$ */
7793   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7794   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7795   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7796   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7797     @<Decrease the velocities,
7798       if necessary, to stay inside the bounding triangle@>;
7799   }
7800   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7801                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7802                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7803   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7804                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7805                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7806   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7807                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7808                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7809   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7810                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7811                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7812   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7813 }
7814
7815 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7816 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7817 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7818 there is no ``bounding triangle.''
7819 @:at_least_}{\&{atleast} primitive@>
7820
7821 @<Decrease the velocities, if necessary...@>=
7822 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7823   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7824                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7825   if ( sine>0 ) {
7826     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7827     if ( right_tension(p)<0 )
7828      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7829       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7830     if ( left_tension(q)<0 )
7831      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7832       ss=mp_make_fraction(mp, abs(mp->st),sine);
7833   }
7834 }
7835
7836 @ Only the simple cases remain to be handled.
7837
7838 @<Reduce to simple case of two givens and |return|@>=
7839
7840   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7841   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7842   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7843   mp_set_controls(mp, p,q,0); return;
7844 }
7845
7846 @ @<Reduce to simple case of straight line and |return|@>=
7847
7848   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7849   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7850   if ( rt==unity ) {
7851     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7852     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7853     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7854     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7855   } else { 
7856     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7857     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7858     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7859   }
7860   if ( lt==unity ) {
7861     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7862     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7863     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7864     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7865   } else  { 
7866     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7867     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7868     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7869   }
7870   return;
7871 }
7872
7873 @* \[19] Measuring paths.
7874 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7875 allow the user to measure the bounding box of anything that can go into a
7876 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7877 by just finding the bounding box of the knots and the control points. We
7878 need a more accurate version of the bounding box, but we can still use the
7879 easy estimate to save time by focusing on the interesting parts of the path.
7880
7881 @ Computing an accurate bounding box involves a theme that will come up again
7882 and again. Given a Bernshte{\u\i}n polynomial
7883 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7884 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7885 we can conveniently bisect its range as follows:
7886
7887 \smallskip
7888 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7889
7890 \smallskip
7891 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7892 |0<=k<n-j|, for |0<=j<n|.
7893
7894 \smallskip\noindent
7895 Then
7896 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7897  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7898 This formula gives us the coefficients of polynomials to use over the ranges
7899 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7900
7901 @ Now here's a subroutine that's handy for all sorts of path computations:
7902 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7903 returns the unique |fraction| value |t| between 0 and~1 at which
7904 $B(a,b,c;t)$ changes from positive to negative, or returns
7905 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7906 is already negative at |t=0|), |crossing_point| returns the value zero.
7907
7908 @d no_crossing {  return (fraction_one+1); }
7909 @d one_crossing { return fraction_one; }
7910 @d zero_crossing { return 0; }
7911 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7912
7913 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7914   integer d; /* recursive counter */
7915   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7916   if ( a<0 ) zero_crossing;
7917   if ( c>=0 ) { 
7918     if ( b>=0 ) {
7919       if ( c>0 ) { no_crossing; }
7920       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7921       else { one_crossing; } 
7922     }
7923     if ( a==0 ) zero_crossing;
7924   } else if ( a==0 ) {
7925     if ( b<=0 ) zero_crossing;
7926   }
7927   @<Use bisection to find the crossing point, if one exists@>;
7928 }
7929
7930 @ The general bisection method is quite simple when $n=2$, hence
7931 |crossing_point| does not take much time. At each stage in the
7932 recursion we have a subinterval defined by |l| and~|j| such that
7933 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7934 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7935
7936 It is convenient for purposes of calculation to combine the values
7937 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7938 of bisection then corresponds simply to doubling $d$ and possibly
7939 adding~1. Furthermore it proves to be convenient to modify
7940 our previous conventions for bisection slightly, maintaining the
7941 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7942 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7943 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7944
7945 The following code maintains the invariant relations
7946 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7947 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7948 it has been constructed in such a way that no arithmetic overflow
7949 will occur if the inputs satisfy
7950 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7951
7952 @<Use bisection to find the crossing point...@>=
7953 d=1; x0=a; x1=a-b; x2=b-c;
7954 do {  
7955   x=half(x1+x2);
7956   if ( x1-x0>x0 ) { 
7957     x2=x; x0+=x0; d+=d;  
7958   } else { 
7959     xx=x1+x-x0;
7960     if ( xx>x0 ) { 
7961       x2=x; x0+=x0; d+=d;
7962     }  else { 
7963       x0=x0-xx;
7964       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7965       x1=x; d=d+d+1;
7966     }
7967   }
7968 } while (d<fraction_one);
7969 return (d-fraction_one)
7970
7971 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7972 a cubic corresponding to the |fraction| value~|t|.
7973
7974 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7975 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7976
7977 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
7978
7979 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7980   scaled x1,x2,x3; /* intermediate values */
7981   x1=t_of_the_way(knot_coord(p),right_coord(p));
7982   x2=t_of_the_way(right_coord(p),left_coord(q));
7983   x3=t_of_the_way(left_coord(q),knot_coord(q));
7984   x1=t_of_the_way(x1,x2);
7985   x2=t_of_the_way(x2,x3);
7986   return t_of_the_way(x1,x2);
7987 }
7988
7989 @ The actual bounding box information is stored in global variables.
7990 Since it is convenient to address the $x$ and $y$ information
7991 separately, we define arrays indexed by |x_code..y_code| and use
7992 macros to give them more convenient names.
7993
7994 @<Types...@>=
7995 enum mp_bb_code  {
7996   mp_x_code=0, /* index for |minx| and |maxx| */
7997   mp_y_code /* index for |miny| and |maxy| */
7998 } ;
7999
8000
8001 @d minx mp->bbmin[mp_x_code]
8002 @d maxx mp->bbmax[mp_x_code]
8003 @d miny mp->bbmin[mp_y_code]
8004 @d maxy mp->bbmax[mp_y_code]
8005
8006 @<Glob...@>=
8007 scaled bbmin[mp_y_code+1];
8008 scaled bbmax[mp_y_code+1]; 
8009 /* the result of procedures that compute bounding box information */
8010
8011 @ Now we're ready for the key part of the bounding box computation.
8012 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8013 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8014     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8015 $$
8016 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8017 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8018 The |c| parameter is |x_code| or |y_code|.
8019
8020 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8021   boolean wavy; /* whether we need to look for extremes */
8022   scaled del1,del2,del3,del,dmax; /* proportional to the control
8023      points of a quadratic derived from a cubic */
8024   fraction t,tt; /* where a quadratic crosses zero */
8025   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8026   x=knot_coord(q);
8027   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8028   @<Check the control points against the bounding box and set |wavy:=true|
8029     if any of them lie outside@>;
8030   if ( wavy ) {
8031     del1=right_coord(p)-knot_coord(p);
8032     del2=left_coord(q)-right_coord(p);
8033     del3=knot_coord(q)-left_coord(q);
8034     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8035       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8036     if ( del<0 ) {
8037       negate(del1); negate(del2); negate(del3);
8038     };
8039     t=mp_crossing_point(mp, del1,del2,del3);
8040     if ( t<fraction_one ) {
8041       @<Test the extremes of the cubic against the bounding box@>;
8042     }
8043   }
8044 }
8045
8046 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8047 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8048 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8049
8050 @ @<Check the control points against the bounding box and set...@>=
8051 wavy=true;
8052 if ( mp->bbmin[c]<=right_coord(p) )
8053   if ( right_coord(p)<=mp->bbmax[c] )
8054     if ( mp->bbmin[c]<=left_coord(q) )
8055       if ( left_coord(q)<=mp->bbmax[c] )
8056         wavy=false
8057
8058 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8059 section. We just set |del=0| in that case.
8060
8061 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8062 if ( del1!=0 ) del=del1;
8063 else if ( del2!=0 ) del=del2;
8064 else del=del3;
8065 if ( del!=0 ) {
8066   dmax=abs(del1);
8067   if ( abs(del2)>dmax ) dmax=abs(del2);
8068   if ( abs(del3)>dmax ) dmax=abs(del3);
8069   while ( dmax<fraction_half ) {
8070     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8071   }
8072 }
8073
8074 @ Since |crossing_point| has tried to choose |t| so that
8075 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8076 slope, the value of |del2| computed below should not be positive.
8077 But rounding error could make it slightly positive in which case we
8078 must cut it to zero to avoid confusion.
8079
8080 @<Test the extremes of the cubic against the bounding box@>=
8081
8082   x=mp_eval_cubic(mp, p,q,t);
8083   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8084   del2=t_of_the_way(del2,del3);
8085     /* now |0,del2,del3| represent the derivative on the remaining interval */
8086   if ( del2>0 ) del2=0;
8087   tt=mp_crossing_point(mp, 0,-del2,-del3);
8088   if ( tt<fraction_one ) {
8089     @<Test the second extreme against the bounding box@>;
8090   }
8091 }
8092
8093 @ @<Test the second extreme against the bounding box@>=
8094 {
8095    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8096   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8097 }
8098
8099 @ Finding the bounding box of a path is basically a matter of applying
8100 |bound_cubic| twice for each pair of adjacent knots.
8101
8102 @c void mp_path_bbox (MP mp,pointer h) {
8103   pointer p,q; /* a pair of adjacent knots */
8104    minx=x_coord(h); miny=y_coord(h);
8105   maxx=minx; maxy=miny;
8106   p=h;
8107   do {  
8108     if ( right_type(p)==mp_endpoint ) return;
8109     q=link(p);
8110     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8111     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8112     p=q;
8113   } while (p!=h);
8114 }
8115
8116 @ Another important way to measure a path is to find its arc length.  This
8117 is best done by using the general bisection algorithm to subdivide the path
8118 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8119 by simple means.
8120
8121 Since the arc length is the integral with respect to time of the magnitude of
8122 the velocity, it is natural to use Simpson's rule for the approximation.
8123 @^Simpson's rule@>
8124 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8125 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8126 for the arc length of a path of length~1.  For a cubic spline
8127 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8128 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8129 approximation is
8130 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8131 where
8132 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8133 is the result of the bisection algorithm.
8134
8135 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8136 This could be done via the theoretical error bound for Simpson's rule,
8137 @^Simpson's rule@>
8138 but this is impractical because it requires an estimate of the fourth
8139 derivative of the quantity being integrated.  It is much easier to just perform
8140 a bisection step and see how much the arc length estimate changes.  Since the
8141 error for Simpson's rule is proportional to the fourth power of the sample
8142 spacing, the remaining error is typically about $1\over16$ of the amount of
8143 the change.  We say ``typically'' because the error has a pseudo-random behavior
8144 that could cause the two estimates to agree when each contain large errors.
8145
8146 To protect against disasters such as undetected cusps, the bisection process
8147 should always continue until all the $dz_i$ vectors belong to a single
8148 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8149 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8150 If such a spline happens to produce an erroneous arc length estimate that
8151 is little changed by bisection, the amount of the error is likely to be fairly
8152 small.  We will try to arrange things so that freak accidents of this type do
8153 not destroy the inverse relationship between the \&{arclength} and
8154 \&{arctime} operations.
8155 @:arclength_}{\&{arclength} primitive@>
8156 @:arctime_}{\&{arctime} primitive@>
8157
8158 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8159 @^recursion@>
8160 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8161 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8162 returns the time when the arc length reaches |a_goal| if there is such a time.
8163 Thus the return value is either an arc length less than |a_goal| or, if the
8164 arc length would be at least |a_goal|, it returns a time value decreased by
8165 |two|.  This allows the caller to use the sign of the result to distinguish
8166 between arc lengths and time values.  On certain types of overflow, it is
8167 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8168 Otherwise, the result is always less than |a_goal|.
8169
8170 Rather than halving the control point coordinates on each recursive call to
8171 |arc_test|, it is better to keep them proportional to velocity on the original
8172 curve and halve the results instead.  This means that recursive calls can
8173 potentially use larger error tolerances in their arc length estimates.  How
8174 much larger depends on to what extent the errors behave as though they are
8175 independent of each other.  To save computing time, we use optimistic assumptions
8176 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8177 call.
8178
8179 In addition to the tolerance parameter, |arc_test| should also have parameters
8180 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8181 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8182 and they are needed in different instances of |arc_test|.
8183
8184 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8185 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8186                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8187                     scaled v2, scaled a_goal, scaled tol) {
8188   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8189   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8190   scaled v002, v022;
8191     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8192   scaled arc; /* best arc length estimate before recursion */
8193   @<Other local variables in |arc_test|@>;
8194   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8195     |dx2|, |dy2|@>;
8196   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8197     set |arc_test| and |return|@>;
8198   @<Test if the control points are confined to one quadrant or rotating them
8199     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8200   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8201     if ( arc < a_goal ) {
8202       return arc;
8203     } else {
8204        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8205          that time minus |two|@>;
8206     }
8207   } else {
8208     @<Use one or two recursive calls to compute the |arc_test| function@>;
8209   }
8210 }
8211
8212 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8213 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8214 |make_fraction| in this inner loop.
8215 @^inner loop@>
8216
8217 @<Use one or two recursive calls to compute the |arc_test| function@>=
8218
8219   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8220     large as possible@>;
8221   tol = tol + halfp(tol);
8222   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8223                   halfp(v02), a_new, tol);
8224   if ( a<0 )  {
8225      return (-halfp(two-a));
8226   } else { 
8227     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8228     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8229                     halfp(v02), v022, v2, a_new, tol);
8230     if ( b<0 )  
8231       return (-halfp(-b) - half_unit);
8232     else  
8233       return (a + half(b-a));
8234   }
8235 }
8236
8237 @ @<Other local variables in |arc_test|@>=
8238 scaled a,b; /* results of recursive calls */
8239 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8240
8241 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8242 a_aux = el_gordo - a_goal;
8243 if ( a_goal > a_aux ) {
8244   a_aux = a_goal - a_aux;
8245   a_new = el_gordo;
8246 } else { 
8247   a_new = a_goal + a_goal;
8248   a_aux = 0;
8249 }
8250
8251 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8252 to force the additions and subtractions to be done in an order that avoids
8253 overflow.
8254
8255 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8256 if ( a > a_aux ) {
8257   a_aux = a_aux - a;
8258   a_new = a_new + a_aux;
8259 }
8260
8261 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8262 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8263 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8264 this bound.  Note that recursive calls will maintain this invariant.
8265
8266 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8267 dx01 = half(dx0 + dx1);
8268 dx12 = half(dx1 + dx2);
8269 dx02 = half(dx01 + dx12);
8270 dy01 = half(dy0 + dy1);
8271 dy12 = half(dy1 + dy2);
8272 dy02 = half(dy01 + dy12)
8273
8274 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8275 |a_goal=el_gordo| is guaranteed to yield the arc length.
8276
8277 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8278 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8279 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8280 tmp = halfp(v02+2);
8281 arc1 = v002 + half(halfp(v0+tmp) - v002);
8282 arc = v022 + half(halfp(v2+tmp) - v022);
8283 if ( (arc < el_gordo-arc1) )  {
8284   arc = arc+arc1;
8285 } else { 
8286   mp->arith_error = true;
8287   if ( a_goal==el_gordo )  return (el_gordo);
8288   else return (-two);
8289 }
8290
8291 @ @<Other local variables in |arc_test|@>=
8292 scaled tmp, tmp2; /* all purpose temporary registers */
8293 scaled arc1; /* arc length estimate for the first half */
8294
8295 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8296 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8297          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8298 if ( simple )
8299   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8300            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8301 if ( ! simple ) {
8302   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8303            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8304   if ( simple ) 
8305     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8306              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8307 }
8308
8309 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8310 @^Simpson's rule@>
8311 it is appropriate to use the same approximation to decide when the integral
8312 reaches the intermediate value |a_goal|.  At this point
8313 $$\eqalign{
8314     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8315     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8316     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8317     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8318     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8319 }
8320 $$
8321 and
8322 $$ {\vb\dot B(t)\vb\over 3} \approx
8323   \cases{B\left(\hbox{|v0|},
8324       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8325       {1\over 2}\hbox{|v02|}; 2t \right)&
8326     if $t\le{1\over 2}$\cr
8327   B\left({1\over 2}\hbox{|v02|},
8328       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8329       \hbox{|v2|}; 2t-1 \right)&
8330     if $t\ge{1\over 2}$.\cr}
8331  \eqno (*)
8332 $$
8333 We can integrate $\vb\dot B(t)\vb$ by using
8334 $$\int 3B(a,b,c;\tau)\,dt =
8335   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8336 $$
8337
8338 This construction allows us to find the time when the arc length reaches
8339 |a_goal| by solving a cubic equation of the form
8340 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8341 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8342 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8343 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8344 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8345 $\tau$ given $a$, $b$, $c$, and $x$.
8346
8347 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8348
8349   tmp = (v02 + 2) / 4;
8350   if ( a_goal<=arc1 ) {
8351     tmp2 = halfp(v0);
8352     return 
8353       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8354   } else { 
8355     tmp2 = halfp(v2);
8356     return ((half_unit - two) +
8357       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8358   }
8359 }
8360
8361 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8362 $$ B(0, a, a+b, a+b+c; t) = x. $$
8363 This routine is based on |crossing_point| but is simplified by the
8364 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8365 If rounding error causes this condition to be violated slightly, we just ignore
8366 it and proceed with binary search.  This finds a time when the function value
8367 reaches |x| and the slope is positive.
8368
8369 @<Declare subroutines needed by |arc_test|@>=
8370 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8371   scaled ab, bc, ac; /* bisection results */
8372   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8373   integer xx; /* temporary for updating |x| */
8374   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8375 @:this can't happen rising?}{\quad rising?@>
8376   if ( x<=0 ) {
8377         return 0;
8378   } else if ( x >= a+b+c ) {
8379     return unity;
8380   } else { 
8381     t = 1;
8382     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8383       |el_gordo div 3|@>;
8384     do {  
8385       t+=t;
8386       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8387       xx = x - a - ab - ac;
8388       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8389       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8390     } while (t < unity);
8391     return (t - unity);
8392   }
8393 }
8394
8395 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8396 ab = half(a+b);
8397 bc = half(b+c);
8398 ac = half(ab+bc)
8399
8400 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8401
8402 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8403 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8404   a = halfp(a);
8405   b = half(b);
8406   c = halfp(c);
8407   x = halfp(x);
8408 }
8409
8410 @ It is convenient to have a simpler interface to |arc_test| that requires no
8411 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8412 length less than |fraction_four|.
8413
8414 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8415
8416 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8417                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8418   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8419   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8420   v0 = mp_pyth_add(mp, dx0,dy0);
8421   v1 = mp_pyth_add(mp, dx1,dy1);
8422   v2 = mp_pyth_add(mp, dx2,dy2);
8423   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8424     mp->arith_error = true;
8425     if ( a_goal==el_gordo )  return el_gordo;
8426     else return (-two);
8427   } else { 
8428     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8429     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8430                                  v0, v02, v2, a_goal, arc_tol));
8431   }
8432 }
8433
8434 @ Now it is easy to find the arc length of an entire path.
8435
8436 @c scaled mp_get_arc_length (MP mp,pointer h) {
8437   pointer p,q; /* for traversing the path */
8438   scaled a,a_tot; /* current and total arc lengths */
8439   a_tot = 0;
8440   p = h;
8441   while ( right_type(p)!=mp_endpoint ){ 
8442     q = link(p);
8443     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8444       left_x(q)-right_x(p), left_y(q)-right_y(p),
8445       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8446     a_tot = mp_slow_add(mp, a, a_tot);
8447     if ( q==h ) break;  else p=q;
8448   }
8449   check_arith;
8450   return a_tot;
8451 }
8452
8453 @ The inverse operation of finding the time on a path~|h| when the arc length
8454 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8455 is required to handle very large times or negative times on cyclic paths.  For
8456 non-cyclic paths, |arc0| values that are negative or too large cause
8457 |get_arc_time| to return 0 or the length of path~|h|.
8458
8459 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8460 time value greater than the length of the path.  Since it could be much greater,
8461 we must be prepared to compute the arc length of path~|h| and divide this into
8462 |arc0| to find how many multiples of the length of path~|h| to add.
8463
8464 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8465   pointer p,q; /* for traversing the path */
8466   scaled t_tot; /* accumulator for the result */
8467   scaled t; /* the result of |do_arc_test| */
8468   scaled arc; /* portion of |arc0| not used up so far */
8469   integer n; /* number of extra times to go around the cycle */
8470   if ( arc0<0 ) {
8471     @<Deal with a negative |arc0| value and |return|@>;
8472   }
8473   if ( arc0==el_gordo ) decr(arc0);
8474   t_tot = 0;
8475   arc = arc0;
8476   p = h;
8477   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8478     q = link(p);
8479     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8480       left_x(q)-right_x(p), left_y(q)-right_y(p),
8481       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8482     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8483     if ( q==h ) {
8484       @<Update |t_tot| and |arc| to avoid going around the cyclic
8485         path too many times but set |arith_error:=true| and |goto done| on
8486         overflow@>;
8487     }
8488     p = q;
8489   }
8490   check_arith;
8491   return t_tot;
8492 }
8493
8494 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8495 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8496 else { t_tot = t_tot + unity;  arc = arc - t;  }
8497
8498 @ @<Deal with a negative |arc0| value and |return|@>=
8499
8500   if ( left_type(h)==mp_endpoint ) {
8501     t_tot=0;
8502   } else { 
8503     p = mp_htap_ypoc(mp, h);
8504     t_tot = -mp_get_arc_time(mp, p, -arc0);
8505     mp_toss_knot_list(mp, p);
8506   }
8507   check_arith;
8508   return t_tot;
8509 }
8510
8511 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8512 if ( arc>0 ) { 
8513   n = arc / (arc0 - arc);
8514   arc = arc - n*(arc0 - arc);
8515   if ( t_tot > el_gordo / (n+1) ) { 
8516     mp->arith_error = true;
8517     t_tot = el_gordo;
8518     break;
8519   }
8520   t_tot = (n + 1)*t_tot;
8521 }
8522
8523 @* \[20] Data structures for pens.
8524 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8525 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8526 @:stroke}{\&{stroke} command@>
8527 converted into an area fill as described in the next part of this program.
8528 The mathematics behind this process is based on simple aspects of the theory
8529 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8530 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8531 Foundations of Computer Science {\bf 24} (1983), 100--111].
8532
8533 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8534 @:makepen_}{\&{makepen} primitive@>
8535 This path representation is almost sufficient for our purposes except that
8536 a pen path should always be a convex polygon with the vertices in
8537 counter-clockwise order.
8538 Since we will need to scan pen polygons both forward and backward, a pen
8539 should be represented as a doubly linked ring of knot nodes.  There is
8540 room for the extra back pointer because we do not need the
8541 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8542 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8543 so that certain procedures can operate on both pens and paths.  In particular,
8544 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8545
8546 @d knil info
8547   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8548
8549 @ The |make_pen| procedure turns a path into a pen by initializing
8550 the |knil| pointers and making sure the knots form a convex polygon.
8551 Thus each cubic in the given path becomes a straight line and the control
8552 points are ignored.  If the path is not cyclic, the ends are connected by a
8553 straight line.
8554
8555 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8556
8557 @c @<Declare a function called |convex_hull|@>;
8558 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8559   pointer p,q; /* two consecutive knots */
8560   q=h;
8561   do {  
8562     p=q; q=link(q);
8563     knil(q)=p;
8564   } while (q!=h);
8565   if ( need_hull ){ 
8566     h=mp_convex_hull(mp, h);
8567     @<Make sure |h| isn't confused with an elliptical pen@>;
8568   }
8569   return h;
8570 }
8571
8572 @ The only information required about an elliptical pen is the overall
8573 transformation that has been applied to the original \&{pencircle}.
8574 @:pencircle_}{\&{pencircle} primitive@>
8575 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8576 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8577 knot node and transformed as if it were a path.
8578
8579 @d pen_is_elliptical(A) ((A)==link((A)))
8580
8581 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8582   pointer h; /* the knot node to return */
8583   h=mp_get_node(mp, knot_node_size);
8584   link(h)=h; knil(h)=h;
8585   originator(h)=mp_program_code;
8586   x_coord(h)=0; y_coord(h)=0;
8587   left_x(h)=diam; left_y(h)=0;
8588   right_x(h)=0; right_y(h)=diam;
8589   return h;
8590 }
8591
8592 @ If the polygon being returned by |make_pen| has only one vertex, it will
8593 be interpreted as an elliptical pen.  This is no problem since a degenerate
8594 polygon can equally well be thought of as a degenerate ellipse.  We need only
8595 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8596
8597 @<Make sure |h| isn't confused with an elliptical pen@>=
8598 if ( pen_is_elliptical( h) ){ 
8599   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8600   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8601 }
8602
8603 @ We have to cheat a little here but most operations on pens only use
8604 the first three words in each knot node.
8605 @^data structure assumptions@>
8606
8607 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8608 x_coord(test_pen)=-half_unit;
8609 y_coord(test_pen)=0;
8610 x_coord(test_pen+3)=half_unit;
8611 y_coord(test_pen+3)=0;
8612 x_coord(test_pen+6)=0;
8613 y_coord(test_pen+6)=unity;
8614 link(test_pen)=test_pen+3;
8615 link(test_pen+3)=test_pen+6;
8616 link(test_pen+6)=test_pen;
8617 knil(test_pen)=test_pen+6;
8618 knil(test_pen+3)=test_pen;
8619 knil(test_pen+6)=test_pen+3
8620
8621 @ Printing a polygonal pen is very much like printing a path
8622
8623 @<Declare subroutines for printing expressions@>=
8624 void mp_pr_pen (MP mp,pointer h) {
8625   pointer p,q; /* for list traversal */
8626   if ( pen_is_elliptical(h) ) {
8627     @<Print the elliptical pen |h|@>;
8628   } else { 
8629     p=h;
8630     do {  
8631       mp_print_two(mp, x_coord(p),y_coord(p));
8632       mp_print_nl(mp, " .. ");
8633       @<Advance |p| making sure the links are OK and |return| if there is
8634         a problem@>;
8635      } while (p!=h);
8636      mp_print(mp, "cycle");
8637   }
8638 }
8639
8640 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8641 q=link(p);
8642 if ( (q==null) || (knil(q)!=p) ) { 
8643   mp_print_nl(mp, "???"); return; /* this won't happen */
8644 @.???@>
8645 }
8646 p=q
8647
8648 @ @<Print the elliptical pen |h|@>=
8649
8650 mp_print(mp, "pencircle transformed (");
8651 mp_print_scaled(mp, x_coord(h));
8652 mp_print_char(mp, ',');
8653 mp_print_scaled(mp, y_coord(h));
8654 mp_print_char(mp, ',');
8655 mp_print_scaled(mp, left_x(h)-x_coord(h));
8656 mp_print_char(mp, ',');
8657 mp_print_scaled(mp, right_x(h)-x_coord(h));
8658 mp_print_char(mp, ',');
8659 mp_print_scaled(mp, left_y(h)-y_coord(h));
8660 mp_print_char(mp, ',');
8661 mp_print_scaled(mp, right_y(h)-y_coord(h));
8662 mp_print_char(mp, ')');
8663 }
8664
8665 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8666 message.
8667
8668 @<Declare subroutines for printing expressions@>=
8669 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8670   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8671 @.Pen at line...@>
8672   mp_pr_pen(mp, h);
8673   mp_end_diagnostic(mp, true);
8674 }
8675
8676 @ Making a polygonal pen into a path involves restoring the |left_type| and
8677 |right_type| fields and setting the control points so as to make a polygonal
8678 path.
8679
8680 @c 
8681 void mp_make_path (MP mp,pointer h) {
8682   pointer p; /* for traversing the knot list */
8683   small_number k; /* a loop counter */
8684   @<Other local variables in |make_path|@>;
8685   if ( pen_is_elliptical(h) ) {
8686     @<Make the elliptical pen |h| into a path@>;
8687   } else { 
8688     p=h;
8689     do {  
8690       left_type(p)=mp_explicit;
8691       right_type(p)=mp_explicit;
8692       @<copy the coordinates of knot |p| into its control points@>;
8693        p=link(p);
8694     } while (p!=h);
8695   }
8696 }
8697
8698 @ @<copy the coordinates of knot |p| into its control points@>=
8699 left_x(p)=x_coord(p);
8700 left_y(p)=y_coord(p);
8701 right_x(p)=x_coord(p);
8702 right_y(p)=y_coord(p)
8703
8704 @ We need an eight knot path to get a good approximation to an ellipse.
8705
8706 @<Make the elliptical pen |h| into a path@>=
8707
8708   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8709   p=h;
8710   for (k=0;k<=7;k++ ) { 
8711     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8712       transforming it appropriately@>;
8713     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8714     p=link(p);
8715   }
8716 }
8717
8718 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8719 center_x=x_coord(h);
8720 center_y=y_coord(h);
8721 width_x=left_x(h)-center_x;
8722 width_y=left_y(h)-center_y;
8723 height_x=right_x(h)-center_x;
8724 height_y=right_y(h)-center_y
8725
8726 @ @<Other local variables in |make_path|@>=
8727 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8728 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8729 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8730 scaled dx,dy; /* the vector from knot |p| to its right control point */
8731 integer kk;
8732   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8733
8734 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8735 find the point $k/8$ of the way around the circle and the direction vector
8736 to use there.
8737
8738 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8739 kk=(k+6)% 8;
8740 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8741            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8742 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8743            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8744 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8745    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8746 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8747    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8748 right_x(p)=x_coord(p)+dx;
8749 right_y(p)=y_coord(p)+dy;
8750 left_x(p)=x_coord(p)-dx;
8751 left_y(p)=y_coord(p)-dy;
8752 left_type(p)=mp_explicit;
8753 right_type(p)=mp_explicit;
8754 originator(p)=mp_program_code
8755
8756 @ @<Glob...@>=
8757 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8758 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8759
8760 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8761 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8762 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8763 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8764   \approx 0.132608244919772.
8765 $$
8766
8767 @<Set init...@>=
8768 mp->half_cos[0]=fraction_half;
8769 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8770 mp->half_cos[2]=0;
8771 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8772 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8773 mp->d_cos[2]=0;
8774 for (k=3;k<= 4;k++ ) { 
8775   mp->half_cos[k]=-mp->half_cos[4-k];
8776   mp->d_cos[k]=-mp->d_cos[4-k];
8777 }
8778 for (k=5;k<= 7;k++ ) { 
8779   mp->half_cos[k]=mp->half_cos[8-k];
8780   mp->d_cos[k]=mp->d_cos[8-k];
8781 }
8782
8783 @ The |convex_hull| function forces a pen polygon to be convex when it is
8784 returned by |make_pen| and after any subsequent transformation where rounding
8785 error might allow the convexity to be lost.
8786 The convex hull algorithm used here is described by F.~P. Preparata and
8787 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8788
8789 @<Declare a function called |convex_hull|@>=
8790 @<Declare a procedure called |move_knot|@>;
8791 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8792   pointer l,r; /* the leftmost and rightmost knots */
8793   pointer p,q; /* knots being scanned */
8794   pointer s; /* the starting point for an upcoming scan */
8795   scaled dx,dy; /* a temporary pointer */
8796   if ( pen_is_elliptical(h) ) {
8797      return h;
8798   } else { 
8799     @<Set |l| to the leftmost knot in polygon~|h|@>;
8800     @<Set |r| to the rightmost knot in polygon~|h|@>;
8801     if ( l!=r ) { 
8802       s=link(r);
8803       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8804         move them past~|r|@>;
8805       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8806         move them past~|l|@>;
8807       @<Sort the path from |l| to |r| by increasing $x$@>;
8808       @<Sort the path from |r| to |l| by decreasing $x$@>;
8809     }
8810     if ( l!=link(l) ) {
8811       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8812     }
8813     return l;
8814   }
8815 }
8816
8817 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8818
8819 @<Set |l| to the leftmost knot in polygon~|h|@>=
8820 l=h;
8821 p=link(h);
8822 while ( p!=h ) { 
8823   if ( x_coord(p)<=x_coord(l) )
8824     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8825       l=p;
8826   p=link(p);
8827 }
8828
8829 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8830 r=h;
8831 p=link(h);
8832 while ( p!=h ) { 
8833   if ( x_coord(p)>=x_coord(r) )
8834     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8835       r=p;
8836   p=link(p);
8837 }
8838
8839 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8840 dx=x_coord(r)-x_coord(l);
8841 dy=y_coord(r)-y_coord(l);
8842 p=link(l);
8843 while ( p!=r ) { 
8844   q=link(p);
8845   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8846     mp_move_knot(mp, p, r);
8847   p=q;
8848 }
8849
8850 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8851 it after |q|.
8852
8853 @ @<Declare a procedure called |move_knot|@>=
8854 void mp_move_knot (MP mp,pointer p, pointer q) { 
8855   link(knil(p))=link(p);
8856   knil(link(p))=knil(p);
8857   knil(p)=q;
8858   link(p)=link(q);
8859   link(q)=p;
8860   knil(link(p))=p;
8861 }
8862
8863 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8864 p=s;
8865 while ( p!=l ) { 
8866   q=link(p);
8867   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8868     mp_move_knot(mp, p,l);
8869   p=q;
8870 }
8871
8872 @ The list is likely to be in order already so we just do linear insertions.
8873 Secondary comparisons on $y$ ensure that the sort is consistent with the
8874 choice of |l| and |r|.
8875
8876 @<Sort the path from |l| to |r| by increasing $x$@>=
8877 p=link(l);
8878 while ( p!=r ) { 
8879   q=knil(p);
8880   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8881   while ( x_coord(q)==x_coord(p) ) {
8882     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8883   }
8884   if ( q==knil(p) ) p=link(p);
8885   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8886 }
8887
8888 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8889 p=link(r);
8890 while ( p!=l ){ 
8891   q=knil(p);
8892   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8893   while ( x_coord(q)==x_coord(p) ) {
8894     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8895   }
8896   if ( q==knil(p) ) p=link(p);
8897   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8898 }
8899
8900 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8901 at knot |q|.  There usually will be a left turn so we streamline the case
8902 where the |then| clause is not executed.
8903
8904 @<Do a Gramm scan and remove vertices where there...@>=
8905
8906 p=l; q=link(l);
8907 while (1) { 
8908   dx=x_coord(q)-x_coord(p);
8909   dy=y_coord(q)-y_coord(p);
8910   p=q; q=link(q);
8911   if ( p==l ) break;
8912   if ( p!=r )
8913     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8914       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8915     }
8916   }
8917 }
8918
8919 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8920
8921 s=knil(p);
8922 mp_free_node(mp, p,knot_node_size);
8923 link(s)=q; knil(q)=s;
8924 if ( s==l ) p=s;
8925 else { p=knil(s); q=s; };
8926 }
8927
8928 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8929 offset associated with the given direction |(x,y)|.  If two different offsets
8930 apply, it chooses one of them.
8931
8932 @c 
8933 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8934   pointer p,q; /* consecutive knots */
8935   scaled wx,wy,hx,hy;
8936   /* the transformation matrix for an elliptical pen */
8937   fraction xx,yy; /* untransformed offset for an elliptical pen */
8938   fraction d; /* a temporary register */
8939   if ( pen_is_elliptical(h) ) {
8940     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8941   } else { 
8942     q=h;
8943     do {  
8944       p=q; q=link(q);
8945     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8946     do {  
8947       p=q; q=link(q);
8948     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8949     mp->cur_x=x_coord(p);
8950     mp->cur_y=y_coord(p);
8951   }
8952 }
8953
8954 @ @<Glob...@>=
8955 scaled cur_x;
8956 scaled cur_y; /* all-purpose return value registers */
8957
8958 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8959 if ( (x==0) && (y==0) ) {
8960   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8961 } else { 
8962   @<Find the non-constant part of the transformation for |h|@>;
8963   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8964     x+=x; y+=y;  
8965   };
8966   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8967     untransformed version of |(x,y)|@>;
8968   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8969   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8970 }
8971
8972 @ @<Find the non-constant part of the transformation for |h|@>=
8973 wx=left_x(h)-x_coord(h);
8974 wy=left_y(h)-y_coord(h);
8975 hx=right_x(h)-x_coord(h);
8976 hy=right_y(h)-y_coord(h)
8977
8978 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8979 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8980 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8981 d=mp_pyth_add(mp, xx,yy);
8982 if ( d>0 ) { 
8983   xx=half(mp_make_fraction(mp, xx,d));
8984   yy=half(mp_make_fraction(mp, yy,d));
8985 }
8986
8987 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8988 But we can handle that case by just calling |find_offset| twice.  The answer
8989 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8990
8991 @c 
8992 void mp_pen_bbox (MP mp,pointer h) {
8993   pointer p; /* for scanning the knot list */
8994   if ( pen_is_elliptical(h) ) {
8995     @<Find the bounding box of an elliptical pen@>;
8996   } else { 
8997     minx=x_coord(h); maxx=minx;
8998     miny=y_coord(h); maxy=miny;
8999     p=link(h);
9000     while ( p!=h ) {
9001       if ( x_coord(p)<minx ) minx=x_coord(p);
9002       if ( y_coord(p)<miny ) miny=y_coord(p);
9003       if ( x_coord(p)>maxx ) maxx=x_coord(p);
9004       if ( y_coord(p)>maxy ) maxy=y_coord(p);
9005       p=link(p);
9006     }
9007   }
9008 }
9009
9010 @ @<Find the bounding box of an elliptical pen@>=
9011
9012 mp_find_offset(mp, 0,fraction_one,h);
9013 maxx=mp->cur_x;
9014 minx=2*x_coord(h)-mp->cur_x;
9015 mp_find_offset(mp, -fraction_one,0,h);
9016 maxy=mp->cur_y;
9017 miny=2*y_coord(h)-mp->cur_y;
9018 }
9019
9020 @* \[21] Edge structures.
9021 Now we come to \MP's internal scheme for representing pictures.
9022 The representation is very different from \MF's edge structures
9023 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9024 images.  However, the basic idea is somewhat similar in that shapes
9025 are represented via their boundaries.
9026
9027 The main purpose of edge structures is to keep track of graphical objects
9028 until it is time to translate them into \ps.  Since \MP\ does not need to
9029 know anything about an edge structure other than how to translate it into
9030 \ps\ and how to find its bounding box, edge structures can be just linked
9031 lists of graphical objects.  \MP\ has no easy way to determine whether
9032 two such objects overlap, but it suffices to draw the first one first and
9033 let the second one overwrite it if necessary.
9034
9035 @<Types...@>=
9036 enum mp_graphical_object_code {
9037   @<Graphical object codes@>
9038 };
9039
9040 @ Let's consider the types of graphical objects one at a time.
9041 First of all, a filled contour is represented by a eight-word node.  The first
9042 word contains |type| and |link| fields, and the next six words contain a
9043 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9044 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9045 give the relevant information.
9046
9047 @d path_p(A) link((A)+1)
9048   /* a pointer to the path that needs filling */
9049 @d pen_p(A) info((A)+1)
9050   /* a pointer to the pen to fill or stroke with */
9051 @d color_model(A) type((A)+2) /*  the color model  */
9052 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9053 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9054 @d obj_grey_loc obj_red_loc  /* the location for the color */
9055 @d red_val(A) mp->mem[(A)+3].sc
9056   /* the red component of the color in the range $0\ldots1$ */
9057 @d cyan_val red_val
9058 @d grey_val red_val
9059 @d green_val(A) mp->mem[(A)+4].sc
9060   /* the green component of the color in the range $0\ldots1$ */
9061 @d magenta_val green_val
9062 @d blue_val(A) mp->mem[(A)+5].sc
9063   /* the blue component of the color in the range $0\ldots1$ */
9064 @d yellow_val blue_val
9065 @d black_val(A) mp->mem[(A)+6].sc
9066   /* the blue component of the color in the range $0\ldots1$ */
9067 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9068 @:mp_linejoin_}{\&{linejoin} primitive@>
9069 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9070 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9071 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9072   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9073 @d pre_script(A) mp->mem[(A)+8].hh.lh
9074 @d post_script(A) mp->mem[(A)+8].hh.rh
9075 @d fill_node_size 9
9076
9077 @ @<Graphical object codes@>=
9078 mp_fill_code=1,
9079
9080 @ @c 
9081 pointer mp_new_fill_node (MP mp,pointer p) {
9082   /* make a fill node for cyclic path |p| and color black */
9083   pointer t; /* the new node */
9084   t=mp_get_node(mp, fill_node_size);
9085   type(t)=mp_fill_code;
9086   path_p(t)=p;
9087   pen_p(t)=null; /* |null| means don't use a pen */
9088   red_val(t)=0;
9089   green_val(t)=0;
9090   blue_val(t)=0;
9091   black_val(t)=0;
9092   color_model(t)=mp_uninitialized_model;
9093   pre_script(t)=null;
9094   post_script(t)=null;
9095   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9096   return t;
9097 }
9098
9099 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9100 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9101 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9102 else ljoin_val(t)=0;
9103 if ( mp->internal[mp_miterlimit]<unity )
9104   miterlim_val(t)=unity;
9105 else
9106   miterlim_val(t)=mp->internal[mp_miterlimit]
9107
9108 @ A stroked path is represented by an eight-word node that is like a filled
9109 contour node except that it contains the current \&{linecap} value, a scale
9110 factor for the dash pattern, and a pointer that is non-null if the stroke
9111 is to be dashed.  The purpose of the scale factor is to allow a picture to
9112 be transformed without touching the picture that |dash_p| points to.
9113
9114 @d dash_p(A) link((A)+9)
9115   /* a pointer to the edge structure that gives the dash pattern */
9116 @d lcap_val(A) type((A)+9)
9117   /* the value of \&{linecap} */
9118 @:mp_linecap_}{\&{linecap} primitive@>
9119 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9120 @d stroked_node_size 11
9121
9122 @ @<Graphical object codes@>=
9123 mp_stroked_code=2,
9124
9125 @ @c 
9126 pointer mp_new_stroked_node (MP mp,pointer p) {
9127   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9128   pointer t; /* the new node */
9129   t=mp_get_node(mp, stroked_node_size);
9130   type(t)=mp_stroked_code;
9131   path_p(t)=p; pen_p(t)=null;
9132   dash_p(t)=null;
9133   dash_scale(t)=unity;
9134   red_val(t)=0;
9135   green_val(t)=0;
9136   blue_val(t)=0;
9137   black_val(t)=0;
9138   color_model(t)=mp_uninitialized_model;
9139   pre_script(t)=null;
9140   post_script(t)=null;
9141   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9142   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9143   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9144   else lcap_val(t)=0;
9145   return t;
9146 }
9147
9148 @ When a dashed line is computed in a transformed coordinate system, the dash
9149 lengths get scaled like the pen shape and we need to compensate for this.  Since
9150 there is no unique scale factor for an arbitrary transformation, we use the
9151 the square root of the determinant.  The properties of the determinant make it
9152 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9153 except for the initialization of the scale factor |s|.  The factor of 64 is
9154 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9155 to counteract the effect of |take_fraction|.
9156
9157 @<Declare subroutines needed by |print_edges|@>=
9158 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9159   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9160   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9161   @<Initialize |maxabs|@>;
9162   s=64;
9163   while ( (maxabs<fraction_one) && (s>1) ){ 
9164     a+=a; b+=b; c+=c; d+=d;
9165     maxabs+=maxabs; s=halfp(s);
9166   }
9167   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9168 }
9169 @#
9170 scaled mp_get_pen_scale (MP mp,pointer p) { 
9171   return mp_sqrt_det(mp, 
9172     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9173     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9174 }
9175
9176 @ @<Internal library ...@>=
9177 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9178
9179
9180 @ @<Initialize |maxabs|@>=
9181 maxabs=abs(a);
9182 if ( abs(b)>maxabs ) maxabs=abs(b);
9183 if ( abs(c)>maxabs ) maxabs=abs(c);
9184 if ( abs(d)>maxabs ) maxabs=abs(d)
9185
9186 @ When a picture contains text, this is represented by a fourteen-word node
9187 where the color information and |type| and |link| fields are augmented by
9188 additional fields that describe the text and  how it is transformed.
9189 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9190 the font and a string number that gives the text to be displayed.
9191 The |width|, |height|, and |depth| fields
9192 give the dimensions of the text at its design size, and the remaining six
9193 words give a transformation to be applied to the text.  The |new_text_node|
9194 function initializes everything to default values so that the text comes out
9195 black with its reference point at the origin.
9196
9197 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9198 @d font_n(A) info((A)+1)  /* the font number */
9199 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9200 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9201 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9202 @d text_tx_loc(A) ((A)+11)
9203   /* the first of six locations for transformation parameters */
9204 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9205 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9206 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9207 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9208 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9209 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9210 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9211     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9212 @d text_node_size 17
9213
9214 @ @<Graphical object codes@>=
9215 mp_text_code=3,
9216
9217 @ @c @<Declare text measuring subroutines@>;
9218 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9219   /* make a text node for font |f| and text string |s| */
9220   pointer t; /* the new node */
9221   t=mp_get_node(mp, text_node_size);
9222   type(t)=mp_text_code;
9223   text_p(t)=s;
9224   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9225   red_val(t)=0;
9226   green_val(t)=0;
9227   blue_val(t)=0;
9228   black_val(t)=0;
9229   color_model(t)=mp_uninitialized_model;
9230   pre_script(t)=null;
9231   post_script(t)=null;
9232   tx_val(t)=0; ty_val(t)=0;
9233   txx_val(t)=unity; txy_val(t)=0;
9234   tyx_val(t)=0; tyy_val(t)=unity;
9235   mp_set_text_box(mp, t); /* this finds the bounding box */
9236   return t;
9237 }
9238
9239 @ The last two types of graphical objects that can occur in an edge structure
9240 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9241 @:set_bounds_}{\&{setbounds} primitive@>
9242 to implement because we must keep track of exactly what is being clipped or
9243 bounded when pictures get merged together.  For this reason, each clipping or
9244 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9245 two-word node whose |path_p| gives the relevant path, then there is the list
9246 of objects to clip or bound followed by a two-word node whose second word is
9247 unused.
9248
9249 Using at least two words for each graphical object node allows them all to be
9250 allocated and deallocated similarly with a global array |gr_object_size| to
9251 give the size in words for each object type.
9252
9253 @d start_clip_size 2
9254 @d start_bounds_size 2
9255 @d stop_clip_size 2 /* the second word is not used here */
9256 @d stop_bounds_size 2 /* the second word is not used here */
9257 @#
9258 @d stop_type(A) ((A)+2)
9259   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9260 @d has_color(A) (type((A))<mp_start_clip_code)
9261   /* does a graphical object have color fields? */
9262 @d has_pen(A) (type((A))<mp_text_code)
9263   /* does a graphical object have a |pen_p| field? */
9264 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9265 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9266
9267 @ @<Graphical object codes@>=
9268 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9269 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9270 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9271 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9272
9273 @ @c 
9274 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9275   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9276   pointer t; /* the new node */
9277   t=mp_get_node(mp, mp->gr_object_size[c]);
9278   type(t)=c;
9279   path_p(t)=p;
9280   return t;
9281 };
9282
9283 @ We need an array to keep track of the sizes of graphical objects.
9284
9285 @<Glob...@>=
9286 small_number gr_object_size[mp_stop_bounds_code+1];
9287
9288 @ @<Set init...@>=
9289 mp->gr_object_size[mp_fill_code]=fill_node_size;
9290 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9291 mp->gr_object_size[mp_text_code]=text_node_size;
9292 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9293 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9294 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9295 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9296
9297 @ All the essential information in an edge structure is encoded as a linked list
9298 of graphical objects as we have just seen, but it is helpful to add some
9299 redundant information.  A single edge structure might be used as a dash pattern
9300 many times, and it would be nice to avoid scanning the same structure
9301 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9302 has a header that gives a list of dashes in a sorted order designed for rapid
9303 translation into \ps.
9304
9305 Each dash is represented by a three-word node containing the initial and final
9306 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9307 the dash node with the next higher $x$-coordinates and the final link points
9308 to a special location called |null_dash|.  (There should be no overlap between
9309 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9310 the period of repetition, this needs to be stored in the edge header along
9311 with a pointer to the list of dash nodes.
9312
9313 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9314 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9315 @d dash_node_size 3
9316 @d dash_list link
9317   /* in an edge header this points to the first dash node */
9318 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9319
9320 @ It is also convenient for an edge header to contain the bounding
9321 box information needed by the \&{llcorner} and \&{urcorner} operators
9322 so that this does not have to be recomputed unnecessarily.  This is done by
9323 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9324 how far the bounding box computation has gotten.  Thus if the user asks for
9325 the bounding box and then adds some more text to the picture before asking
9326 for more bounding box information, the second computation need only look at
9327 the additional text.
9328
9329 When the bounding box has not been computed, the |bblast| pointer points
9330 to a dummy link at the head of the graphical object list while the |minx_val|
9331 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9332 fields contain |-el_gordo|.
9333
9334 Since the bounding box of pictures containing objects of type
9335 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9336 @:mp_true_corners_}{\&{truecorners} primitive@>
9337 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9338 field is needed to keep track of this.
9339
9340 @d minx_val(A) mp->mem[(A)+2].sc
9341 @d miny_val(A) mp->mem[(A)+3].sc
9342 @d maxx_val(A) mp->mem[(A)+4].sc
9343 @d maxy_val(A) mp->mem[(A)+5].sc
9344 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9345 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9346 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9347 @d no_bounds 0
9348   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9349 @d bounds_set 1
9350   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9351 @d bounds_unset 2
9352   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9353
9354 @c 
9355 void mp_init_bbox (MP mp,pointer h) {
9356   /* Initialize the bounding box information in edge structure |h| */
9357   bblast(h)=dummy_loc(h);
9358   bbtype(h)=no_bounds;
9359   minx_val(h)=el_gordo;
9360   miny_val(h)=el_gordo;
9361   maxx_val(h)=-el_gordo;
9362   maxy_val(h)=-el_gordo;
9363 }
9364
9365 @ The only other entries in an edge header are a reference count in the first
9366 word and a pointer to the tail of the object list in the last word.
9367
9368 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9369 @d edge_header_size 8
9370
9371 @c 
9372 void mp_init_edges (MP mp,pointer h) {
9373   /* initialize an edge header to null values */
9374   dash_list(h)=null_dash;
9375   obj_tail(h)=dummy_loc(h);
9376   link(dummy_loc(h))=null;
9377   ref_count(h)=null;
9378   mp_init_bbox(mp, h);
9379 }
9380
9381 @ Here is how edge structures are deleted.  The process can be recursive because
9382 of the need to dereference edge structures that are used as dash patterns.
9383 @^recursion@>
9384
9385 @d add_edge_ref(A) incr(ref_count(A))
9386 @d delete_edge_ref(A) { 
9387    if ( ref_count((A))==null ) 
9388      mp_toss_edges(mp, A);
9389    else 
9390      decr(ref_count(A)); 
9391    }
9392
9393 @<Declare the recycling subroutines@>=
9394 void mp_flush_dash_list (MP mp,pointer h);
9395 pointer mp_toss_gr_object (MP mp,pointer p) ;
9396 void mp_toss_edges (MP mp,pointer h) ;
9397
9398 @ @c void mp_toss_edges (MP mp,pointer h) {
9399   pointer p,q;  /* pointers that scan the list being recycled */
9400   pointer r; /* an edge structure that object |p| refers to */
9401   mp_flush_dash_list(mp, h);
9402   q=link(dummy_loc(h));
9403   while ( (q!=null) ) { 
9404     p=q; q=link(q);
9405     r=mp_toss_gr_object(mp, p);
9406     if ( r!=null ) delete_edge_ref(r);
9407   }
9408   mp_free_node(mp, h,edge_header_size);
9409 }
9410 void mp_flush_dash_list (MP mp,pointer h) {
9411   pointer p,q;  /* pointers that scan the list being recycled */
9412   q=dash_list(h);
9413   while ( q!=null_dash ) { 
9414     p=q; q=link(q);
9415     mp_free_node(mp, p,dash_node_size);
9416   }
9417   dash_list(h)=null_dash;
9418 }
9419 pointer mp_toss_gr_object (MP mp,pointer p) {
9420   /* returns an edge structure that needs to be dereferenced */
9421   pointer e; /* the edge structure to return */
9422   e=null;
9423   @<Prepare to recycle graphical object |p|@>;
9424   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9425   return e;
9426 }
9427
9428 @ @<Prepare to recycle graphical object |p|@>=
9429 switch (type(p)) {
9430 case mp_fill_code: 
9431   mp_toss_knot_list(mp, path_p(p));
9432   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9433   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9434   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9435   break;
9436 case mp_stroked_code: 
9437   mp_toss_knot_list(mp, path_p(p));
9438   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9439   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9440   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9441   e=dash_p(p);
9442   break;
9443 case mp_text_code: 
9444   delete_str_ref(text_p(p));
9445   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9446   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9447   break;
9448 case mp_start_clip_code:
9449 case mp_start_bounds_code: 
9450   mp_toss_knot_list(mp, path_p(p));
9451   break;
9452 case mp_stop_clip_code:
9453 case mp_stop_bounds_code: 
9454   break;
9455 } /* there are no other cases */
9456
9457 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9458 to be done before making a significant change to an edge structure.  Much of
9459 the work is done in a separate routine |copy_objects| that copies a list of
9460 graphical objects into a new edge header.
9461
9462 @c @<Declare a function called |copy_objects|@>;
9463 pointer mp_private_edges (MP mp,pointer h) {
9464   /* make a private copy of the edge structure headed by |h| */
9465   pointer hh;  /* the edge header for the new copy */
9466   pointer p,pp;  /* pointers for copying the dash list */
9467   if ( ref_count(h)==null ) {
9468     return h;
9469   } else { 
9470     decr(ref_count(h));
9471     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9472     @<Copy the dash list from |h| to |hh|@>;
9473     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9474       point into the new object list@>;
9475     return hh;
9476   }
9477 }
9478
9479 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9480 @^data structure assumptions@>
9481
9482 @<Copy the dash list from |h| to |hh|@>=
9483 pp=hh; p=dash_list(h);
9484 while ( (p!=null_dash) ) { 
9485   link(pp)=mp_get_node(mp, dash_node_size);
9486   pp=link(pp);
9487   start_x(pp)=start_x(p);
9488   stop_x(pp)=stop_x(p);
9489   p=link(p);
9490 }
9491 link(pp)=null_dash;
9492 dash_y(hh)=dash_y(h)
9493
9494
9495 @ |h| is an edge structure
9496
9497 @d gr_start_x(A)    (A)->start_x_field
9498 @d gr_stop_x(A)     (A)->stop_x_field
9499 @d gr_dash_link(A)  (A)->next_field
9500
9501 @d gr_dash_list(A)  (A)->list_field
9502 @d gr_dash_y(A)     (A)->y_field
9503
9504 @c
9505 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9506   struct mp_dash_list *dl;
9507   struct mp_dash_item *dh, *di;
9508   pointer p;
9509   if (h==null ||  dash_list(h)==null_dash) 
9510         return NULL;
9511   p = dash_list(h);
9512   dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9513   gr_dash_list(dl) = NULL;
9514   gr_dash_y(dl) = dash_y(h);
9515   dh = NULL;
9516   while (p != null_dash) { 
9517     di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9518     gr_dash_link(di) = NULL;
9519     gr_start_x(di) = start_x(p);
9520     gr_stop_x(di) = stop_x(p);
9521     if (dh==NULL) {
9522       gr_dash_list(dl) = di;
9523     } else {
9524       gr_dash_link(dh) = di;
9525     }
9526     dh = di;
9527     p=link(p);
9528   }
9529   return dl;
9530 }
9531
9532
9533 @ @<Copy the bounding box information from |h| to |hh|...@>=
9534 minx_val(hh)=minx_val(h);
9535 miny_val(hh)=miny_val(h);
9536 maxx_val(hh)=maxx_val(h);
9537 maxy_val(hh)=maxy_val(h);
9538 bbtype(hh)=bbtype(h);
9539 p=dummy_loc(h); pp=dummy_loc(hh);
9540 while ((p!=bblast(h)) ) { 
9541   if ( p==null ) mp_confusion(mp, "bblast");
9542 @:this can't happen bblast}{\quad bblast@>
9543   p=link(p); pp=link(pp);
9544 }
9545 bblast(hh)=pp
9546
9547 @ Here is the promised routine for copying graphical objects into a new edge
9548 structure.  It starts copying at object~|p| and stops just before object~|q|.
9549 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9550 structure requires further initialization by |init_bbox|.
9551
9552 @<Declare a function called |copy_objects|@>=
9553 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9554   pointer hh;  /* the new edge header */
9555   pointer pp;  /* the last newly copied object */
9556   small_number k;  /* temporary register */
9557   hh=mp_get_node(mp, edge_header_size);
9558   dash_list(hh)=null_dash;
9559   ref_count(hh)=null;
9560   pp=dummy_loc(hh);
9561   while ( (p!=q) ) {
9562     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9563   }
9564   obj_tail(hh)=pp;
9565   link(pp)=null;
9566   return hh;
9567 }
9568
9569 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9570 { k=mp->gr_object_size[type(p)];
9571   link(pp)=mp_get_node(mp, k);
9572   pp=link(pp);
9573   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9574   @<Fix anything in graphical object |pp| that should differ from the
9575     corresponding field in |p|@>;
9576   p=link(p);
9577 }
9578
9579 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9580 switch (type(p)) {
9581 case mp_start_clip_code:
9582 case mp_start_bounds_code: 
9583   path_p(pp)=mp_copy_path(mp, path_p(p));
9584   break;
9585 case mp_fill_code: 
9586   path_p(pp)=mp_copy_path(mp, path_p(p));
9587   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9588   break;
9589 case mp_stroked_code: 
9590   path_p(pp)=mp_copy_path(mp, path_p(p));
9591   pen_p(pp)=copy_pen(pen_p(p));
9592   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9593   break;
9594 case mp_text_code: 
9595   add_str_ref(text_p(pp));
9596   break;
9597 case mp_stop_clip_code:
9598 case mp_stop_bounds_code: 
9599   break;
9600 }  /* there are no other cases */
9601
9602 @ Here is one way to find an acceptable value for the second argument to
9603 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9604 skips past one picture component, where a ``picture component'' is a single
9605 graphical object, or a start bounds or start clip object and everything up
9606 through the matching stop bounds or stop clip object.  The macro version avoids
9607 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9608 unless |p| points to a stop bounds or stop clip node, in which case it executes
9609 |e| instead.
9610
9611 @d skip_component(A)
9612     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9613     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9614     else 
9615
9616 @c 
9617 pointer mp_skip_1component (MP mp,pointer p) {
9618   integer lev; /* current nesting level */
9619   lev=0;
9620   do {  
9621    if ( is_start_or_stop(p) ) {
9622      if ( is_stop(p) ) decr(lev);  else incr(lev);
9623    }
9624    p=link(p);
9625   } while (lev!=0);
9626   return p;
9627 }
9628
9629 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9630
9631 @<Declare subroutines for printing expressions@>=
9632 @<Declare subroutines needed by |print_edges|@>;
9633 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9634   pointer p;  /* a graphical object to be printed */
9635   pointer hh,pp;  /* temporary pointers */
9636   scaled scf;  /* a scale factor for the dash pattern */
9637   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9638   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9639   p=dummy_loc(h);
9640   while ( link(p)!=null ) { 
9641     p=link(p);
9642     mp_print_ln(mp);
9643     switch (type(p)) {
9644       @<Cases for printing graphical object node |p|@>;
9645     default: 
9646           mp_print(mp, "[unknown object type!]");
9647           break;
9648     }
9649   }
9650   mp_print_nl(mp, "End edges");
9651   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9652 @.End edges?@>
9653   mp_end_diagnostic(mp, true);
9654 }
9655
9656 @ @<Cases for printing graphical object node |p|@>=
9657 case mp_fill_code: 
9658   mp_print(mp, "Filled contour ");
9659   mp_print_obj_color(mp, p);
9660   mp_print_char(mp, ':'); mp_print_ln(mp);
9661   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9662   if ( (pen_p(p)!=null) ) {
9663     @<Print join type for graphical object |p|@>;
9664     mp_print(mp, " with pen"); mp_print_ln(mp);
9665     mp_pr_pen(mp, pen_p(p));
9666   }
9667   break;
9668
9669 @ @<Print join type for graphical object |p|@>=
9670 switch (ljoin_val(p)) {
9671 case 0:
9672   mp_print(mp, "mitered joins limited ");
9673   mp_print_scaled(mp, miterlim_val(p));
9674   break;
9675 case 1:
9676   mp_print(mp, "round joins");
9677   break;
9678 case 2:
9679   mp_print(mp, "beveled joins");
9680   break;
9681 default: 
9682   mp_print(mp, "?? joins");
9683 @.??@>
9684   break;
9685 }
9686
9687 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9688
9689 @<Print join and cap types for stroked node |p|@>=
9690 switch (lcap_val(p)) {
9691 case 0:mp_print(mp, "butt"); break;
9692 case 1:mp_print(mp, "round"); break;
9693 case 2:mp_print(mp, "square"); break;
9694 default: mp_print(mp, "??"); break;
9695 @.??@>
9696 }
9697 mp_print(mp, " ends, ");
9698 @<Print join type for graphical object |p|@>
9699
9700 @ Here is a routine that prints the color of a graphical object if it isn't
9701 black (the default color).
9702
9703 @<Declare subroutines needed by |print_edges|@>=
9704 @<Declare a procedure called |print_compact_node|@>;
9705 void mp_print_obj_color (MP mp,pointer p) { 
9706   if ( color_model(p)==mp_grey_model ) {
9707     if ( grey_val(p)>0 ) { 
9708       mp_print(mp, "greyed ");
9709       mp_print_compact_node(mp, obj_grey_loc(p),1);
9710     };
9711   } else if ( color_model(p)==mp_cmyk_model ) {
9712     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9713          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9714       mp_print(mp, "processcolored ");
9715       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9716     };
9717   } else if ( color_model(p)==mp_rgb_model ) {
9718     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9719       mp_print(mp, "colored "); 
9720       mp_print_compact_node(mp, obj_red_loc(p),3);
9721     };
9722   }
9723 }
9724
9725 @ We also need a procedure for printing consecutive scaled values as if they
9726 were a known big node.
9727
9728 @<Declare a procedure called |print_compact_node|@>=
9729 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9730   pointer q;  /* last location to print */
9731   q=p+k-1;
9732   mp_print_char(mp, '(');
9733   while ( p<=q ){ 
9734     mp_print_scaled(mp, mp->mem[p].sc);
9735     if ( p<q ) mp_print_char(mp, ',');
9736     incr(p);
9737   }
9738   mp_print_char(mp, ')');
9739 }
9740
9741 @ @<Cases for printing graphical object node |p|@>=
9742 case mp_stroked_code: 
9743   mp_print(mp, "Filled pen stroke ");
9744   mp_print_obj_color(mp, p);
9745   mp_print_char(mp, ':'); mp_print_ln(mp);
9746   mp_pr_path(mp, path_p(p));
9747   if ( dash_p(p)!=null ) { 
9748     mp_print_nl(mp, "dashed (");
9749     @<Finish printing the dash pattern that |p| refers to@>;
9750   }
9751   mp_print_ln(mp);
9752   @<Print join and cap types for stroked node |p|@>;
9753   mp_print(mp, " with pen"); mp_print_ln(mp);
9754   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9755 @.???@>
9756   else mp_pr_pen(mp, pen_p(p));
9757   break;
9758
9759 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9760 when it is not known to define a suitable dash pattern.  This is disallowed
9761 here because the |dash_p| field should never point to such an edge header.
9762 Note that memory is allocated for |start_x(null_dash)| and we are free to
9763 give it any convenient value.
9764
9765 @<Finish printing the dash pattern that |p| refers to@>=
9766 ok_to_dash=pen_is_elliptical(pen_p(p));
9767 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9768 hh=dash_p(p);
9769 pp=dash_list(hh);
9770 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9771   mp_print(mp, " ??");
9772 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9773   while ( pp!=null_dash ) { 
9774     mp_print(mp, "on ");
9775     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9776     mp_print(mp, " off ");
9777     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9778     pp = link(pp);
9779     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9780   }
9781   mp_print(mp, ") shifted ");
9782   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9783   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9784 }
9785
9786 @ @<Declare subroutines needed by |print_edges|@>=
9787 scaled mp_dash_offset (MP mp,pointer h) {
9788   scaled x;  /* the answer */
9789   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9790 @:this can't happen dash0}{\quad dash0@>
9791   if ( dash_y(h)==0 ) {
9792     x=0; 
9793   } else { 
9794     x=-(start_x(dash_list(h)) % dash_y(h));
9795     if ( x<0 ) x=x+dash_y(h);
9796   }
9797   return x;
9798 }
9799
9800 @ @<Cases for printing graphical object node |p|@>=
9801 case mp_text_code: 
9802   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9803   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9804   mp_print_char(mp, '"'); mp_print_ln(mp);
9805   mp_print_obj_color(mp, p);
9806   mp_print(mp, "transformed ");
9807   mp_print_compact_node(mp, text_tx_loc(p),6);
9808   break;
9809
9810 @ @<Cases for printing graphical object node |p|@>=
9811 case mp_start_clip_code: 
9812   mp_print(mp, "clipping path:");
9813   mp_print_ln(mp);
9814   mp_pr_path(mp, path_p(p));
9815   break;
9816 case mp_stop_clip_code: 
9817   mp_print(mp, "stop clipping");
9818   break;
9819
9820 @ @<Cases for printing graphical object node |p|@>=
9821 case mp_start_bounds_code: 
9822   mp_print(mp, "setbounds path:");
9823   mp_print_ln(mp);
9824   mp_pr_path(mp, path_p(p));
9825   break;
9826 case mp_stop_bounds_code: 
9827   mp_print(mp, "end of setbounds");
9828   break;
9829
9830 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9831 subroutine that scans an edge structure and tries to interpret it as a dash
9832 pattern.  This can only be done when there are no filled regions or clipping
9833 paths and all the pen strokes have the same color.  The first step is to let
9834 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9835 project all the pen stroke paths onto the line $y=y_0$ and require that there
9836 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9837 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9838 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9839
9840 @c @<Declare a procedure called |x_retrace_error|@>;
9841 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9842   pointer p;  /* this scans the stroked nodes in the object list */
9843   pointer p0;  /* if not |null| this points to the first stroked node */
9844   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9845   pointer d,dd;  /* pointers used to create the dash list */
9846   @<Other local variables in |make_dashes|@>;
9847   scaled y0=0;  /* the initial $y$ coordinate */
9848   if ( dash_list(h)!=null_dash ) 
9849         return h;
9850   p0=null;
9851   p=link(dummy_loc(h));
9852   while ( p!=null ) { 
9853     if ( type(p)!=mp_stroked_code ) {
9854       @<Compain that the edge structure contains a node of the wrong type
9855         and |goto not_found|@>;
9856     }
9857     pp=path_p(p);
9858     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9859     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9860       or |goto not_found| if there is an error@>;
9861     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9862     p=link(p);
9863   }
9864   if ( dash_list(h)==null_dash ) 
9865     goto NOT_FOUND; /* No error message */
9866   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9867   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9868   return h;
9869 NOT_FOUND: 
9870   @<Flush the dash list, recycle |h| and return |null|@>;
9871 };
9872
9873 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9874
9875 print_err("Picture is too complicated to use as a dash pattern");
9876 help3("When you say `dashed p', picture p should not contain any")
9877   ("text, filled regions, or clipping paths.  This time it did")
9878   ("so I'll just make it a solid line instead.");
9879 mp_put_get_error(mp);
9880 goto NOT_FOUND;
9881 }
9882
9883 @ A similar error occurs when monotonicity fails.
9884
9885 @<Declare a procedure called |x_retrace_error|@>=
9886 void mp_x_retrace_error (MP mp) { 
9887 print_err("Picture is too complicated to use as a dash pattern");
9888 help3("When you say `dashed p', every path in p should be monotone")
9889   ("in x and there must be no overlapping.  This failed")
9890   ("so I'll just make it a solid line instead.");
9891 mp_put_get_error(mp);
9892 }
9893
9894 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9895 handle the case where the pen stroke |p| is itself dashed.
9896
9897 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9898 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9899   an error@>;
9900 rr=pp;
9901 if ( link(pp)!=pp ) {
9902   do {  
9903     qq=rr; rr=link(rr);
9904     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9905       if there is a problem@>;
9906   } while (right_type(rr)!=mp_endpoint);
9907 }
9908 d=mp_get_node(mp, dash_node_size);
9909 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9910 if ( x_coord(pp)<x_coord(rr) ) { 
9911   start_x(d)=x_coord(pp);
9912   stop_x(d)=x_coord(rr);
9913 } else { 
9914   start_x(d)=x_coord(rr);
9915   stop_x(d)=x_coord(pp);
9916 }
9917
9918 @ We also need to check for the case where the segment from |qq| to |rr| is
9919 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9920
9921 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9922 x0=x_coord(qq);
9923 x1=right_x(qq);
9924 x2=left_x(rr);
9925 x3=x_coord(rr);
9926 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9927   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9928     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9929       mp_x_retrace_error(mp); goto NOT_FOUND;
9930     }
9931   }
9932 }
9933 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9934   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9935     mp_x_retrace_error(mp); goto NOT_FOUND;
9936   }
9937 }
9938
9939 @ @<Other local variables in |make_dashes|@>=
9940   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9941
9942 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9943 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9944   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9945   print_err("Picture is too complicated to use as a dash pattern");
9946   help3("When you say `dashed p', everything in picture p should")
9947     ("be the same color.  I can\'t handle your color changes")
9948     ("so I'll just make it a solid line instead.");
9949   mp_put_get_error(mp);
9950   goto NOT_FOUND;
9951 }
9952
9953 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9954 start_x(null_dash)=stop_x(d);
9955 dd=h; /* this makes |link(dd)=dash_list(h)| */
9956 while ( start_x(link(dd))<stop_x(d) )
9957   dd=link(dd);
9958 if ( dd!=h ) {
9959   if ( (stop_x(dd)>start_x(d)) )
9960     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9961 }
9962 link(d)=link(dd);
9963 link(dd)=d
9964
9965 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9966 d=dash_list(h);
9967 while ( (link(d)!=null_dash) )
9968   d=link(d);
9969 dd=dash_list(h);
9970 dash_y(h)=stop_x(d)-start_x(dd);
9971 if ( abs(y0)>dash_y(h) ) {
9972   dash_y(h)=abs(y0);
9973 } else if ( d!=dd ) { 
9974   dash_list(h)=link(dd);
9975   stop_x(d)=stop_x(dd)+dash_y(h);
9976   mp_free_node(mp, dd,dash_node_size);
9977 }
9978
9979 @ We get here when the argument is a null picture or when there is an error.
9980 Recovering from an error involves making |dash_list(h)| empty to indicate
9981 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9982 since it is not being used for the return value.
9983
9984 @<Flush the dash list, recycle |h| and return |null|@>=
9985 mp_flush_dash_list(mp, h);
9986 delete_edge_ref(h);
9987 return null
9988
9989 @ Having carefully saved the dashed stroked nodes in the
9990 corresponding dash nodes, we must be prepared to break up these dashes into
9991 smaller dashes.
9992
9993 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9994 d=h;  /* now |link(d)=dash_list(h)| */
9995 while ( link(d)!=null_dash ) {
9996   ds=info(link(d));
9997   if ( ds==null ) { 
9998     d=link(d);
9999   } else {
10000     hh=dash_p(ds);
10001     hsf=dash_scale(ds);
10002     if ( (hh==null) ) mp_confusion(mp, "dash1");
10003 @:this can't happen dash0}{\quad dash1@>
10004     if ( dash_y(hh)==0 ) {
10005       d=link(d);
10006     } else { 
10007       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10008 @:this can't happen dash0}{\quad dash1@>
10009       @<Replace |link(d)| by a dashed version as determined by edge header
10010           |hh| and scale factor |ds|@>;
10011     }
10012   }
10013 }
10014
10015 @ @<Other local variables in |make_dashes|@>=
10016 pointer dln;  /* |link(d)| */
10017 pointer hh;  /* an edge header that tells how to break up |dln| */
10018 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10019 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10020 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10021
10022 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10023 dln=link(d);
10024 dd=dash_list(hh);
10025 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10026         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10027 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10028                    +mp_take_scaled(mp, hsf,dash_y(hh));
10029 stop_x(null_dash)=start_x(null_dash);
10030 @<Advance |dd| until finding the first dash that overlaps |dln| when
10031   offset by |xoff|@>;
10032 while ( start_x(dln)<=stop_x(dln) ) {
10033   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10034   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10035     of |dd|@>;
10036   dd=link(dd);
10037   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10038 }
10039 link(d)=link(dln);
10040 mp_free_node(mp, dln,dash_node_size)
10041
10042 @ The name of this module is a bit of a lie because we just find the
10043 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10044 overlap possible.  It could be that the unoffset version of dash |dln| falls
10045 in the gap between |dd| and its predecessor.
10046
10047 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10048 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10049   dd=link(dd);
10050 }
10051
10052 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10053 if ( dd==null_dash ) { 
10054   dd=dash_list(hh);
10055   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10056 }
10057
10058 @ At this point we already know that
10059 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10060
10061 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10062 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10063   link(d)=mp_get_node(mp, dash_node_size);
10064   d=link(d);
10065   link(d)=dln;
10066   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10067     start_x(d)=start_x(dln);
10068   else 
10069     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10070   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10071     stop_x(d)=stop_x(dln);
10072   else 
10073     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10074 }
10075
10076 @ The next major task is to update the bounding box information in an edge
10077 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10078 header's bounding box to accommodate the box computed by |path_bbox| or
10079 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10080 |maxy|.)
10081
10082 @c void mp_adjust_bbox (MP mp,pointer h) { 
10083   if ( minx<minx_val(h) ) minx_val(h)=minx;
10084   if ( miny<miny_val(h) ) miny_val(h)=miny;
10085   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10086   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10087 }
10088
10089 @ Here is a special routine for updating the bounding box information in
10090 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10091 that is to be stroked with the pen~|pp|.
10092
10093 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10094   pointer q;  /* a knot node adjacent to knot |p| */
10095   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10096   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10097   scaled z;  /* a coordinate being tested against the bounding box */
10098   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10099   integer i; /* a loop counter */
10100   if ( right_type(p)!=mp_endpoint ) { 
10101     q=link(p);
10102     while (1) { 
10103       @<Make |(dx,dy)| the final direction for the path segment from
10104         |q| to~|p|; set~|d|@>;
10105       d=mp_pyth_add(mp, dx,dy);
10106       if ( d>0 ) { 
10107          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10108          for (i=1;i<= 2;i++) { 
10109            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10110              update the bounding box to accommodate it@>;
10111            dx=-dx; dy=-dy; 
10112         }
10113       }
10114       if ( right_type(p)==mp_endpoint ) {
10115          return;
10116       } else {
10117         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10118       } 
10119     }
10120   }
10121 }
10122
10123 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10124 if ( q==link(p) ) { 
10125   dx=x_coord(p)-right_x(p);
10126   dy=y_coord(p)-right_y(p);
10127   if ( (dx==0)&&(dy==0) ) {
10128     dx=x_coord(p)-left_x(q);
10129     dy=y_coord(p)-left_y(q);
10130   }
10131 } else { 
10132   dx=x_coord(p)-left_x(p);
10133   dy=y_coord(p)-left_y(p);
10134   if ( (dx==0)&&(dy==0) ) {
10135     dx=x_coord(p)-right_x(q);
10136     dy=y_coord(p)-right_y(q);
10137   }
10138 }
10139 dx=x_coord(p)-x_coord(q);
10140 dy=y_coord(p)-y_coord(q)
10141
10142 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10143 dx=mp_make_fraction(mp, dx,d);
10144 dy=mp_make_fraction(mp, dy,d);
10145 mp_find_offset(mp, -dy,dx,pp);
10146 xx=mp->cur_x; yy=mp->cur_y
10147
10148 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10149 mp_find_offset(mp, dx,dy,pp);
10150 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10151 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10152   mp_confusion(mp, "box_ends");
10153 @:this can't happen box ends}{\quad\\{box\_ends}@>
10154 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10155 if ( z<minx_val(h) ) minx_val(h)=z;
10156 if ( z>maxx_val(h) ) maxx_val(h)=z;
10157 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10158 if ( z<miny_val(h) ) miny_val(h)=z;
10159 if ( z>maxy_val(h) ) maxy_val(h)=z
10160
10161 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10162 do {  
10163   q=p;
10164   p=link(p);
10165 } while (right_type(p)!=mp_endpoint)
10166
10167 @ The major difficulty in finding the bounding box of an edge structure is the
10168 effect of clipping paths.  We treat them conservatively by only clipping to the
10169 clipping path's bounding box, but this still
10170 requires recursive calls to |set_bbox| in order to find the bounding box of
10171 @^recursion@>
10172 the objects to be clipped.  Such calls are distinguished by the fact that the
10173 boolean parameter |top_level| is false.
10174
10175 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10176   pointer p;  /* a graphical object being considered */
10177   scaled sminx,sminy,smaxx,smaxy;
10178   /* for saving the bounding box during recursive calls */
10179   scaled x0,x1,y0,y1;  /* temporary registers */
10180   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10181   @<Wipe out any existing bounding box information if |bbtype(h)| is
10182   incompatible with |internal[mp_true_corners]|@>;
10183   while ( link(bblast(h))!=null ) { 
10184     p=link(bblast(h));
10185     bblast(h)=p;
10186     switch (type(p)) {
10187     case mp_stop_clip_code: 
10188       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10189 @:this can't happen bbox}{\quad bbox@>
10190       break;
10191     @<Other cases for updating the bounding box based on the type of object |p|@>;
10192     } /* all cases are enumerated above */
10193   }
10194   if ( ! top_level ) mp_confusion(mp, "bbox");
10195 }
10196
10197 @ @<Internal library declarations@>=
10198 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10199
10200 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10201 switch (bbtype(h)) {
10202 case no_bounds: 
10203   break;
10204 case bounds_set: 
10205   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10206   break;
10207 case bounds_unset: 
10208   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10209   break;
10210 } /* there are no other cases */
10211
10212 @ @<Other cases for updating the bounding box...@>=
10213 case mp_fill_code: 
10214   mp_path_bbox(mp, path_p(p));
10215   if ( pen_p(p)!=null ) { 
10216     x0=minx; y0=miny;
10217     x1=maxx; y1=maxy;
10218     mp_pen_bbox(mp, pen_p(p));
10219     minx=minx+x0;
10220     miny=miny+y0;
10221     maxx=maxx+x1;
10222     maxy=maxy+y1;
10223   }
10224   mp_adjust_bbox(mp, h);
10225   break;
10226
10227 @ @<Other cases for updating the bounding box...@>=
10228 case mp_start_bounds_code: 
10229   if ( mp->internal[mp_true_corners]>0 ) {
10230     bbtype(h)=bounds_unset;
10231   } else { 
10232     bbtype(h)=bounds_set;
10233     mp_path_bbox(mp, path_p(p));
10234     mp_adjust_bbox(mp, h);
10235     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10236       |bblast(h)|@>;
10237   }
10238   break;
10239 case mp_stop_bounds_code: 
10240   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10241 @:this can't happen bbox2}{\quad bbox2@>
10242   break;
10243
10244 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10245 lev=1;
10246 while ( lev!=0 ) { 
10247   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10248 @:this can't happen bbox2}{\quad bbox2@>
10249   p=link(p);
10250   if ( type(p)==mp_start_bounds_code ) incr(lev);
10251   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10252 }
10253 bblast(h)=p
10254
10255 @ It saves a lot of grief here to be slightly conservative and not account for
10256 omitted parts of dashed lines.  We also don't worry about the material omitted
10257 when using butt end caps.  The basic computation is for round end caps and
10258 |box_ends| augments it for square end caps.
10259
10260 @<Other cases for updating the bounding box...@>=
10261 case mp_stroked_code: 
10262   mp_path_bbox(mp, path_p(p));
10263   x0=minx; y0=miny;
10264   x1=maxx; y1=maxy;
10265   mp_pen_bbox(mp, pen_p(p));
10266   minx=minx+x0;
10267   miny=miny+y0;
10268   maxx=maxx+x1;
10269   maxy=maxy+y1;
10270   mp_adjust_bbox(mp, h);
10271   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10272     mp_box_ends(mp, path_p(p), pen_p(p), h);
10273   break;
10274
10275 @ The height width and depth information stored in a text node determines a
10276 rectangle that needs to be transformed according to the transformation
10277 parameters stored in the text node.
10278
10279 @<Other cases for updating the bounding box...@>=
10280 case mp_text_code: 
10281   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10282   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10283   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10284   minx=tx_val(p);
10285   maxx=minx;
10286   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10287   else         { minx=minx+y1; maxx=maxx+y0;  }
10288   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10289   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10290   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10291   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10292   miny=ty_val(p);
10293   maxy=miny;
10294   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10295   else         { miny=miny+y1; maxy=maxy+y0;  }
10296   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10297   mp_adjust_bbox(mp, h);
10298   break;
10299
10300 @ This case involves a recursive call that advances |bblast(h)| to the node of
10301 type |mp_stop_clip_code| that matches |p|.
10302
10303 @<Other cases for updating the bounding box...@>=
10304 case mp_start_clip_code: 
10305   mp_path_bbox(mp, path_p(p));
10306   x0=minx; y0=miny;
10307   x1=maxx; y1=maxy;
10308   sminx=minx_val(h); sminy=miny_val(h);
10309   smaxx=maxx_val(h); smaxy=maxy_val(h);
10310   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10311     starting at |link(p)|@>;
10312   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10313     |y0|, |y1|@>;
10314   minx=sminx; miny=sminy;
10315   maxx=smaxx; maxy=smaxy;
10316   mp_adjust_bbox(mp, h);
10317   break;
10318
10319 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10320 minx_val(h)=el_gordo;
10321 miny_val(h)=el_gordo;
10322 maxx_val(h)=-el_gordo;
10323 maxy_val(h)=-el_gordo;
10324 mp_set_bbox(mp, h,false)
10325
10326 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10327 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10328 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10329 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10330 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10331
10332 @* \[22] Finding an envelope.
10333 When \MP\ has a path and a polygonal pen, it needs to express the desired
10334 shape in terms of things \ps\ can understand.  The present task is to compute
10335 a new path that describes the region to be filled.  It is convenient to
10336 define this as a two step process where the first step is determining what
10337 offset to use for each segment of the path.
10338
10339 @ Given a pointer |c| to a cyclic path,
10340 and a pointer~|h| to the first knot of a pen polygon,
10341 the |offset_prep| routine changes the path into cubics that are
10342 associated with particular pen offsets. Thus if the cubic between |p|
10343 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10344 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10345 to because |l-k| could be negative.)
10346
10347 After overwriting the type information with offset differences, we no longer
10348 have a true path so we refer to the knot list returned by |offset_prep| as an
10349 ``envelope spec.''
10350 @^envelope spec@>
10351 Since an envelope spec only determines relative changes in pen offsets,
10352 |offset_prep| sets a global variable |spec_offset| to the relative change from
10353 |h| to the first offset.
10354
10355 @d zero_off 16384 /* added to offset changes to make them positive */
10356
10357 @<Glob...@>=
10358 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10359
10360 @ @c @<Declare subroutines needed by |offset_prep|@>;
10361 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10362   halfword n; /* the number of vertices in the pen polygon */
10363   pointer p,q,q0,r,w, ww; /* for list manipulation */
10364   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10365   pointer w0; /* a pointer to pen offset to use just before |p| */
10366   scaled dxin,dyin; /* the direction into knot |p| */
10367   integer turn_amt; /* change in pen offsets for the current cubic */
10368   @<Other local variables for |offset_prep|@>;
10369   dx0=0; dy0=0;
10370   @<Initialize the pen size~|n|@>;
10371   @<Initialize the incoming direction and pen offset at |c|@>;
10372   p=c; k_needed=0;
10373   do {  
10374     q=link(p);
10375     @<Split the cubic between |p| and |q|, if necessary, into cubics
10376       associated with single offsets, after which |q| should
10377       point to the end of the final such cubic@>;
10378   NOT_FOUND:
10379     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10380       might have been introduced by the splitting process@>;
10381   } while (q!=c);
10382   @<Fix the offset change in |info(c)| and set |c| to the return value of
10383     |offset_prep|@>;
10384   return c;
10385 }
10386
10387 @ We shall want to keep track of where certain knots on the cyclic path
10388 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10389 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10390 |offset_prep| updates the following pointers
10391
10392 @<Glob...@>=
10393 pointer spec_p1;
10394 pointer spec_p2; /* pointers to distinguished knots */
10395
10396 @ @<Set init...@>=
10397 mp->spec_p1=null; mp->spec_p2=null;
10398
10399 @ @<Initialize the pen size~|n|@>=
10400 n=0; p=h;
10401 do {  
10402   incr(n);
10403   p=link(p);
10404 } while (p!=h)
10405
10406 @ Since the true incoming direction isn't known yet, we just pick a direction
10407 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10408 later.
10409
10410 @<Initialize the incoming direction and pen offset at |c|@>=
10411 dxin=x_coord(link(h))-x_coord(knil(h));
10412 dyin=y_coord(link(h))-y_coord(knil(h));
10413 if ( (dxin==0)&&(dyin==0) ) {
10414   dxin=y_coord(knil(h))-y_coord(h);
10415   dyin=x_coord(h)-x_coord(knil(h));
10416 }
10417 w0=h
10418
10419 @ We must be careful not to remove the only cubic in a cycle.
10420
10421 But we must also be careful for another reason. If the user-supplied
10422 path starts with a set of degenerate cubics, the target node |q| can
10423 be collapsed to the initial node |p| which might be the same as the
10424 initial node |c| of the curve. This would cause the |offset_prep| routine
10425 to bail out too early, causing distress later on. (See for example
10426 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10427 on Sarovar.)
10428
10429 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10430 q0=q;
10431 do { 
10432   r=link(p);
10433   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10434        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10435        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10436        r!=p ) {
10437       @<Remove the cubic following |p| and update the data structures
10438         to merge |r| into |p|@>;
10439   }
10440   p=r;
10441 } while (p!=q);
10442 /* Check if we removed too much */
10443 if(q!=q0)
10444   q = link(q)
10445
10446 @ @<Remove the cubic following |p| and update the data structures...@>=
10447 { k_needed=info(p)-zero_off;
10448   if ( r==q ) { 
10449     q=p;
10450   } else { 
10451     info(p)=k_needed+info(r);
10452     k_needed=0;
10453   };
10454   if ( r==c ) { info(p)=info(c); c=p; };
10455   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10456   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10457   r=p; mp_remove_cubic(mp, p);
10458 }
10459
10460 @ Not setting the |info| field of the newly created knot allows the splitting
10461 routine to work for paths.
10462
10463 @<Declare subroutines needed by |offset_prep|@>=
10464 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10465   scaled v; /* an intermediate value */
10466   pointer q,r; /* for list manipulation */
10467   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10468   originator(r)=mp_program_code;
10469   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10470   v=t_of_the_way(right_x(p),left_x(q));
10471   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10472   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10473   left_x(r)=t_of_the_way(right_x(p),v);
10474   right_x(r)=t_of_the_way(v,left_x(q));
10475   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10476   v=t_of_the_way(right_y(p),left_y(q));
10477   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10478   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10479   left_y(r)=t_of_the_way(right_y(p),v);
10480   right_y(r)=t_of_the_way(v,left_y(q));
10481   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10482 }
10483
10484 @ This does not set |info(p)| or |right_type(p)|.
10485
10486 @<Declare subroutines needed by |offset_prep|@>=
10487 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10488   pointer q; /* the node that disappears */
10489   q=link(p); link(p)=link(q);
10490   right_x(p)=right_x(q); right_y(p)=right_y(q);
10491   mp_free_node(mp, q,knot_node_size);
10492 }
10493
10494 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10495 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10496 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10497 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10498 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10499 When listed by increasing $k$, these directions occur in counter-clockwise
10500 order so that $d_k\preceq d\k$ for all~$k$.
10501 The goal of |offset_prep| is to find an offset index~|k| to associate with
10502 each cubic, such that the direction $d(t)$ of the cubic satisfies
10503 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10504 We may have to split a cubic into many pieces before each
10505 piece corresponds to a unique offset.
10506
10507 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10508 info(p)=zero_off+k_needed;
10509 k_needed=0;
10510 @<Prepare for derivative computations;
10511   |goto not_found| if the current cubic is dead@>;
10512 @<Find the initial direction |(dx,dy)|@>;
10513 @<Update |info(p)| and find the offset $w_k$ such that
10514   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10515   the direction change at |p|@>;
10516 @<Find the final direction |(dxin,dyin)|@>;
10517 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10518 @<Complete the offset splitting process@>;
10519 w0=mp_pen_walk(mp, w0,turn_amt)
10520
10521 @ @<Declare subroutines needed by |offset_prep|@>=
10522 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10523   /* walk |k| steps around a pen from |w| */
10524   while ( k>0 ) { w=link(w); decr(k);  };
10525   while ( k<0 ) { w=knil(w); incr(k);  };
10526   return w;
10527 }
10528
10529 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10530 calculated from the quadratic polynomials
10531 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10532 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10533 Since we may be calculating directions from several cubics
10534 split from the current one, it is desirable to do these calculations
10535 without losing too much precision. ``Scaled up'' values of the
10536 derivatives, which will be less tainted by accumulated errors than
10537 derivatives found from the cubics themselves, are maintained in
10538 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10539 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10540 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)$.
10541
10542 @<Other local variables for |offset_prep|@>=
10543 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10544 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10545 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10546 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10547 integer max_coef; /* used while scaling */
10548 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10549 fraction t; /* where the derivative passes through zero */
10550 fraction s; /* a temporary value */
10551
10552 @ @<Prepare for derivative computations...@>=
10553 x0=right_x(p)-x_coord(p);
10554 x2=x_coord(q)-left_x(q);
10555 x1=left_x(q)-right_x(p);
10556 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10557 y1=left_y(q)-right_y(p);
10558 max_coef=abs(x0);
10559 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10560 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10561 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10562 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10563 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10564 if ( max_coef==0 ) goto NOT_FOUND;
10565 while ( max_coef<fraction_half ) {
10566   double(max_coef);
10567   double(x0); double(x1); double(x2);
10568   double(y0); double(y1); double(y2);
10569 }
10570
10571 @ Let us first solve a special case of the problem: Suppose we
10572 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10573 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10574 $d(0)\succ d_{k-1}$.
10575 Then, in a sense, we're halfway done, since one of the two relations
10576 in $(*)$ is satisfied, and the other couldn't be satisfied for
10577 any other value of~|k|.
10578
10579 Actually, the conditions can be relaxed somewhat since a relation such as
10580 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10581 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10582 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10583 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10584 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10585 counterclockwise direction.
10586
10587 The |fin_offset_prep| subroutine solves the stated subproblem.
10588 It has a parameter called |rise| that is |1| in
10589 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10590 the derivative of the cubic following |p|.
10591 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10592 be set properly.  The |turn_amt| parameter gives the absolute value of the
10593 overall net change in pen offsets.
10594
10595 @<Declare subroutines needed by |offset_prep|@>=
10596 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10597   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10598   integer rise, integer turn_amt)  {
10599   pointer ww; /* for list manipulation */
10600   scaled du,dv; /* for slope calculation */
10601   integer t0,t1,t2; /* test coefficients */
10602   fraction t; /* place where the derivative passes a critical slope */
10603   fraction s; /* slope or reciprocal slope */
10604   integer v; /* intermediate value for updating |x0..y2| */
10605   pointer q; /* original |link(p)| */
10606   q=link(p);
10607   while (1)  { 
10608     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10609     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10610     @<Compute test coefficients |(t0,t1,t2)|
10611       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10612     t=mp_crossing_point(mp, t0,t1,t2);
10613     if ( t>=fraction_one ) {
10614       if ( turn_amt>0 ) t=fraction_one;  else return;
10615     }
10616     @<Split the cubic at $t$,
10617       and split off another cubic if the derivative crosses back@>;
10618     w=ww;
10619   }
10620 }
10621
10622 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10623 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10624 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10625 begins to fail.
10626
10627 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10628 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10629 if ( abs(du)>=abs(dv) ) {
10630   s=mp_make_fraction(mp, dv,du);
10631   t0=mp_take_fraction(mp, x0,s)-y0;
10632   t1=mp_take_fraction(mp, x1,s)-y1;
10633   t2=mp_take_fraction(mp, x2,s)-y2;
10634   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10635 } else { 
10636   s=mp_make_fraction(mp, du,dv);
10637   t0=x0-mp_take_fraction(mp, y0,s);
10638   t1=x1-mp_take_fraction(mp, y1,s);
10639   t2=x2-mp_take_fraction(mp, y2,s);
10640   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10641 }
10642 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10643
10644 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10645 $(*)$, and it might cross again, yielding another solution of $(*)$.
10646
10647 @<Split the cubic at $t$, and split off another...@>=
10648
10649 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10650 decr(turn_amt);
10651 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10652 x0=t_of_the_way(v,x1);
10653 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10654 y0=t_of_the_way(v,y1);
10655 if ( turn_amt<0 ) {
10656   t1=t_of_the_way(t1,t2);
10657   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10658   t=mp_crossing_point(mp, 0,-t1,-t2);
10659   if ( t>fraction_one ) t=fraction_one;
10660   incr(turn_amt);
10661   if ( (t==fraction_one)&&(link(p)!=q) ) {
10662     info(link(p))=info(link(p))-rise;
10663   } else { 
10664     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10665     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10666     x2=t_of_the_way(x1,v);
10667     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10668     y2=t_of_the_way(y1,v);
10669   }
10670 }
10671 }
10672
10673 @ Now we must consider the general problem of |offset_prep|, when
10674 nothing is known about a given cubic. We start by finding its
10675 direction in the vicinity of |t=0|.
10676
10677 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10678 has not yet introduced any more numerical errors.  Thus we can compute
10679 the true initial direction for the given cubic, even if it is almost
10680 degenerate.
10681
10682 @<Find the initial direction |(dx,dy)|@>=
10683 dx=x0; dy=y0;
10684 if ( dx==0 && dy==0 ) { 
10685   dx=x1; dy=y1;
10686   if ( dx==0 && dy==0 ) { 
10687     dx=x2; dy=y2;
10688   }
10689 }
10690 if ( p==c ) { dx0=dx; dy0=dy;  }
10691
10692 @ @<Find the final direction |(dxin,dyin)|@>=
10693 dxin=x2; dyin=y2;
10694 if ( dxin==0 && dyin==0 ) {
10695   dxin=x1; dyin=y1;
10696   if ( dxin==0 && dyin==0 ) {
10697     dxin=x0; dyin=y0;
10698   }
10699 }
10700
10701 @ The next step is to bracket the initial direction between consecutive
10702 edges of the pen polygon.  We must be careful to turn clockwise only if
10703 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10704 counter-clockwise in order to make \&{doublepath} envelopes come out
10705 @:double_path_}{\&{doublepath} primitive@>
10706 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10707
10708 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10709 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10710 w=mp_pen_walk(mp, w0, turn_amt);
10711 w0=w;
10712 info(p)=info(p)+turn_amt
10713
10714 @ Decide how many pen offsets to go away from |w| in order to find the offset
10715 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10716 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10717 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10718
10719 If the pen polygon has only two edges, they could both be parallel
10720 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10721 such edge in order to avoid an infinite loop.
10722
10723 @<Declare subroutines needed by |offset_prep|@>=
10724 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10725                          scaled dy, boolean  ccw) {
10726   pointer ww; /* a neighbor of knot~|w| */
10727   integer s; /* turn amount so far */
10728   integer t; /* |ab_vs_cd| result */
10729   s=0;
10730   if ( ccw ) { 
10731     ww=link(w);
10732     do {  
10733       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10734                         dx,(y_coord(ww)-y_coord(w)));
10735       if ( t<0 ) break;
10736       incr(s);
10737       w=ww; ww=link(ww);
10738     } while (t>0);
10739   } else { 
10740     ww=knil(w);
10741     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10742                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10743       decr(s);
10744       w=ww; ww=knil(ww);
10745     }
10746   }
10747   return s;
10748 }
10749
10750 @ When we're all done, the final offset is |w0| and the final curve direction
10751 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10752 can correct |info(c)| which was erroneously based on an incoming offset
10753 of~|h|.
10754
10755 @d fix_by(A) info(c)=info(c)+(A)
10756
10757 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10758 mp->spec_offset=info(c)-zero_off;
10759 if ( link(c)==c ) {
10760   info(c)=zero_off+n;
10761 } else { 
10762   fix_by(k_needed);
10763   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10764   while ( info(c)<=zero_off-n ) fix_by(n);
10765   while ( info(c)>zero_off ) fix_by(-n);
10766   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10767 }
10768 return c
10769
10770 @ Finally we want to reduce the general problem to situations that
10771 |fin_offset_prep| can handle. We split the cubic into at most three parts
10772 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10773
10774 @<Complete the offset splitting process@>=
10775 ww=knil(w);
10776 @<Compute test coeff...@>;
10777 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10778   |t:=fraction_one+1|@>;
10779 if ( t>fraction_one ) {
10780   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10781 } else {
10782   mp_split_cubic(mp, p,t); r=link(p);
10783   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10784   x2a=t_of_the_way(x1a,x1);
10785   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10786   y2a=t_of_the_way(y1a,y1);
10787   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10788   info(r)=zero_off-1;
10789   if ( turn_amt>=0 ) {
10790     t1=t_of_the_way(t1,t2);
10791     if ( t1>0 ) t1=0;
10792     t=mp_crossing_point(mp, 0,-t1,-t2);
10793     if ( t>fraction_one ) t=fraction_one;
10794     @<Split off another rising cubic for |fin_offset_prep|@>;
10795     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10796   } else {
10797     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10798   }
10799 }
10800
10801 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10802 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10803 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10804 x0a=t_of_the_way(x1,x1a);
10805 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10806 y0a=t_of_the_way(y1,y1a);
10807 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10808 x2=x0a; y2=y0a
10809
10810 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10811 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10812 need to decide whether the directions are parallel or antiparallel.  We
10813 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10814 should be avoided when the value of |turn_amt| already determines the
10815 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10816 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10817 crossing and the first crossing cannot be antiparallel.
10818
10819 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10820 t=mp_crossing_point(mp, t0,t1,t2);
10821 if ( turn_amt>=0 ) {
10822   if ( t2<0 ) {
10823     t=fraction_one+1;
10824   } else { 
10825     u0=t_of_the_way(x0,x1);
10826     u1=t_of_the_way(x1,x2);
10827     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10828     v0=t_of_the_way(y0,y1);
10829     v1=t_of_the_way(y1,y2);
10830     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10831     if ( ss<0 ) t=fraction_one+1;
10832   }
10833 } else if ( t>fraction_one ) {
10834   t=fraction_one;
10835 }
10836
10837 @ @<Other local variables for |offset_prep|@>=
10838 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10839 integer ss = 0; /* the part of the dot product computed so far */
10840 int d_sign; /* sign of overall change in direction for this cubic */
10841
10842 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10843 problem to decide which way it loops around but that's OK as long we're
10844 consistent.  To make \&{doublepath} envelopes work properly, reversing
10845 the path should always change the sign of |turn_amt|.
10846
10847 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10848 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10849 if ( d_sign==0 ) {
10850   @<Check rotation direction based on node position@>
10851 }
10852 if ( d_sign==0 ) {
10853   if ( dx==0 ) {
10854     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10855   } else {
10856     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10857   }
10858 }
10859 @<Make |ss| negative if and only if the total change in direction is
10860   more than $180^\circ$@>;
10861 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10862 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10863
10864 @ We check rotation direction by looking at the vector connecting the current
10865 node with the next. If its angle with incoming and outgoing tangents has the
10866 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10867 Otherwise we proceed to the cusp code.
10868
10869 @<Check rotation direction based on node position@>=
10870 u0=x_coord(q)-x_coord(p);
10871 u1=y_coord(q)-y_coord(p);
10872 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10873   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10874
10875 @ In order to be invariant under path reversal, the result of this computation
10876 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10877 then swapped with |(x2,y2)|.  We make use of the identities
10878 |take_fraction(-a,-b)=take_fraction(a,b)| and
10879 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10880
10881 @<Make |ss| negative if and only if the total change in direction is...@>=
10882 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10883 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10884 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10885 if ( t0>0 ) {
10886   t=mp_crossing_point(mp, t0,t1,-t0);
10887   u0=t_of_the_way(x0,x1);
10888   u1=t_of_the_way(x1,x2);
10889   v0=t_of_the_way(y0,y1);
10890   v1=t_of_the_way(y1,y2);
10891 } else { 
10892   t=mp_crossing_point(mp, -t0,t1,t0);
10893   u0=t_of_the_way(x2,x1);
10894   u1=t_of_the_way(x1,x0);
10895   v0=t_of_the_way(y2,y1);
10896   v1=t_of_the_way(y1,y0);
10897 }
10898 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10899    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10900
10901 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10902 that the |cur_pen| has not been walked around to the first offset.
10903
10904 @c 
10905 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10906   pointer p,q; /* list traversal */
10907   pointer w; /* the current pen offset */
10908   mp_print_diagnostic(mp, "Envelope spec",s,true);
10909   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10910   mp_print_ln(mp);
10911   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10912   mp_print(mp, " % beginning with offset ");
10913   mp_print_two(mp, x_coord(w),y_coord(w));
10914   do { 
10915     while (1) {  
10916       q=link(p);
10917       @<Print the cubic between |p| and |q|@>;
10918       p=q;
10919           if ((p==cur_spec) || (info(p)!=zero_off)) 
10920         break;
10921     }
10922     if ( info(p)!=zero_off ) {
10923       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10924     }
10925   } while (p!=cur_spec);
10926   mp_print_nl(mp, " & cycle");
10927   mp_end_diagnostic(mp, true);
10928 }
10929
10930 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10931
10932   w=mp_pen_walk(mp, w, (info(p)-zero_off));
10933   mp_print(mp, " % ");
10934   if ( info(p)>zero_off ) mp_print(mp, "counter");
10935   mp_print(mp, "clockwise to offset ");
10936   mp_print_two(mp, x_coord(w),y_coord(w));
10937 }
10938
10939 @ @<Print the cubic between |p| and |q|@>=
10940
10941   mp_print_nl(mp, "   ..controls ");
10942   mp_print_two(mp, right_x(p),right_y(p));
10943   mp_print(mp, " and ");
10944   mp_print_two(mp, left_x(q),left_y(q));
10945   mp_print_nl(mp, " ..");
10946   mp_print_two(mp, x_coord(q),y_coord(q));
10947 }
10948
10949 @ Once we have an envelope spec, the remaining task to construct the actual
10950 envelope by offsetting each cubic as determined by the |info| fields in
10951 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10952 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10953 the envelope.
10954
10955 The |ljoin| and |miterlim| parameters control the treatment of points where the
10956 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10957 The endpoints are easily located because |c| is given in undoubled form
10958 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10959 track of the endpoints and treat them like very sharp corners.
10960 Butt end caps are treated like beveled joins; round end caps are treated like
10961 round joins; and square end caps are achieved by setting |join_type:=3|.
10962
10963 None of these parameters apply to inside joins where the convolution tracing
10964 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10965 approach that is achieved by setting |join_type:=2|.
10966
10967 @c @<Declare a function called |insert_knot|@>;
10968 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10969   small_number lcap, scaled miterlim) {
10970   pointer p,q,r,q0; /* for manipulating the path */
10971   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10972   pointer w,w0; /* the pen knot for the current offset */
10973   scaled qx,qy; /* unshifted coordinates of |q| */
10974   halfword k,k0; /* controls pen edge insertion */
10975   @<Other local variables for |make_envelope|@>;
10976   dxin=0; dyin=0; dxout=0; dyout=0;
10977   mp->spec_p1=null; mp->spec_p2=null;
10978   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10979   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10980     the initial offset@>;
10981   w=h;
10982   p=c;
10983   do {  
10984     q=link(p); q0=q;
10985     qx=x_coord(q); qy=y_coord(q);
10986     k=info(q);
10987     k0=k; w0=w;
10988     if ( k!=zero_off ) {
10989       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10990     }
10991     @<Add offset |w| to the cubic from |p| to |q|@>;
10992     while ( k!=zero_off ) { 
10993       @<Step |w| and move |k| one step closer to |zero_off|@>;
10994       if ( (join_type==1)||(k==zero_off) )
10995          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10996     };
10997     if ( q!=link(p) ) {
10998       @<Set |p=link(p)| and add knots between |p| and |q| as
10999         required by |join_type|@>;
11000     }
11001     p=q;
11002   } while (q0!=c);
11003   return c;
11004 }
11005
11006 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11007 c=mp_offset_prep(mp, c,h);
11008 if ( mp->internal[mp_tracing_specs]>0 ) 
11009   mp_print_spec(mp, c,h,"");
11010 h=mp_pen_walk(mp, h,mp->spec_offset)
11011
11012 @ Mitered and squared-off joins depend on path directions that are difficult to
11013 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11014 have degenerate cubics only if the entire cycle collapses to a single
11015 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11016 envelope degenerate as well.
11017
11018 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11019 if ( k<zero_off ) {
11020   join_type=2;
11021 } else {
11022   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11023   else if ( lcap==2 ) join_type=3;
11024   else join_type=2-lcap;
11025   if ( (join_type==0)||(join_type==3) ) {
11026     @<Set the incoming and outgoing directions at |q|; in case of
11027       degeneracy set |join_type:=2|@>;
11028     if ( join_type==0 ) {
11029       @<If |miterlim| is less than the secant of half the angle at |q|
11030         then set |join_type:=2|@>;
11031     }
11032   }
11033 }
11034
11035 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11036
11037   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11038       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11039   if ( tmp<unity )
11040     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11041 }
11042
11043 @ @<Other local variables for |make_envelope|@>=
11044 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11045 scaled tmp; /* a temporary value */
11046
11047 @ The coordinates of |p| have already been shifted unless |p| is the first
11048 knot in which case they get shifted at the very end.
11049
11050 @<Add offset |w| to the cubic from |p| to |q|@>=
11051 right_x(p)=right_x(p)+x_coord(w);
11052 right_y(p)=right_y(p)+y_coord(w);
11053 left_x(q)=left_x(q)+x_coord(w);
11054 left_y(q)=left_y(q)+y_coord(w);
11055 x_coord(q)=x_coord(q)+x_coord(w);
11056 y_coord(q)=y_coord(q)+y_coord(w);
11057 left_type(q)=mp_explicit;
11058 right_type(q)=mp_explicit
11059
11060 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11061 if ( k>zero_off ){ w=link(w); decr(k);  }
11062 else { w=knil(w); incr(k);  }
11063
11064 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11065 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11066 case the cubic containing these control points is ``yet to be examined.''
11067
11068 @<Declare a function called |insert_knot|@>=
11069 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11070   /* returns the inserted knot */
11071   pointer r; /* the new knot */
11072   r=mp_get_node(mp, knot_node_size);
11073   link(r)=link(q); link(q)=r;
11074   right_x(r)=right_x(q);
11075   right_y(r)=right_y(q);
11076   x_coord(r)=x;
11077   y_coord(r)=y;
11078   right_x(q)=x_coord(q);
11079   right_y(q)=y_coord(q);
11080   left_x(r)=x_coord(r);
11081   left_y(r)=y_coord(r);
11082   left_type(r)=mp_explicit;
11083   right_type(r)=mp_explicit;
11084   originator(r)=mp_program_code;
11085   return r;
11086 }
11087
11088 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11089
11090 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11091
11092   p=link(p);
11093   if ( (join_type==0)||(join_type==3) ) {
11094     if ( join_type==0 ) {
11095       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11096     } else {
11097       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11098         squared join@>;
11099     }
11100     if ( r!=null ) { 
11101       right_x(r)=x_coord(r);
11102       right_y(r)=y_coord(r);
11103     }
11104   }
11105 }
11106
11107 @ For very small angles, adding a knot is unnecessary and would cause numerical
11108 problems, so we just set |r:=null| in that case.
11109
11110 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11111
11112   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11113   if ( abs(det)<26844 ) { 
11114      r=null; /* sine $<10^{-4}$ */
11115   } else { 
11116     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11117         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11118     tmp=mp_make_fraction(mp, tmp,det);
11119     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11120       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11121   }
11122 }
11123
11124 @ @<Other local variables for |make_envelope|@>=
11125 fraction det; /* a determinant used for mitered join calculations */
11126
11127 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11128
11129   ht_x=y_coord(w)-y_coord(w0);
11130   ht_y=x_coord(w0)-x_coord(w);
11131   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11132     ht_x+=ht_x; ht_y+=ht_y;
11133   }
11134   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11135     product with |(ht_x,ht_y)|@>;
11136   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11137                                   mp_take_fraction(mp, dyin,ht_y));
11138   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11139                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11140   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11141                                   mp_take_fraction(mp, dyout,ht_y));
11142   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11143                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11144 }
11145
11146 @ @<Other local variables for |make_envelope|@>=
11147 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11148 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11149 halfword kk; /* keeps track of the pen vertices being scanned */
11150 pointer ww; /* the pen vertex being tested */
11151
11152 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11153 from zero to |max_ht|.
11154
11155 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11156 max_ht=0;
11157 kk=zero_off;
11158 ww=w;
11159 while (1)  { 
11160   @<Step |ww| and move |kk| one step closer to |k0|@>;
11161   if ( kk==k0 ) break;
11162   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11163       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11164   if ( tmp>max_ht ) max_ht=tmp;
11165 }
11166
11167
11168 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11169 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11170 else { ww=knil(ww); incr(kk);  }
11171
11172 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11173 if ( left_type(c)==mp_endpoint ) { 
11174   mp->spec_p1=mp_htap_ypoc(mp, c);
11175   mp->spec_p2=mp->path_tail;
11176   originator(mp->spec_p1)=mp_program_code;
11177   link(mp->spec_p2)=link(mp->spec_p1);
11178   link(mp->spec_p1)=c;
11179   mp_remove_cubic(mp, mp->spec_p1);
11180   c=mp->spec_p1;
11181   if ( c!=link(c) ) {
11182     originator(mp->spec_p2)=mp_program_code;
11183     mp_remove_cubic(mp, mp->spec_p2);
11184   } else {
11185     @<Make |c| look like a cycle of length one@>;
11186   }
11187 }
11188
11189 @ @<Make |c| look like a cycle of length one@>=
11190
11191   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11192   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11193   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11194 }
11195
11196 @ In degenerate situations we might have to look at the knot preceding~|q|.
11197 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11198
11199 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11200 dxin=x_coord(q)-left_x(q);
11201 dyin=y_coord(q)-left_y(q);
11202 if ( (dxin==0)&&(dyin==0) ) {
11203   dxin=x_coord(q)-right_x(p);
11204   dyin=y_coord(q)-right_y(p);
11205   if ( (dxin==0)&&(dyin==0) ) {
11206     dxin=x_coord(q)-x_coord(p);
11207     dyin=y_coord(q)-y_coord(p);
11208     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11209       dxin=dxin+x_coord(w);
11210       dyin=dyin+y_coord(w);
11211     }
11212   }
11213 }
11214 tmp=mp_pyth_add(mp, dxin,dyin);
11215 if ( tmp==0 ) {
11216   join_type=2;
11217 } else { 
11218   dxin=mp_make_fraction(mp, dxin,tmp);
11219   dyin=mp_make_fraction(mp, dyin,tmp);
11220   @<Set the outgoing direction at |q|@>;
11221 }
11222
11223 @ If |q=c| then the coordinates of |r| and the control points between |q|
11224 and~|r| have already been offset by |h|.
11225
11226 @<Set the outgoing direction at |q|@>=
11227 dxout=right_x(q)-x_coord(q);
11228 dyout=right_y(q)-y_coord(q);
11229 if ( (dxout==0)&&(dyout==0) ) {
11230   r=link(q);
11231   dxout=left_x(r)-x_coord(q);
11232   dyout=left_y(r)-y_coord(q);
11233   if ( (dxout==0)&&(dyout==0) ) {
11234     dxout=x_coord(r)-x_coord(q);
11235     dyout=y_coord(r)-y_coord(q);
11236   }
11237 }
11238 if ( q==c ) {
11239   dxout=dxout-x_coord(h);
11240   dyout=dyout-y_coord(h);
11241 }
11242 tmp=mp_pyth_add(mp, dxout,dyout);
11243 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11244 @:this can't happen degerate spec}{\quad degenerate spec@>
11245 dxout=mp_make_fraction(mp, dxout,tmp);
11246 dyout=mp_make_fraction(mp, dyout,tmp)
11247
11248 @* \[23] Direction and intersection times.
11249 A path of length $n$ is defined parametrically by functions $x(t)$ and
11250 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11251 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11252 we shall consider operations that determine special times associated with
11253 given paths: the first time that a path travels in a given direction, and
11254 a pair of times at which two paths cross each other.
11255
11256 @ Let's start with the easier task. The function |find_direction_time| is
11257 given a direction |(x,y)| and a path starting at~|h|. If the path never
11258 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11259 it will be nonnegative.
11260
11261 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11262 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11263 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11264 assumed to match any given direction at time~|t|.
11265
11266 The routine solves this problem in nondegenerate cases by rotating the path
11267 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11268 to find when a given path first travels ``due east.''
11269
11270 @c 
11271 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11272   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11273   pointer p,q; /* for list traversal */
11274   scaled n; /* the direction time at knot |p| */
11275   scaled tt; /* the direction time within a cubic */
11276   @<Other local variables for |find_direction_time|@>;
11277   @<Normalize the given direction for better accuracy;
11278     but |return| with zero result if it's zero@>;
11279   n=0; p=h; phi=0;
11280   while (1) { 
11281     if ( right_type(p)==mp_endpoint ) break;
11282     q=link(p);
11283     @<Rotate the cubic between |p| and |q|; then
11284       |goto found| if the rotated cubic travels due east at some time |tt|;
11285       but |break| if an entire cyclic path has been traversed@>;
11286     p=q; n=n+unity;
11287   }
11288   return (-unity);
11289 FOUND: 
11290   return (n+tt);
11291 }
11292
11293 @ @<Normalize the given direction for better accuracy...@>=
11294 if ( abs(x)<abs(y) ) { 
11295   x=mp_make_fraction(mp, x,abs(y));
11296   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11297 } else if ( x==0 ) { 
11298   return 0;
11299 } else  { 
11300   y=mp_make_fraction(mp, y,abs(x));
11301   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11302 }
11303
11304 @ Since we're interested in the tangent directions, we work with the
11305 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11306 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11307 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11308 in order to achieve better accuracy.
11309
11310 The given path may turn abruptly at a knot, and it might pass the critical
11311 tangent direction at such a time. Therefore we remember the direction |phi|
11312 in which the previous rotated cubic was traveling. (The value of |phi| will be
11313 undefined on the first cubic, i.e., when |n=0|.)
11314
11315 @<Rotate the cubic between |p| and |q|; then...@>=
11316 tt=0;
11317 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11318   points of the rotated derivatives@>;
11319 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11320 if ( n>0 ) { 
11321   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11322   if ( p==h ) break;
11323   };
11324 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11325 @<Exit to |found| if the curve whose derivatives are specified by
11326   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11327
11328 @ @<Other local variables for |find_direction_time|@>=
11329 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11330 angle theta,phi; /* angles of exit and entry at a knot */
11331 fraction t; /* temp storage */
11332
11333 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11334 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11335 x3=x_coord(q)-left_x(q);
11336 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11337 y3=y_coord(q)-left_y(q);
11338 max=abs(x1);
11339 if ( abs(x2)>max ) max=abs(x2);
11340 if ( abs(x3)>max ) max=abs(x3);
11341 if ( abs(y1)>max ) max=abs(y1);
11342 if ( abs(y2)>max ) max=abs(y2);
11343 if ( abs(y3)>max ) max=abs(y3);
11344 if ( max==0 ) goto FOUND;
11345 while ( max<fraction_half ){ 
11346   max+=max; x1+=x1; x2+=x2; x3+=x3;
11347   y1+=y1; y2+=y2; y3+=y3;
11348 }
11349 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11350 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11351 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11352 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11353 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11354 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11355
11356 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11357 theta=mp_n_arg(mp, x1,y1);
11358 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11359 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11360
11361 @ In this step we want to use the |crossing_point| routine to find the
11362 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11363 Several complications arise: If the quadratic equation has a double root,
11364 the curve never crosses zero, and |crossing_point| will find nothing;
11365 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11366 equation has simple roots, or only one root, we may have to negate it
11367 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11368 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11369 identically zero.
11370
11371 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11372 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11373 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11374   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11375     either |goto found| or |goto done|@>;
11376 }
11377 if ( y1<=0 ) {
11378   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11379   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11380 }
11381 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11382   $B(x_1,x_2,x_3;t)\ge0$@>;
11383 DONE:
11384
11385 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11386 two roots, because we know that it isn't identically zero.
11387
11388 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11389 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11390 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11391 subject to rounding errors. Yet this code optimistically tries to
11392 do the right thing.
11393
11394 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11395
11396 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11397 t=mp_crossing_point(mp, y1,y2,y3);
11398 if ( t>fraction_one ) goto DONE;
11399 y2=t_of_the_way(y2,y3);
11400 x1=t_of_the_way(x1,x2);
11401 x2=t_of_the_way(x2,x3);
11402 x1=t_of_the_way(x1,x2);
11403 if ( x1>=0 ) we_found_it;
11404 if ( y2>0 ) y2=0;
11405 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11406 if ( t>fraction_one ) goto DONE;
11407 x1=t_of_the_way(x1,x2);
11408 x2=t_of_the_way(x2,x3);
11409 if ( t_of_the_way(x1,x2)>=0 ) { 
11410   t=t_of_the_way(tt,fraction_one); we_found_it;
11411 }
11412
11413 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11414     either |goto found| or |goto done|@>=
11415
11416   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11417     t=mp_make_fraction(mp, y1,y1-y2);
11418     x1=t_of_the_way(x1,x2);
11419     x2=t_of_the_way(x2,x3);
11420     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11421   } else if ( y3==0 ) {
11422     if ( y1==0 ) {
11423       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11424     } else if ( x3>=0 ) {
11425       tt=unity; goto FOUND;
11426     }
11427   }
11428   goto DONE;
11429 }
11430
11431 @ At this point we know that the derivative of |y(t)| is identically zero,
11432 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11433 traveling east.
11434
11435 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11436
11437   t=mp_crossing_point(mp, -x1,-x2,-x3);
11438   if ( t<=fraction_one ) we_found_it;
11439   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11440     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11441   }
11442 }
11443
11444 @ The intersection of two cubics can be found by an interesting variant
11445 of the general bisection scheme described in the introduction to
11446 |crossing_point|.\
11447 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)$,
11448 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11449 if an intersection exists. First we find the smallest rectangle that
11450 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11451 the smallest rectangle that encloses
11452 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11453 But if the rectangles do overlap, we bisect the intervals, getting
11454 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11455 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11456 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11457 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11458 levels of bisection we will have determined the intersection times $t_1$
11459 and~$t_2$ to $l$~bits of accuracy.
11460
11461 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11462 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11463 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11464 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11465 to determine when the enclosing rectangles overlap. Here's why:
11466 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11467 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11468 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11469 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11470 overlap if and only if $u\submin\L x\submax$ and
11471 $x\submin\L u\submax$. Letting
11472 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11473   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11474 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11475 reduces to
11476 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11477 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11478 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11479 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11480 because of the overlap condition; i.e., we know that $X\submin$,
11481 $X\submax$, and their relatives are bounded, hence $X\submax-
11482 U\submin$ and $X\submin-U\submax$ are bounded.
11483
11484 @ Incidentally, if the given cubics intersect more than once, the process
11485 just sketched will not necessarily find the lexicographically smallest pair
11486 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11487 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11488 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11489 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11490 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11491 Shuffled order agrees with lexicographic order if all pairs of solutions
11492 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11493 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11494 and the bisection algorithm would be substantially less efficient if it were
11495 constrained by lexicographic order.
11496
11497 For example, suppose that an overlap has been found for $l=3$ and
11498 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11499 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11500 Then there is probably an intersection in one of the subintervals
11501 $(.1011,.011x)$; but lexicographic order would require us to explore
11502 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11503 want to store all of the subdivision data for the second path, so the
11504 subdivisions would have to be regenerated many times. Such inefficiencies
11505 would be associated with every `1' in the binary representation of~$t_1$.
11506
11507 @ The subdivision process introduces rounding errors, hence we need to
11508 make a more liberal test for overlap. It is not hard to show that the
11509 computed values of $U_i$ differ from the truth by at most~$l$, on
11510 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11511 If $\beta$ is an upper bound on the absolute error in the computed
11512 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11513 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11514 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11515
11516 More accuracy is obtained if we try the algorithm first with |tol=0|;
11517 the more liberal tolerance is used only if an exact approach fails.
11518 It is convenient to do this double-take by letting `3' in the preceding
11519 paragraph be a parameter, which is first 0, then 3.
11520
11521 @<Glob...@>=
11522 unsigned int tol_step; /* either 0 or 3, usually */
11523
11524 @ We shall use an explicit stack to implement the recursive bisection
11525 method described above. The |bisect_stack| array will contain numerous 5-word
11526 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11527 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11528
11529 The following macros define the allocation of stack positions to
11530 the quantities needed for bisection-intersection.
11531
11532 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11533 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11534 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11535 @d stack_min(A) mp->bisect_stack[(A)+3]
11536   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11537 @d stack_max(A) mp->bisect_stack[(A)+4]
11538   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11539 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11540 @#
11541 @d u_packet(A) ((A)-5)
11542 @d v_packet(A) ((A)-10)
11543 @d x_packet(A) ((A)-15)
11544 @d y_packet(A) ((A)-20)
11545 @d l_packets (mp->bisect_ptr-int_packets)
11546 @d r_packets mp->bisect_ptr
11547 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11548 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11549 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11550 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11551 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11552 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11553 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11554 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11555 @#
11556 @d u1l stack_1(ul_packet) /* $U'_1$ */
11557 @d u2l stack_2(ul_packet) /* $U'_2$ */
11558 @d u3l stack_3(ul_packet) /* $U'_3$ */
11559 @d v1l stack_1(vl_packet) /* $V'_1$ */
11560 @d v2l stack_2(vl_packet) /* $V'_2$ */
11561 @d v3l stack_3(vl_packet) /* $V'_3$ */
11562 @d x1l stack_1(xl_packet) /* $X'_1$ */
11563 @d x2l stack_2(xl_packet) /* $X'_2$ */
11564 @d x3l stack_3(xl_packet) /* $X'_3$ */
11565 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11566 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11567 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11568 @d u1r stack_1(ur_packet) /* $U''_1$ */
11569 @d u2r stack_2(ur_packet) /* $U''_2$ */
11570 @d u3r stack_3(ur_packet) /* $U''_3$ */
11571 @d v1r stack_1(vr_packet) /* $V''_1$ */
11572 @d v2r stack_2(vr_packet) /* $V''_2$ */
11573 @d v3r stack_3(vr_packet) /* $V''_3$ */
11574 @d x1r stack_1(xr_packet) /* $X''_1$ */
11575 @d x2r stack_2(xr_packet) /* $X''_2$ */
11576 @d x3r stack_3(xr_packet) /* $X''_3$ */
11577 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11578 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11579 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11580 @#
11581 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11582 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11583 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11584 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11585 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11586 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11587
11588 @<Glob...@>=
11589 integer *bisect_stack;
11590 unsigned int bisect_ptr;
11591
11592 @ @<Allocate or initialize ...@>=
11593 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11594
11595 @ @<Dealloc variables@>=
11596 xfree(mp->bisect_stack);
11597
11598 @ @<Check the ``constant''...@>=
11599 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11600
11601 @ Computation of the min and max is a tedious but fairly fast sequence of
11602 instructions; exactly four comparisons are made in each branch.
11603
11604 @d set_min_max(A) 
11605   if ( stack_1((A))<0 ) {
11606     if ( stack_3((A))>=0 ) {
11607       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11608       else stack_min((A))=stack_1((A));
11609       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11610       if ( stack_max((A))<0 ) stack_max((A))=0;
11611     } else { 
11612       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11613       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11614       stack_max((A))=stack_1((A))+stack_2((A));
11615       if ( stack_max((A))<0 ) stack_max((A))=0;
11616     }
11617   } else if ( stack_3((A))<=0 ) {
11618     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11619     else stack_max((A))=stack_1((A));
11620     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11621     if ( stack_min((A))>0 ) stack_min((A))=0;
11622   } else  { 
11623     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11624     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11625     stack_min((A))=stack_1((A))+stack_2((A));
11626     if ( stack_min((A))>0 ) stack_min((A))=0;
11627   }
11628
11629 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11630 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11631 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11632 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11633 plus the |scaled| values of $t_1$ and~$t_2$.
11634
11635 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11636 finds no intersection. The routine gives up and gives an approximate answer
11637 if it has backtracked
11638 more than 5000 times (otherwise there are cases where several minutes
11639 of fruitless computation would be possible).
11640
11641 @d max_patience 5000
11642
11643 @<Glob...@>=
11644 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11645 integer time_to_go; /* this many backtracks before giving up */
11646 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11647
11648 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11649 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11650 and |(pp,link(pp))|, respectively.
11651
11652 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11653   pointer q,qq; /* |link(p)|, |link(pp)| */
11654   mp->time_to_go=max_patience; mp->max_t=2;
11655   @<Initialize for intersections at level zero@>;
11656 CONTINUE:
11657   while (1) { 
11658     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11659     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11660     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11661     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11662     { 
11663       if ( mp->cur_t>=mp->max_t ){ 
11664         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11665            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11666         }
11667         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11668       }
11669       @<Subdivide for a new level of intersection@>;
11670       goto CONTINUE;
11671     }
11672     if ( mp->time_to_go>0 ) {
11673       decr(mp->time_to_go);
11674     } else { 
11675       while ( mp->appr_t<unity ) { 
11676         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11677       }
11678       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11679     }
11680     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11681   }
11682 }
11683
11684 @ The following variables are global, although they are used only by
11685 |cubic_intersection|, because it is necessary on some machines to
11686 split |cubic_intersection| up into two procedures.
11687
11688 @<Glob...@>=
11689 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11690 integer tol; /* bound on the uncertainly in the overlap test */
11691 unsigned int uv;
11692 unsigned int xy; /* pointers to the current packets of interest */
11693 integer three_l; /* |tol_step| times the bisection level */
11694 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11695
11696 @ We shall assume that the coordinates are sufficiently non-extreme that
11697 integer overflow will not occur.
11698
11699 @<Initialize for intersections at level zero@>=
11700 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11701 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11702 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11703 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11704 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11705 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11706 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11707 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11708 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11709 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11710 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11711 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11712
11713 @ @<Subdivide for a new level of intersection@>=
11714 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11715 stack_uv=mp->uv; stack_xy=mp->xy;
11716 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11717 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11718 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11719 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11720 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11721 u3l=half(u2l+u2r); u1r=u3l;
11722 set_min_max(ul_packet); set_min_max(ur_packet);
11723 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11724 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11725 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11726 v3l=half(v2l+v2r); v1r=v3l;
11727 set_min_max(vl_packet); set_min_max(vr_packet);
11728 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11729 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11730 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11731 x3l=half(x2l+x2r); x1r=x3l;
11732 set_min_max(xl_packet); set_min_max(xr_packet);
11733 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11734 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11735 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11736 y3l=half(y2l+y2r); y1r=y3l;
11737 set_min_max(yl_packet); set_min_max(yr_packet);
11738 mp->uv=l_packets; mp->xy=l_packets;
11739 mp->delx+=mp->delx; mp->dely+=mp->dely;
11740 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11741 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11742
11743 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11744 NOT_FOUND: 
11745 if ( odd(mp->cur_tt) ) {
11746   if ( odd(mp->cur_t) ) {
11747      @<Descend to the previous level and |goto not_found|@>;
11748   } else { 
11749     incr(mp->cur_t);
11750     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11751       +stack_3(u_packet(mp->uv));
11752     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11753       +stack_3(v_packet(mp->uv));
11754     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11755     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11756          /* switch from |r_packet| to |l_packet| */
11757     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11758       +stack_3(x_packet(mp->xy));
11759     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11760       +stack_3(y_packet(mp->xy));
11761   }
11762 } else { 
11763   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
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   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11769 }
11770
11771 @ @<Descend to the previous level...@>=
11772
11773   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11774   if ( mp->cur_t==0 ) return;
11775   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11776   mp->three_l=mp->three_l-mp->tol_step;
11777   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11778   mp->uv=stack_uv; mp->xy=stack_xy;
11779   goto NOT_FOUND;
11780 }
11781
11782 @ The |path_intersection| procedure is much simpler.
11783 It invokes |cubic_intersection| in lexicographic order until finding a
11784 pair of cubics that intersect. The final intersection times are placed in
11785 |cur_t| and~|cur_tt|.
11786
11787 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11788   pointer p,pp; /* link registers that traverse the given paths */
11789   integer n,nn; /* integer parts of intersection times, minus |unity| */
11790   @<Change one-point paths into dead cycles@>;
11791   mp->tol_step=0;
11792   do {  
11793     n=-unity; p=h;
11794     do {  
11795       if ( right_type(p)!=mp_endpoint ) { 
11796         nn=-unity; pp=hh;
11797         do {  
11798           if ( right_type(pp)!=mp_endpoint )  { 
11799             mp_cubic_intersection(mp, p,pp);
11800             if ( mp->cur_t>0 ) { 
11801               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11802               return;
11803             }
11804           }
11805           nn=nn+unity; pp=link(pp);
11806         } while (pp!=hh);
11807       }
11808       n=n+unity; p=link(p);
11809     } while (p!=h);
11810     mp->tol_step=mp->tol_step+3;
11811   } while (mp->tol_step<=3);
11812   mp->cur_t=-unity; mp->cur_tt=-unity;
11813 }
11814
11815 @ @<Change one-point paths...@>=
11816 if ( right_type(h)==mp_endpoint ) {
11817   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11818   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11819 }
11820 if ( right_type(hh)==mp_endpoint ) {
11821   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11822   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11823 }
11824
11825 @* \[24] Dynamic linear equations.
11826 \MP\ users define variables implicitly by stating equations that should be
11827 satisfied; the computer is supposed to be smart enough to solve those equations.
11828 And indeed, the computer tries valiantly to do so, by distinguishing five
11829 different types of numeric values:
11830
11831 \smallskip\hang
11832 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11833 of the variable whose address is~|p|.
11834
11835 \smallskip\hang
11836 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11837 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11838 as a |scaled| number plus a sum of independent variables with |fraction|
11839 coefficients.
11840
11841 \smallskip\hang
11842 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11843 number'' reflecting the time this variable was first used in an equation;
11844 also |0<=m<64|, and each dependent variable
11845 that refers to this one is actually referring to the future value of
11846 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11847 scaling are sometimes needed to keep the coefficients in dependency lists
11848 from getting too large. The value of~|m| will always be even.)
11849
11850 \smallskip\hang
11851 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11852 equation before, but it has been explicitly declared to be numeric.
11853
11854 \smallskip\hang
11855 |type(p)=undefined| means that variable |p| hasn't appeared before.
11856
11857 \smallskip\noindent
11858 We have actually discussed these five types in the reverse order of their
11859 history during a computation: Once |known|, a variable never again
11860 becomes |dependent|; once |dependent|, it almost never again becomes
11861 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11862 and once |mp_numeric_type|, it never again becomes |undefined| (except
11863 of course when the user specifically decides to scrap the old value
11864 and start again). A backward step may, however, take place: Sometimes
11865 a |dependent| variable becomes |mp_independent| again, when one of the
11866 independent variables it depends on is reverting to |undefined|.
11867
11868
11869 The next patch detects overflow of independent-variable serial
11870 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11871
11872 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11873 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11874 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11875 @d new_indep(A)  /* create a new independent variable */
11876   { if ( mp->serial_no==max_serial_no )
11877     mp_fatal_error(mp, "variable instance identifiers exhausted");
11878   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11879   value((A))=mp->serial_no;
11880   }
11881
11882 @<Glob...@>=
11883 integer serial_no; /* the most recent serial number, times |s_scale| */
11884
11885 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11886
11887 @ But how are dependency lists represented? It's simple: The linear combination
11888 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11889 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11890 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11891 of $\alpha_1$; and |link(p)| points to the dependency list
11892 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11893 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11894 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11895 they appear in decreasing order of their |value| fields (i.e., of
11896 their serial numbers). \ (It is convenient to use decreasing order,
11897 since |value(null)=0|. If the independent variables were not sorted by
11898 serial number but by some other criterion, such as their location in |mem|,
11899 the equation-solving mechanism would be too system-dependent, because
11900 the ordering can affect the computed results.)
11901
11902 The |link| field in the node that contains the constant term $\beta$ is
11903 called the {\sl final link\/} of the dependency list. \MP\ maintains
11904 a doubly-linked master list of all dependency lists, in terms of a permanently
11905 allocated node
11906 in |mem| called |dep_head|. If there are no dependencies, we have
11907 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11908 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11909 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11910 points to its dependency list. If the final link of that dependency list
11911 occurs in location~|q|, then |link(q)| points to the next dependent
11912 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11913
11914 @d dep_list(A) link(value_loc((A)))
11915   /* half of the |value| field in a |dependent| variable */
11916 @d prev_dep(A) info(value_loc((A)))
11917   /* the other half; makes a doubly linked list */
11918 @d dep_node_size 2 /* the number of words per dependency node */
11919
11920 @<Initialize table entries...@>= mp->serial_no=0;
11921 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11922 info(dep_head)=null; dep_list(dep_head)=null;
11923
11924 @ Actually the description above contains a little white lie. There's
11925 another kind of variable called |mp_proto_dependent|, which is
11926 just like a |dependent| one except that the $\alpha$ coefficients
11927 in its dependency list are |scaled| instead of being fractions.
11928 Proto-dependency lists are mixed with dependency lists in the
11929 nodes reachable from |dep_head|.
11930
11931 @ Here is a procedure that prints a dependency list in symbolic form.
11932 The second parameter should be either |dependent| or |mp_proto_dependent|,
11933 to indicate the scaling of the coefficients.
11934
11935 @<Declare subroutines for printing expressions@>=
11936 void mp_print_dependency (MP mp,pointer p, small_number t) {
11937   integer v; /* a coefficient */
11938   pointer pp,q; /* for list manipulation */
11939   pp=p;
11940   while (1) { 
11941     v=abs(value(p)); q=info(p);
11942     if ( q==null ) { /* the constant term */
11943       if ( (v!=0)||(p==pp) ) {
11944          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11945          mp_print_scaled(mp, value(p));
11946       }
11947       return;
11948     }
11949     @<Print the coefficient, unless it's $\pm1.0$@>;
11950     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11951 @:this can't happen dep}{\quad dep@>
11952     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11953     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11954     p=link(p);
11955   }
11956 }
11957
11958 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11959 if ( value(p)<0 ) mp_print_char(mp, '-');
11960 else if ( p!=pp ) mp_print_char(mp, '+');
11961 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11962 if ( v!=unity ) mp_print_scaled(mp, v)
11963
11964 @ The maximum absolute value of a coefficient in a given dependency list
11965 is returned by the following simple function.
11966
11967 @c fraction mp_max_coef (MP mp,pointer p) {
11968   fraction x; /* the maximum so far */
11969   x=0;
11970   while ( info(p)!=null ) {
11971     if ( abs(value(p))>x ) x=abs(value(p));
11972     p=link(p);
11973   }
11974   return x;
11975 }
11976
11977 @ One of the main operations needed on dependency lists is to add a multiple
11978 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11979 to dependency lists and |f| is a fraction.
11980
11981 If the coefficient of any independent variable becomes |coef_bound| or
11982 more, in absolute value, this procedure changes the type of that variable
11983 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11984 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11985 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11986 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11987 2.3723$, the safer value 7/3 is taken as the threshold.)
11988
11989 The changes mentioned in the preceding paragraph are actually done only if
11990 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11991 it is |false| only when \MP\ is making a dependency list that will soon
11992 be equated to zero.
11993
11994 Several procedures that act on dependency lists, including |p_plus_fq|,
11995 set the global variable |dep_final| to the final (constant term) node of
11996 the dependency list that they produce.
11997
11998 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11999 @d independent_needing_fix 0
12000
12001 @<Glob...@>=
12002 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12003 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12004 pointer dep_final; /* location of the constant term and final link */
12005
12006 @ @<Set init...@>=
12007 mp->fix_needed=false; mp->watch_coefs=true;
12008
12009 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12010 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12011 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12012 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12013
12014 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12015
12016 The final link of the dependency list or proto-dependency list returned
12017 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12018 constant term of the result will be located in the same |mem| location
12019 as the original constant term of~|p|.
12020
12021 Coefficients of the result are assumed to be zero if they are less than
12022 a certain threshold. This compensates for inevitable rounding errors,
12023 and tends to make more variables `|known|'. The threshold is approximately
12024 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12025 proto-dependencies.
12026
12027 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12028 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12029 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12030 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12031
12032 @<Declare basic dependency-list subroutines@>=
12033 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12034                       pointer q, small_number t, small_number tt) ;
12035
12036 @ @c
12037 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12038                       pointer q, small_number t, small_number tt) {
12039   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12040   pointer r,s; /* for list manipulation */
12041   integer mp_threshold; /* defines a neighborhood of zero */
12042   integer v; /* temporary register */
12043   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12044   else mp_threshold=scaled_threshold;
12045   r=temp_head; pp=info(p); qq=info(q);
12046   while (1) {
12047     if ( pp==qq ) {
12048       if ( pp==null ) {
12049        break;
12050       } else {
12051         @<Contribute a term from |p|, plus |f| times the
12052           corresponding term from |q|@>
12053       }
12054     } else if ( value(pp)<value(qq) ) {
12055       @<Contribute a term from |q|, multiplied by~|f|@>
12056     } else { 
12057      link(r)=p; r=p; p=link(p); pp=info(p);
12058     }
12059   }
12060   if ( t==mp_dependent )
12061     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12062   else  
12063     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12064   link(r)=p; mp->dep_final=p; 
12065   return link(temp_head);
12066 }
12067
12068 @ @<Contribute a term from |p|, plus |f|...@>=
12069
12070   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12071   else v=value(p)+mp_take_scaled(mp, f,value(q));
12072   value(p)=v; s=p; p=link(p);
12073   if ( abs(v)<mp_threshold ) {
12074     mp_free_node(mp, s,dep_node_size);
12075   } else {
12076     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12077       type(qq)=independent_needing_fix; mp->fix_needed=true;
12078     }
12079     link(r)=s; r=s;
12080   };
12081   pp=info(p); q=link(q); qq=info(q);
12082 }
12083
12084 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12085
12086   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12087   else v=mp_take_scaled(mp, f,value(q));
12088   if ( abs(v)>halfp(mp_threshold) ) { 
12089     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12090     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12091       type(qq)=independent_needing_fix; mp->fix_needed=true;
12092     }
12093     link(r)=s; r=s;
12094   }
12095   q=link(q); qq=info(q);
12096 }
12097
12098 @ It is convenient to have another subroutine for the special case
12099 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12100 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12101
12102 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12103   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12104   pointer r,s; /* for list manipulation */
12105   integer mp_threshold; /* defines a neighborhood of zero */
12106   integer v; /* temporary register */
12107   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12108   else mp_threshold=scaled_threshold;
12109   r=temp_head; pp=info(p); qq=info(q);
12110   while (1) {
12111     if ( pp==qq ) {
12112       if ( pp==null ) {
12113         break;
12114       } else {
12115         @<Contribute a term from |p|, plus the
12116           corresponding term from |q|@>
12117       }
12118     } else if ( value(pp)<value(qq) ) {
12119       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12120       q=link(q); qq=info(q); link(r)=s; r=s;
12121     } else { 
12122       link(r)=p; r=p; p=link(p); pp=info(p);
12123     }
12124   }
12125   value(p)=mp_slow_add(mp, value(p),value(q));
12126   link(r)=p; mp->dep_final=p; 
12127   return link(temp_head);
12128 }
12129
12130 @ @<Contribute a term from |p|, plus the...@>=
12131
12132   v=value(p)+value(q);
12133   value(p)=v; s=p; p=link(p); pp=info(p);
12134   if ( abs(v)<mp_threshold ) {
12135     mp_free_node(mp, s,dep_node_size);
12136   } else { 
12137     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12138       type(qq)=independent_needing_fix; mp->fix_needed=true;
12139     }
12140     link(r)=s; r=s;
12141   }
12142   q=link(q); qq=info(q);
12143 }
12144
12145 @ A somewhat simpler routine will multiply a dependency list
12146 by a given constant~|v|. The constant is either a |fraction| less than
12147 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12148 convert a dependency list to a proto-dependency list.
12149 Parameters |t0| and |t1| are the list types before and after;
12150 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12151 and |v_is_scaled=true|.
12152
12153 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12154                          small_number t1, boolean v_is_scaled) {
12155   pointer r,s; /* for list manipulation */
12156   integer w; /* tentative coefficient */
12157   integer mp_threshold;
12158   boolean scaling_down;
12159   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12160   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12161   else mp_threshold=half_scaled_threshold;
12162   r=temp_head;
12163   while ( info(p)!=null ) {    
12164     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12165     else w=mp_take_scaled(mp, v,value(p));
12166     if ( abs(w)<=mp_threshold ) { 
12167       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12168     } else {
12169       if ( abs(w)>=coef_bound ) { 
12170         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12171       }
12172       link(r)=p; r=p; value(p)=w; p=link(p);
12173     }
12174   }
12175   link(r)=p;
12176   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12177   else value(p)=mp_take_fraction(mp, value(p),v);
12178   return link(temp_head);
12179 };
12180
12181 @ Similarly, we sometimes need to divide a dependency list
12182 by a given |scaled| constant.
12183
12184 @<Declare basic dependency-list subroutines@>=
12185 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12186   t0, small_number t1) ;
12187
12188 @ @c
12189 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12190   t0, small_number t1) {
12191   pointer r,s; /* for list manipulation */
12192   integer w; /* tentative coefficient */
12193   integer mp_threshold;
12194   boolean scaling_down;
12195   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12196   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12197   else mp_threshold=half_scaled_threshold;
12198   r=temp_head;
12199   while ( info( p)!=null ) {
12200     if ( scaling_down ) {
12201       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12202       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12203     } else {
12204       w=mp_make_scaled(mp, value(p),v);
12205     }
12206     if ( abs(w)<=mp_threshold ) {
12207       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12208     } else { 
12209       if ( abs(w)>=coef_bound ) {
12210          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12211       }
12212       link(r)=p; r=p; value(p)=w; p=link(p);
12213     }
12214   }
12215   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12216   return link(temp_head);
12217 };
12218
12219 @ Here's another utility routine for dependency lists. When an independent
12220 variable becomes dependent, we want to remove it from all existing
12221 dependencies. The |p_with_x_becoming_q| function computes the
12222 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12223
12224 This procedure has basically the same calling conventions as |p_plus_fq|:
12225 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12226 final link are inherited from~|p|; and the fourth parameter tells whether
12227 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12228 is not altered if |x| does not occur in list~|p|.
12229
12230 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12231            pointer x, pointer q, small_number t) {
12232   pointer r,s; /* for list manipulation */
12233   integer v; /* coefficient of |x| */
12234   integer sx; /* serial number of |x| */
12235   s=p; r=temp_head; sx=value(x);
12236   while ( value(info(s))>sx ) { r=s; s=link(s); };
12237   if ( info(s)!=x ) { 
12238     return p;
12239   } else { 
12240     link(temp_head)=p; link(r)=link(s); v=value(s);
12241     mp_free_node(mp, s,dep_node_size);
12242     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12243   }
12244 }
12245
12246 @ Here's a simple procedure that reports an error when a variable
12247 has just received a known value that's out of the required range.
12248
12249 @<Declare basic dependency-list subroutines@>=
12250 void mp_val_too_big (MP mp,scaled x) ;
12251
12252 @ @c void mp_val_too_big (MP mp,scaled x) { 
12253   if ( mp->internal[mp_warning_check]>0 ) { 
12254     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12255 @.Value is too large@>
12256     help4("The equation I just processed has given some variable")
12257       ("a value of 4096 or more. Continue and I'll try to cope")
12258       ("with that big value; but it might be dangerous.")
12259       ("(Set warningcheck:=0 to suppress this message.)");
12260     mp_error(mp);
12261   }
12262 }
12263
12264 @ When a dependent variable becomes known, the following routine
12265 removes its dependency list. Here |p| points to the variable, and
12266 |q| points to the dependency list (which is one node long).
12267
12268 @<Declare basic dependency-list subroutines@>=
12269 void mp_make_known (MP mp,pointer p, pointer q) ;
12270
12271 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12272   int t; /* the previous type */
12273   prev_dep(link(q))=prev_dep(p);
12274   link(prev_dep(p))=link(q); t=type(p);
12275   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12276   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12277   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12278     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12279 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12280     mp_print_variable_name(mp, p); 
12281     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12282     mp_end_diagnostic(mp, false);
12283   }
12284   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12285     mp->cur_type=mp_known; mp->cur_exp=value(p);
12286     mp_free_node(mp, p,value_node_size);
12287   }
12288 }
12289
12290 @ The |fix_dependencies| routine is called into action when |fix_needed|
12291 has been triggered. The program keeps a list~|s| of independent variables
12292 whose coefficients must be divided by~4.
12293
12294 In unusual cases, this fixup process might reduce one or more coefficients
12295 to zero, so that a variable will become known more or less by default.
12296
12297 @<Declare basic dependency-list subroutines@>=
12298 void mp_fix_dependencies (MP mp);
12299
12300 @ @c void mp_fix_dependencies (MP mp) {
12301   pointer p,q,r,s,t; /* list manipulation registers */
12302   pointer x; /* an independent variable */
12303   r=link(dep_head); s=null;
12304   while ( r!=dep_head ){ 
12305     t=r;
12306     @<Run through the dependency list for variable |t|, fixing
12307       all nodes, and ending with final link~|q|@>;
12308     r=link(q);
12309     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12310   }
12311   while ( s!=null ) { 
12312     p=link(s); x=info(s); free_avail(s); s=p;
12313     type(x)=mp_independent; value(x)=value(x)+2;
12314   }
12315   mp->fix_needed=false;
12316 }
12317
12318 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12319
12320 @<Run through the dependency list for variable |t|...@>=
12321 r=value_loc(t); /* |link(r)=dep_list(t)| */
12322 while (1) { 
12323   q=link(r); x=info(q);
12324   if ( x==null ) break;
12325   if ( type(x)<=independent_being_fixed ) {
12326     if ( type(x)<independent_being_fixed ) {
12327       p=mp_get_avail(mp); link(p)=s; s=p;
12328       info(s)=x; type(x)=independent_being_fixed;
12329     }
12330     value(q)=value(q) / 4;
12331     if ( value(q)==0 ) {
12332       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12333     }
12334   }
12335   r=q;
12336 }
12337
12338
12339 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12340 linking it into the list of all known dependencies. We assume that
12341 |dep_final| points to the final node of list~|p|.
12342
12343 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12344   pointer r; /* what used to be the first dependency */
12345   dep_list(q)=p; prev_dep(q)=dep_head;
12346   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12347   link(dep_head)=q;
12348 }
12349
12350 @ Here is one of the ways a dependency list gets started.
12351 The |const_dependency| routine produces a list that has nothing but
12352 a constant term.
12353
12354 @c pointer mp_const_dependency (MP mp, scaled v) {
12355   mp->dep_final=mp_get_node(mp, dep_node_size);
12356   value(mp->dep_final)=v; info(mp->dep_final)=null;
12357   return mp->dep_final;
12358 }
12359
12360 @ And here's a more interesting way to start a dependency list from scratch:
12361 The parameter to |single_dependency| is the location of an
12362 independent variable~|x|, and the result is the simple dependency list
12363 `|x+0|'.
12364
12365 In the unlikely event that the given independent variable has been doubled so
12366 often that we can't refer to it with a nonzero coefficient,
12367 |single_dependency| returns the simple list `0'.  This case can be
12368 recognized by testing that the returned list pointer is equal to
12369 |dep_final|.
12370
12371 @c pointer mp_single_dependency (MP mp,pointer p) {
12372   pointer q; /* the new dependency list */
12373   integer m; /* the number of doublings */
12374   m=value(p) % s_scale;
12375   if ( m>28 ) {
12376     return mp_const_dependency(mp, 0);
12377   } else { 
12378     q=mp_get_node(mp, dep_node_size);
12379     value(q)=two_to_the(28-m); info(q)=p;
12380     link(q)=mp_const_dependency(mp, 0);
12381     return q;
12382   }
12383 }
12384
12385 @ We sometimes need to make an exact copy of a dependency list.
12386
12387 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12388   pointer q; /* the new dependency list */
12389   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12390   while (1) { 
12391     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12392     if ( info(mp->dep_final)==null ) break;
12393     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12394     mp->dep_final=link(mp->dep_final); p=link(p);
12395   }
12396   return q;
12397 }
12398
12399 @ But how do variables normally become known? Ah, now we get to the heart of the
12400 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12401 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12402 appears. It equates this list to zero, by choosing an independent variable
12403 with the largest coefficient and making it dependent on the others. The
12404 newly dependent variable is eliminated from all current dependencies,
12405 thereby possibly making other dependent variables known.
12406
12407 The given list |p| is, of course, totally destroyed by all this processing.
12408
12409 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12410   pointer q,r,s; /* for link manipulation */
12411   pointer x; /* the variable that loses its independence */
12412   integer n; /* the number of times |x| had been halved */
12413   integer v; /* the coefficient of |x| in list |p| */
12414   pointer prev_r; /* lags one step behind |r| */
12415   pointer final_node; /* the constant term of the new dependency list */
12416   integer w; /* a tentative coefficient */
12417    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12418   x=info(q); n=value(x) % s_scale;
12419   @<Divide list |p| by |-v|, removing node |q|@>;
12420   if ( mp->internal[mp_tracing_equations]>0 ) {
12421     @<Display the new dependency@>;
12422   }
12423   @<Simplify all existing dependencies by substituting for |x|@>;
12424   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12425   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12426 }
12427
12428 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12429 q=p; r=link(p); v=value(q);
12430 while ( info(r)!=null ) { 
12431   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12432   r=link(r);
12433 }
12434
12435 @ Here we want to change the coefficients from |scaled| to |fraction|,
12436 except in the constant term. In the common case of a trivial equation
12437 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12438
12439 @<Divide list |p| by |-v|, removing node |q|@>=
12440 s=temp_head; link(s)=p; r=p;
12441 do { 
12442   if ( r==q ) {
12443     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12444   } else  { 
12445     w=mp_make_fraction(mp, value(r),v);
12446     if ( abs(w)<=half_fraction_threshold ) {
12447       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12448     } else { 
12449       value(r)=-w; s=r;
12450     }
12451   }
12452   r=link(s);
12453 } while (info(r)!=null);
12454 if ( t==mp_proto_dependent ) {
12455   value(r)=-mp_make_scaled(mp, value(r),v);
12456 } else if ( v!=-fraction_one ) {
12457   value(r)=-mp_make_fraction(mp, value(r),v);
12458 }
12459 final_node=r; p=link(temp_head)
12460
12461 @ @<Display the new dependency@>=
12462 if ( mp_interesting(mp, x) ) {
12463   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12464   mp_print_variable_name(mp, x);
12465 @:]]]\#\#_}{\.{\#\#}@>
12466   w=n;
12467   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12468   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12469   mp_end_diagnostic(mp, false);
12470 }
12471
12472 @ @<Simplify all existing dependencies by substituting for |x|@>=
12473 prev_r=dep_head; r=link(dep_head);
12474 while ( r!=dep_head ) {
12475   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12476   if ( info(q)==null ) {
12477     mp_make_known(mp, r,q);
12478   } else { 
12479     dep_list(r)=q;
12480     do {  q=link(q); } while (info(q)!=null);
12481     prev_r=q;
12482   }
12483   r=link(prev_r);
12484 }
12485
12486 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12487 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12488 if ( info(p)==null ) {
12489   type(x)=mp_known;
12490   value(x)=value(p);
12491   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12492   mp_free_node(mp, p,dep_node_size);
12493   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12494     mp->cur_exp=value(x); mp->cur_type=mp_known;
12495     mp_free_node(mp, x,value_node_size);
12496   }
12497 } else { 
12498   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12499   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12500 }
12501
12502 @ @<Divide list |p| by $2^n$@>=
12503
12504   s=temp_head; link(temp_head)=p; r=p;
12505   do {  
12506     if ( n>30 ) w=0;
12507     else w=value(r) / two_to_the(n);
12508     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12509       link(s)=link(r);
12510       mp_free_node(mp, r,dep_node_size);
12511     } else { 
12512       value(r)=w; s=r;
12513     }
12514     r=link(s);
12515   } while (info(s)!=null);
12516   p=link(temp_head);
12517 }
12518
12519 @ The |check_mem| procedure, which is used only when \MP\ is being
12520 debugged, makes sure that the current dependency lists are well formed.
12521
12522 @<Check the list of linear dependencies@>=
12523 q=dep_head; p=link(q);
12524 while ( p!=dep_head ) {
12525   if ( prev_dep(p)!=q ) {
12526     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12527 @.Bad PREVDEP...@>
12528   }
12529   p=dep_list(p);
12530   while (1) {
12531     r=info(p); q=p; p=link(q);
12532     if ( r==null ) break;
12533     if ( value(info(p))>=value(r) ) {
12534       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12535 @.Out of order...@>
12536     }
12537   }
12538 }
12539
12540 @* \[25] Dynamic nonlinear equations.
12541 Variables of numeric type are maintained by the general scheme of
12542 independent, dependent, and known values that we have just studied;
12543 and the components of pair and transform variables are handled in the
12544 same way. But \MP\ also has five other types of values: \&{boolean},
12545 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12546
12547 Equations are allowed between nonlinear quantities, but only in a
12548 simple form. Two variables that haven't yet been assigned values are
12549 either equal to each other, or they're not.
12550
12551 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12552 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12553 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12554 |null| (which means that no other variables are equivalent to this one), or
12555 it points to another variable of the same undefined type. The pointers in the
12556 latter case form a cycle of nodes, which we shall call a ``ring.''
12557 Rings of undefined variables may include capsules, which arise as
12558 intermediate results within expressions or as \&{expr} parameters to macros.
12559
12560 When one member of a ring receives a value, the same value is given to
12561 all the other members. In the case of paths and pictures, this implies
12562 making separate copies of a potentially large data structure; users should
12563 restrain their enthusiasm for such generality, unless they have lots and
12564 lots of memory space.
12565
12566 @ The following procedure is called when a capsule node is being
12567 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12568
12569 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12570   pointer q; /* the new capsule node */
12571   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12572   type(q)=type(p);
12573   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12574   value(p)=q;
12575   return q;
12576 }
12577
12578 @ Conversely, we might delete a capsule or a variable before it becomes known.
12579 The following procedure simply detaches a quantity from its ring,
12580 without recycling the storage.
12581
12582 @<Declare the recycling subroutines@>=
12583 void mp_ring_delete (MP mp,pointer p) {
12584   pointer q; 
12585   q=value(p);
12586   if ( q!=null ) if ( q!=p ){ 
12587     while ( value(q)!=p ) q=value(q);
12588     value(q)=value(p);
12589   }
12590 }
12591
12592 @ Eventually there might be an equation that assigns values to all of the
12593 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12594 propagation of values.
12595
12596 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12597 value, it will soon be recycled.
12598
12599 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12600   small_number t; /* the type of ring |p| */
12601   pointer q,r; /* link manipulation registers */
12602   t=type(p)-unknown_tag; q=value(p);
12603   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12604   do {  
12605     r=value(q); type(q)=t;
12606     switch (t) {
12607     case mp_boolean_type: value(q)=v; break;
12608     case mp_string_type: value(q)=v; add_str_ref(v); break;
12609     case mp_pen_type: value(q)=copy_pen(v); break;
12610     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12611     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12612     } /* there ain't no more cases */
12613     q=r;
12614   } while (q!=p);
12615 }
12616
12617 @ If two members of rings are equated, and if they have the same type,
12618 the |ring_merge| procedure is called on to make them equivalent.
12619
12620 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12621   pointer r; /* traverses one list */
12622   r=value(p);
12623   while ( r!=p ) {
12624     if ( r==q ) {
12625       @<Exclaim about a redundant equation@>;
12626       return;
12627     };
12628     r=value(r);
12629   }
12630   r=value(p); value(p)=value(q); value(q)=r;
12631 }
12632
12633 @ @<Exclaim about a redundant equation@>=
12634
12635   print_err("Redundant equation");
12636 @.Redundant equation@>
12637   help2("I already knew that this equation was true.")
12638    ("But perhaps no harm has been done; let's continue.");
12639   mp_put_get_error(mp);
12640 }
12641
12642 @* \[26] Introduction to the syntactic routines.
12643 Let's pause a moment now and try to look at the Big Picture.
12644 The \MP\ program consists of three main parts: syntactic routines,
12645 semantic routines, and output routines. The chief purpose of the
12646 syntactic routines is to deliver the user's input to the semantic routines,
12647 while parsing expressions and locating operators and operands. The
12648 semantic routines act as an interpreter responding to these operators,
12649 which may be regarded as commands. And the output routines are
12650 periodically called on to produce compact font descriptions that can be
12651 used for typesetting or for making interim proof drawings. We have
12652 discussed the basic data structures and many of the details of semantic
12653 operations, so we are good and ready to plunge into the part of \MP\ that
12654 actually controls the activities.
12655
12656 Our current goal is to come to grips with the |get_next| procedure,
12657 which is the keystone of \MP's input mechanism. Each call of |get_next|
12658 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12659 representing the next input token.
12660 $$\vbox{\halign{#\hfil\cr
12661   \hbox{|cur_cmd| denotes a command code from the long list of codes
12662    given earlier;}\cr
12663   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12664   \hbox{|cur_sym| is the hash address of the symbolic token that was
12665    just scanned,}\cr
12666   \hbox{\qquad or zero in the case of a numeric or string
12667    or capsule token.}\cr}}$$
12668 Underlying this external behavior of |get_next| is all the machinery
12669 necessary to convert from character files to tokens. At a given time we
12670 may be only partially finished with the reading of several files (for
12671 which \&{input} was specified), and partially finished with the expansion
12672 of some user-defined macros and/or some macro parameters, and partially
12673 finished reading some text that the user has inserted online,
12674 and so on. When reading a character file, the characters must be
12675 converted to tokens; comments and blank spaces must
12676 be removed, numeric and string tokens must be evaluated.
12677
12678 To handle these situations, which might all be present simultaneously,
12679 \MP\ uses various stacks that hold information about the incomplete
12680 activities, and there is a finite state control for each level of the
12681 input mechanism. These stacks record the current state of an implicitly
12682 recursive process, but the |get_next| procedure is not recursive.
12683
12684 @<Glob...@>=
12685 eight_bits cur_cmd; /* current command set by |get_next| */
12686 integer cur_mod; /* operand of current command */
12687 halfword cur_sym; /* hash address of current symbol */
12688
12689 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12690 command code and its modifier.
12691 It consists of a rather tedious sequence of print
12692 commands, and most of it is essentially an inverse to the |primitive|
12693 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12694 all of this procedure appears elsewhere in the program, together with the
12695 corresponding |primitive| calls.
12696
12697 @<Declare the procedure called |print_cmd_mod|@>=
12698 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12699  switch (c) {
12700   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12701   default: mp_print(mp, "[unknown command code!]"); break;
12702   }
12703 }
12704
12705 @ Here is a procedure that displays a given command in braces, in the
12706 user's transcript file.
12707
12708 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12709
12710 @c 
12711 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12712   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12713   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12714   mp_end_diagnostic(mp, false);
12715 }
12716
12717 @* \[27] Input stacks and states.
12718 The state of \MP's input mechanism appears in the input stack, whose
12719 entries are records with five fields, called |index|, |start|, |loc|,
12720 |limit|, and |name|. The top element of this stack is maintained in a
12721 global variable for which no subscripting needs to be done; the other
12722 elements of the stack appear in an array. Hence the stack is declared thus:
12723
12724 @<Types...@>=
12725 typedef struct {
12726   quarterword index_field;
12727   halfword start_field, loc_field, limit_field, name_field;
12728 } in_state_record;
12729
12730 @ @<Glob...@>=
12731 in_state_record *input_stack;
12732 integer input_ptr; /* first unused location of |input_stack| */
12733 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12734 in_state_record cur_input; /* the ``top'' input state */
12735 int stack_size; /* maximum number of simultaneous input sources */
12736
12737 @ @<Allocate or initialize ...@>=
12738 mp->stack_size = 300;
12739 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12740
12741 @ @<Dealloc variables@>=
12742 xfree(mp->input_stack);
12743
12744 @ We've already defined the special variable |loc==cur_input.loc_field|
12745 in our discussion of basic input-output routines. The other components of
12746 |cur_input| are defined in the same way:
12747
12748 @d index mp->cur_input.index_field /* reference for buffer information */
12749 @d start mp->cur_input.start_field /* starting position in |buffer| */
12750 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12751 @d name mp->cur_input.name_field /* name of the current file */
12752
12753 @ Let's look more closely now at the five control variables
12754 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12755 assuming that \MP\ is reading a line of characters that have been input
12756 from some file or from the user's terminal. There is an array called
12757 |buffer| that acts as a stack of all lines of characters that are
12758 currently being read from files, including all lines on subsidiary
12759 levels of the input stack that are not yet completed. \MP\ will return to
12760 the other lines when it is finished with the present input file.
12761
12762 (Incidentally, on a machine with byte-oriented addressing, it would be
12763 appropriate to combine |buffer| with the |str_pool| array,
12764 letting the buffer entries grow downward from the top of the string pool
12765 and checking that these two tables don't bump into each other.)
12766
12767 The line we are currently working on begins in position |start| of the
12768 buffer; the next character we are about to read is |buffer[loc]|; and
12769 |limit| is the location of the last character present. We always have
12770 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12771 that the end of a line is easily sensed.
12772
12773 The |name| variable is a string number that designates the name of
12774 the current file, if we are reading an ordinary text file.  Special codes
12775 |is_term..max_spec_src| indicate other sources of input text.
12776
12777 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12778 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12779 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12780 @d max_spec_src is_scantok
12781
12782 @ Additional information about the current line is available via the
12783 |index| variable, which counts how many lines of characters are present
12784 in the buffer below the current level. We have |index=0| when reading
12785 from the terminal and prompting the user for each line; then if the user types,
12786 e.g., `\.{input figs}', we will have |index=1| while reading
12787 the file \.{figs.mp}. However, it does not follow that |index| is the
12788 same as the input stack pointer, since many of the levels on the input
12789 stack may come from token lists and some |index| values may correspond
12790 to \.{MPX} files that are not currently on the stack.
12791
12792 The global variable |in_open| is equal to the highest |index| value counting
12793 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12794 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12795 when we are not reading a token list.
12796
12797 If we are not currently reading from the terminal,
12798 we are reading from the file variable |input_file[index]|. We use
12799 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12800 and |cur_file| as an abbreviation for |input_file[index]|.
12801
12802 When \MP\ is not reading from the terminal, the global variable |line| contains
12803 the line number in the current file, for use in error messages. More precisely,
12804 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12805 the line number for each file in the |input_file| array.
12806
12807 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12808 array so that the name doesn't get lost when the file is temporarily removed
12809 from the input stack.
12810 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12811 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12812 Since this is not an \.{MPX} file, we have
12813 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12814 This |name| field is set to |finished| when |input_file[k]| is completely
12815 read.
12816
12817 If more information about the input state is needed, it can be
12818 included in small arrays like those shown here. For example,
12819 the current page or segment number in the input file might be put
12820 into a variable |page|, that is really a macro for the current entry
12821 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12822 by analogy with |line_stack|.
12823 @^system dependencies@>
12824
12825 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12826 @d cur_file mp->input_file[index] /* the current |void *| variable */
12827 @d line mp->line_stack[index] /* current line number in the current source file */
12828 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12829 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12830 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12831 @d mpx_reading (mp->mpx_name[index]>absent)
12832   /* when reading a file, is it an \.{MPX} file? */
12833 @d finished 0
12834   /* |name_field| value when the corresponding \.{MPX} file is finished */
12835
12836 @<Glob...@>=
12837 integer in_open; /* the number of lines in the buffer, less one */
12838 unsigned int open_parens; /* the number of open text files */
12839 void  * *input_file ;
12840 integer *line_stack ; /* the line number for each file */
12841 char *  *iname_stack; /* used for naming \.{MPX} files */
12842 char *  *iarea_stack; /* used for naming \.{MPX} files */
12843 halfword*mpx_name  ;
12844
12845 @ @<Allocate or ...@>=
12846 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
12847 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12848 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12849 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12850 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12851 {
12852   int k;
12853   for (k=0;k<=mp->max_in_open;k++) {
12854     mp->iname_stack[k] =NULL;
12855     mp->iarea_stack[k] =NULL;
12856   }
12857 }
12858
12859 @ @<Dealloc variables@>=
12860 {
12861   int l;
12862   for (l=0;l<=mp->max_in_open;l++) {
12863     xfree(mp->iname_stack[l]);
12864     xfree(mp->iarea_stack[l]);
12865   }
12866 }
12867 xfree(mp->input_file);
12868 xfree(mp->line_stack);
12869 xfree(mp->iname_stack);
12870 xfree(mp->iarea_stack);
12871 xfree(mp->mpx_name);
12872
12873
12874 @ However, all this discussion about input state really applies only to the
12875 case that we are inputting from a file. There is another important case,
12876 namely when we are currently getting input from a token list. In this case
12877 |index>max_in_open|, and the conventions about the other state variables
12878 are different:
12879
12880 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12881 the node that will be read next. If |loc=null|, the token list has been
12882 fully read.
12883
12884 \yskip\hang|start| points to the first node of the token list; this node
12885 may or may not contain a reference count, depending on the type of token
12886 list involved.
12887
12888 \yskip\hang|token_type|, which takes the place of |index| in the
12889 discussion above, is a code number that explains what kind of token list
12890 is being scanned.
12891
12892 \yskip\hang|name| points to the |eqtb| address of the control sequence
12893 being expanded, if the current token list is a macro not defined by
12894 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12895 can be deduced by looking at their first two parameters.
12896
12897 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12898 the parameters of the current macro or loop text begin in the |param_stack|.
12899
12900 \yskip\noindent The |token_type| can take several values, depending on
12901 where the current token list came from:
12902
12903 \yskip
12904 \indent|forever_text|, if the token list being scanned is the body of
12905 a \&{forever} loop;
12906
12907 \indent|loop_text|, if the token list being scanned is the body of
12908 a \&{for} or \&{forsuffixes} loop;
12909
12910 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12911
12912 \indent|backed_up|, if the token list being scanned has been inserted as
12913 `to be read again'.
12914
12915 \indent|inserted|, if the token list being scanned has been inserted as
12916 part of error recovery;
12917
12918 \indent|macro|, if the expansion of a user-defined symbolic token is being
12919 scanned.
12920
12921 \yskip\noindent
12922 The token list begins with a reference count if and only if |token_type=
12923 macro|.
12924 @^reference counts@>
12925
12926 @d token_type index /* type of current token list */
12927 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12928 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12929 @d param_start limit /* base of macro parameters in |param_stack| */
12930 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12931 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12932 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12933 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12934 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12935 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12936
12937 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12938 lists for parameters at the current level and subsidiary levels of input.
12939 This stack grows at a different rate from the others.
12940
12941 @<Glob...@>=
12942 pointer *param_stack;  /* token list pointers for parameters */
12943 integer param_ptr; /* first unused entry in |param_stack| */
12944 integer max_param_stack;  /* largest value of |param_ptr| */
12945
12946 @ @<Allocate or initialize ...@>=
12947 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12948
12949 @ @<Dealloc variables@>=
12950 xfree(mp->param_stack);
12951
12952 @ Notice that the |line| isn't valid when |token_state| is true because it
12953 depends on |index|.  If we really need to know the line number for the
12954 topmost file in the index stack we use the following function.  If a page
12955 number or other information is needed, this routine should be modified to
12956 compute it as well.
12957 @^system dependencies@>
12958
12959 @<Declare a function called |true_line|@>=
12960 integer mp_true_line (MP mp) {
12961   int k; /* an index into the input stack */
12962   if ( file_state && (name>max_spec_src) ) {
12963      return line;
12964   } else { 
12965     k=mp->input_ptr;
12966     while ((k>0) &&
12967            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12968             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12969       decr(k);
12970     }
12971     return (k>0 ? mp->line_stack[(k-1)] : 0 );
12972   }
12973   return 0; 
12974 }
12975
12976 @ Thus, the ``current input state'' can be very complicated indeed; there
12977 can be many levels and each level can arise in a variety of ways. The
12978 |show_context| procedure, which is used by \MP's error-reporting routine to
12979 print out the current input state on all levels down to the most recent
12980 line of characters from an input file, illustrates most of these conventions.
12981 The global variable |file_ptr| contains the lowest level that was
12982 displayed by this procedure.
12983
12984 @<Glob...@>=
12985 integer file_ptr; /* shallowest level shown by |show_context| */
12986
12987 @ The status at each level is indicated by printing two lines, where the first
12988 line indicates what was read so far and the second line shows what remains
12989 to be read. The context is cropped, if necessary, so that the first line
12990 contains at most |half_error_line| characters, and the second contains
12991 at most |error_line|. Non-current input levels whose |token_type| is
12992 `|backed_up|' are shown only if they have not been fully read.
12993
12994 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12995   int old_setting; /* saved |selector| setting */
12996   @<Local variables for formatting calculations@>
12997   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12998   /* store current state */
12999   while (1) { 
13000     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13001     @<Display the current context@>;
13002     if ( file_state )
13003       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13004     decr(mp->file_ptr);
13005   }
13006   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13007 }
13008
13009 @ @<Display the current context@>=
13010 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13011    (token_type!=backed_up) || (loc!=null) ) {
13012     /* we omit backed-up token lists that have already been read */
13013   mp->tally=0; /* get ready to count characters */
13014   old_setting=mp->selector;
13015   if ( file_state ) {
13016     @<Print location of current line@>;
13017     @<Pseudoprint the line@>;
13018   } else { 
13019     @<Print type of token list@>;
13020     @<Pseudoprint the token list@>;
13021   }
13022   mp->selector=old_setting; /* stop pseudoprinting */
13023   @<Print two lines using the tricky pseudoprinted information@>;
13024 }
13025
13026 @ This routine should be changed, if necessary, to give the best possible
13027 indication of where the current line resides in the input file.
13028 For example, on some systems it is best to print both a page and line number.
13029 @^system dependencies@>
13030
13031 @<Print location of current line@>=
13032 if ( name>max_spec_src ) {
13033   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13034 } else if ( terminal_input ) {
13035   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13036   else mp_print_nl(mp, "<insert>");
13037 } else if ( name==is_scantok ) {
13038   mp_print_nl(mp, "<scantokens>");
13039 } else {
13040   mp_print_nl(mp, "<read>");
13041 }
13042 mp_print_char(mp, ' ')
13043
13044 @ Can't use case statement here because the |token_type| is not
13045 a constant expression.
13046
13047 @<Print type of token list@>=
13048 {
13049   if(token_type==forever_text) {
13050     mp_print_nl(mp, "<forever> ");
13051   } else if (token_type==loop_text) {
13052     @<Print the current loop value@>;
13053   } else if (token_type==parameter) {
13054     mp_print_nl(mp, "<argument> "); 
13055   } else if (token_type==backed_up) { 
13056     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13057     else mp_print_nl(mp, "<to be read again> ");
13058   } else if (token_type==inserted) {
13059     mp_print_nl(mp, "<inserted text> ");
13060   } else if (token_type==macro) {
13061     mp_print_ln(mp);
13062     if ( name!=null ) mp_print_text(name);
13063     else @<Print the name of a \&{vardef}'d macro@>;
13064     mp_print(mp, "->");
13065   } else {
13066     mp_print_nl(mp, "?");/* this should never happen */
13067 @.?\relax@>
13068   }
13069 }
13070
13071 @ The parameter that corresponds to a loop text is either a token list
13072 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13073 We'll discuss capsules later; for now, all we need to know is that
13074 the |link| field in a capsule parameter is |void| and that
13075 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13076
13077 @<Print the current loop value@>=
13078 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13079   if ( p!=null ) {
13080     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13081     else mp_show_token_list(mp, p,null,20,mp->tally);
13082   }
13083   mp_print(mp, ")> ");
13084 }
13085
13086 @ The first two parameters of a macro defined by \&{vardef} will be token
13087 lists representing the macro's prefix and ``at point.'' By putting these
13088 together, we get the macro's full name.
13089
13090 @<Print the name of a \&{vardef}'d macro@>=
13091 { p=mp->param_stack[param_start];
13092   if ( p==null ) {
13093     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13094   } else { 
13095     q=p;
13096     while ( link(q)!=null ) q=link(q);
13097     link(q)=mp->param_stack[param_start+1];
13098     mp_show_token_list(mp, p,null,20,mp->tally);
13099     link(q)=null;
13100   }
13101 }
13102
13103 @ Now it is necessary to explain a little trick. We don't want to store a long
13104 string that corresponds to a token list, because that string might take up
13105 lots of memory; and we are printing during a time when an error message is
13106 being given, so we dare not do anything that might overflow one of \MP's
13107 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13108 that stores characters into a buffer of length |error_line|, where character
13109 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13110 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13111 |tally:=0| and |trick_count:=1000000|; then when we reach the
13112 point where transition from line 1 to line 2 should occur, we
13113 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13114 tally+1+error_line-half_error_line)|. At the end of the
13115 pseudoprinting, the values of |first_count|, |tally|, and
13116 |trick_count| give us all the information we need to print the two lines,
13117 and all of the necessary text is in |trick_buf|.
13118
13119 Namely, let |l| be the length of the descriptive information that appears
13120 on the first line. The length of the context information gathered for that
13121 line is |k=first_count|, and the length of the context information
13122 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13123 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13124 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13125 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13126 and print `\.{...}' followed by
13127 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13128 where subscripts of |trick_buf| are circular modulo |error_line|. The
13129 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13130 unless |n+m>error_line|; in the latter case, further cropping is done.
13131 This is easier to program than to explain.
13132
13133 @<Local variables for formatting...@>=
13134 int i; /* index into |buffer| */
13135 integer l; /* length of descriptive information on line 1 */
13136 integer m; /* context information gathered for line 2 */
13137 int n; /* length of line 1 */
13138 integer p; /* starting or ending place in |trick_buf| */
13139 integer q; /* temporary index */
13140
13141 @ The following code tells the print routines to gather
13142 the desired information.
13143
13144 @d begin_pseudoprint { 
13145   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13146   mp->trick_count=1000000;
13147 }
13148 @d set_trick_count {
13149   mp->first_count=mp->tally;
13150   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13151   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13152 }
13153
13154 @ And the following code uses the information after it has been gathered.
13155
13156 @<Print two lines using the tricky pseudoprinted information@>=
13157 if ( mp->trick_count==1000000 ) set_trick_count;
13158   /* |set_trick_count| must be performed */
13159 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13160 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13161 if ( l+mp->first_count<=mp->half_error_line ) {
13162   p=0; n=l+mp->first_count;
13163 } else  { 
13164   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13165   n=mp->half_error_line;
13166 }
13167 for (q=p;q<=mp->first_count-1;q++) {
13168   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13169 }
13170 mp_print_ln(mp);
13171 for (q=1;q<=n;q++) {
13172   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13173 }
13174 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13175 else p=mp->first_count+(mp->error_line-n-3);
13176 for (q=mp->first_count;q<=p-1;q++) {
13177   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13178 }
13179 if ( m+n>mp->error_line ) mp_print(mp, "...")
13180
13181 @ But the trick is distracting us from our current goal, which is to
13182 understand the input state. So let's concentrate on the data structures that
13183 are being pseudoprinted as we finish up the |show_context| procedure.
13184
13185 @<Pseudoprint the line@>=
13186 begin_pseudoprint;
13187 if ( limit>0 ) {
13188   for (i=start;i<=limit-1;i++) {
13189     if ( i==loc ) set_trick_count;
13190     mp_print_str(mp, mp->buffer[i]);
13191   }
13192 }
13193
13194 @ @<Pseudoprint the token list@>=
13195 begin_pseudoprint;
13196 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13197 else mp_show_macro(mp, start,loc,100000)
13198
13199 @ Here is the missing piece of |show_token_list| that is activated when the
13200 token beginning line~2 is about to be shown:
13201
13202 @<Do magic computation@>=set_trick_count
13203
13204 @* \[28] Maintaining the input stacks.
13205 The following subroutines change the input status in commonly needed ways.
13206
13207 First comes |push_input|, which stores the current state and creates a
13208 new level (having, initially, the same properties as the old).
13209
13210 @d push_input  { /* enter a new input level, save the old */
13211   if ( mp->input_ptr>mp->max_in_stack ) {
13212     mp->max_in_stack=mp->input_ptr;
13213     if ( mp->input_ptr==mp->stack_size ) {
13214       int l = (mp->stack_size+(mp->stack_size>>2));
13215       XREALLOC(mp->input_stack, l, in_state_record);
13216       mp->stack_size = l;
13217     }         
13218   }
13219   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13220   incr(mp->input_ptr);
13221 }
13222
13223 @ And of course what goes up must come down.
13224
13225 @d pop_input { /* leave an input level, re-enter the old */
13226     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13227   }
13228
13229 @ Here is a procedure that starts a new level of token-list input, given
13230 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13231 set |name|, reset~|loc|, and increase the macro's reference count.
13232
13233 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13234
13235 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13236   push_input; start=p; token_type=t;
13237   param_start=mp->param_ptr; loc=p;
13238 }
13239
13240 @ When a token list has been fully scanned, the following computations
13241 should be done as we leave that level of input.
13242 @^inner loop@>
13243
13244 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13245   pointer p; /* temporary register */
13246   if ( token_type>=backed_up ) { /* token list to be deleted */
13247     if ( token_type<=inserted ) { 
13248       mp_flush_token_list(mp, start); goto DONE;
13249     } else {
13250       mp_delete_mac_ref(mp, start); /* update reference count */
13251     }
13252   }
13253   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13254     decr(mp->param_ptr);
13255     p=mp->param_stack[mp->param_ptr];
13256     if ( p!=null ) {
13257       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13258         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13259       } else {
13260         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13261       }
13262     }
13263   }
13264 DONE: 
13265   pop_input; check_interrupt;
13266 }
13267
13268 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13269 token by the |cur_tok| routine.
13270 @^inner loop@>
13271
13272 @c @<Declare the procedure called |make_exp_copy|@>;
13273 pointer mp_cur_tok (MP mp) {
13274   pointer p; /* a new token node */
13275   small_number save_type; /* |cur_type| to be restored */
13276   integer save_exp; /* |cur_exp| to be restored */
13277   if ( mp->cur_sym==0 ) {
13278     if ( mp->cur_cmd==capsule_token ) {
13279       save_type=mp->cur_type; save_exp=mp->cur_exp;
13280       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13281       mp->cur_type=save_type; mp->cur_exp=save_exp;
13282     } else { 
13283       p=mp_get_node(mp, token_node_size);
13284       value(p)=mp->cur_mod; name_type(p)=mp_token;
13285       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13286       else type(p)=mp_string_type;
13287     }
13288   } else { 
13289     fast_get_avail(p); info(p)=mp->cur_sym;
13290   }
13291   return p;
13292 }
13293
13294 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13295 seen. The |back_input| procedure takes care of this by putting the token
13296 just scanned back into the input stream, ready to be read again.
13297 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13298
13299 @<Declarations@>= 
13300 void mp_back_input (MP mp);
13301
13302 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13303   pointer p; /* a token list of length one */
13304   p=mp_cur_tok(mp);
13305   while ( token_state &&(loc==null) ) 
13306     mp_end_token_list(mp); /* conserve stack space */
13307   back_list(p);
13308 }
13309
13310 @ The |back_error| routine is used when we want to restore or replace an
13311 offending token just before issuing an error message.  We disable interrupts
13312 during the call of |back_input| so that the help message won't be lost.
13313
13314 @<Declarations@>=
13315 void mp_error (MP mp);
13316 void mp_back_error (MP mp);
13317
13318 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13319   mp->OK_to_interrupt=false; 
13320   mp_back_input(mp); 
13321   mp->OK_to_interrupt=true; mp_error(mp);
13322 }
13323 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13324   mp->OK_to_interrupt=false; 
13325   mp_back_input(mp); token_type=inserted;
13326   mp->OK_to_interrupt=true; mp_error(mp);
13327 }
13328
13329 @ The |begin_file_reading| procedure starts a new level of input for lines
13330 of characters to be read from a file, or as an insertion from the
13331 terminal. It does not take care of opening the file, nor does it set |loc|
13332 or |limit| or |line|.
13333 @^system dependencies@>
13334
13335 @c void mp_begin_file_reading (MP mp) { 
13336   if ( mp->in_open==mp->max_in_open ) 
13337     mp_overflow(mp, "text input levels",mp->max_in_open);
13338 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13339   if ( mp->first==mp->buf_size ) 
13340     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13341   incr(mp->in_open); push_input; index=mp->in_open;
13342   mp->mpx_name[index]=absent;
13343   start=mp->first;
13344   name=is_term; /* |terminal_input| is now |true| */
13345 }
13346
13347 @ Conversely, the variables must be downdated when such a level of input
13348 is finished.  Any associated \.{MPX} file must also be closed and popped
13349 off the file stack.
13350
13351 @c void mp_end_file_reading (MP mp) { 
13352   if ( mp->in_open>index ) {
13353     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13354       mp_confusion(mp, "endinput");
13355 @:this can't happen endinput}{\quad endinput@>
13356     } else { 
13357       (mp->close_file)(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13358       delete_str_ref(mp->mpx_name[mp->in_open]);
13359       decr(mp->in_open);
13360     }
13361   }
13362   mp->first=start;
13363   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13364   if ( name>max_spec_src ) {
13365     (mp->close_file)(cur_file);
13366     delete_str_ref(name);
13367     xfree(in_name); 
13368     xfree(in_area);
13369   }
13370   pop_input; decr(mp->in_open);
13371 }
13372
13373 @ Here is a function that tries to resume input from an \.{MPX} file already
13374 associated with the current input file.  It returns |false| if this doesn't
13375 work.
13376
13377 @c boolean mp_begin_mpx_reading (MP mp) { 
13378   if ( mp->in_open!=index+1 ) {
13379      return false;
13380   } else { 
13381     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13382 @:this can't happen mpx}{\quad mpx@>
13383     if ( mp->first==mp->buf_size ) 
13384       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13385     push_input; index=mp->in_open;
13386     start=mp->first;
13387     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13388     @<Put an empty line in the input buffer@>;
13389     return true;
13390   }
13391 }
13392
13393 @ This procedure temporarily stops reading an \.{MPX} file.
13394
13395 @c void mp_end_mpx_reading (MP mp) { 
13396   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13397 @:this can't happen mpx}{\quad mpx@>
13398   if ( loc<limit ) {
13399     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13400   }
13401   mp->first=start;
13402   pop_input;
13403 }
13404
13405 @ Here we enforce a restriction that simplifies the input stacks considerably.
13406 This should not inconvenience the user because \.{MPX} files are generated
13407 by an auxiliary program called \.{DVItoMP}.
13408
13409 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13410
13411 print_err("`mpxbreak' must be at the end of a line");
13412 help4("This file contains picture expressions for btex...etex")
13413   ("blocks.  Such files are normally generated automatically")
13414   ("but this one seems to be messed up.  I'm going to ignore")
13415   ("the rest of this line.");
13416 mp_error(mp);
13417 }
13418
13419 @ In order to keep the stack from overflowing during a long sequence of
13420 inserted `\.{show}' commands, the following routine removes completed
13421 error-inserted lines from memory.
13422
13423 @c void mp_clear_for_error_prompt (MP mp) { 
13424   while ( file_state && terminal_input &&
13425     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13426   mp_print_ln(mp); clear_terminal;
13427 }
13428
13429 @ To get \MP's whole input mechanism going, we perform the following
13430 actions.
13431
13432 @<Initialize the input routines@>=
13433 { mp->input_ptr=0; mp->max_in_stack=0;
13434   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13435   mp->param_ptr=0; mp->max_param_stack=0;
13436   mp->first=1;
13437   start=1; index=0; line=0; name=is_term;
13438   mp->mpx_name[0]=absent;
13439   mp->force_eof=false;
13440   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13441   limit=mp->last; mp->first=mp->last+1; 
13442   /* |init_terminal| has set |loc| and |last| */
13443 }
13444
13445 @* \[29] Getting the next token.
13446 The heart of \MP's input mechanism is the |get_next| procedure, which
13447 we shall develop in the next few sections of the program. Perhaps we
13448 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13449 eyes and mouth, reading the source files and gobbling them up. And it also
13450 helps \MP\ to regurgitate stored token lists that are to be processed again.
13451
13452 The main duty of |get_next| is to input one token and to set |cur_cmd|
13453 and |cur_mod| to that token's command code and modifier. Furthermore, if
13454 the input token is a symbolic token, that token's |hash| address
13455 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13456
13457 Underlying this simple description is a certain amount of complexity
13458 because of all the cases that need to be handled.
13459 However, the inner loop of |get_next| is reasonably short and fast.
13460
13461 @ Before getting into |get_next|, we need to consider a mechanism by which
13462 \MP\ helps keep errors from propagating too far. Whenever the program goes
13463 into a mode where it keeps calling |get_next| repeatedly until a certain
13464 condition is met, it sets |scanner_status| to some value other than |normal|.
13465 Then if an input file ends, or if an `\&{outer}' symbol appears,
13466 an appropriate error recovery will be possible.
13467
13468 The global variable |warning_info| helps in this error recovery by providing
13469 additional information. For example, |warning_info| might indicate the
13470 name of a macro whose replacement text is being scanned.
13471
13472 @d normal 0 /* |scanner_status| at ``quiet times'' */
13473 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13474 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13475 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13476 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13477 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13478 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13479 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13480
13481 @<Glob...@>=
13482 integer scanner_status; /* are we scanning at high speed? */
13483 integer warning_info; /* if so, what else do we need to know,
13484     in case an error occurs? */
13485
13486 @ @<Initialize the input routines@>=
13487 mp->scanner_status=normal;
13488
13489 @ The following subroutine
13490 is called when an `\&{outer}' symbolic token has been scanned or
13491 when the end of a file has been reached. These two cases are distinguished
13492 by |cur_sym|, which is zero at the end of a file.
13493
13494 @c boolean mp_check_outer_validity (MP mp) {
13495   pointer p; /* points to inserted token list */
13496   if ( mp->scanner_status==normal ) {
13497     return true;
13498   } else if ( mp->scanner_status==tex_flushing ) {
13499     @<Check if the file has ended while flushing \TeX\ material and set the
13500       result value for |check_outer_validity|@>;
13501   } else { 
13502     mp->deletions_allowed=false;
13503     @<Back up an outer symbolic token so that it can be reread@>;
13504     if ( mp->scanner_status>skipping ) {
13505       @<Tell the user what has run away and try to recover@>;
13506     } else { 
13507       print_err("Incomplete if; all text was ignored after line ");
13508 @.Incomplete if...@>
13509       mp_print_int(mp, mp->warning_info);
13510       help3("A forbidden `outer' token occurred in skipped text.")
13511         ("This kind of error happens when you say `if...' and forget")
13512         ("the matching `fi'. I've inserted a `fi'; this might work.");
13513       if ( mp->cur_sym==0 ) 
13514         mp->help_line[2]="The file ended while I was skipping conditional text.";
13515       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13516     }
13517     mp->deletions_allowed=true; 
13518         return false;
13519   }
13520 }
13521
13522 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13523 if ( mp->cur_sym!=0 ) { 
13524    return true;
13525 } else { 
13526   mp->deletions_allowed=false;
13527   print_err("TeX mode didn't end; all text was ignored after line ");
13528   mp_print_int(mp, mp->warning_info);
13529   help2("The file ended while I was looking for the `etex' to")
13530     ("finish this TeX material.  I've inserted `etex' now.");
13531   mp->cur_sym = frozen_etex;
13532   mp_ins_error(mp);
13533   mp->deletions_allowed=true;
13534   return false;
13535 }
13536
13537 @ @<Back up an outer symbolic token so that it can be reread@>=
13538 if ( mp->cur_sym!=0 ) {
13539   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13540   back_list(p); /* prepare to read the symbolic token again */
13541 }
13542
13543 @ @<Tell the user what has run away...@>=
13544
13545   mp_runaway(mp); /* print the definition-so-far */
13546   if ( mp->cur_sym==0 ) {
13547     print_err("File ended");
13548 @.File ended while scanning...@>
13549   } else { 
13550     print_err("Forbidden token found");
13551 @.Forbidden token found...@>
13552   }
13553   mp_print(mp, " while scanning ");
13554   help4("I suspect you have forgotten an `enddef',")
13555     ("causing me to read past where you wanted me to stop.")
13556     ("I'll try to recover; but if the error is serious,")
13557     ("you'd better type `E' or `X' now and fix your file.");
13558   switch (mp->scanner_status) {
13559     @<Complete the error message,
13560       and set |cur_sym| to a token that might help recover from the error@>
13561   } /* there are no other cases */
13562   mp_ins_error(mp);
13563 }
13564
13565 @ As we consider various kinds of errors, it is also appropriate to
13566 change the first line of the help message just given; |help_line[3]|
13567 points to the string that might be changed.
13568
13569 @<Complete the error message,...@>=
13570 case flushing: 
13571   mp_print(mp, "to the end of the statement");
13572   mp->help_line[3]="A previous error seems to have propagated,";
13573   mp->cur_sym=frozen_semicolon;
13574   break;
13575 case absorbing: 
13576   mp_print(mp, "a text argument");
13577   mp->help_line[3]="It seems that a right delimiter was left out,";
13578   if ( mp->warning_info==0 ) {
13579     mp->cur_sym=frozen_end_group;
13580   } else { 
13581     mp->cur_sym=frozen_right_delimiter;
13582     equiv(frozen_right_delimiter)=mp->warning_info;
13583   }
13584   break;
13585 case var_defining:
13586 case op_defining: 
13587   mp_print(mp, "the definition of ");
13588   if ( mp->scanner_status==op_defining ) 
13589      mp_print_text(mp->warning_info);
13590   else 
13591      mp_print_variable_name(mp, mp->warning_info);
13592   mp->cur_sym=frozen_end_def;
13593   break;
13594 case loop_defining: 
13595   mp_print(mp, "the text of a "); 
13596   mp_print_text(mp->warning_info);
13597   mp_print(mp, " loop");
13598   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13599   mp->cur_sym=frozen_end_for;
13600   break;
13601
13602 @ The |runaway| procedure displays the first part of the text that occurred
13603 when \MP\ began its special |scanner_status|, if that text has been saved.
13604
13605 @<Declare the procedure called |runaway|@>=
13606 void mp_runaway (MP mp) { 
13607   if ( mp->scanner_status>flushing ) { 
13608      mp_print_nl(mp, "Runaway ");
13609          switch (mp->scanner_status) { 
13610          case absorbing: mp_print(mp, "text?"); break;
13611          case var_defining: 
13612      case op_defining: mp_print(mp,"definition?"); break;
13613      case loop_defining: mp_print(mp, "loop?"); break;
13614      } /* there are no other cases */
13615      mp_print_ln(mp); 
13616      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13617   }
13618 }
13619
13620 @ We need to mention a procedure that may be called by |get_next|.
13621
13622 @<Declarations@>= 
13623 void mp_firm_up_the_line (MP mp);
13624
13625 @ And now we're ready to take the plunge into |get_next| itself.
13626 Note that the behavior depends on the |scanner_status| because percent signs
13627 and double quotes need to be passed over when skipping TeX material.
13628
13629 @c 
13630 void mp_get_next (MP mp) {
13631   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13632 @^inner loop@>
13633   /*restart*/ /* go here to get the next input token */
13634   /*exit*/ /* go here when the next input token has been got */
13635   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13636   /*found*/ /* go here when the end of a symbolic token has been found */
13637   /*switch*/ /* go here to branch on the class of an input character */
13638   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13639     /* go here at crucial stages when scanning a number */
13640   int k; /* an index into |buffer| */
13641   ASCII_code c; /* the current character in the buffer */
13642   ASCII_code class; /* its class number */
13643   integer n,f; /* registers for decimal-to-binary conversion */
13644 RESTART: 
13645   mp->cur_sym=0;
13646   if ( file_state ) {
13647     @<Input from external file; |goto restart| if no input found,
13648     or |return| if a non-symbolic token is found@>;
13649   } else {
13650     @<Input from token list; |goto restart| if end of list or
13651       if a parameter needs to be expanded,
13652       or |return| if a non-symbolic token is found@>;
13653   }
13654 COMMON_ENDING: 
13655   @<Finish getting the symbolic token in |cur_sym|;
13656    |goto restart| if it is illegal@>;
13657 }
13658
13659 @ When a symbolic token is declared to be `\&{outer}', its command code
13660 is increased by |outer_tag|.
13661 @^inner loop@>
13662
13663 @<Finish getting the symbolic token in |cur_sym|...@>=
13664 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13665 if ( mp->cur_cmd>=outer_tag ) {
13666   if ( mp_check_outer_validity(mp) ) 
13667     mp->cur_cmd=mp->cur_cmd-outer_tag;
13668   else 
13669     goto RESTART;
13670 }
13671
13672 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13673 to have a special test for end-of-line.
13674 @^inner loop@>
13675
13676 @<Input from external file;...@>=
13677
13678 SWITCH: 
13679   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13680   switch (class) {
13681   case digit_class: goto START_NUMERIC_TOKEN; break;
13682   case period_class: 
13683     class=mp->char_class[mp->buffer[loc]];
13684     if ( class>period_class ) {
13685       goto SWITCH;
13686     } else if ( class<period_class ) { /* |class=digit_class| */
13687       n=0; goto START_DECIMAL_TOKEN;
13688     }
13689 @:. }{\..\ token@>
13690     break;
13691   case space_class: goto SWITCH; break;
13692   case percent_class: 
13693     if ( mp->scanner_status==tex_flushing ) {
13694       if ( loc<limit ) goto SWITCH;
13695     }
13696     @<Move to next line of file, or |goto restart| if there is no next line@>;
13697     check_interrupt;
13698     goto SWITCH;
13699     break;
13700   case string_class: 
13701     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13702     else @<Get a string token and |return|@>;
13703     break;
13704   case isolated_classes: 
13705     k=loc-1; goto FOUND; break;
13706   case invalid_class: 
13707     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13708     else @<Decry the invalid character and |goto restart|@>;
13709     break;
13710   default: break; /* letters, etc. */
13711   }
13712   k=loc-1;
13713   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13714   goto FOUND;
13715 START_NUMERIC_TOKEN:
13716   @<Get the integer part |n| of a numeric token;
13717     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13718 START_DECIMAL_TOKEN:
13719   @<Get the fraction part |f| of a numeric token@>;
13720 FIN_NUMERIC_TOKEN:
13721   @<Pack the numeric and fraction parts of a numeric token
13722     and |return|@>;
13723 FOUND: 
13724   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13725 }
13726
13727 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13728 |token_list| after the error has been dealt with
13729 (cf.\ |clear_for_error_prompt|).
13730
13731 @<Decry the invalid...@>=
13732
13733   print_err("Text line contains an invalid character");
13734 @.Text line contains...@>
13735   help2("A funny symbol that I can\'t read has just been input.")
13736     ("Continue, and I'll forget that it ever happened.");
13737   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13738   goto RESTART;
13739 }
13740
13741 @ @<Get a string token and |return|@>=
13742
13743   if ( mp->buffer[loc]=='"' ) {
13744     mp->cur_mod=rts("");
13745   } else { 
13746     k=loc; mp->buffer[limit+1]='"';
13747     do {  
13748      incr(loc);
13749     } while (mp->buffer[loc]!='"');
13750     if ( loc>limit ) {
13751       @<Decry the missing string delimiter and |goto restart|@>;
13752     }
13753     if ( loc==k+1 ) {
13754       mp->cur_mod=mp->buffer[k];
13755     } else { 
13756       str_room(loc-k);
13757       do {  
13758         append_char(mp->buffer[k]); incr(k);
13759       } while (k!=loc);
13760       mp->cur_mod=mp_make_string(mp);
13761     }
13762   }
13763   incr(loc); mp->cur_cmd=string_token; 
13764   return;
13765 }
13766
13767 @ We go to |restart| after this error message, not to |SWITCH|,
13768 because the |clear_for_error_prompt| routine might have reinstated
13769 |token_state| after |error| has finished.
13770
13771 @<Decry the missing string delimiter and |goto restart|@>=
13772
13773   loc=limit; /* the next character to be read on this line will be |"%"| */
13774   print_err("Incomplete string token has been flushed");
13775 @.Incomplete string token...@>
13776   help3("Strings should finish on the same line as they began.")
13777     ("I've deleted the partial string; you might want to")
13778     ("insert another by typing, e.g., `I\"new string\"'.");
13779   mp->deletions_allowed=false; mp_error(mp);
13780   mp->deletions_allowed=true; 
13781   goto RESTART;
13782 }
13783
13784 @ @<Get the integer part |n| of a numeric token...@>=
13785 n=c-'0';
13786 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13787   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13788   incr(loc);
13789 }
13790 if ( mp->buffer[loc]=='.' ) 
13791   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13792     goto DONE;
13793 f=0; 
13794 goto FIN_NUMERIC_TOKEN;
13795 DONE: incr(loc)
13796
13797 @ @<Get the fraction part |f| of a numeric token@>=
13798 k=0;
13799 do { 
13800   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13801     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13802   }
13803   incr(loc);
13804 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13805 f=mp_round_decimals(mp, k);
13806 if ( f==unity ) {
13807   incr(n); f=0;
13808 }
13809
13810 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13811 if ( n<32768 ) {
13812   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13813 } else if ( mp->scanner_status!=tex_flushing ) {
13814   print_err("Enormous number has been reduced");
13815 @.Enormous number...@>
13816   help2("I can\'t handle numbers bigger than 32767.99998;")
13817     ("so I've changed your constant to that maximum amount.");
13818   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13819   mp->cur_mod=el_gordo;
13820 }
13821 mp->cur_cmd=numeric_token; return
13822
13823 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13824
13825   mp->cur_mod=n*unity+f;
13826   if ( mp->cur_mod>=fraction_one ) {
13827     if ( (mp->internal[mp_warning_check]>0) &&
13828          (mp->scanner_status!=tex_flushing) ) {
13829       print_err("Number is too large (");
13830       mp_print_scaled(mp, mp->cur_mod);
13831       mp_print_char(mp, ')');
13832       help3("It is at least 4096. Continue and I'll try to cope")
13833       ("with that big value; but it might be dangerous.")
13834       ("(Set warningcheck:=0 to suppress this message.)");
13835       mp_error(mp);
13836     }
13837   }
13838 }
13839
13840 @ Let's consider now what happens when |get_next| is looking at a token list.
13841 @^inner loop@>
13842
13843 @<Input from token list;...@>=
13844 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13845   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13846   if ( mp->cur_sym>=expr_base ) {
13847     if ( mp->cur_sym>=suffix_base ) {
13848       @<Insert a suffix or text parameter and |goto restart|@>;
13849     } else { 
13850       mp->cur_cmd=capsule_token;
13851       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13852       mp->cur_sym=0; return;
13853     }
13854   }
13855 } else if ( loc>null ) {
13856   @<Get a stored numeric or string or capsule token and |return|@>
13857 } else { /* we are done with this token list */
13858   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13859 }
13860
13861 @ @<Insert a suffix or text parameter...@>=
13862
13863   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13864   /* |param_size=text_base-suffix_base| */
13865   mp_begin_token_list(mp,
13866                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13867                       parameter);
13868   goto RESTART;
13869 }
13870
13871 @ @<Get a stored numeric or string or capsule token...@>=
13872
13873   if ( name_type(loc)==mp_token ) {
13874     mp->cur_mod=value(loc);
13875     if ( type(loc)==mp_known ) {
13876       mp->cur_cmd=numeric_token;
13877     } else { 
13878       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13879     }
13880   } else { 
13881     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13882   };
13883   loc=link(loc); return;
13884 }
13885
13886 @ All of the easy branches of |get_next| have now been taken care of.
13887 There is one more branch.
13888
13889 @<Move to next line of file, or |goto restart|...@>=
13890 if ( name>max_spec_src ) {
13891   @<Read next line of file into |buffer|, or
13892     |goto restart| if the file has ended@>;
13893 } else { 
13894   if ( mp->input_ptr>0 ) {
13895      /* text was inserted during error recovery or by \&{scantokens} */
13896     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13897   }
13898   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13899   if ( mp->interaction>mp_nonstop_mode ) {
13900     if ( limit==start ) /* previous line was empty */
13901       mp_print_nl(mp, "(Please type a command or say `end')");
13902 @.Please type...@>
13903     mp_print_ln(mp); mp->first=start;
13904     prompt_input("*"); /* input on-line into |buffer| */
13905 @.*\relax@>
13906     limit=mp->last; mp->buffer[limit]='%';
13907     mp->first=limit+1; loc=start;
13908   } else {
13909     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13910 @.job aborted@>
13911     /* nonstop mode, which is intended for overnight batch processing,
13912     never waits for on-line input */
13913   }
13914 }
13915
13916 @ The global variable |force_eof| is normally |false|; it is set |true|
13917 by an \&{endinput} command.
13918
13919 @<Glob...@>=
13920 boolean force_eof; /* should the next \&{input} be aborted early? */
13921
13922 @ We must decrement |loc| in order to leave the buffer in a valid state
13923 when an error condition causes us to |goto restart| without calling
13924 |end_file_reading|.
13925
13926 @<Read next line of file into |buffer|, or
13927   |goto restart| if the file has ended@>=
13928
13929   incr(line); mp->first=start;
13930   if ( ! mp->force_eof ) {
13931     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
13932       mp_firm_up_the_line(mp); /* this sets |limit| */
13933     else 
13934       mp->force_eof=true;
13935   };
13936   if ( mp->force_eof ) {
13937     mp->force_eof=false;
13938     decr(loc);
13939     if ( mpx_reading ) {
13940       @<Complain that the \.{MPX} file ended unexpectly; then set
13941         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13942     } else { 
13943       mp_print_char(mp, ')'); decr(mp->open_parens);
13944       update_terminal; /* show user that file has been read */
13945       mp_end_file_reading(mp); /* resume previous level */
13946       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13947       else goto RESTART;
13948     }
13949   }
13950   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13951 }
13952
13953 @ We should never actually come to the end of an \.{MPX} file because such
13954 files should have an \&{mpxbreak} after the translation of the last
13955 \&{btex}$\,\ldots\,$\&{etex} block.
13956
13957 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13958
13959   mp->mpx_name[index]=finished;
13960   print_err("mpx file ended unexpectedly");
13961   help4("The file had too few picture expressions for btex...etex")
13962     ("blocks.  Such files are normally generated automatically")
13963     ("but this one got messed up.  You might want to insert a")
13964     ("picture expression now.");
13965   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13966   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13967 }
13968
13969 @ Sometimes we want to make it look as though we have just read a blank line
13970 without really doing so.
13971
13972 @<Put an empty line in the input buffer@>=
13973 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13974 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13975
13976 @ If the user has set the |mp_pausing| parameter to some positive value,
13977 and if nonstop mode has not been selected, each line of input is displayed
13978 on the terminal and the transcript file, followed by `\.{=>}'.
13979 \MP\ waits for a response. If the response is null (i.e., if nothing is
13980 typed except perhaps a few blank spaces), the original
13981 line is accepted as it stands; otherwise the line typed is
13982 used instead of the line in the file.
13983
13984 @c void mp_firm_up_the_line (MP mp) {
13985   size_t k; /* an index into |buffer| */
13986   limit=mp->last;
13987   if ( mp->internal[mp_pausing]>0) if ( mp->interaction>mp_nonstop_mode ) {
13988     wake_up_terminal; mp_print_ln(mp);
13989     if ( start<limit ) {
13990       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13991         mp_print_str(mp, mp->buffer[k]);
13992       } 
13993     }
13994     mp->first=limit; prompt_input("=>"); /* wait for user response */
13995 @.=>@>
13996     if ( mp->last>mp->first ) {
13997       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13998         mp->buffer[k+start-mp->first]=mp->buffer[k];
13999       }
14000       limit=start+mp->last-mp->first;
14001     }
14002   }
14003 }
14004
14005 @* \[30] Dealing with \TeX\ material.
14006 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14007 features need to be implemented at a low level in the scanning process
14008 so that \MP\ can stay in synch with the a preprocessor that treats
14009 blocks of \TeX\ material as they occur in the input file without trying
14010 to expand \MP\ macros.  Thus we need a special version of |get_next|
14011 that does not expand macros and such but does handle \&{btex},
14012 \&{verbatimtex}, etc.
14013
14014 The special version of |get_next| is called |get_t_next|.  It works by flushing
14015 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14016 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14017 \&{btex}, and switching back when it sees \&{mpxbreak}.
14018
14019 @d btex_code 0
14020 @d verbatim_code 1
14021
14022 @ @<Put each...@>=
14023 mp_primitive(mp, "btex",start_tex,btex_code);
14024 @:btex_}{\&{btex} primitive@>
14025 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14026 @:verbatimtex_}{\&{verbatimtex} primitive@>
14027 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14028 @:etex_}{\&{etex} primitive@>
14029 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14030 @:mpx_break_}{\&{mpxbreak} primitive@>
14031
14032 @ @<Cases of |print_cmd...@>=
14033 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14034   else mp_print(mp, "verbatimtex"); break;
14035 case etex_marker: mp_print(mp, "etex"); break;
14036 case mpx_break: mp_print(mp, "mpxbreak"); break;
14037
14038 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14039 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14040 is encountered.
14041
14042 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14043
14044 @<Declarations@>=
14045 void mp_start_mpx_input (MP mp);
14046
14047 @ @c 
14048 void mp_t_next (MP mp) {
14049   int old_status; /* saves the |scanner_status| */
14050   integer old_info; /* saves the |warning_info| */
14051   while ( mp->cur_cmd<=max_pre_command ) {
14052     if ( mp->cur_cmd==mpx_break ) {
14053       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14054         @<Complain about a misplaced \&{mpxbreak}@>;
14055       } else { 
14056         mp_end_mpx_reading(mp); 
14057         goto TEX_FLUSH;
14058       }
14059     } else if ( mp->cur_cmd==start_tex ) {
14060       if ( token_state || (name<=max_spec_src) ) {
14061         @<Complain that we are not reading a file@>;
14062       } else if ( mpx_reading ) {
14063         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14064       } else if ( (mp->cur_mod!=verbatim_code)&&
14065                   (mp->mpx_name[index]!=finished) ) {
14066         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14067       } else {
14068         goto TEX_FLUSH;
14069       }
14070     } else {
14071        @<Complain about a misplaced \&{etex}@>;
14072     }
14073     goto COMMON_ENDING;
14074   TEX_FLUSH: 
14075     @<Flush the \TeX\ material@>;
14076   COMMON_ENDING: 
14077     mp_get_next(mp);
14078   }
14079 }
14080
14081 @ We could be in the middle of an operation such as skipping false conditional
14082 text when \TeX\ material is encountered, so we must be careful to save the
14083 |scanner_status|.
14084
14085 @<Flush the \TeX\ material@>=
14086 old_status=mp->scanner_status;
14087 old_info=mp->warning_info;
14088 mp->scanner_status=tex_flushing;
14089 mp->warning_info=line;
14090 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14091 mp->scanner_status=old_status;
14092 mp->warning_info=old_info
14093
14094 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14095 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14096 help4("This file contains picture expressions for btex...etex")
14097   ("blocks.  Such files are normally generated automatically")
14098   ("but this one seems to be messed up.  I'll just keep going")
14099   ("and hope for the best.");
14100 mp_error(mp);
14101 }
14102
14103 @ @<Complain that we are not reading a file@>=
14104 { print_err("You can only use `btex' or `verbatimtex' in a file");
14105 help3("I'll have to ignore this preprocessor command because it")
14106   ("only works when there is a file to preprocess.  You might")
14107   ("want to delete everything up to the next `etex`.");
14108 mp_error(mp);
14109 }
14110
14111 @ @<Complain about a misplaced \&{mpxbreak}@>=
14112 { print_err("Misplaced mpxbreak");
14113 help2("I'll ignore this preprocessor command because it")
14114   ("doesn't belong here");
14115 mp_error(mp);
14116 }
14117
14118 @ @<Complain about a misplaced \&{etex}@>=
14119 { print_err("Extra etex will be ignored");
14120 help1("There is no btex or verbatimtex for this to match");
14121 mp_error(mp);
14122 }
14123
14124 @* \[31] Scanning macro definitions.
14125 \MP\ has a variety of ways to tuck tokens away into token lists for later
14126 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14127 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14128 All such operations are handled by the routines in this part of the program.
14129
14130 The modifier part of each command code is zero for the ``ending delimiters''
14131 like \&{enddef} and \&{endfor}.
14132
14133 @d start_def 1 /* command modifier for \&{def} */
14134 @d var_def 2 /* command modifier for \&{vardef} */
14135 @d end_def 0 /* command modifier for \&{enddef} */
14136 @d start_forever 1 /* command modifier for \&{forever} */
14137 @d end_for 0 /* command modifier for \&{endfor} */
14138
14139 @<Put each...@>=
14140 mp_primitive(mp, "def",macro_def,start_def);
14141 @:def_}{\&{def} primitive@>
14142 mp_primitive(mp, "vardef",macro_def,var_def);
14143 @:var_def_}{\&{vardef} primitive@>
14144 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14145 @:primary_def_}{\&{primarydef} primitive@>
14146 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14147 @:secondary_def_}{\&{secondarydef} primitive@>
14148 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14149 @:tertiary_def_}{\&{tertiarydef} primitive@>
14150 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14151 @:end_def_}{\&{enddef} primitive@>
14152 @#
14153 mp_primitive(mp, "for",iteration,expr_base);
14154 @:for_}{\&{for} primitive@>
14155 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14156 @:for_suffixes_}{\&{forsuffixes} primitive@>
14157 mp_primitive(mp, "forever",iteration,start_forever);
14158 @:forever_}{\&{forever} primitive@>
14159 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14160 @:end_for_}{\&{endfor} primitive@>
14161
14162 @ @<Cases of |print_cmd...@>=
14163 case macro_def:
14164   if ( m<=var_def ) {
14165     if ( m==start_def ) mp_print(mp, "def");
14166     else if ( m<start_def ) mp_print(mp, "enddef");
14167     else mp_print(mp, "vardef");
14168   } else if ( m==secondary_primary_macro ) { 
14169     mp_print(mp, "primarydef");
14170   } else if ( m==tertiary_secondary_macro ) { 
14171     mp_print(mp, "secondarydef");
14172   } else { 
14173     mp_print(mp, "tertiarydef");
14174   }
14175   break;
14176 case iteration: 
14177   if ( m<=start_forever ) {
14178     if ( m==start_forever ) mp_print(mp, "forever"); 
14179     else mp_print(mp, "endfor");
14180   } else if ( m==expr_base ) {
14181     mp_print(mp, "for"); 
14182   } else { 
14183     mp_print(mp, "forsuffixes");
14184   }
14185   break;
14186
14187 @ Different macro-absorbing operations have different syntaxes, but they
14188 also have a lot in common. There is a list of special symbols that are to
14189 be replaced by parameter tokens; there is a special command code that
14190 ends the definition; the quotation conventions are identical.  Therefore
14191 it makes sense to have most of the work done by a single subroutine. That
14192 subroutine is called |scan_toks|.
14193
14194 The first parameter to |scan_toks| is the command code that will
14195 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14196
14197 The second parameter, |subst_list|, points to a (possibly empty) list
14198 of two-word nodes whose |info| and |value| fields specify symbol tokens
14199 before and after replacement. The list will be returned to free storage
14200 by |scan_toks|.
14201
14202 The third parameter is simply appended to the token list that is built.
14203 And the final parameter tells how many of the special operations
14204 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14205 When such parameters are present, they are called \.{(SUFFIX0)},
14206 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14207
14208 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14209   subst_list, pointer tail_end, small_number suffix_count) {
14210   pointer p; /* tail of the token list being built */
14211   pointer q; /* temporary for link management */
14212   integer balance; /* left delimiters minus right delimiters */
14213   p=hold_head; balance=1; link(hold_head)=null;
14214   while (1) { 
14215     get_t_next;
14216     if ( mp->cur_sym>0 ) {
14217       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14218       if ( mp->cur_cmd==terminator ) {
14219         @<Adjust the balance; |break| if it's zero@>;
14220       } else if ( mp->cur_cmd==macro_special ) {
14221         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14222       }
14223     }
14224     link(p)=mp_cur_tok(mp); p=link(p);
14225   }
14226   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14227   return link(hold_head);
14228 }
14229
14230 @ @<Substitute for |cur_sym|...@>=
14231
14232   q=subst_list;
14233   while ( q!=null ) {
14234     if ( info(q)==mp->cur_sym ) {
14235       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14236     }
14237     q=link(q);
14238   }
14239 }
14240
14241 @ @<Adjust the balance; |break| if it's zero@>=
14242 if ( mp->cur_mod>0 ) {
14243   incr(balance);
14244 } else { 
14245   decr(balance);
14246   if ( balance==0 )
14247     break;
14248 }
14249
14250 @ Four commands are intended to be used only within macro texts: \&{quote},
14251 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14252 code called |macro_special|.
14253
14254 @d quote 0 /* |macro_special| modifier for \&{quote} */
14255 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14256 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14257 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14258
14259 @<Put each...@>=
14260 mp_primitive(mp, "quote",macro_special,quote);
14261 @:quote_}{\&{quote} primitive@>
14262 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14263 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14264 mp_primitive(mp, "@@",macro_special,macro_at);
14265 @:]]]\AT!_}{\.{\AT!} primitive@>
14266 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14267 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14268
14269 @ @<Cases of |print_cmd...@>=
14270 case macro_special: 
14271   switch (m) {
14272   case macro_prefix: mp_print(mp, "#@@"); break;
14273   case macro_at: mp_print_char(mp, '@@'); break;
14274   case macro_suffix: mp_print(mp, "@@#"); break;
14275   default: mp_print(mp, "quote"); break;
14276   }
14277   break;
14278
14279 @ @<Handle quoted...@>=
14280
14281   if ( mp->cur_mod==quote ) { get_t_next; } 
14282   else if ( mp->cur_mod<=suffix_count ) 
14283     mp->cur_sym=suffix_base-1+mp->cur_mod;
14284 }
14285
14286 @ Here is a routine that's used whenever a token will be redefined. If
14287 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14288 substituted; the latter is redefinable but essentially impossible to use,
14289 hence \MP's tables won't get fouled up.
14290
14291 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14292 RESTART: 
14293   get_t_next;
14294   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14295     print_err("Missing symbolic token inserted");
14296 @.Missing symbolic token...@>
14297     help3("Sorry: You can\'t redefine a number, string, or expr.")
14298       ("I've inserted an inaccessible symbol so that your")
14299       ("definition will be completed without mixing me up too badly.");
14300     if ( mp->cur_sym>0 )
14301       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14302     else if ( mp->cur_cmd==string_token ) 
14303       delete_str_ref(mp->cur_mod);
14304     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14305   }
14306 }
14307
14308 @ Before we actually redefine a symbolic token, we need to clear away its
14309 former value, if it was a variable. The following stronger version of
14310 |get_symbol| does that.
14311
14312 @c void mp_get_clear_symbol (MP mp) { 
14313   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14314 }
14315
14316 @ Here's another little subroutine; it checks that an equals sign
14317 or assignment sign comes along at the proper place in a macro definition.
14318
14319 @c void mp_check_equals (MP mp) { 
14320   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14321      mp_missing_err(mp, "=");
14322 @.Missing `='@>
14323     help5("The next thing in this `def' should have been `=',")
14324       ("because I've already looked at the definition heading.")
14325       ("But don't worry; I'll pretend that an equals sign")
14326       ("was present. Everything from here to `enddef'")
14327       ("will be the replacement text of this macro.");
14328     mp_back_error(mp);
14329   }
14330 }
14331
14332 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14333 handled now that we have |scan_toks|.  In this case there are
14334 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14335 |expr_base| and |expr_base+1|).
14336
14337 @c void mp_make_op_def (MP mp) {
14338   command_code m; /* the type of definition */
14339   pointer p,q,r; /* for list manipulation */
14340   m=mp->cur_mod;
14341   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14342   info(q)=mp->cur_sym; value(q)=expr_base;
14343   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14344   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14345   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14346   get_t_next; mp_check_equals(mp);
14347   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14348   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14349   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14350   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14351   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14352 }
14353
14354 @ Parameters to macros are introduced by the keywords \&{expr},
14355 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14356
14357 @<Put each...@>=
14358 mp_primitive(mp, "expr",param_type,expr_base);
14359 @:expr_}{\&{expr} primitive@>
14360 mp_primitive(mp, "suffix",param_type,suffix_base);
14361 @:suffix_}{\&{suffix} primitive@>
14362 mp_primitive(mp, "text",param_type,text_base);
14363 @:text_}{\&{text} primitive@>
14364 mp_primitive(mp, "primary",param_type,primary_macro);
14365 @:primary_}{\&{primary} primitive@>
14366 mp_primitive(mp, "secondary",param_type,secondary_macro);
14367 @:secondary_}{\&{secondary} primitive@>
14368 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14369 @:tertiary_}{\&{tertiary} primitive@>
14370
14371 @ @<Cases of |print_cmd...@>=
14372 case param_type:
14373   if ( m>=expr_base ) {
14374     if ( m==expr_base ) mp_print(mp, "expr");
14375     else if ( m==suffix_base ) mp_print(mp, "suffix");
14376     else mp_print(mp, "text");
14377   } else if ( m<secondary_macro ) {
14378     mp_print(mp, "primary");
14379   } else if ( m==secondary_macro ) {
14380     mp_print(mp, "secondary");
14381   } else {
14382     mp_print(mp, "tertiary");
14383   }
14384   break;
14385
14386 @ Let's turn next to the more complex processing associated with \&{def}
14387 and \&{vardef}. When the following procedure is called, |cur_mod|
14388 should be either |start_def| or |var_def|.
14389
14390 @c @<Declare the procedure called |check_delimiter|@>;
14391 @<Declare the function called |scan_declared_variable|@>;
14392 void mp_scan_def (MP mp) {
14393   int m; /* the type of definition */
14394   int n; /* the number of special suffix parameters */
14395   int k; /* the total number of parameters */
14396   int c; /* the kind of macro we're defining */
14397   pointer r; /* parameter-substitution list */
14398   pointer q; /* tail of the macro token list */
14399   pointer p; /* temporary storage */
14400   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14401   pointer l_delim,r_delim; /* matching delimiters */
14402   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14403   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14404   @<Scan the token or variable to be defined;
14405     set |n|, |scanner_status|, and |warning_info|@>;
14406   k=n;
14407   if ( mp->cur_cmd==left_delimiter ) {
14408     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14409   }
14410   if ( mp->cur_cmd==param_type ) {
14411     @<Absorb undelimited parameters, putting them into list |r|@>;
14412   }
14413   mp_check_equals(mp);
14414   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14415   @<Attach the replacement text to the tail of node |p|@>;
14416   mp->scanner_status=normal; mp_get_x_next(mp);
14417 }
14418
14419 @ We don't put `|frozen_end_group|' into the replacement text of
14420 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14421
14422 @<Attach the replacement text to the tail of node |p|@>=
14423 if ( m==start_def ) {
14424   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14425 } else { 
14426   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14427   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14428   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14429 }
14430 if ( mp->warning_info==bad_vardef ) 
14431   mp_flush_token_list(mp, value(bad_vardef))
14432
14433 @ @<Glob...@>=
14434 int bg_loc;
14435 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14436
14437 @ @<Scan the token or variable to be defined;...@>=
14438 if ( m==start_def ) {
14439   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14440   mp->scanner_status=op_defining; n=0;
14441   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14442 } else { 
14443   p=mp_scan_declared_variable(mp);
14444   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14445   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14446   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14447   mp->scanner_status=var_defining; n=2;
14448   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14449     n=3; get_t_next;
14450   }
14451   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14452 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14453
14454 @ @<Change to `\.{a bad variable}'@>=
14455
14456   print_err("This variable already starts with a macro");
14457 @.This variable already...@>
14458   help2("After `vardef a' you can\'t say `vardef a.b'.")
14459     ("So I'll have to discard this definition.");
14460   mp_error(mp); mp->warning_info=bad_vardef;
14461 }
14462
14463 @ @<Initialize table entries...@>=
14464 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14465 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14466
14467 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14468 do {  
14469   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14470   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14471    base=mp->cur_mod;
14472   } else { 
14473     print_err("Missing parameter type; `expr' will be assumed");
14474 @.Missing parameter type@>
14475     help1("You should've had `expr' or `suffix' or `text' here.");
14476     mp_back_error(mp); base=expr_base;
14477   }
14478   @<Absorb parameter tokens for type |base|@>;
14479   mp_check_delimiter(mp, l_delim,r_delim);
14480   get_t_next;
14481 } while (mp->cur_cmd==left_delimiter)
14482
14483 @ @<Absorb parameter tokens for type |base|@>=
14484 do { 
14485   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14486   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14487   value(p)=base+k; info(p)=mp->cur_sym;
14488   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14489 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14490   incr(k); link(p)=r; r=p; get_t_next;
14491 } while (mp->cur_cmd==comma)
14492
14493 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14494
14495   p=mp_get_node(mp, token_node_size);
14496   if ( mp->cur_mod<expr_base ) {
14497     c=mp->cur_mod; value(p)=expr_base+k;
14498   } else { 
14499     value(p)=mp->cur_mod+k;
14500     if ( mp->cur_mod==expr_base ) c=expr_macro;
14501     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14502     else c=text_macro;
14503   }
14504   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14505   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14506   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14507     c=of_macro; p=mp_get_node(mp, token_node_size);
14508     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14509     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14510     link(p)=r; r=p; get_t_next;
14511   }
14512 }
14513
14514 @* \[32] Expanding the next token.
14515 Only a few command codes |<min_command| can possibly be returned by
14516 |get_t_next|; in increasing order, they are
14517 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14518 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14519
14520 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14521 like |get_t_next| except that it keeps getting more tokens until
14522 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14523 macros and removes conditionals or iterations or input instructions that
14524 might be present.
14525
14526 It follows that |get_x_next| might invoke itself recursively. In fact,
14527 there is massive recursion, since macro expansion can involve the
14528 scanning of arbitrarily complex expressions, which in turn involve
14529 macro expansion and conditionals, etc.
14530 @^recursion@>
14531
14532 Therefore it's necessary to declare a whole bunch of |forward|
14533 procedures at this point, and to insert some other procedures
14534 that will be invoked by |get_x_next|.
14535
14536 @<Declarations@>= 
14537 void mp_scan_primary (MP mp);
14538 void mp_scan_secondary (MP mp);
14539 void mp_scan_tertiary (MP mp);
14540 void mp_scan_expression (MP mp);
14541 void mp_scan_suffix (MP mp);
14542 @<Declare the procedure called |macro_call|@>;
14543 void mp_get_boolean (MP mp);
14544 void mp_pass_text (MP mp);
14545 void mp_conditional (MP mp);
14546 void mp_start_input (MP mp);
14547 void mp_begin_iteration (MP mp);
14548 void mp_resume_iteration (MP mp);
14549 void mp_stop_iteration (MP mp);
14550
14551 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14552 when it has to do exotic expansion commands.
14553
14554 @c void mp_expand (MP mp) {
14555   pointer p; /* for list manipulation */
14556   size_t k; /* something that we hope is |<=buf_size| */
14557   pool_pointer j; /* index into |str_pool| */
14558   if ( mp->internal[mp_tracing_commands]>unity ) 
14559     if ( mp->cur_cmd!=defined_macro )
14560       show_cur_cmd_mod;
14561   switch (mp->cur_cmd)  {
14562   case if_test:
14563     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14564     break;
14565   case fi_or_else:
14566     @<Terminate the current conditional and skip to \&{fi}@>;
14567     break;
14568   case input:
14569     @<Initiate or terminate input from a file@>;
14570     break;
14571   case iteration:
14572     if ( mp->cur_mod==end_for ) {
14573       @<Scold the user for having an extra \&{endfor}@>;
14574     } else {
14575       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14576     }
14577     break;
14578   case repeat_loop: 
14579     @<Repeat a loop@>;
14580     break;
14581   case exit_test: 
14582     @<Exit a loop if the proper time has come@>;
14583     break;
14584   case relax: 
14585     break;
14586   case expand_after: 
14587     @<Expand the token after the next token@>;
14588     break;
14589   case scan_tokens: 
14590     @<Put a string into the input buffer@>;
14591     break;
14592   case defined_macro:
14593    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14594    break;
14595   }; /* there are no other cases */
14596 };
14597
14598 @ @<Scold the user...@>=
14599
14600   print_err("Extra `endfor'");
14601 @.Extra `endfor'@>
14602   help2("I'm not currently working on a for loop,")
14603     ("so I had better not try to end anything.");
14604   mp_error(mp);
14605 }
14606
14607 @ The processing of \&{input} involves the |start_input| subroutine,
14608 which will be declared later; the processing of \&{endinput} is trivial.
14609
14610 @<Put each...@>=
14611 mp_primitive(mp, "input",input,0);
14612 @:input_}{\&{input} primitive@>
14613 mp_primitive(mp, "endinput",input,1);
14614 @:end_input_}{\&{endinput} primitive@>
14615
14616 @ @<Cases of |print_cmd_mod|...@>=
14617 case input: 
14618   if ( m==0 ) mp_print(mp, "input");
14619   else mp_print(mp, "endinput");
14620   break;
14621
14622 @ @<Initiate or terminate input...@>=
14623 if ( mp->cur_mod>0 ) mp->force_eof=true;
14624 else mp_start_input(mp)
14625
14626 @ We'll discuss the complicated parts of loop operations later. For now
14627 it suffices to know that there's a global variable called |loop_ptr|
14628 that will be |null| if no loop is in progress.
14629
14630 @<Repeat a loop@>=
14631 { while ( token_state &&(loc==null) ) 
14632     mp_end_token_list(mp); /* conserve stack space */
14633   if ( mp->loop_ptr==null ) {
14634     print_err("Lost loop");
14635 @.Lost loop@>
14636     help2("I'm confused; after exiting from a loop, I still seem")
14637       ("to want to repeat it. I'll try to forget the problem.");
14638     mp_error(mp);
14639   } else {
14640     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14641   }
14642 }
14643
14644 @ @<Exit a loop if the proper time has come@>=
14645 { mp_get_boolean(mp);
14646   if ( mp->internal[mp_tracing_commands]>unity ) 
14647     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14648   if ( mp->cur_exp==true_code ) {
14649     if ( mp->loop_ptr==null ) {
14650       print_err("No loop is in progress");
14651 @.No loop is in progress@>
14652       help1("Why say `exitif' when there's nothing to exit from?");
14653       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14654     } else {
14655      @<Exit prematurely from an iteration@>;
14656     }
14657   } else if ( mp->cur_cmd!=semicolon ) {
14658     mp_missing_err(mp, ";");
14659 @.Missing `;'@>
14660     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14661     ("I shall pretend that one was there."); mp_back_error(mp);
14662   }
14663 }
14664
14665 @ Here we use the fact that |forever_text| is the only |token_type| that
14666 is less than |loop_text|.
14667
14668 @<Exit prematurely...@>=
14669 { p=null;
14670   do {  
14671     if ( file_state ) {
14672       mp_end_file_reading(mp);
14673     } else { 
14674       if ( token_type<=loop_text ) p=start;
14675       mp_end_token_list(mp);
14676     }
14677   } while (p==null);
14678   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14679 @.loop confusion@>
14680   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14681 }
14682
14683 @ @<Expand the token after the next token@>=
14684 { get_t_next;
14685   p=mp_cur_tok(mp); get_t_next;
14686   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14687   else mp_back_input(mp);
14688   back_list(p);
14689 }
14690
14691 @ @<Put a string into the input buffer@>=
14692 { mp_get_x_next(mp); mp_scan_primary(mp);
14693   if ( mp->cur_type!=mp_string_type ) {
14694     mp_disp_err(mp, null,"Not a string");
14695 @.Not a string@>
14696     help2("I'm going to flush this expression, since")
14697        ("scantokens should be followed by a known string.");
14698     mp_put_get_flush_error(mp, 0);
14699   } else { 
14700     mp_back_input(mp);
14701     if ( length(mp->cur_exp)>0 )
14702        @<Pretend we're reading a new one-line file@>;
14703   }
14704 }
14705
14706 @ @<Pretend we're reading a new one-line file@>=
14707 { mp_begin_file_reading(mp); name=is_scantok;
14708   k=mp->first+length(mp->cur_exp);
14709   if ( k>=mp->max_buf_stack ) {
14710     while ( k>=mp->buf_size ) {
14711       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14712     }
14713     mp->max_buf_stack=k+1;
14714   }
14715   j=mp->str_start[mp->cur_exp]; limit=k;
14716   while ( mp->first<(size_t)limit ) {
14717     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14718   }
14719   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14720   mp_flush_cur_exp(mp, 0);
14721 }
14722
14723 @ Here finally is |get_x_next|.
14724
14725 The expression scanning routines to be considered later
14726 communicate via the global quantities |cur_type| and |cur_exp|;
14727 we must be very careful to save and restore these quantities while
14728 macros are being expanded.
14729 @^inner loop@>
14730
14731 @<Declarations@>=
14732 void mp_get_x_next (MP mp);
14733
14734 @ @c void mp_get_x_next (MP mp) {
14735   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14736   get_t_next;
14737   if ( mp->cur_cmd<min_command ) {
14738     save_exp=mp_stash_cur_exp(mp);
14739     do {  
14740       if ( mp->cur_cmd==defined_macro ) 
14741         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14742       else 
14743         mp_expand(mp);
14744       get_t_next;
14745      } while (mp->cur_cmd<min_command);
14746      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14747   }
14748 }
14749
14750 @ Now let's consider the |macro_call| procedure, which is used to start up
14751 all user-defined macros. Since the arguments to a macro might be expressions,
14752 |macro_call| is recursive.
14753 @^recursion@>
14754
14755 The first parameter to |macro_call| points to the reference count of the
14756 token list that defines the macro. The second parameter contains any
14757 arguments that have already been parsed (see below).  The third parameter
14758 points to the symbolic token that names the macro. If the third parameter
14759 is |null|, the macro was defined by \&{vardef}, so its name can be
14760 reconstructed from the prefix and ``at'' arguments found within the
14761 second parameter.
14762
14763 What is this second parameter? It's simply a linked list of one-word items,
14764 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14765 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14766 the first scanned argument, and |link(arg_list)| points to the list of
14767 further arguments (if any).
14768
14769 Arguments of type \&{expr} are so-called capsules, which we will
14770 discuss later when we concentrate on expressions; they can be
14771 recognized easily because their |link| field is |void|. Arguments of type
14772 \&{suffix} and \&{text} are token lists without reference counts.
14773
14774 @ After argument scanning is complete, the arguments are moved to the
14775 |param_stack|. (They can't be put on that stack any sooner, because
14776 the stack is growing and shrinking in unpredictable ways as more arguments
14777 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14778 the replacement text of the macro is placed at the top of the \MP's
14779 input stack, so that |get_t_next| will proceed to read it next.
14780
14781 @<Declare the procedure called |macro_call|@>=
14782 @<Declare the procedure called |print_macro_name|@>;
14783 @<Declare the procedure called |print_arg|@>;
14784 @<Declare the procedure called |scan_text_arg|@>;
14785 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14786                     pointer macro_name) ;
14787
14788 @ @c
14789 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14790                     pointer macro_name) {
14791   /* invokes a user-defined control sequence */
14792   pointer r; /* current node in the macro's token list */
14793   pointer p,q; /* for list manipulation */
14794   integer n; /* the number of arguments */
14795   pointer tail = 0; /* tail of the argument list */
14796   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14797   r=link(def_ref); add_mac_ref(def_ref);
14798   if ( arg_list==null ) {
14799     n=0;
14800   } else {
14801    @<Determine the number |n| of arguments already supplied,
14802     and set |tail| to the tail of |arg_list|@>;
14803   }
14804   if ( mp->internal[mp_tracing_macros]>0 ) {
14805     @<Show the text of the macro being expanded, and the existing arguments@>;
14806   }
14807   @<Scan the remaining arguments, if any; set |r| to the first token
14808     of the replacement text@>;
14809   @<Feed the arguments and replacement text to the scanner@>;
14810 }
14811
14812 @ @<Show the text of the macro...@>=
14813 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14814 mp_print_macro_name(mp, arg_list,macro_name);
14815 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14816 mp_show_macro(mp, def_ref,null,100000);
14817 if ( arg_list!=null ) {
14818   n=0; p=arg_list;
14819   do {  
14820     q=info(p);
14821     mp_print_arg(mp, q,n,0);
14822     incr(n); p=link(p);
14823   } while (p!=null);
14824 }
14825 mp_end_diagnostic(mp, false)
14826
14827
14828 @ @<Declare the procedure called |print_macro_name|@>=
14829 void mp_print_macro_name (MP mp,pointer a, pointer n);
14830
14831 @ @c
14832 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14833   pointer p,q; /* they traverse the first part of |a| */
14834   if ( n!=null ) {
14835     mp_print_text(n);
14836   } else  { 
14837     p=info(a);
14838     if ( p==null ) {
14839       mp_print_text(info(info(link(a))));
14840     } else { 
14841       q=p;
14842       while ( link(q)!=null ) q=link(q);
14843       link(q)=info(link(a));
14844       mp_show_token_list(mp, p,null,1000,0);
14845       link(q)=null;
14846     }
14847   }
14848 }
14849
14850 @ @<Declare the procedure called |print_arg|@>=
14851 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14852
14853 @ @c
14854 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14855   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14856   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14857   else mp_print_nl(mp, "(TEXT");
14858   mp_print_int(mp, n); mp_print(mp, ")<-");
14859   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14860   else mp_show_token_list(mp, q,null,1000,0);
14861 }
14862
14863 @ @<Determine the number |n| of arguments already supplied...@>=
14864 {  
14865   n=1; tail=arg_list;
14866   while ( link(tail)!=null ) { 
14867     incr(n); tail=link(tail);
14868   }
14869 }
14870
14871 @ @<Scan the remaining arguments, if any; set |r|...@>=
14872 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14873 while ( info(r)>=expr_base ) { 
14874   @<Scan the delimited argument represented by |info(r)|@>;
14875   r=link(r);
14876 };
14877 if ( mp->cur_cmd==comma ) {
14878   print_err("Too many arguments to ");
14879 @.Too many arguments...@>
14880   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14881   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14882 @.Missing `)'...@>
14883   mp_print(mp, "' has been inserted");
14884   help3("I'm going to assume that the comma I just read was a")
14885    ("right delimiter, and then I'll begin expanding the macro.")
14886    ("You might want to delete some tokens before continuing.");
14887   mp_error(mp);
14888 }
14889 if ( info(r)!=general_macro ) {
14890   @<Scan undelimited argument(s)@>;
14891 }
14892 r=link(r)
14893
14894 @ At this point, the reader will find it advisable to review the explanation
14895 of token list format that was presented earlier, paying special attention to
14896 the conventions that apply only at the beginning of a macro's token list.
14897
14898 On the other hand, the reader will have to take the expression-parsing
14899 aspects of the following program on faith; we will explain |cur_type|
14900 and |cur_exp| later. (Several things in this program depend on each other,
14901 and it's necessary to jump into the circle somewhere.)
14902
14903 @<Scan the delimited argument represented by |info(r)|@>=
14904 if ( mp->cur_cmd!=comma ) {
14905   mp_get_x_next(mp);
14906   if ( mp->cur_cmd!=left_delimiter ) {
14907     print_err("Missing argument to ");
14908 @.Missing argument...@>
14909     mp_print_macro_name(mp, arg_list,macro_name);
14910     help3("That macro has more parameters than you thought.")
14911      ("I'll continue by pretending that each missing argument")
14912      ("is either zero or null.");
14913     if ( info(r)>=suffix_base ) {
14914       mp->cur_exp=null; mp->cur_type=mp_token_list;
14915     } else { 
14916       mp->cur_exp=0; mp->cur_type=mp_known;
14917     }
14918     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14919     goto FOUND;
14920   }
14921   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14922 }
14923 @<Scan the argument represented by |info(r)|@>;
14924 if ( mp->cur_cmd!=comma ) 
14925   @<Check that the proper right delimiter was present@>;
14926 FOUND:  
14927 @<Append the current expression to |arg_list|@>
14928
14929 @ @<Check that the proper right delim...@>=
14930 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14931   if ( info(link(r))>=expr_base ) {
14932     mp_missing_err(mp, ",");
14933 @.Missing `,'@>
14934     help3("I've finished reading a macro argument and am about to")
14935       ("read another; the arguments weren't delimited correctly.")
14936        ("You might want to delete some tokens before continuing.");
14937     mp_back_error(mp); mp->cur_cmd=comma;
14938   } else { 
14939     mp_missing_err(mp, str(text(r_delim)));
14940 @.Missing `)'@>
14941     help2("I've gotten to the end of the macro parameter list.")
14942        ("You might want to delete some tokens before continuing.");
14943     mp_back_error(mp);
14944   }
14945 }
14946
14947 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14948 a token list pointed to by |cur_exp|, in which case we will have
14949 |cur_type=token_list|.
14950
14951 @<Append the current expression to |arg_list|@>=
14952
14953   p=mp_get_avail(mp);
14954   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14955   else info(p)=mp_stash_cur_exp(mp);
14956   if ( mp->internal[mp_tracing_macros]>0 ) {
14957     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14958     mp_end_diagnostic(mp, false);
14959   }
14960   if ( arg_list==null ) arg_list=p;
14961   else link(tail)=p;
14962   tail=p; incr(n);
14963 }
14964
14965 @ @<Scan the argument represented by |info(r)|@>=
14966 if ( info(r)>=text_base ) {
14967   mp_scan_text_arg(mp, l_delim,r_delim);
14968 } else { 
14969   mp_get_x_next(mp);
14970   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14971   else mp_scan_expression(mp);
14972 }
14973
14974 @ The parameters to |scan_text_arg| are either a pair of delimiters
14975 or zero; the latter case is for undelimited text arguments, which
14976 end with the first semicolon or \&{endgroup} or \&{end} that is not
14977 contained in a group.
14978
14979 @<Declare the procedure called |scan_text_arg|@>=
14980 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14981
14982 @ @c
14983 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14984   integer balance; /* excess of |l_delim| over |r_delim| */
14985   pointer p; /* list tail */
14986   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14987   p=hold_head; balance=1; link(hold_head)=null;
14988   while (1)  { 
14989     get_t_next;
14990     if ( l_delim==0 ) {
14991       @<Adjust the balance for an undelimited argument; |break| if done@>;
14992     } else {
14993           @<Adjust the balance for a delimited argument; |break| if done@>;
14994     }
14995     link(p)=mp_cur_tok(mp); p=link(p);
14996   }
14997   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14998   mp->scanner_status=normal;
14999 };
15000
15001 @ @<Adjust the balance for a delimited argument...@>=
15002 if ( mp->cur_cmd==right_delimiter ) { 
15003   if ( mp->cur_mod==l_delim ) { 
15004     decr(balance);
15005     if ( balance==0 ) break;
15006   }
15007 } else if ( mp->cur_cmd==left_delimiter ) {
15008   if ( mp->cur_mod==r_delim ) incr(balance);
15009 }
15010
15011 @ @<Adjust the balance for an undelimited...@>=
15012 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15013   if ( balance==1 ) { break; }
15014   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15015 } else if ( mp->cur_cmd==begin_group ) { 
15016   incr(balance); 
15017 }
15018
15019 @ @<Scan undelimited argument(s)@>=
15020
15021   if ( info(r)<text_macro ) {
15022     mp_get_x_next(mp);
15023     if ( info(r)!=suffix_macro ) {
15024       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15025     }
15026   }
15027   switch (info(r)) {
15028   case primary_macro:mp_scan_primary(mp); break;
15029   case secondary_macro:mp_scan_secondary(mp); break;
15030   case tertiary_macro:mp_scan_tertiary(mp); break;
15031   case expr_macro:mp_scan_expression(mp); break;
15032   case of_macro:
15033     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15034     break;
15035   case suffix_macro:
15036     @<Scan a suffix with optional delimiters@>;
15037     break;
15038   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15039   } /* there are no other cases */
15040   mp_back_input(mp); 
15041   @<Append the current expression to |arg_list|@>;
15042 }
15043
15044 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15045
15046   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15047   if ( mp->internal[mp_tracing_macros]>0 ) { 
15048     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15049     mp_end_diagnostic(mp, false);
15050   }
15051   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15052   tail=p;incr(n);
15053   if ( mp->cur_cmd!=of_token ) {
15054     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15055 @.Missing `of'@>
15056     mp_print_macro_name(mp, arg_list,macro_name);
15057     help1("I've got the first argument; will look now for the other.");
15058     mp_back_error(mp);
15059   }
15060   mp_get_x_next(mp); mp_scan_primary(mp);
15061 }
15062
15063 @ @<Scan a suffix with optional delimiters@>=
15064
15065   if ( mp->cur_cmd!=left_delimiter ) {
15066     l_delim=null;
15067   } else { 
15068     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15069   };
15070   mp_scan_suffix(mp);
15071   if ( l_delim!=null ) {
15072     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15073       mp_missing_err(mp, str(text(r_delim)));
15074 @.Missing `)'@>
15075       help2("I've gotten to the end of the macro parameter list.")
15076          ("You might want to delete some tokens before continuing.");
15077       mp_back_error(mp);
15078     }
15079     mp_get_x_next(mp);
15080   }
15081 }
15082
15083 @ Before we put a new token list on the input stack, it is wise to clean off
15084 all token lists that have recently been depleted. Then a user macro that ends
15085 with a call to itself will not require unbounded stack space.
15086
15087 @<Feed the arguments and replacement text to the scanner@>=
15088 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15089 if ( mp->param_ptr+n>mp->max_param_stack ) {
15090   mp->max_param_stack=mp->param_ptr+n;
15091   if ( mp->max_param_stack>mp->param_size )
15092     mp_overflow(mp, "parameter stack size",mp->param_size);
15093 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15094 }
15095 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15096 if ( n>0 ) {
15097   p=arg_list;
15098   do {  
15099    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15100   } while (p!=null);
15101   mp_flush_list(mp, arg_list);
15102 }
15103
15104 @ It's sometimes necessary to put a single argument onto |param_stack|.
15105 The |stack_argument| subroutine does this.
15106
15107 @c void mp_stack_argument (MP mp,pointer p) { 
15108   if ( mp->param_ptr==mp->max_param_stack ) {
15109     incr(mp->max_param_stack);
15110     if ( mp->max_param_stack>mp->param_size )
15111       mp_overflow(mp, "parameter stack size",mp->param_size);
15112 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15113   }
15114   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15115 }
15116
15117 @* \[33] Conditional processing.
15118 Let's consider now the way \&{if} commands are handled.
15119
15120 Conditions can be inside conditions, and this nesting has a stack
15121 that is independent of other stacks.
15122 Four global variables represent the top of the condition stack:
15123 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15124 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15125 the largest code of a |fi_or_else| command that is syntactically legal;
15126 and |if_line| is the line number at which the current conditional began.
15127
15128 If no conditions are currently in progress, the condition stack has the
15129 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15130 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15131 |link| fields of the first word contain |if_limit|, |cur_if|, and
15132 |cond_ptr| at the next level, and the second word contains the
15133 corresponding |if_line|.
15134
15135 @d if_node_size 2 /* number of words in stack entry for conditionals */
15136 @d if_line_field(A) mp->mem[(A)+1].cint
15137 @d if_code 1 /* code for \&{if} being evaluated */
15138 @d fi_code 2 /* code for \&{fi} */
15139 @d else_code 3 /* code for \&{else} */
15140 @d else_if_code 4 /* code for \&{elseif} */
15141
15142 @<Glob...@>=
15143 pointer cond_ptr; /* top of the condition stack */
15144 integer if_limit; /* upper bound on |fi_or_else| codes */
15145 small_number cur_if; /* type of conditional being worked on */
15146 integer if_line; /* line where that conditional began */
15147
15148 @ @<Set init...@>=
15149 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15150
15151 @ @<Put each...@>=
15152 mp_primitive(mp, "if",if_test,if_code);
15153 @:if_}{\&{if} primitive@>
15154 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15155 @:fi_}{\&{fi} primitive@>
15156 mp_primitive(mp, "else",fi_or_else,else_code);
15157 @:else_}{\&{else} primitive@>
15158 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15159 @:else_if_}{\&{elseif} primitive@>
15160
15161 @ @<Cases of |print_cmd_mod|...@>=
15162 case if_test:
15163 case fi_or_else: 
15164   switch (m) {
15165   case if_code:mp_print(mp, "if"); break;
15166   case fi_code:mp_print(mp, "fi");  break;
15167   case else_code:mp_print(mp, "else"); break;
15168   default: mp_print(mp, "elseif"); break;
15169   }
15170   break;
15171
15172 @ Here is a procedure that ignores text until coming to an \&{elseif},
15173 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15174 nesting. After it has acted, |cur_mod| will indicate the token that
15175 was found.
15176
15177 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15178 makes the skipping process a bit simpler.
15179
15180 @c 
15181 void mp_pass_text (MP mp) {
15182   integer l = 0;
15183   mp->scanner_status=skipping;
15184   mp->warning_info=mp_true_line(mp);
15185   while (1)  { 
15186     get_t_next;
15187     if ( mp->cur_cmd<=fi_or_else ) {
15188       if ( mp->cur_cmd<fi_or_else ) {
15189         incr(l);
15190       } else { 
15191         if ( l==0 ) break;
15192         if ( mp->cur_mod==fi_code ) decr(l);
15193       }
15194     } else {
15195       @<Decrease the string reference count,
15196        if the current token is a string@>;
15197     }
15198   }
15199   mp->scanner_status=normal;
15200 }
15201
15202 @ @<Decrease the string reference count...@>=
15203 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15204
15205 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15206 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15207 condition has been evaluated, a colon will be inserted.
15208 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15209
15210 @<Push the condition stack@>=
15211 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15212   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15213   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15214   mp->cur_if=if_code;
15215 }
15216
15217 @ @<Pop the condition stack@>=
15218 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15219   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15220   mp_free_node(mp, p,if_node_size);
15221 }
15222
15223 @ Here's a procedure that changes the |if_limit| code corresponding to
15224 a given value of |cond_ptr|.
15225
15226 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15227   pointer q;
15228   if ( p==mp->cond_ptr ) {
15229     mp->if_limit=l; /* that's the easy case */
15230   } else  { 
15231     q=mp->cond_ptr;
15232     while (1) { 
15233       if ( q==null ) mp_confusion(mp, "if");
15234 @:this can't happen if}{\quad if@>
15235       if ( link(q)==p ) { 
15236         type(q)=l; return;
15237       }
15238       q=link(q);
15239     }
15240   }
15241 }
15242
15243 @ The user is supposed to put colons into the proper parts of conditional
15244 statements. Therefore, \MP\ has to check for their presence.
15245
15246 @c 
15247 void mp_check_colon (MP mp) { 
15248   if ( mp->cur_cmd!=colon ) { 
15249     mp_missing_err(mp, ":");
15250 @.Missing `:'@>
15251     help2("There should've been a colon after the condition.")
15252          ("I shall pretend that one was there.");;
15253     mp_back_error(mp);
15254   }
15255 }
15256
15257 @ A condition is started when the |get_x_next| procedure encounters
15258 an |if_test| command; in that case |get_x_next| calls |conditional|,
15259 which is a recursive procedure.
15260 @^recursion@>
15261
15262 @c void mp_conditional (MP mp) {
15263   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15264   int new_if_limit; /* future value of |if_limit| */
15265   pointer p; /* temporary register */
15266   @<Push the condition stack@>; 
15267   save_cond_ptr=mp->cond_ptr;
15268 RESWITCH: 
15269   mp_get_boolean(mp); new_if_limit=else_if_code;
15270   if ( mp->internal[mp_tracing_commands]>unity ) {
15271     @<Display the boolean value of |cur_exp|@>;
15272   }
15273 FOUND: 
15274   mp_check_colon(mp);
15275   if ( mp->cur_exp==true_code ) {
15276     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15277     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15278   };
15279   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15280 DONE: 
15281   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15282   if ( mp->cur_mod==fi_code ) {
15283     @<Pop the condition stack@>
15284   } else if ( mp->cur_mod==else_if_code ) {
15285     goto RESWITCH;
15286   } else  { 
15287     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15288     goto FOUND;
15289   }
15290 }
15291
15292 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15293 \&{else}: \\{bar} \&{fi}', the first \&{else}
15294 that we come to after learning that the \&{if} is false is not the
15295 \&{else} we're looking for. Hence the following curious logic is needed.
15296
15297 @<Skip to \&{elseif}...@>=
15298 while (1) { 
15299   mp_pass_text(mp);
15300   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15301   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15302 }
15303
15304
15305 @ @<Display the boolean value...@>=
15306 { mp_begin_diagnostic(mp);
15307   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15308   else mp_print(mp, "{false}");
15309   mp_end_diagnostic(mp, false);
15310 }
15311
15312 @ The processing of conditionals is complete except for the following
15313 code, which is actually part of |get_x_next|. It comes into play when
15314 \&{elseif}, \&{else}, or \&{fi} is scanned.
15315
15316 @<Terminate the current conditional and skip to \&{fi}@>=
15317 if ( mp->cur_mod>mp->if_limit ) {
15318   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15319     mp_missing_err(mp, ":");
15320 @.Missing `:'@>
15321     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15322   } else  { 
15323     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15324 @.Extra else@>
15325 @.Extra elseif@>
15326 @.Extra fi@>
15327     help1("I'm ignoring this; it doesn't match any if.");
15328     mp_error(mp);
15329   }
15330 } else  { 
15331   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15332   @<Pop the condition stack@>;
15333 }
15334
15335 @* \[34] Iterations.
15336 To bring our treatment of |get_x_next| to a close, we need to consider what
15337 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15338
15339 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15340 that are currently active. If |loop_ptr=null|, no loops are in progress;
15341 otherwise |info(loop_ptr)| points to the iterative text of the current
15342 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15343 loops that enclose the current one.
15344
15345 A loop-control node also has two other fields, called |loop_type| and
15346 |loop_list|, whose contents depend on the type of loop:
15347
15348 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15349 points to a list of one-word nodes whose |info| fields point to the
15350 remaining argument values of a suffix list and expression list.
15351
15352 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15353 `\&{forever}'.
15354
15355 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15356 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15357 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15358 progression.
15359
15360 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15361 header and |loop_list(loop_ptr)| points into the graphical object list for
15362 that edge header.
15363
15364 \yskip\noindent In the case of a progression node, the first word is not used
15365 because the link field of words in the dynamic memory area cannot be arbitrary.
15366
15367 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15368 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15369 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15370 @d loop_node_size 2 /* the number of words in a loop control node */
15371 @d progression_node_size 4 /* the number of words in a progression node */
15372 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15373 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15374 @d progression_flag (null+2)
15375   /* |loop_type| value when |loop_list| points to a progression node */
15376
15377 @<Glob...@>=
15378 pointer loop_ptr; /* top of the loop-control-node stack */
15379
15380 @ @<Set init...@>=
15381 mp->loop_ptr=null;
15382
15383 @ If the expressions that define an arithmetic progression in
15384 a \&{for} loop don't have known numeric values, the |bad_for|
15385 subroutine screams at the user.
15386
15387 @c void mp_bad_for (MP mp, char * s) {
15388   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15389 @.Improper...replaced by 0@>
15390   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15391   help4("When you say `for x=a step b until c',")
15392     ("the initial value `a' and the step size `b'")
15393     ("and the final value `c' must have known numeric values.")
15394     ("I'm zeroing this one. Proceed, with fingers crossed.");
15395   mp_put_get_flush_error(mp, 0);
15396 };
15397
15398 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15399 has just been scanned. (This code requires slight familiarity with
15400 expression-parsing routines that we have not yet discussed; but it seems
15401 to belong in the present part of the program, even though the original author
15402 didn't write it until later. The reader may wish to come back to it.)
15403
15404 @c void mp_begin_iteration (MP mp) {
15405   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15406   halfword n; /* hash address of the current symbol */
15407   pointer s; /* the new loop-control node */
15408   pointer p; /* substitution list for |scan_toks| */
15409   pointer q;  /* link manipulation register */
15410   pointer pp; /* a new progression node */
15411   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15412   if ( m==start_forever ){ 
15413     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15414   } else { 
15415     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15416     info(p)=mp->cur_sym; value(p)=m;
15417     mp_get_x_next(mp);
15418     if ( mp->cur_cmd==within_token ) {
15419       @<Set up a picture iteration@>;
15420     } else { 
15421       @<Check for the |"="| or |":="| in a loop header@>;
15422       @<Scan the values to be used in the loop@>;
15423     }
15424   }
15425   @<Check for the presence of a colon@>;
15426   @<Scan the loop text and put it on the loop control stack@>;
15427   mp_resume_iteration(mp);
15428 }
15429
15430 @ @<Check for the |"="| or |":="| in a loop header@>=
15431 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15432   mp_missing_err(mp, "=");
15433 @.Missing `='@>
15434   help3("The next thing in this loop should have been `=' or `:='.")
15435     ("But don't worry; I'll pretend that an equals sign")
15436     ("was present, and I'll look for the values next.");
15437   mp_back_error(mp);
15438 }
15439
15440 @ @<Check for the presence of a colon@>=
15441 if ( mp->cur_cmd!=colon ) { 
15442   mp_missing_err(mp, ":");
15443 @.Missing `:'@>
15444   help3("The next thing in this loop should have been a `:'.")
15445     ("So I'll pretend that a colon was present;")
15446     ("everything from here to `endfor' will be iterated.");
15447   mp_back_error(mp);
15448 }
15449
15450 @ We append a special |frozen_repeat_loop| token in place of the
15451 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15452 at the proper time to cause the loop to be repeated.
15453
15454 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15455 he will be foiled by the |get_symbol| routine, which keeps frozen
15456 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15457 token, so it won't be lost accidentally.)
15458
15459 @ @<Scan the loop text...@>=
15460 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15461 mp->scanner_status=loop_defining; mp->warning_info=n;
15462 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15463 link(s)=mp->loop_ptr; mp->loop_ptr=s
15464
15465 @ @<Initialize table...@>=
15466 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15467 text(frozen_repeat_loop)=intern(" ENDFOR");
15468
15469 @ The loop text is inserted into \MP's scanning apparatus by the
15470 |resume_iteration| routine.
15471
15472 @c void mp_resume_iteration (MP mp) {
15473   pointer p,q; /* link registers */
15474   p=loop_type(mp->loop_ptr);
15475   if ( p==progression_flag ) { 
15476     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15477     mp->cur_exp=value(p);
15478     if ( @<The arithmetic progression has ended@> ) {
15479       mp_stop_iteration(mp);
15480       return;
15481     }
15482     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15483     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15484   } else if ( p==null ) { 
15485     p=loop_list(mp->loop_ptr);
15486     if ( p==null ) {
15487       mp_stop_iteration(mp);
15488       return;
15489     }
15490     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15491   } else if ( p==mp_void ) { 
15492     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15493   } else {
15494     @<Make |q| a capsule containing the next picture component from
15495       |loop_list(loop_ptr)| or |goto not_found|@>;
15496   }
15497   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15498   mp_stack_argument(mp, q);
15499   if ( mp->internal[mp_tracing_commands]>unity ) {
15500      @<Trace the start of a loop@>;
15501   }
15502   return;
15503 NOT_FOUND:
15504   mp_stop_iteration(mp);
15505 }
15506
15507 @ @<The arithmetic progression has ended@>=
15508 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15509  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15510
15511 @ @<Trace the start of a loop@>=
15512
15513   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15514 @.loop value=n@>
15515   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15516   else mp_show_token_list(mp, q,null,50,0);
15517   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15518 }
15519
15520 @ @<Make |q| a capsule containing the next picture component from...@>=
15521 { q=loop_list(mp->loop_ptr);
15522   if ( q==null ) goto NOT_FOUND;
15523   skip_component(q) goto NOT_FOUND;
15524   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15525   mp_init_bbox(mp, mp->cur_exp);
15526   mp->cur_type=mp_picture_type;
15527   loop_list(mp->loop_ptr)=q;
15528   q=mp_stash_cur_exp(mp);
15529 }
15530
15531 @ A level of loop control disappears when |resume_iteration| has decided
15532 not to resume, or when an \&{exitif} construction has removed the loop text
15533 from the input stack.
15534
15535 @c void mp_stop_iteration (MP mp) {
15536   pointer p,q; /* the usual */
15537   p=loop_type(mp->loop_ptr);
15538   if ( p==progression_flag )  {
15539     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15540   } else if ( p==null ){ 
15541     q=loop_list(mp->loop_ptr);
15542     while ( q!=null ) {
15543       p=info(q);
15544       if ( p!=null ) {
15545         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15546           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15547         } else {
15548           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15549         }
15550       }
15551       p=q; q=link(q); free_avail(p);
15552     }
15553   } else if ( p>progression_flag ) {
15554     delete_edge_ref(p);
15555   }
15556   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15557   mp_free_node(mp, p,loop_node_size);
15558 }
15559
15560 @ Now that we know all about loop control, we can finish up
15561 the missing portion of |begin_iteration| and we'll be done.
15562
15563 The following code is performed after the `\.=' has been scanned in
15564 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15565 (if |m=suffix_base|).
15566
15567 @<Scan the values to be used in the loop@>=
15568 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15569 do {  
15570   mp_get_x_next(mp);
15571   if ( m!=expr_base ) {
15572     mp_scan_suffix(mp);
15573   } else { 
15574     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15575           goto CONTINUE;
15576     mp_scan_expression(mp);
15577     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15578       @<Prepare for step-until construction and |break|@>;
15579     }
15580     mp->cur_exp=mp_stash_cur_exp(mp);
15581   }
15582   link(q)=mp_get_avail(mp); q=link(q); 
15583   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15584 CONTINUE:
15585   ;
15586 } while (mp->cur_cmd==comma)
15587
15588 @ @<Prepare for step-until construction and |break|@>=
15589
15590   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15591   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15592   mp_get_x_next(mp); mp_scan_expression(mp);
15593   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15594   step_size(pp)=mp->cur_exp;
15595   if ( mp->cur_cmd!=until_token ) { 
15596     mp_missing_err(mp, "until");
15597 @.Missing `until'@>
15598     help2("I assume you meant to say `until' after `step'.")
15599       ("So I'll look for the final value and colon next.");
15600     mp_back_error(mp);
15601   }
15602   mp_get_x_next(mp); mp_scan_expression(mp);
15603   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15604   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15605   loop_type(s)=progression_flag; 
15606   break;
15607 }
15608
15609 @ The last case is when we have just seen ``\&{within}'', and we need to
15610 parse a picture expression and prepare to iterate over it.
15611
15612 @<Set up a picture iteration@>=
15613 { mp_get_x_next(mp);
15614   mp_scan_expression(mp);
15615   @<Make sure the current expression is a known picture@>;
15616   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15617   q=link(dummy_loc(mp->cur_exp));
15618   if ( q!= null ) 
15619     if ( is_start_or_stop(q) )
15620       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15621   loop_list(s)=q;
15622 }
15623
15624 @ @<Make sure the current expression is a known picture@>=
15625 if ( mp->cur_type!=mp_picture_type ) {
15626   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15627   help1("When you say `for x in p', p must be a known picture.");
15628   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15629   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15630 }
15631
15632 @* \[35] File names.
15633 It's time now to fret about file names.  Besides the fact that different
15634 operating systems treat files in different ways, we must cope with the
15635 fact that completely different naming conventions are used by different
15636 groups of people. The following programs show what is required for one
15637 particular operating system; similar routines for other systems are not
15638 difficult to devise.
15639 @^system dependencies@>
15640
15641 \MP\ assumes that a file name has three parts: the name proper; its
15642 ``extension''; and a ``file area'' where it is found in an external file
15643 system.  The extension of an input file is assumed to be
15644 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15645 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15646 metric files that describe characters in any fonts created by \MP; it is
15647 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15648 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15649 The file area can be arbitrary on input files, but files are usually
15650 output to the user's current area.  If an input file cannot be
15651 found on the specified area, \MP\ will look for it on a special system
15652 area; this special area is intended for commonly used input files.
15653
15654 Simple uses of \MP\ refer only to file names that have no explicit
15655 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15656 instead of `\.{input} \.{cmr10.new}'. Simple file
15657 names are best, because they make the \MP\ source files portable;
15658 whenever a file name consists entirely of letters and digits, it should be
15659 treated in the same way by all implementations of \MP. However, users
15660 need the ability to refer to other files in their environment, especially
15661 when responding to error messages concerning unopenable files; therefore
15662 we want to let them use the syntax that appears in their favorite
15663 operating system.
15664
15665 @ \MP\ uses the same conventions that have proved to be satisfactory for
15666 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15667 @^system dependencies@>
15668 the system-independent parts of \MP\ are expressed in terms
15669 of three system-dependent
15670 procedures called |begin_name|, |more_name|, and |end_name|. In
15671 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15672 the system-independent driver program does the operations
15673 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15674 \,|end_name|.$$
15675 These three procedures communicate with each other via global variables.
15676 Afterwards the file name will appear in the string pool as three strings
15677 called |cur_name|\penalty10000\hskip-.05em,
15678 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15679 |""|), unless they were explicitly specified by the user.
15680
15681 Actually the situation is slightly more complicated, because \MP\ needs
15682 to know when the file name ends. The |more_name| routine is a function
15683 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15684 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15685 returns |false|; or, it returns |true| and $c_n$ is the last character
15686 on the current input line. In other words,
15687 |more_name| is supposed to return |true| unless it is sure that the
15688 file name has been completely scanned; and |end_name| is supposed to be able
15689 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15690 whether $|more_name|(c_n)$ returned |true| or |false|.
15691
15692 @<Glob...@>=
15693 char * cur_name; /* name of file just scanned */
15694 char * cur_area; /* file area just scanned, or \.{""} */
15695 char * cur_ext; /* file extension just scanned, or \.{""} */
15696
15697 @ It is easier to maintain reference counts if we assign initial values.
15698
15699 @<Set init...@>=
15700 mp->cur_name=xstrdup(""); 
15701 mp->cur_area=xstrdup(""); 
15702 mp->cur_ext=xstrdup("");
15703
15704 @ @<Dealloc variables@>=
15705 xfree(mp->cur_area);
15706 xfree(mp->cur_name);
15707 xfree(mp->cur_ext);
15708
15709 @ The file names we shall deal with for illustrative purposes have the
15710 following structure:  If the name contains `\.>' or `\.:', the file area
15711 consists of all characters up to and including the final such character;
15712 otherwise the file area is null.  If the remaining file name contains
15713 `\..', the file extension consists of all such characters from the first
15714 remaining `\..' to the end, otherwise the file extension is null.
15715 @^system dependencies@>
15716
15717 We can scan such file names easily by using two global variables that keep track
15718 of the occurrences of area and extension delimiters.  Note that these variables
15719 cannot be of type |pool_pointer| because a string pool compaction could occur
15720 while scanning a file name.
15721
15722 @<Glob...@>=
15723 integer area_delimiter;
15724   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15725 integer ext_delimiter; /* the relevant `\..', if any */
15726
15727 @ Input files that can't be found in the user's area may appear in standard
15728 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15729 extension is |".mf"|.)  The standard system area for font metric files
15730 to be read is |MP_font_area|.
15731 This system area name will, of course, vary from place to place.
15732 @^system dependencies@>
15733
15734 @d MP_area "MPinputs:"
15735 @.MPinputs@>
15736 @d MF_area "MFinputs:"
15737 @.MFinputs@>
15738 @d MP_font_area ""
15739 @.TeXfonts@>
15740
15741 @ Here now is the first of the system-dependent routines for file name scanning.
15742 @^system dependencies@>
15743
15744 @<Declare subroutines for parsing file names@>=
15745 void mp_begin_name (MP mp) { 
15746   xfree(mp->cur_name); 
15747   xfree(mp->cur_area); 
15748   xfree(mp->cur_ext);
15749   mp->area_delimiter=-1; 
15750   mp->ext_delimiter=-1;
15751 }
15752
15753 @ And here's the second.
15754 @^system dependencies@>
15755
15756 @<Declare subroutines for parsing file names@>=
15757 boolean mp_more_name (MP mp, ASCII_code c) { 
15758   if (c==' ') {
15759     return false;
15760   } else { 
15761     if ( (c=='>')||(c==':') ) { 
15762       mp->area_delimiter=mp->pool_ptr; 
15763       mp->ext_delimiter=-1;
15764     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15765       mp->ext_delimiter=mp->pool_ptr;
15766     }
15767     str_room(1); append_char(c); /* contribute |c| to the current string */
15768     return true;
15769   }
15770 }
15771
15772 @ The third.
15773 @^system dependencies@>
15774
15775 @d copy_pool_segment(A,B,C) { 
15776       A = xmalloc(C+1,sizeof(char)); 
15777       strncpy(A,(char *)(mp->str_pool+B),C);  
15778       A[C] = 0;}
15779
15780 @<Declare subroutines for parsing file names@>=
15781 void mp_end_name (MP mp) {
15782   pool_pointer s; /* length of area, name, and extension */
15783   unsigned int len;
15784   /* "my/w.mp" */
15785   s = mp->str_start[mp->str_ptr];
15786   if ( mp->area_delimiter<0 ) {    
15787     mp->cur_area=xstrdup("");
15788   } else {
15789     len = mp->area_delimiter-s; 
15790     copy_pool_segment(mp->cur_area,s,len);
15791     s += len+1;
15792   }
15793   if ( mp->ext_delimiter<0 ) {
15794     mp->cur_ext=xstrdup("");
15795     len = mp->pool_ptr-s; 
15796   } else {
15797     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15798     len = mp->ext_delimiter-s;
15799   }
15800   copy_pool_segment(mp->cur_name,s,len);
15801   mp->pool_ptr=s; /* don't need this partial string */
15802 }
15803
15804 @ Conversely, here is a routine that takes three strings and prints a file
15805 name that might have produced them. (The routine is system dependent, because
15806 some operating systems put the file area last instead of first.)
15807 @^system dependencies@>
15808
15809 @<Basic printing...@>=
15810 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15811   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15812 };
15813
15814 @ Another system-dependent routine is needed to convert three internal
15815 \MP\ strings
15816 to the |name_of_file| value that is used to open files. The present code
15817 allows both lowercase and uppercase letters in the file name.
15818 @^system dependencies@>
15819
15820 @d append_to_name(A) { c=(A); 
15821   if ( k<file_name_size ) {
15822     mp->name_of_file[k]=xchr(c);
15823     incr(k);
15824   }
15825 }
15826
15827 @<Declare subroutines for parsing file names@>=
15828 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15829   integer k; /* number of positions filled in |name_of_file| */
15830   ASCII_code c; /* character being packed */
15831   char *j; /* a character  index */
15832   k=0;
15833   assert(n);
15834   if (a!=NULL) {
15835     for (j=a;*j;j++) { append_to_name(*j); }
15836   }
15837   for (j=n;*j;j++) { append_to_name(*j); }
15838   if (e!=NULL) {
15839     for (j=e;*j;j++) { append_to_name(*j); }
15840   }
15841   mp->name_of_file[k]=0;
15842   mp->name_length=k; 
15843 }
15844
15845 @ @<Internal library declarations@>=
15846 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15847
15848 @ A messier routine is also needed, since mem file names must be scanned
15849 before \MP's string mechanism has been initialized. We shall use the
15850 global variable |MP_mem_default| to supply the text for default system areas
15851 and extensions related to mem files.
15852 @^system dependencies@>
15853
15854 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15855 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15856 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15857
15858 @<Glob...@>=
15859 char *MP_mem_default;
15860
15861 @ @<Option variables@>=
15862 char *mem_name; /* for commandline */
15863
15864 @ @<Allocate or initialize ...@>=
15865 mp->MP_mem_default = xstrdup("plain.mem");
15866 mp->mem_name = xstrdup(opt->mem_name);
15867 @.plain@>
15868 @^system dependencies@>
15869
15870 @ @<Dealloc variables@>=
15871 xfree(mp->MP_mem_default);
15872 xfree(mp->mem_name);
15873
15874 @ @<Check the ``constant'' values for consistency@>=
15875 if ( mem_default_length>file_name_size ) mp->bad=20;
15876
15877 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15878 from the first |n| characters of |MP_mem_default|, followed by
15879 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15880 |MP_mem_default|.
15881
15882 We dare not give error messages here, since \MP\ calls this routine before
15883 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15884 since the error will be detected in another way when a strange file name
15885 isn't found.
15886 @^system dependencies@>
15887
15888 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15889                                integer b) {
15890   integer k; /* number of positions filled in |name_of_file| */
15891   ASCII_code c; /* character being packed */
15892   integer j; /* index into |buffer| or |MP_mem_default| */
15893   if ( n+b-a+1+mem_ext_length>file_name_size )
15894     b=a+file_name_size-n-1-mem_ext_length;
15895   k=0;
15896   for (j=0;j<n;j++) {
15897     append_to_name(xord((int)mp->MP_mem_default[j]));
15898   }
15899   for (j=a;j<b;j++) {
15900     append_to_name(mp->buffer[j]);
15901   }
15902   for (j=mem_default_length-mem_ext_length;
15903       j<mem_default_length;j++) {
15904     append_to_name(xord((int)mp->MP_mem_default[j]));
15905   } 
15906   mp->name_of_file[k]=0;
15907   mp->name_length=k; 
15908 }
15909
15910 @ Here is the only place we use |pack_buffered_name|. This part of the program
15911 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15912 the preliminary initialization, or when the user is substituting another
15913 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15914 contains the first line of input in |buffer[loc..(last-1)]|, where
15915 |loc<last| and |buffer[loc]<>" "|.
15916
15917 @<Declarations@>=
15918 boolean mp_open_mem_file (MP mp) ;
15919
15920 @ @c
15921 boolean mp_open_mem_file (MP mp) {
15922   int j; /* the first space after the file name */
15923   if (mp->mem_name!=NULL) {
15924     mp->mem_file = (mp->open_file)(mp->mem_name, "rb", mp_filetype_memfile);
15925     if ( mp->mem_file ) return true;
15926   }
15927   j=loc;
15928   if ( mp->buffer[loc]=='&' ) {
15929     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15930     while ( mp->buffer[j]!=' ' ) incr(j);
15931     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15932     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15933     wake_up_terminal;
15934     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15935 @.Sorry, I can't find...@>
15936     update_terminal;
15937   }
15938   /* now pull out all the stops: try for the system \.{plain} file */
15939   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15940   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15941     wake_up_terminal;
15942     wterm_ln("I can\'t find the PLAIN mem file!\n");
15943 @.I can't find PLAIN...@>
15944 @.plain@>
15945     return false;
15946   }
15947 FOUND:
15948   loc=j; return true;
15949 }
15950
15951 @ Operating systems often make it possible to determine the exact name (and
15952 possible version number) of a file that has been opened. The following routine,
15953 which simply makes a \MP\ string from the value of |name_of_file|, should
15954 ideally be changed to deduce the full name of file~|f|, which is the file
15955 most recently opened, if it is possible to do this.
15956 @^system dependencies@>
15957
15958 @<Declarations@>=
15959 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15960 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15961 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15962
15963 @ @c 
15964 str_number mp_make_name_string (MP mp) {
15965   int k; /* index into |name_of_file| */
15966   str_room(mp->name_length);
15967   for (k=0;k<mp->name_length;k++) {
15968     append_char(xord((int)mp->name_of_file[k]));
15969   }
15970   return mp_make_string(mp);
15971 }
15972
15973 @ Now let's consider the ``driver''
15974 routines by which \MP\ deals with file names
15975 in a system-independent manner.  First comes a procedure that looks for a
15976 file name in the input by taking the information from the input buffer.
15977 (We can't use |get_next|, because the conversion to tokens would
15978 destroy necessary information.)
15979
15980 This procedure doesn't allow semicolons or percent signs to be part of
15981 file names, because of other conventions of \MP.
15982 {\sl The {\logos METAFONT\/}book} doesn't
15983 use semicolons or percents immediately after file names, but some users
15984 no doubt will find it natural to do so; therefore system-dependent
15985 changes to allow such characters in file names should probably
15986 be made with reluctance, and only when an entire file name that
15987 includes special characters is ``quoted'' somehow.
15988 @^system dependencies@>
15989
15990 @c void mp_scan_file_name (MP mp) { 
15991   mp_begin_name(mp);
15992   while ( mp->buffer[loc]==' ' ) incr(loc);
15993   while (1) { 
15994     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15995     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15996     incr(loc);
15997   }
15998   mp_end_name(mp);
15999 }
16000
16001 @ Here is another version that takes its input from a string.
16002
16003 @<Declare subroutines for parsing file names@>=
16004 void mp_str_scan_file (MP mp,  str_number s) {
16005   pool_pointer p,q; /* current position and stopping point */
16006   mp_begin_name(mp);
16007   p=mp->str_start[s]; q=str_stop(s);
16008   while ( p<q ){ 
16009     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16010     incr(p);
16011   }
16012   mp_end_name(mp);
16013 }
16014
16015 @ And one that reads from a |char*|.
16016
16017 @<Declare subroutines for parsing file names@>=
16018 void mp_ptr_scan_file (MP mp,  char *s) {
16019   char *p, *q; /* current position and stopping point */
16020   mp_begin_name(mp);
16021   p=s; q=p+strlen(s);
16022   while ( p<q ){ 
16023     if ( ! mp_more_name(mp, *p)) break;
16024     p++;
16025   }
16026   mp_end_name(mp);
16027 }
16028
16029
16030 @ The global variable |job_name| contains the file name that was first
16031 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16032 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16033
16034 @<Glob...@>=
16035 boolean log_opened; /* has the transcript file been opened? */
16036 char *log_name; /* full name of the log file */
16037
16038 @ @<Option variables@>=
16039 char *job_name; /* principal file name */
16040
16041 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16042 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16043 except of course for a short time just after |job_name| has become nonzero.
16044
16045 @<Allocate or ...@>=
16046 mp->job_name=opt->job_name; 
16047 mp->log_opened=false;
16048
16049 @ @<Dealloc variables@>=
16050 xfree(mp->job_name);
16051
16052 @ Here is a routine that manufactures the output file names, assuming that
16053 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16054 and |cur_ext|.
16055
16056 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16057
16058 @<Declarations@>=
16059 void mp_pack_job_name (MP mp, char *s) ;
16060
16061 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16062   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16063   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16064   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16065   pack_cur_name;
16066 }
16067
16068 @ If some trouble arises when \MP\ tries to open a file, the following
16069 routine calls upon the user to supply another file name. Parameter~|s|
16070 is used in the error message to identify the type of file; parameter~|e|
16071 is the default extension if none is given. Upon exit from the routine,
16072 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16073 ready for another attempt at file opening.
16074
16075 @<Declarations@>=
16076 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16077
16078 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16079   size_t k; /* index into |buffer| */
16080   char * saved_cur_name;
16081   if ( mp->interaction==mp_scroll_mode ) 
16082         wake_up_terminal;
16083   if (strcmp(s,"input file name")==0) {
16084         print_err("I can\'t find file `");
16085 @.I can't find file x@>
16086   } else {
16087         print_err("I can\'t write on file `");
16088   }
16089 @.I can't write on file x@>
16090   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16091   mp_print(mp, "'.");
16092   if (strcmp(e,"")==0) 
16093         mp_show_context(mp);
16094   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16095 @.Please type...@>
16096   if ( mp->interaction<mp_scroll_mode )
16097     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16098 @.job aborted, file error...@>
16099   saved_cur_name = xstrdup(mp->cur_name);
16100   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16101   if (strcmp(mp->cur_ext,"")==0) 
16102         mp->cur_ext=e;
16103   if (strlen(mp->cur_name)==0) {
16104     mp->cur_name=saved_cur_name;
16105   } else {
16106     xfree(saved_cur_name);
16107   }
16108   pack_cur_name;
16109 }
16110
16111 @ @<Scan file name in the buffer@>=
16112
16113   mp_begin_name(mp); k=mp->first;
16114   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16115   while (1) { 
16116     if ( k==mp->last ) break;
16117     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16118     incr(k);
16119   }
16120   mp_end_name(mp);
16121 }
16122
16123 @ The |open_log_file| routine is used to open the transcript file and to help
16124 it catch up to what has previously been printed on the terminal.
16125
16126 @c void mp_open_log_file (MP mp) {
16127   int old_setting; /* previous |selector| setting */
16128   int k; /* index into |months| and |buffer| */
16129   int l; /* end of first input line */
16130   integer m; /* the current month */
16131   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16132     /* abbreviations of month names */
16133   old_setting=mp->selector;
16134   if ( mp->job_name==NULL ) {
16135      mp->job_name=xstrdup("mpout");
16136   }
16137   mp_pack_job_name(mp,".log");
16138   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16139     @<Try to get a different log file name@>;
16140   }
16141   mp->log_name=xstrdup(mp->name_of_file);
16142   mp->selector=log_only; mp->log_opened=true;
16143   @<Print the banner line, including the date and time@>;
16144   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16145     /* make sure bottom level is in memory */
16146 @.**@>
16147   if (!mp->noninteractive) {
16148     mp_print_nl(mp, "**");
16149     l=mp->input_stack[0].limit_field-1; /* last position of first line */
16150     for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16151     mp_print_ln(mp); /* now the transcript file contains the first line of input */
16152   }
16153   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16154 }
16155
16156 @ @<Dealloc variables@>=
16157 xfree(mp->log_name);
16158
16159 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16160 unable to print error messages or even to |show_context|.
16161 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16162 routine will not be invoked because |log_opened| will be false.
16163
16164 The normal idea of |mp_batch_mode| is that nothing at all should be written
16165 on the terminal. However, in the unusual case that
16166 no log file could be opened, we make an exception and allow
16167 an explanatory message to be seen.
16168
16169 Incidentally, the program always refers to the log file as a `\.{transcript
16170 file}', because some systems cannot use the extension `\.{.log}' for
16171 this file.
16172
16173 @<Try to get a different log file name@>=
16174 {  
16175   mp->selector=term_only;
16176   mp_prompt_file_name(mp, "transcript file name",".log");
16177 }
16178
16179 @ @<Print the banner...@>=
16180
16181   wlog(banner);
16182   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16183   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16184   mp_print_char(mp, ' ');
16185   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16186   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16187   mp_print_char(mp, ' '); 
16188   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16189   mp_print_char(mp, ' ');
16190   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16191   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16192 }
16193
16194 @ The |try_extension| function tries to open an input file determined by
16195 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16196 can't find the file in |cur_area| or the appropriate system area.
16197
16198 @c boolean mp_try_extension (MP mp,char *ext) { 
16199   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16200   in_name=xstrdup(mp->cur_name); 
16201   in_area=xstrdup(mp->cur_area);
16202   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16203     return true;
16204   } else { 
16205     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16206     else in_area=xstrdup(MP_area);
16207     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16208     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16209   }
16210   return false;
16211 }
16212
16213 @ Let's turn now to the procedure that is used to initiate file reading
16214 when an `\.{input}' command is being processed.
16215
16216 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16217   char *fname = NULL;
16218   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16219   while (1) { 
16220     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16221     if ( strlen(mp->cur_ext)==0 ) {
16222       if ( mp_try_extension(mp, ".mp") ) break;
16223       else if ( mp_try_extension(mp, "") ) break;
16224       else if ( mp_try_extension(mp, ".mf") ) break;
16225       /* |else do_nothing; | */
16226     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16227       break;
16228     }
16229     mp_end_file_reading(mp); /* remove the level that didn't work */
16230     mp_prompt_file_name(mp, "input file name","");
16231   }
16232   name=mp_a_make_name_string(mp, cur_file);
16233   fname = xstrdup(mp->name_of_file);
16234   if ( mp->job_name==NULL ) {
16235     mp->job_name=xstrdup(mp->cur_name); 
16236     mp_open_log_file(mp);
16237   } /* |open_log_file| doesn't |show_context|, so |limit|
16238         and |loc| needn't be set to meaningful values yet */
16239   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16240   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16241   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16242   xfree(fname);
16243   update_terminal;
16244   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16245   @<Read the first line of the new file@>;
16246 }
16247
16248 @ This code should be omitted if |a_make_name_string| returns something other
16249 than just a copy of its argument and the full file name is needed for opening
16250 \.{MPX} files or implementing the switch-to-editor option.
16251 @^system dependencies@>
16252
16253 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16254 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16255
16256 @ If the file is empty, it is considered to contain a single blank line,
16257 so there is no need to test the return value.
16258
16259 @<Read the first line...@>=
16260
16261   line=1;
16262   (void)mp_input_ln(mp, cur_file ); 
16263   mp_firm_up_the_line(mp);
16264   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16265 }
16266
16267 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16268 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16269 if ( token_state ) { 
16270   print_err("File names can't appear within macros");
16271 @.File names can't...@>
16272   help3("Sorry...I've converted what follows to tokens,")
16273     ("possibly garbaging the name you gave.")
16274     ("Please delete the tokens and insert the name again.");
16275   mp_error(mp);
16276 }
16277 if ( file_state ) {
16278   mp_scan_file_name(mp);
16279 } else { 
16280    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16281    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16282    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16283 }
16284
16285 @ The following simple routine starts reading the \.{MPX} file associated
16286 with the current input file.
16287
16288 @c void mp_start_mpx_input (MP mp) {
16289   char *origname = NULL; /* a copy of nameoffile */
16290   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16291   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16292     |goto not_found| if there is a problem@>;
16293   mp_begin_file_reading(mp);
16294   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16295     mp_end_file_reading(mp);
16296     goto NOT_FOUND;
16297   }
16298   name=mp_a_make_name_string(mp, cur_file);
16299   mp->mpx_name[index]=name; add_str_ref(name);
16300   @<Read the first line of the new file@>;
16301   return;
16302 NOT_FOUND: 
16303     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16304   xfree(origname);
16305 }
16306
16307 @ This should ideally be changed to do whatever is necessary to create the
16308 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16309 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16310 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16311 completely different typesetting program if suitable postprocessor is
16312 available to perform the function of \.{DVItoMP}.)
16313 @^system dependencies@>
16314
16315 @ @<Exported types@>=
16316 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16317
16318 @ @<Option variables@>=
16319 mp_run_make_mpx_command run_make_mpx;
16320
16321 @ @<Allocate or initialize ...@>=
16322 set_callback_option(run_make_mpx);
16323
16324 @ @<Internal library declarations@>=
16325 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16326
16327 @ The default does nothing.
16328 @c 
16329 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16330   if (mp && origname && mtxname) /* for -W */
16331     return false;
16332   return false;
16333 }
16334
16335 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16336   |goto not_found| if there is a problem@>=
16337 origname = mp_xstrdup(mp,mp->name_of_file);
16338 *(origname+strlen(origname)-1)=0; /* drop the x */
16339 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16340   goto NOT_FOUND 
16341
16342 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16343 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16344 mp_print_nl(mp, ">> ");
16345 mp_print(mp, origname);
16346 mp_print_nl(mp, ">> ");
16347 mp_print(mp, mp->name_of_file);
16348 mp_print_nl(mp, "! Unable to make mpx file");
16349 help4("The two files given above are one of your source files")
16350   ("and an auxiliary file I need to read to find out what your")
16351   ("btex..etex blocks mean. If you don't know why I had trouble,")
16352   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16353 succumb;
16354
16355 @ The last file-opening commands are for files accessed via the \&{readfrom}
16356 @:read_from_}{\&{readfrom} primitive@>
16357 operator and the \&{write} command.  Such files are stored in separate arrays.
16358 @:write_}{\&{write} primitive@>
16359
16360 @<Types in the outer block@>=
16361 typedef unsigned int readf_index; /* |0..max_read_files| */
16362 typedef unsigned int write_index;  /* |0..max_write_files| */
16363
16364 @ @<Glob...@>=
16365 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16366 void ** rd_file; /* \&{readfrom} files */
16367 char ** rd_fname; /* corresponding file name or 0 if file not open */
16368 readf_index read_files; /* number of valid entries in the above arrays */
16369 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16370 void ** wr_file; /* \&{write} files */
16371 char ** wr_fname; /* corresponding file name or 0 if file not open */
16372 write_index write_files; /* number of valid entries in the above arrays */
16373
16374 @ @<Allocate or initialize ...@>=
16375 mp->max_read_files=8;
16376 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16377 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16378 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16379 mp->read_files=0;
16380 mp->max_write_files=8;
16381 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16382 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16383 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16384 mp->write_files=0;
16385
16386
16387 @ This routine starts reading the file named by string~|s| without setting
16388 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16389 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16390
16391 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16392   mp_ptr_scan_file(mp, s);
16393   pack_cur_name;
16394   mp_begin_file_reading(mp);
16395   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (mp_filetype_text+n)) ) 
16396         goto NOT_FOUND;
16397   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16398     (mp->close_file)(mp->rd_file[n]); 
16399         goto NOT_FOUND; 
16400   }
16401   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16402   return true;
16403 NOT_FOUND: 
16404   mp_end_file_reading(mp);
16405   return false;
16406 }
16407
16408 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16409
16410 @<Declarations@>=
16411 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16412
16413 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16414   mp_ptr_scan_file(mp, s);
16415   pack_cur_name;
16416   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (mp_filetype_text+n)) )
16417     mp_prompt_file_name(mp, "file name for write output","");
16418   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16419 }
16420
16421
16422 @* \[36] Introduction to the parsing routines.
16423 We come now to the central nervous system that sparks many of \MP's activities.
16424 By evaluating expressions, from their primary constituents to ever larger
16425 subexpressions, \MP\ builds the structures that ultimately define complete
16426 pictures or fonts of type.
16427
16428 Four mutually recursive subroutines are involved in this process: We call them
16429 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16430 and |scan_expression|.}$$
16431 @^recursion@>
16432 Each of them is parameterless and begins with the first token to be scanned
16433 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16434 the value of the primary or secondary or tertiary or expression that was
16435 found will appear in the global variables |cur_type| and |cur_exp|. The
16436 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16437 and |cur_sym|.
16438
16439 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16440 backup mechanisms have been added in order to provide reasonable error
16441 recovery.
16442
16443 @<Glob...@>=
16444 small_number cur_type; /* the type of the expression just found */
16445 integer cur_exp; /* the value of the expression just found */
16446
16447 @ @<Set init...@>=
16448 mp->cur_exp=0;
16449
16450 @ Many different kinds of expressions are possible, so it is wise to have
16451 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16452
16453 \smallskip\hang
16454 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16455 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16456 construction in which there was no expression before the \&{endgroup}.
16457 In this case |cur_exp| has some irrelevant value.
16458
16459 \smallskip\hang
16460 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16461 or |false_code|.
16462
16463 \smallskip\hang
16464 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16465 node that is in the ring of variables equivalent
16466 to at least one undefined boolean variable.
16467
16468 \smallskip\hang
16469 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16470 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16471 includes this particular reference.
16472
16473 \smallskip\hang
16474 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16475 node that is in the ring of variables equivalent
16476 to at least one undefined string variable.
16477
16478 \smallskip\hang
16479 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16480 else points to any of the nodes in this pen.  The pen may be polygonal or
16481 elliptical.
16482
16483 \smallskip\hang
16484 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16485 node that is in the ring of variables equivalent
16486 to at least one undefined pen variable.
16487
16488 \smallskip\hang
16489 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16490 a path; nobody else points to this particular path. The control points of
16491 the path will have been chosen.
16492
16493 \smallskip\hang
16494 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16495 node that is in the ring of variables equivalent
16496 to at least one undefined path variable.
16497
16498 \smallskip\hang
16499 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16500 There may be other pointers to this particular set of edges.  The header node
16501 contains a reference count that includes this particular reference.
16502
16503 \smallskip\hang
16504 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16505 node that is in the ring of variables equivalent
16506 to at least one undefined picture variable.
16507
16508 \smallskip\hang
16509 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16510 capsule node. The |value| part of this capsule
16511 points to a transform node that contains six numeric values,
16512 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16513
16514 \smallskip\hang
16515 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16516 capsule node. The |value| part of this capsule
16517 points to a color node that contains three numeric values,
16518 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16519
16520 \smallskip\hang
16521 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16522 capsule node. The |value| part of this capsule
16523 points to a color node that contains four numeric values,
16524 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16525
16526 \smallskip\hang
16527 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16528 node whose type is |mp_pair_type|. The |value| part of this capsule
16529 points to a pair node that contains two numeric values,
16530 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16531
16532 \smallskip\hang
16533 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16534
16535 \smallskip\hang
16536 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16537 is |dependent|. The |dep_list| field in this capsule points to the associated
16538 dependency list.
16539
16540 \smallskip\hang
16541 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16542 capsule node. The |dep_list| field in this capsule
16543 points to the associated dependency list.
16544
16545 \smallskip\hang
16546 |cur_type=independent| means that |cur_exp| points to a capsule node
16547 whose type is |independent|. This somewhat unusual case can arise, for
16548 example, in the expression
16549 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16550
16551 \smallskip\hang
16552 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16553 tokens. This case arises only on the left-hand side of an assignment
16554 (`\.{:=}') operation, under very special circumstances.
16555
16556 \smallskip\noindent
16557 The possible settings of |cur_type| have been listed here in increasing
16558 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16559 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16560 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16561 |token_list|.
16562
16563 @ Capsules are two-word nodes that have a similar meaning
16564 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16565 and |link<=mp_void|; and their |type| field is one of the possibilities for
16566 |cur_type| listed above.
16567
16568 The |value| field of a capsule is, in most cases, the value that
16569 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16570 However, when |cur_exp| would point to a capsule,
16571 no extra layer of indirection is present; the |value|
16572 field is what would have been called |value(cur_exp)| if it had not been
16573 encapsulated.  Furthermore, if the type is |dependent| or
16574 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16575 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16576 always part of the general |dep_list| structure.
16577
16578 The |get_x_next| routine is careful not to change the values of |cur_type|
16579 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16580 call a macro, which might parse an expression, which might execute lots of
16581 commands in a group; hence it's possible that |cur_type| might change
16582 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16583 |known| or |independent|, during the time |get_x_next| is called. The
16584 programs below are careful to stash sensitive intermediate results in
16585 capsules, so that \MP's generality doesn't cause trouble.
16586
16587 Here's a procedure that illustrates these conventions. It takes
16588 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16589 and stashes them away in a
16590 capsule. It is not used when |cur_type=mp_token_list|.
16591 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16592 copy path lists or to update reference counts, etc.
16593
16594 The special link |mp_void| is put on the capsule returned by
16595 |stash_cur_exp|, because this procedure is used to store macro parameters
16596 that must be easily distinguishable from token lists.
16597
16598 @<Declare the stashing/unstashing routines@>=
16599 pointer mp_stash_cur_exp (MP mp) {
16600   pointer p; /* the capsule that will be returned */
16601   switch (mp->cur_type) {
16602   case unknown_types:
16603   case mp_transform_type:
16604   case mp_color_type:
16605   case mp_pair_type:
16606   case mp_dependent:
16607   case mp_proto_dependent:
16608   case mp_independent: 
16609   case mp_cmykcolor_type:
16610     p=mp->cur_exp;
16611     break;
16612   default: 
16613     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16614     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16615     break;
16616   }
16617   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16618   return p;
16619 }
16620
16621 @ The inverse of |stash_cur_exp| is the following procedure, which
16622 deletes an unnecessary capsule and puts its contents into |cur_type|
16623 and |cur_exp|.
16624
16625 The program steps of \MP\ can be divided into two categories: those in
16626 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16627 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16628 information or not. It's important not to ignore them when they're alive,
16629 and it's important not to pay attention to them when they're dead.
16630
16631 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16632 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16633 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16634 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16635 only when they are alive or dormant.
16636
16637 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16638 are alive or dormant. The \\{unstash} procedure assumes that they are
16639 dead or dormant; it resuscitates them.
16640
16641 @<Declare the stashing/unstashing...@>=
16642 void mp_unstash_cur_exp (MP mp,pointer p) ;
16643
16644 @ @c
16645 void mp_unstash_cur_exp (MP mp,pointer p) { 
16646   mp->cur_type=type(p);
16647   switch (mp->cur_type) {
16648   case unknown_types:
16649   case mp_transform_type:
16650   case mp_color_type:
16651   case mp_pair_type:
16652   case mp_dependent: 
16653   case mp_proto_dependent:
16654   case mp_independent:
16655   case mp_cmykcolor_type: 
16656     mp->cur_exp=p;
16657     break;
16658   default:
16659     mp->cur_exp=value(p);
16660     mp_free_node(mp, p,value_node_size);
16661     break;
16662   }
16663 }
16664
16665 @ The following procedure prints the values of expressions in an
16666 abbreviated format. If its first parameter |p| is null, the value of
16667 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16668 containing the desired value. The second parameter controls the amount of
16669 output. If it is~0, dependency lists will be abbreviated to
16670 `\.{linearform}' unless they consist of a single term.  If it is greater
16671 than~1, complicated structures (pens, pictures, and paths) will be displayed
16672 in full.
16673
16674 @<Declare subroutines for printing expressions@>=
16675 @<Declare the procedure called |print_dp|@>;
16676 @<Declare the stashing/unstashing routines@>;
16677 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16678   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16679   small_number t; /* the type of the expression */
16680   pointer q; /* a big node being displayed */
16681   integer v=0; /* the value of the expression */
16682   if ( p!=null ) {
16683     restore_cur_exp=false;
16684   } else { 
16685     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16686   }
16687   t=type(p);
16688   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16689   @<Print an abbreviated value of |v| with format depending on |t|@>;
16690   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16691 }
16692
16693 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16694 switch (t) {
16695 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16696 case mp_boolean_type:
16697   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16698   break;
16699 case unknown_types: case mp_numeric_type:
16700   @<Display a variable that's been declared but not defined@>;
16701   break;
16702 case mp_string_type:
16703   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16704   break;
16705 case mp_pen_type: case mp_path_type: case mp_picture_type:
16706   @<Display a complex type@>;
16707   break;
16708 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16709   if ( v==null ) mp_print_type(mp, t);
16710   else @<Display a big node@>;
16711   break;
16712 case mp_known:mp_print_scaled(mp, v); break;
16713 case mp_dependent: case mp_proto_dependent:
16714   mp_print_dp(mp, t,v,verbosity);
16715   break;
16716 case mp_independent:mp_print_variable_name(mp, p); break;
16717 default: mp_confusion(mp, "exp"); break;
16718 @:this can't happen exp}{\quad exp@>
16719 }
16720
16721 @ @<Display a big node@>=
16722
16723   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16724   do {  
16725     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16726     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16727     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16728     v=v+2;
16729     if ( v!=q ) mp_print_char(mp, ',');
16730   } while (v!=q);
16731   mp_print_char(mp, ')');
16732 }
16733
16734 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16735 in the log file only, unless the user has given a positive value to
16736 \\{tracingonline}.
16737
16738 @<Display a complex type@>=
16739 if ( verbosity<=1 ) {
16740   mp_print_type(mp, t);
16741 } else { 
16742   if ( mp->selector==term_and_log )
16743    if ( mp->internal[mp_tracing_online]<=0 ) {
16744     mp->selector=term_only;
16745     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16746     mp->selector=term_and_log;
16747   };
16748   switch (t) {
16749   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16750   case mp_path_type:mp_print_path(mp, v,"",false); break;
16751   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16752   } /* there are no other cases */
16753 }
16754
16755 @ @<Declare the procedure called |print_dp|@>=
16756 void mp_print_dp (MP mp,small_number t, pointer p, 
16757                   small_number verbosity)  {
16758   pointer q; /* the node following |p| */
16759   q=link(p);
16760   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16761   else mp_print(mp, "linearform");
16762 }
16763
16764 @ The displayed name of a variable in a ring will not be a capsule unless
16765 the ring consists entirely of capsules.
16766
16767 @<Display a variable that's been declared but not defined@>=
16768 { mp_print_type(mp, t);
16769 if ( v!=null )
16770   { mp_print_char(mp, ' ');
16771   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16772   mp_print_variable_name(mp, v);
16773   };
16774 }
16775
16776 @ When errors are detected during parsing, it is often helpful to
16777 display an expression just above the error message, using |exp_err|
16778 or |disp_err| instead of |print_err|.
16779
16780 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16781
16782 @<Declare subroutines for printing expressions@>=
16783 void mp_disp_err (MP mp,pointer p, char *s) { 
16784   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16785   mp_print_nl(mp, ">> ");
16786 @.>>@>
16787   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16788   if (strlen(s)) { 
16789     mp_print_nl(mp, "! "); mp_print(mp, s);
16790 @.!\relax@>
16791   }
16792 }
16793
16794 @ If |cur_type| and |cur_exp| contain relevant information that should
16795 be recycled, we will use the following procedure, which changes |cur_type|
16796 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16797 and |cur_exp| as either alive or dormant after this has been done,
16798 because |cur_exp| will not contain a pointer value.
16799
16800 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16801   switch (mp->cur_type) {
16802   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16803   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16804     mp_recycle_value(mp, mp->cur_exp); 
16805     mp_free_node(mp, mp->cur_exp,value_node_size);
16806     break;
16807   case mp_string_type:
16808     delete_str_ref(mp->cur_exp); break;
16809   case mp_pen_type: case mp_path_type: 
16810     mp_toss_knot_list(mp, mp->cur_exp); break;
16811   case mp_picture_type:
16812     delete_edge_ref(mp->cur_exp); break;
16813   default: 
16814     break;
16815   }
16816   mp->cur_type=mp_known; mp->cur_exp=v;
16817 }
16818
16819 @ There's a much more general procedure that is capable of releasing
16820 the storage associated with any two-word value packet.
16821
16822 @<Declare the recycling subroutines@>=
16823 void mp_recycle_value (MP mp,pointer p) ;
16824
16825 @ @c void mp_recycle_value (MP mp,pointer p) {
16826   small_number t; /* a type code */
16827   integer vv; /* another value */
16828   pointer q,r,s,pp; /* link manipulation registers */
16829   integer v=0; /* a value */
16830   t=type(p);
16831   if ( t<mp_dependent ) v=value(p);
16832   switch (t) {
16833   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16834   case mp_numeric_type:
16835     break;
16836   case unknown_types:
16837     mp_ring_delete(mp, p); break;
16838   case mp_string_type:
16839     delete_str_ref(v); break;
16840   case mp_path_type: case mp_pen_type:
16841     mp_toss_knot_list(mp, v); break;
16842   case mp_picture_type:
16843     delete_edge_ref(v); break;
16844   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16845   case mp_transform_type:
16846     @<Recycle a big node@>; break; 
16847   case mp_dependent: case mp_proto_dependent:
16848     @<Recycle a dependency list@>; break;
16849   case mp_independent:
16850     @<Recycle an independent variable@>; break;
16851   case mp_token_list: case mp_structured:
16852     mp_confusion(mp, "recycle"); break;
16853 @:this can't happen recycle}{\quad recycle@>
16854   case mp_unsuffixed_macro: case mp_suffixed_macro:
16855     mp_delete_mac_ref(mp, value(p)); break;
16856   } /* there are no other cases */
16857   type(p)=undefined;
16858 }
16859
16860 @ @<Recycle a big node@>=
16861 if ( v!=null ){ 
16862   q=v+mp->big_node_size[t];
16863   do {  
16864     q=q-2; mp_recycle_value(mp, q);
16865   } while (q!=v);
16866   mp_free_node(mp, v,mp->big_node_size[t]);
16867 }
16868
16869 @ @<Recycle a dependency list@>=
16870
16871   q=dep_list(p);
16872   while ( info(q)!=null ) q=link(q);
16873   link(prev_dep(p))=link(q);
16874   prev_dep(link(q))=prev_dep(p);
16875   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16876 }
16877
16878 @ When an independent variable disappears, it simply fades away, unless
16879 something depends on it. In the latter case, a dependent variable whose
16880 coefficient of dependence is maximal will take its place.
16881 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16882 as part of his Ph.D. thesis (Stanford University, December 1982).
16883 @^Zabala Salelles, Ignacio Andres@>
16884
16885 For example, suppose that variable $x$ is being recycled, and that the
16886 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16887 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16888 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16889 we will print `\.{\#\#\# -2x=-y+a}'.
16890
16891 There's a slight complication, however: An independent variable $x$
16892 can occur both in dependency lists and in proto-dependency lists.
16893 This makes it necessary to be careful when deciding which coefficient
16894 is maximal.
16895
16896 Furthermore, this complication is not so slight when
16897 a proto-dependent variable is chosen to become independent. For example,
16898 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16899 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16900 large coefficient `50'.
16901
16902 In order to deal with these complications without wasting too much time,
16903 we shall link together the occurrences of~$x$ among all the linear
16904 dependencies, maintaining separate lists for the dependent and
16905 proto-dependent cases.
16906
16907 @<Recycle an independent variable@>=
16908
16909   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16910   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16911   q=link(dep_head);
16912   while ( q!=dep_head ) { 
16913     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16914     while (1) { 
16915       r=link(s);
16916       if ( info(r)==null ) break;;
16917       if ( info(r)!=p ) { 
16918        s=r;
16919       } else  { 
16920         t=type(q); link(s)=link(r); info(r)=q;
16921         if ( abs(value(r))>mp->max_c[t] ) {
16922           @<Record a new maximum coefficient of type |t|@>;
16923         } else { 
16924           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16925         }
16926       }
16927     }   
16928     q=link(r);
16929   }
16930   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16931     @<Choose a dependent variable to take the place of the disappearing
16932     independent variable, and change all remaining dependencies
16933     accordingly@>;
16934   }
16935 }
16936
16937 @ The code for independency removal makes use of three two-word arrays.
16938
16939 @<Glob...@>=
16940 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16941 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16942 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16943
16944 @ @<Record a new maximum coefficient...@>=
16945
16946   if ( mp->max_c[t]>0 ) {
16947     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16948   }
16949   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16950 }
16951
16952 @ @<Choose a dependent...@>=
16953
16954   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16955     t=mp_dependent;
16956   else 
16957     t=mp_proto_dependent;
16958   @<Determine the dependency list |s| to substitute for the independent
16959     variable~|p|@>;
16960   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16961   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16962     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16963   }
16964   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16965   else { @<Substitute new proto-dependencies in place of |p|@>;}
16966   mp_flush_node_list(mp, s);
16967   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16968   check_arith;
16969 }
16970
16971 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16972 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16973 whose dependency list we have removed node~|s|. We must reinsert
16974 node~|s| into the dependency list, with coefficient $-1.0$, and with
16975 |pp| as the new independent variable. Since |pp| will have a larger serial
16976 number than any other variable, we can put node |s| at the head of the
16977 list.
16978
16979 @<Determine the dep...@>=
16980 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16981 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16982 r=dep_list(pp); link(s)=r;
16983 while ( info(r)!=null ) r=link(r);
16984 q=link(r); link(r)=null;
16985 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16986 new_indep(pp);
16987 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16988 if ( mp->internal[mp_tracing_equations]>0 ) { 
16989   @<Show the transformed dependency@>; 
16990 }
16991
16992 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16993 by the dependency list~|s|.
16994
16995 @<Show the transformed...@>=
16996 if ( mp_interesting(mp, p) ) {
16997   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16998 @:]]]\#\#\#_}{\.{\#\#\#}@>
16999   if ( v>0 ) mp_print_char(mp, '-');
17000   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17001   else vv=mp->max_c[mp_proto_dependent];
17002   if ( vv!=unity ) mp_print_scaled(mp, vv);
17003   mp_print_variable_name(mp, p);
17004   while ( value(p) % s_scale>0 ) {
17005     mp_print(mp, "*4"); value(p)=value(p)-2;
17006   }
17007   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
17008   mp_print_dependency(mp, s,t);
17009   mp_end_diagnostic(mp, false);
17010 }
17011
17012 @ Finally, there are dependent and proto-dependent variables whose
17013 dependency lists must be brought up to date.
17014
17015 @<Substitute new dependencies...@>=
17016 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17017   r=mp->max_link[t];
17018   while ( r!=null ) {
17019     q=info(r);
17020     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17021      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17022     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17023     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17024   }
17025 }
17026
17027 @ @<Substitute new proto...@>=
17028 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17029   r=mp->max_link[t];
17030   while ( r!=null ) {
17031     q=info(r);
17032     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17033       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17034         mp->cur_type=mp_proto_dependent;
17035       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17036       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17037     }
17038     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17039       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17040     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17041     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17042   }
17043 }
17044
17045 @ Here are some routines that provide handy combinations of actions
17046 that are often needed during error recovery. For example,
17047 `|flush_error|' flushes the current expression, replaces it by
17048 a given value, and calls |error|.
17049
17050 Errors often are detected after an extra token has already been scanned.
17051 The `\\{put\_get}' routines put that token back before calling |error|;
17052 then they get it back again. (Or perhaps they get another token, if
17053 the user has changed things.)
17054
17055 @<Declarations@>=
17056 void mp_flush_error (MP mp,scaled v);
17057 void mp_put_get_error (MP mp);
17058 void mp_put_get_flush_error (MP mp,scaled v) ;
17059
17060 @ @c
17061 void mp_flush_error (MP mp,scaled v) { 
17062   mp_error(mp); mp_flush_cur_exp(mp, v); 
17063 }
17064 void mp_put_get_error (MP mp) { 
17065   mp_back_error(mp); mp_get_x_next(mp); 
17066 }
17067 void mp_put_get_flush_error (MP mp,scaled v) { 
17068   mp_put_get_error(mp);
17069   mp_flush_cur_exp(mp, v); 
17070 }
17071
17072 @ A global variable |var_flag| is set to a special command code
17073 just before \MP\ calls |scan_expression|, if the expression should be
17074 treated as a variable when this command code immediately follows. For
17075 example, |var_flag| is set to |assignment| at the beginning of a
17076 statement, because we want to know the {\sl location\/} of a variable at
17077 the left of `\.{:=}', not the {\sl value\/} of that variable.
17078
17079 The |scan_expression| subroutine calls |scan_tertiary|,
17080 which calls |scan_secondary|, which calls |scan_primary|, which sets
17081 |var_flag:=0|. In this way each of the scanning routines ``knows''
17082 when it has been called with a special |var_flag|, but |var_flag| is
17083 usually zero.
17084
17085 A variable preceding a command that equals |var_flag| is converted to a
17086 token list rather than a value. Furthermore, an `\.{=}' sign following an
17087 expression with |var_flag=assignment| is not considered to be a relation
17088 that produces boolean expressions.
17089
17090
17091 @<Glob...@>=
17092 int var_flag; /* command that wants a variable */
17093
17094 @ @<Set init...@>=
17095 mp->var_flag=0;
17096
17097 @* \[37] Parsing primary expressions.
17098 The first parsing routine, |scan_primary|, is also the most complicated one,
17099 since it involves so many different cases. But each case---with one
17100 exception---is fairly simple by itself.
17101
17102 When |scan_primary| begins, the first token of the primary to be scanned
17103 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17104 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17105 earlier. If |cur_cmd| is not between |min_primary_command| and
17106 |max_primary_command|, inclusive, a syntax error will be signaled.
17107
17108 @<Declare the basic parsing subroutines@>=
17109 void mp_scan_primary (MP mp) {
17110   pointer p,q,r; /* for list manipulation */
17111   quarterword c; /* a primitive operation code */
17112   int my_var_flag; /* initial value of |my_var_flag| */
17113   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17114   @<Other local variables for |scan_primary|@>;
17115   my_var_flag=mp->var_flag; mp->var_flag=0;
17116 RESTART:
17117   check_arith;
17118   @<Supply diagnostic information, if requested@>;
17119   switch (mp->cur_cmd) {
17120   case left_delimiter:
17121     @<Scan a delimited primary@>; break;
17122   case begin_group:
17123     @<Scan a grouped primary@>; break;
17124   case string_token:
17125     @<Scan a string constant@>; break;
17126   case numeric_token:
17127     @<Scan a primary that starts with a numeric token@>; break;
17128   case nullary:
17129     @<Scan a nullary operation@>; break;
17130   case unary: case type_name: case cycle: case plus_or_minus:
17131     @<Scan a unary operation@>; break;
17132   case primary_binary:
17133     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17134   case str_op:
17135     @<Convert a suffix to a string@>; break;
17136   case internal_quantity:
17137     @<Scan an internal numeric quantity@>; break;
17138   case capsule_token:
17139     mp_make_exp_copy(mp, mp->cur_mod); break;
17140   case tag_token:
17141     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17142   default: 
17143     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17144 @.A primary expression...@>
17145   }
17146   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17147 DONE: 
17148   if ( mp->cur_cmd==left_bracket ) {
17149     if ( mp->cur_type>=mp_known ) {
17150       @<Scan a mediation construction@>;
17151     }
17152   }
17153 }
17154
17155
17156
17157 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17158
17159 @c void mp_bad_exp (MP mp,char * s) {
17160   int save_flag;
17161   print_err(s); mp_print(mp, " expression can't begin with `");
17162   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17163   mp_print_char(mp, '\'');
17164   help4("I'm afraid I need some sort of value in order to continue,")
17165     ("so I've tentatively inserted `0'. You may want to")
17166     ("delete this zero and insert something else;")
17167     ("see Chapter 27 of The METAFONTbook for an example.");
17168 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17169   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17170   mp->cur_mod=0; mp_ins_error(mp);
17171   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17172   mp->var_flag=save_flag;
17173 }
17174
17175 @ @<Supply diagnostic information, if requested@>=
17176 #ifdef DEBUG
17177 if ( mp->panicking ) mp_check_mem(mp, false);
17178 #endif
17179 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17180   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17181 }
17182
17183 @ @<Scan a delimited primary@>=
17184
17185   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17186   mp_get_x_next(mp); mp_scan_expression(mp);
17187   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17188     @<Scan the rest of a delimited set of numerics@>;
17189   } else {
17190     mp_check_delimiter(mp, l_delim,r_delim);
17191   }
17192 }
17193
17194 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17195 within a ``big node.''
17196
17197 @c void mp_stash_in (MP mp,pointer p) {
17198   pointer q; /* temporary register */
17199   type(p)=mp->cur_type;
17200   if ( mp->cur_type==mp_known ) {
17201     value(p)=mp->cur_exp;
17202   } else { 
17203     if ( mp->cur_type==mp_independent ) {
17204       @<Stash an independent |cur_exp| into a big node@>;
17205     } else { 
17206       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17207       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17208       link(prev_dep(p))=p;
17209     }
17210     mp_free_node(mp, mp->cur_exp,value_node_size);
17211   }
17212   mp->cur_type=mp_vacuous;
17213 }
17214
17215 @ In rare cases the current expression can become |independent|. There
17216 may be many dependency lists pointing to such an independent capsule,
17217 so we can't simply move it into place within a big node. Instead,
17218 we copy it, then recycle it.
17219
17220 @ @<Stash an independent |cur_exp|...@>=
17221
17222   q=mp_single_dependency(mp, mp->cur_exp);
17223   if ( q==mp->dep_final ){ 
17224     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17225   } else { 
17226     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17227   }
17228   mp_recycle_value(mp, mp->cur_exp);
17229 }
17230
17231 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17232 are synonymous with |x_part_loc| and |y_part_loc|.
17233
17234 @<Scan the rest of a delimited set of numerics@>=
17235
17236 p=mp_stash_cur_exp(mp);
17237 mp_get_x_next(mp); mp_scan_expression(mp);
17238 @<Make sure the second part of a pair or color has a numeric type@>;
17239 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17240 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17241 else type(q)=mp_pair_type;
17242 mp_init_big_node(mp, q); r=value(q);
17243 mp_stash_in(mp, y_part_loc(r));
17244 mp_unstash_cur_exp(mp, p);
17245 mp_stash_in(mp, x_part_loc(r));
17246 if ( mp->cur_cmd==comma ) {
17247   @<Scan the last of a triplet of numerics@>;
17248 }
17249 if ( mp->cur_cmd==comma ) {
17250   type(q)=mp_cmykcolor_type;
17251   mp_init_big_node(mp, q); t=value(q);
17252   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17253   value(cyan_part_loc(t))=value(red_part_loc(r));
17254   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17255   value(magenta_part_loc(t))=value(green_part_loc(r));
17256   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17257   value(yellow_part_loc(t))=value(blue_part_loc(r));
17258   mp_recycle_value(mp, r);
17259   r=t;
17260   @<Scan the last of a quartet of numerics@>;
17261 }
17262 mp_check_delimiter(mp, l_delim,r_delim);
17263 mp->cur_type=type(q);
17264 mp->cur_exp=q;
17265 }
17266
17267 @ @<Make sure the second part of a pair or color has a numeric type@>=
17268 if ( mp->cur_type<mp_known ) {
17269   exp_err("Nonnumeric ypart has been replaced by 0");
17270 @.Nonnumeric...replaced by 0@>
17271   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17272     ("but after finding a nice `a' I found a `b' that isn't")
17273     ("of numeric type. So I've changed that part to zero.")
17274     ("(The b that I didn't like appears above the error message.)");
17275   mp_put_get_flush_error(mp, 0);
17276 }
17277
17278 @ @<Scan the last of a triplet of numerics@>=
17279
17280   mp_get_x_next(mp); mp_scan_expression(mp);
17281   if ( mp->cur_type<mp_known ) {
17282     exp_err("Nonnumeric third part has been replaced by 0");
17283 @.Nonnumeric...replaced by 0@>
17284     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17285       ("isn't of numeric type. So I've changed that part to zero.")
17286       ("(The c that I didn't like appears above the error message.)");
17287     mp_put_get_flush_error(mp, 0);
17288   }
17289   mp_stash_in(mp, blue_part_loc(r));
17290 }
17291
17292 @ @<Scan the last of a quartet of numerics@>=
17293
17294   mp_get_x_next(mp); mp_scan_expression(mp);
17295   if ( mp->cur_type<mp_known ) {
17296     exp_err("Nonnumeric blackpart has been replaced by 0");
17297 @.Nonnumeric...replaced by 0@>
17298     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17299       ("of numeric type. So I've changed that part to zero.")
17300       ("(The k that I didn't like appears above the error message.)");
17301     mp_put_get_flush_error(mp, 0);
17302   }
17303   mp_stash_in(mp, black_part_loc(r));
17304 }
17305
17306 @ The local variable |group_line| keeps track of the line
17307 where a \&{begingroup} command occurred; this will be useful
17308 in an error message if the group doesn't actually end.
17309
17310 @<Other local variables for |scan_primary|@>=
17311 integer group_line; /* where a group began */
17312
17313 @ @<Scan a grouped primary@>=
17314
17315   group_line=mp_true_line(mp);
17316   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17317   save_boundary_item(p);
17318   do {  
17319     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17320   } while (! (mp->cur_cmd!=semicolon));
17321   if ( mp->cur_cmd!=end_group ) {
17322     print_err("A group begun on line ");
17323 @.A group...never ended@>
17324     mp_print_int(mp, group_line);
17325     mp_print(mp, " never ended");
17326     help2("I saw a `begingroup' back there that hasn't been matched")
17327          ("by `endgroup'. So I've inserted `endgroup' now.");
17328     mp_back_error(mp); mp->cur_cmd=end_group;
17329   }
17330   mp_unsave(mp); 
17331     /* this might change |cur_type|, if independent variables are recycled */
17332   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17333 }
17334
17335 @ @<Scan a string constant@>=
17336
17337   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17338 }
17339
17340 @ Later we'll come to procedures that perform actual operations like
17341 addition, square root, and so on; our purpose now is to do the parsing.
17342 But we might as well mention those future procedures now, so that the
17343 suspense won't be too bad:
17344
17345 \smallskip
17346 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17347 `\&{true}' or `\&{pencircle}');
17348
17349 \smallskip
17350 |do_unary(c)| applies a primitive operation to the current expression;
17351
17352 \smallskip
17353 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17354 and the current expression.
17355
17356 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17357
17358 @ @<Scan a unary operation@>=
17359
17360   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17361   mp_do_unary(mp, c); goto DONE;
17362 }
17363
17364 @ A numeric token might be a primary by itself, or it might be the
17365 numerator of a fraction composed solely of numeric tokens, or it might
17366 multiply the primary that follows (provided that the primary doesn't begin
17367 with a plus sign or a minus sign). The code here uses the facts that
17368 |max_primary_command=plus_or_minus| and
17369 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17370 than unity, we try to retain higher precision when we use it in scalar
17371 multiplication.
17372
17373 @<Other local variables for |scan_primary|@>=
17374 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17375
17376 @ @<Scan a primary that starts with a numeric token@>=
17377
17378   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17379   if ( mp->cur_cmd!=slash ) { 
17380     num=0; denom=0;
17381   } else { 
17382     mp_get_x_next(mp);
17383     if ( mp->cur_cmd!=numeric_token ) { 
17384       mp_back_input(mp);
17385       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17386       goto DONE;
17387     }
17388     num=mp->cur_exp; denom=mp->cur_mod;
17389     if ( denom==0 ) { @<Protest division by zero@>; }
17390     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17391     check_arith; mp_get_x_next(mp);
17392   }
17393   if ( mp->cur_cmd>=min_primary_command ) {
17394    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17395      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17396      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17397        mp_do_binary(mp, p,times);
17398      } else {
17399        mp_frac_mult(mp, num,denom);
17400        mp_free_node(mp, p,value_node_size);
17401      }
17402     }
17403   }
17404   goto DONE;
17405 }
17406
17407 @ @<Protest division...@>=
17408
17409   print_err("Division by zero");
17410 @.Division by zero@>
17411   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17412 }
17413
17414 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17415
17416   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17417   if ( mp->cur_cmd!=of_token ) {
17418     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17419     mp_print_cmd_mod(mp, primary_binary,c);
17420 @.Missing `of'@>
17421     help1("I've got the first argument; will look now for the other.");
17422     mp_back_error(mp);
17423   }
17424   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17425   mp_do_binary(mp, p,c); goto DONE;
17426 }
17427
17428 @ @<Convert a suffix to a string@>=
17429
17430   mp_get_x_next(mp); mp_scan_suffix(mp); 
17431   mp->old_setting=mp->selector; mp->selector=new_string;
17432   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17433   mp_flush_token_list(mp, mp->cur_exp);
17434   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17435   mp->cur_type=mp_string_type;
17436   goto DONE;
17437 }
17438
17439 @ If an internal quantity appears all by itself on the left of an
17440 assignment, we return a token list of length one, containing the address
17441 of the internal quantity plus |hash_end|. (This accords with the conventions
17442 of the save stack, as described earlier.)
17443
17444 @<Scan an internal...@>=
17445
17446   q=mp->cur_mod;
17447   if ( my_var_flag==assignment ) {
17448     mp_get_x_next(mp);
17449     if ( mp->cur_cmd==assignment ) {
17450       mp->cur_exp=mp_get_avail(mp);
17451       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17452       goto DONE;
17453     }
17454     mp_back_input(mp);
17455   }
17456   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17457 }
17458
17459 @ The most difficult part of |scan_primary| has been saved for last, since
17460 it was necessary to build up some confidence first. We can now face the task
17461 of scanning a variable.
17462
17463 As we scan a variable, we build a token list containing the relevant
17464 names and subscript values, simultaneously following along in the
17465 ``collective'' structure to see if we are actually dealing with a macro
17466 instead of a value.
17467
17468 The local variables |pre_head| and |post_head| will point to the beginning
17469 of the prefix and suffix lists; |tail| will point to the end of the list
17470 that is currently growing.
17471
17472 Another local variable, |tt|, contains partial information about the
17473 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17474 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17475 doesn't bother to update its information about type. And if
17476 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17477
17478 @ @<Other local variables for |scan_primary|@>=
17479 pointer pre_head,post_head,tail;
17480   /* prefix and suffix list variables */
17481 small_number tt; /* approximation to the type of the variable-so-far */
17482 pointer t; /* a token */
17483 pointer macro_ref = 0; /* reference count for a suffixed macro */
17484
17485 @ @<Scan a variable primary...@>=
17486
17487   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17488   while (1) { 
17489     t=mp_cur_tok(mp); link(tail)=t;
17490     if ( tt!=undefined ) {
17491        @<Find the approximate type |tt| and corresponding~|q|@>;
17492       if ( tt>=mp_unsuffixed_macro ) {
17493         @<Either begin an unsuffixed macro call or
17494           prepare for a suffixed one@>;
17495       }
17496     }
17497     mp_get_x_next(mp); tail=t;
17498     if ( mp->cur_cmd==left_bracket ) {
17499       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17500     }
17501     if ( mp->cur_cmd>max_suffix_token ) break;
17502     if ( mp->cur_cmd<min_suffix_token ) break;
17503   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17504   @<Handle unusual cases that masquerade as variables, and |goto restart|
17505     or |goto done| if appropriate;
17506     otherwise make a copy of the variable and |goto done|@>;
17507 }
17508
17509 @ @<Either begin an unsuffixed macro call or...@>=
17510
17511   link(tail)=null;
17512   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17513     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17514     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17515   } else {
17516     @<Set up unsuffixed macro call and |goto restart|@>;
17517   }
17518 }
17519
17520 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17521
17522   mp_get_x_next(mp); mp_scan_expression(mp);
17523   if ( mp->cur_cmd!=right_bracket ) {
17524     @<Put the left bracket and the expression back to be rescanned@>;
17525   } else { 
17526     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17527     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17528   }
17529 }
17530
17531 @ The left bracket that we thought was introducing a subscript might have
17532 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17533 So we don't issue an error message at this point; but we do want to back up
17534 so as to avoid any embarrassment about our incorrect assumption.
17535
17536 @<Put the left bracket and the expression back to be rescanned@>=
17537
17538   mp_back_input(mp); /* that was the token following the current expression */
17539   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17540   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17541 }
17542
17543 @ Here's a routine that puts the current expression back to be read again.
17544
17545 @c void mp_back_expr (MP mp) {
17546   pointer p; /* capsule token */
17547   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17548 }
17549
17550 @ Unknown subscripts lead to the following error message.
17551
17552 @c void mp_bad_subscript (MP mp) { 
17553   exp_err("Improper subscript has been replaced by zero");
17554 @.Improper subscript...@>
17555   help3("A bracketed subscript must have a known numeric value;")
17556     ("unfortunately, what I found was the value that appears just")
17557     ("above this error message. So I'll try a zero subscript.");
17558   mp_flush_error(mp, 0);
17559 }
17560
17561 @ Every time we call |get_x_next|, there's a chance that the variable we've
17562 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17563 into the variable structure; we need to start searching from the root each time.
17564
17565 @<Find the approximate type |tt| and corresponding~|q|@>=
17566 @^inner loop@>
17567
17568   p=link(pre_head); q=info(p); tt=undefined;
17569   if ( eq_type(q) % outer_tag==tag_token ) {
17570     q=equiv(q);
17571     if ( q==null ) goto DONE2;
17572     while (1) { 
17573       p=link(p);
17574       if ( p==null ) {
17575         tt=type(q); goto DONE2;
17576       };
17577       if ( type(q)!=mp_structured ) goto DONE2;
17578       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17579       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17580         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17581         if ( attr_loc(q)>info(p) ) goto DONE2;
17582       }
17583     }
17584   }
17585 DONE2:
17586   ;
17587 }
17588
17589 @ How do things stand now? Well, we have scanned an entire variable name,
17590 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17591 |cur_sym| represent the token that follows. If |post_head=null|, a
17592 token list for this variable name starts at |link(pre_head)|, with all
17593 subscripts evaluated. But if |post_head<>null|, the variable turned out
17594 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17595 |post_head| is the head of a token list containing both `\.{\AT!}' and
17596 the suffix.
17597
17598 Our immediate problem is to see if this variable still exists. (Variable
17599 structures can change drastically whenever we call |get_x_next|; users
17600 aren't supposed to do this, but the fact that it is possible means that
17601 we must be cautious.)
17602
17603 The following procedure prints an error message when a variable
17604 unexpectedly disappears. Its help message isn't quite right for
17605 our present purposes, but we'll be able to fix that up.
17606
17607 @c 
17608 void mp_obliterated (MP mp,pointer q) { 
17609   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17610   mp_print(mp, " has been obliterated");
17611 @.Variable...obliterated@>
17612   help5("It seems you did a nasty thing---probably by accident,")
17613     ("but nevertheless you nearly hornswoggled me...")
17614     ("While I was evaluating the right-hand side of this")
17615     ("command, something happened, and the left-hand side")
17616     ("is no longer a variable! So I won't change anything.");
17617 }
17618
17619 @ If the variable does exist, we also need to check
17620 for a few other special cases before deciding that a plain old ordinary
17621 variable has, indeed, been scanned.
17622
17623 @<Handle unusual cases that masquerade as variables...@>=
17624 if ( post_head!=null ) {
17625   @<Set up suffixed macro call and |goto restart|@>;
17626 }
17627 q=link(pre_head); free_avail(pre_head);
17628 if ( mp->cur_cmd==my_var_flag ) { 
17629   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17630 }
17631 p=mp_find_variable(mp, q);
17632 if ( p!=null ) {
17633   mp_make_exp_copy(mp, p);
17634 } else { 
17635   mp_obliterated(mp, q);
17636   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17637   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17638   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17639   mp_put_get_flush_error(mp, 0);
17640 }
17641 mp_flush_node_list(mp, q); 
17642 goto DONE
17643
17644 @ The only complication associated with macro calling is that the prefix
17645 and ``at'' parameters must be packaged in an appropriate list of lists.
17646
17647 @<Set up unsuffixed macro call and |goto restart|@>=
17648
17649   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17650   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17651   mp_get_x_next(mp); 
17652   goto RESTART;
17653 }
17654
17655 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17656 we don't care, because we have reserved a pointer (|macro_ref|) to its
17657 token list.
17658
17659 @<Set up suffixed macro call and |goto restart|@>=
17660
17661   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17662   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17663   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17664   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17665   mp_get_x_next(mp); goto RESTART;
17666 }
17667
17668 @ Our remaining job is simply to make a copy of the value that has been
17669 found. Some cases are harder than others, but complexity arises solely
17670 because of the multiplicity of possible cases.
17671
17672 @<Declare the procedure called |make_exp_copy|@>=
17673 @<Declare subroutines needed by |make_exp_copy|@>;
17674 void mp_make_exp_copy (MP mp,pointer p) {
17675   pointer q,r,t; /* registers for list manipulation */
17676 RESTART: 
17677   mp->cur_type=type(p);
17678   switch (mp->cur_type) {
17679   case mp_vacuous: case mp_boolean_type: case mp_known:
17680     mp->cur_exp=value(p); break;
17681   case unknown_types:
17682     mp->cur_exp=mp_new_ring_entry(mp, p);
17683     break;
17684   case mp_string_type: 
17685     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17686     break;
17687   case mp_picture_type:
17688     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17689     break;
17690   case mp_pen_type:
17691     mp->cur_exp=copy_pen(value(p));
17692     break; 
17693   case mp_path_type:
17694     mp->cur_exp=mp_copy_path(mp, value(p));
17695     break;
17696   case mp_transform_type: case mp_color_type: 
17697   case mp_cmykcolor_type: case mp_pair_type:
17698     @<Copy the big node |p|@>;
17699     break;
17700   case mp_dependent: case mp_proto_dependent:
17701     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17702     break;
17703   case mp_numeric_type: 
17704     new_indep(p); goto RESTART;
17705     break;
17706   case mp_independent: 
17707     q=mp_single_dependency(mp, p);
17708     if ( q==mp->dep_final ){ 
17709       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17710     } else { 
17711       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17712     }
17713     break;
17714   default: 
17715     mp_confusion(mp, "copy");
17716 @:this can't happen copy}{\quad copy@>
17717     break;
17718   }
17719 }
17720
17721 @ The |encapsulate| subroutine assumes that |dep_final| is the
17722 tail of dependency list~|p|.
17723
17724 @<Declare subroutines needed by |make_exp_copy|@>=
17725 void mp_encapsulate (MP mp,pointer p) { 
17726   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17727   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17728 }
17729
17730 @ The most tedious case arises when the user refers to a
17731 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17732 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17733 or |known|.
17734
17735 @<Copy the big node |p|@>=
17736
17737   if ( value(p)==null ) 
17738     mp_init_big_node(mp, p);
17739   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17740   mp_init_big_node(mp, t);
17741   q=value(p)+mp->big_node_size[mp->cur_type]; 
17742   r=value(t)+mp->big_node_size[mp->cur_type];
17743   do {  
17744     q=q-2; r=r-2; mp_install(mp, r,q);
17745   } while (q!=value(p));
17746   mp->cur_exp=t;
17747 }
17748
17749 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17750 a big node that will be part of a capsule.
17751
17752 @<Declare subroutines needed by |make_exp_copy|@>=
17753 void mp_install (MP mp,pointer r, pointer q) {
17754   pointer p; /* temporary register */
17755   if ( type(q)==mp_known ){ 
17756     value(r)=value(q); type(r)=mp_known;
17757   } else  if ( type(q)==mp_independent ) {
17758     p=mp_single_dependency(mp, q);
17759     if ( p==mp->dep_final ) {
17760       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17761     } else  { 
17762       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17763     }
17764   } else {
17765     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17766   }
17767 }
17768
17769 @ Expressions of the form `\.{a[b,c]}' are converted into
17770 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17771 provided that \.a is numeric.
17772
17773 @<Scan a mediation...@>=
17774
17775   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17776   if ( mp->cur_cmd!=comma ) {
17777     @<Put the left bracket and the expression back...@>;
17778     mp_unstash_cur_exp(mp, p);
17779   } else { 
17780     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17781     if ( mp->cur_cmd!=right_bracket ) {
17782       mp_missing_err(mp, "]");
17783 @.Missing `]'@>
17784       help3("I've scanned an expression of the form `a[b,c',")
17785       ("so a right bracket should have come next.")
17786       ("I shall pretend that one was there.");
17787       mp_back_error(mp);
17788     }
17789     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17790     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17791     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17792   }
17793 }
17794
17795 @ Here is a comparatively simple routine that is used to scan the
17796 \&{suffix} parameters of a macro.
17797
17798 @<Declare the basic parsing subroutines@>=
17799 void mp_scan_suffix (MP mp) {
17800   pointer h,t; /* head and tail of the list being built */
17801   pointer p; /* temporary register */
17802   h=mp_get_avail(mp); t=h;
17803   while (1) { 
17804     if ( mp->cur_cmd==left_bracket ) {
17805       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17806     }
17807     if ( mp->cur_cmd==numeric_token ) {
17808       p=mp_new_num_tok(mp, mp->cur_mod);
17809     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17810        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17811     } else {
17812       break;
17813     }
17814     link(t)=p; t=p; mp_get_x_next(mp);
17815   }
17816   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17817 }
17818
17819 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17820
17821   mp_get_x_next(mp); mp_scan_expression(mp);
17822   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17823   if ( mp->cur_cmd!=right_bracket ) {
17824      mp_missing_err(mp, "]");
17825 @.Missing `]'@>
17826     help3("I've seen a `[' and a subscript value, in a suffix,")
17827       ("so a right bracket should have come next.")
17828       ("I shall pretend that one was there.");
17829     mp_back_error(mp);
17830   }
17831   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17832 }
17833
17834 @* \[38] Parsing secondary and higher expressions.
17835
17836 After the intricacies of |scan_primary|\kern-1pt,
17837 the |scan_secondary| routine is
17838 refreshingly simple. It's not trivial, but the operations are relatively
17839 straightforward; the main difficulty is, again, that expressions and data
17840 structures might change drastically every time we call |get_x_next|, so a
17841 cautious approach is mandatory. For example, a macro defined by
17842 \&{primarydef} might have disappeared by the time its second argument has
17843 been scanned; we solve this by increasing the reference count of its token
17844 list, so that the macro can be called even after it has been clobbered.
17845
17846 @<Declare the basic parsing subroutines@>=
17847 void mp_scan_secondary (MP mp) {
17848   pointer p; /* for list manipulation */
17849   halfword c,d; /* operation codes or modifiers */
17850   pointer mac_name; /* token defined with \&{primarydef} */
17851 RESTART:
17852   if ((mp->cur_cmd<min_primary_command)||
17853       (mp->cur_cmd>max_primary_command) )
17854     mp_bad_exp(mp, "A secondary");
17855 @.A secondary expression...@>
17856   mp_scan_primary(mp);
17857 CONTINUE: 
17858   if ( mp->cur_cmd<=max_secondary_command )
17859     if ( mp->cur_cmd>=min_secondary_command ) {
17860       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17861       if ( d==secondary_primary_macro ) { 
17862         mac_name=mp->cur_sym; add_mac_ref(c);
17863      }
17864      mp_get_x_next(mp); mp_scan_primary(mp);
17865      if ( d!=secondary_primary_macro ) {
17866        mp_do_binary(mp, p,c);
17867      } else  { 
17868        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17869        decr(ref_count(c)); mp_get_x_next(mp); 
17870        goto RESTART;
17871     }
17872     goto CONTINUE;
17873   }
17874 }
17875
17876 @ The following procedure calls a macro that has two parameters,
17877 |p| and |cur_exp|.
17878
17879 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17880   pointer q,r; /* nodes in the parameter list */
17881   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17882   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17883   mp_macro_call(mp, c,q,n);
17884 }
17885
17886 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17887
17888 @<Declare the basic parsing subroutines@>=
17889 void mp_scan_tertiary (MP mp) {
17890   pointer p; /* for list manipulation */
17891   halfword c,d; /* operation codes or modifiers */
17892   pointer mac_name; /* token defined with \&{secondarydef} */
17893 RESTART:
17894   if ((mp->cur_cmd<min_primary_command)||
17895       (mp->cur_cmd>max_primary_command) )
17896     mp_bad_exp(mp, "A tertiary");
17897 @.A tertiary expression...@>
17898   mp_scan_secondary(mp);
17899 CONTINUE: 
17900   if ( mp->cur_cmd<=max_tertiary_command ) {
17901     if ( mp->cur_cmd>=min_tertiary_command ) {
17902       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17903       if ( d==tertiary_secondary_macro ) { 
17904         mac_name=mp->cur_sym; add_mac_ref(c);
17905       };
17906       mp_get_x_next(mp); mp_scan_secondary(mp);
17907       if ( d!=tertiary_secondary_macro ) {
17908         mp_do_binary(mp, p,c);
17909       } else { 
17910         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17911         decr(ref_count(c)); mp_get_x_next(mp); 
17912         goto RESTART;
17913       }
17914       goto CONTINUE;
17915     }
17916   }
17917 }
17918
17919 @ Finally we reach the deepest level in our quartet of parsing routines.
17920 This one is much like the others; but it has an extra complication from
17921 paths, which materialize here.
17922
17923 @d continue_path 25 /* a label inside of |scan_expression| */
17924 @d finish_path 26 /* another */
17925
17926 @<Declare the basic parsing subroutines@>=
17927 void mp_scan_expression (MP mp) {
17928   pointer p,q,r,pp,qq; /* for list manipulation */
17929   halfword c,d; /* operation codes or modifiers */
17930   int my_var_flag; /* initial value of |var_flag| */
17931   pointer mac_name; /* token defined with \&{tertiarydef} */
17932   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17933   scaled x,y; /* explicit coordinates or tension at a path join */
17934   int t; /* knot type following a path join */
17935   t=0; y=0; x=0;
17936   my_var_flag=mp->var_flag; mac_name=null;
17937 RESTART:
17938   if ((mp->cur_cmd<min_primary_command)||
17939       (mp->cur_cmd>max_primary_command) )
17940     mp_bad_exp(mp, "An");
17941 @.An expression...@>
17942   mp_scan_tertiary(mp);
17943 CONTINUE: 
17944   if ( mp->cur_cmd<=max_expression_command )
17945     if ( mp->cur_cmd>=min_expression_command ) {
17946       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17947         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17948         if ( d==expression_tertiary_macro ) {
17949           mac_name=mp->cur_sym; add_mac_ref(c);
17950         }
17951         if ( (d<ampersand)||((d==ampersand)&&
17952              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17953           @<Scan a path construction operation;
17954             but |return| if |p| has the wrong type@>;
17955         } else { 
17956           mp_get_x_next(mp); mp_scan_tertiary(mp);
17957           if ( d!=expression_tertiary_macro ) {
17958             mp_do_binary(mp, p,c);
17959           } else  { 
17960             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17961             decr(ref_count(c)); mp_get_x_next(mp); 
17962             goto RESTART;
17963           }
17964         }
17965         goto CONTINUE;
17966      }
17967   }
17968 }
17969
17970 @ The reader should review the data structure conventions for paths before
17971 hoping to understand the next part of this code.
17972
17973 @<Scan a path construction operation...@>=
17974
17975   cycle_hit=false;
17976   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17977     but |return| if |p| doesn't have a suitable type@>;
17978 CONTINUE_PATH: 
17979   @<Determine the path join parameters;
17980     but |goto finish_path| if there's only a direction specifier@>;
17981   if ( mp->cur_cmd==cycle ) {
17982     @<Get ready to close a cycle@>;
17983   } else { 
17984     mp_scan_tertiary(mp);
17985     @<Convert the right operand, |cur_exp|,
17986       into a partial path from |pp| to~|qq|@>;
17987   }
17988   @<Join the partial paths and reset |p| and |q| to the head and tail
17989     of the result@>;
17990   if ( mp->cur_cmd>=min_expression_command )
17991     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17992 FINISH_PATH:
17993   @<Choose control points for the path and put the result into |cur_exp|@>;
17994 }
17995
17996 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17997
17998   mp_unstash_cur_exp(mp, p);
17999   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18000   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18001   else return;
18002   q=p;
18003   while ( link(q)!=p ) q=link(q);
18004   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
18005     r=mp_copy_knot(mp, p); link(q)=r; q=r;
18006   }
18007   left_type(p)=mp_open; right_type(q)=mp_open;
18008 }
18009
18010 @ A pair of numeric values is changed into a knot node for a one-point path
18011 when \MP\ discovers that the pair is part of a path.
18012
18013 @c@<Declare the procedure called |known_pair|@>;
18014 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18015   pointer q; /* the new node */
18016   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18017   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18018   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18019   return q;
18020 }
18021
18022 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18023 of the current expression, assuming that the current expression is a
18024 pair of known numerics. Unknown components are zeroed, and the
18025 current expression is flushed.
18026
18027 @<Declare the procedure called |known_pair|@>=
18028 void mp_known_pair (MP mp) {
18029   pointer p; /* the pair node */
18030   if ( mp->cur_type!=mp_pair_type ) {
18031     exp_err("Undefined coordinates have been replaced by (0,0)");
18032 @.Undefined coordinates...@>
18033     help5("I need x and y numbers for this part of the path.")
18034       ("The value I found (see above) was no good;")
18035       ("so I'll try to keep going by using zero instead.")
18036       ("(Chapter 27 of The METAFONTbook explains that")
18037 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18038       ("you might want to type `I ??" "?' now.)");
18039     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18040   } else { 
18041     p=value(mp->cur_exp);
18042      @<Make sure that both |x| and |y| parts of |p| are known;
18043        copy them into |cur_x| and |cur_y|@>;
18044     mp_flush_cur_exp(mp, 0);
18045   }
18046 }
18047
18048 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18049 if ( type(x_part_loc(p))==mp_known ) {
18050   mp->cur_x=value(x_part_loc(p));
18051 } else { 
18052   mp_disp_err(mp, x_part_loc(p),
18053     "Undefined x coordinate has been replaced by 0");
18054 @.Undefined coordinates...@>
18055   help5("I need a `known' x value for this part of the path.")
18056     ("The value I found (see above) was no good;")
18057     ("so I'll try to keep going by using zero instead.")
18058     ("(Chapter 27 of The METAFONTbook explains that")
18059 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18060     ("you might want to type `I ??" "?' now.)");
18061   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18062 }
18063 if ( type(y_part_loc(p))==mp_known ) {
18064   mp->cur_y=value(y_part_loc(p));
18065 } else { 
18066   mp_disp_err(mp, y_part_loc(p),
18067     "Undefined y coordinate has been replaced by 0");
18068   help5("I need a `known' y value for this part of the path.")
18069     ("The value I found (see above) was no good;")
18070     ("so I'll try to keep going by using zero instead.")
18071     ("(Chapter 27 of The METAFONTbook explains that")
18072     ("you might want to type `I ??" "?' now.)");
18073   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18074 }
18075
18076 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18077
18078 @<Determine the path join parameters...@>=
18079 if ( mp->cur_cmd==left_brace ) {
18080   @<Put the pre-join direction information into node |q|@>;
18081 }
18082 d=mp->cur_cmd;
18083 if ( d==path_join ) {
18084   @<Determine the tension and/or control points@>;
18085 } else if ( d!=ampersand ) {
18086   goto FINISH_PATH;
18087 }
18088 mp_get_x_next(mp);
18089 if ( mp->cur_cmd==left_brace ) {
18090   @<Put the post-join direction information into |x| and |t|@>;
18091 } else if ( right_type(q)!=mp_explicit ) {
18092   t=mp_open; x=0;
18093 }
18094
18095 @ The |scan_direction| subroutine looks at the directional information
18096 that is enclosed in braces, and also scans ahead to the following character.
18097 A type code is returned, either |open| (if the direction was $(0,0)$),
18098 or |curl| (if the direction was a curl of known value |cur_exp|), or
18099 |given| (if the direction is given by the |angle| value that now
18100 appears in |cur_exp|).
18101
18102 There's nothing difficult about this subroutine, but the program is rather
18103 lengthy because a variety of potential errors need to be nipped in the bud.
18104
18105 @c small_number mp_scan_direction (MP mp) {
18106   int t; /* the type of information found */
18107   scaled x; /* an |x| coordinate */
18108   mp_get_x_next(mp);
18109   if ( mp->cur_cmd==curl_command ) {
18110      @<Scan a curl specification@>;
18111   } else {
18112     @<Scan a given direction@>;
18113   }
18114   if ( mp->cur_cmd!=right_brace ) {
18115     mp_missing_err(mp, "}");
18116 @.Missing `\char`\}'@>
18117     help3("I've scanned a direction spec for part of a path,")
18118       ("so a right brace should have come next.")
18119       ("I shall pretend that one was there.");
18120     mp_back_error(mp);
18121   }
18122   mp_get_x_next(mp); 
18123   return t;
18124 }
18125
18126 @ @<Scan a curl specification@>=
18127 { mp_get_x_next(mp); mp_scan_expression(mp);
18128 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18129   exp_err("Improper curl has been replaced by 1");
18130 @.Improper curl@>
18131   help1("A curl must be a known, nonnegative number.");
18132   mp_put_get_flush_error(mp, unity);
18133 }
18134 t=mp_curl;
18135 }
18136
18137 @ @<Scan a given direction@>=
18138 { mp_scan_expression(mp);
18139   if ( mp->cur_type>mp_pair_type ) {
18140     @<Get given directions separated by commas@>;
18141   } else {
18142     mp_known_pair(mp);
18143   }
18144   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18145   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18146 }
18147
18148 @ @<Get given directions separated by commas@>=
18149
18150   if ( mp->cur_type!=mp_known ) {
18151     exp_err("Undefined x coordinate has been replaced by 0");
18152 @.Undefined coordinates...@>
18153     help5("I need a `known' x value for this part of the path.")
18154       ("The value I found (see above) was no good;")
18155       ("so I'll try to keep going by using zero instead.")
18156       ("(Chapter 27 of The METAFONTbook explains that")
18157 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18158       ("you might want to type `I ??" "?' now.)");
18159     mp_put_get_flush_error(mp, 0);
18160   }
18161   x=mp->cur_exp;
18162   if ( mp->cur_cmd!=comma ) {
18163     mp_missing_err(mp, ",");
18164 @.Missing `,'@>
18165     help2("I've got the x coordinate of a path direction;")
18166       ("will look for the y coordinate next.");
18167     mp_back_error(mp);
18168   }
18169   mp_get_x_next(mp); mp_scan_expression(mp);
18170   if ( mp->cur_type!=mp_known ) {
18171      exp_err("Undefined y coordinate has been replaced by 0");
18172     help5("I need a `known' y value for this part of the path.")
18173       ("The value I found (see above) was no good;")
18174       ("so I'll try to keep going by using zero instead.")
18175       ("(Chapter 27 of The METAFONTbook explains that")
18176       ("you might want to type `I ??" "?' now.)");
18177     mp_put_get_flush_error(mp, 0);
18178   }
18179   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18180 }
18181
18182 @ At this point |right_type(q)| is usually |open|, but it may have been
18183 set to some other value by a previous splicing operation. We must maintain
18184 the value of |right_type(q)| in unusual cases such as
18185 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18186
18187 @<Put the pre-join...@>=
18188
18189   t=mp_scan_direction(mp);
18190   if ( t!=mp_open ) {
18191     right_type(q)=t; right_given(q)=mp->cur_exp;
18192     if ( left_type(q)==mp_open ) {
18193       left_type(q)=t; left_given(q)=mp->cur_exp;
18194     } /* note that |left_given(q)=left_curl(q)| */
18195   }
18196 }
18197
18198 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18199 and since |left_given| is similarly equivalent to |left_x|, we use
18200 |x| and |y| to hold the given direction and tension information when
18201 there are no explicit control points.
18202
18203 @<Put the post-join...@>=
18204
18205   t=mp_scan_direction(mp);
18206   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18207   else t=mp_explicit; /* the direction information is superfluous */
18208 }
18209
18210 @ @<Determine the tension and/or...@>=
18211
18212   mp_get_x_next(mp);
18213   if ( mp->cur_cmd==tension ) {
18214     @<Set explicit tensions@>;
18215   } else if ( mp->cur_cmd==controls ) {
18216     @<Set explicit control points@>;
18217   } else  { 
18218     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18219     goto DONE;
18220   };
18221   if ( mp->cur_cmd!=path_join ) {
18222      mp_missing_err(mp, "..");
18223 @.Missing `..'@>
18224     help1("A path join command should end with two dots.");
18225     mp_back_error(mp);
18226   }
18227 DONE:
18228   ;
18229 }
18230
18231 @ @<Set explicit tensions@>=
18232
18233   mp_get_x_next(mp); y=mp->cur_cmd;
18234   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18235   mp_scan_primary(mp);
18236   @<Make sure that the current expression is a valid tension setting@>;
18237   if ( y==at_least ) negate(mp->cur_exp);
18238   right_tension(q)=mp->cur_exp;
18239   if ( mp->cur_cmd==and_command ) {
18240     mp_get_x_next(mp); y=mp->cur_cmd;
18241     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18242     mp_scan_primary(mp);
18243     @<Make sure that the current expression is a valid tension setting@>;
18244     if ( y==at_least ) negate(mp->cur_exp);
18245   }
18246   y=mp->cur_exp;
18247 }
18248
18249 @ @d min_tension three_quarter_unit
18250
18251 @<Make sure that the current expression is a valid tension setting@>=
18252 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18253   exp_err("Improper tension has been set to 1");
18254 @.Improper tension@>
18255   help1("The expression above should have been a number >=3/4.");
18256   mp_put_get_flush_error(mp, unity);
18257 }
18258
18259 @ @<Set explicit control points@>=
18260
18261   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18262   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18263   if ( mp->cur_cmd!=and_command ) {
18264     x=right_x(q); y=right_y(q);
18265   } else { 
18266     mp_get_x_next(mp); mp_scan_primary(mp);
18267     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18268   }
18269 }
18270
18271 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18272
18273   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18274   else pp=mp->cur_exp;
18275   qq=pp;
18276   while ( link(qq)!=pp ) qq=link(qq);
18277   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18278     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18279   }
18280   left_type(pp)=mp_open; right_type(qq)=mp_open;
18281 }
18282
18283 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18284 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18285 shouldn't have length zero.
18286
18287 @<Get ready to close a cycle@>=
18288
18289   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18290   if ( d==ampersand ) if ( p==q ) {
18291     d=path_join; right_tension(q)=unity; y=unity;
18292   }
18293 }
18294
18295 @ @<Join the partial paths and reset |p| and |q|...@>=
18296
18297 if ( d==ampersand ) {
18298   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18299     print_err("Paths don't touch; `&' will be changed to `..'");
18300 @.Paths don't touch@>
18301     help3("When you join paths `p&q', the ending point of p")
18302       ("must be exactly equal to the starting point of q.")
18303       ("So I'm going to pretend that you said `p..q' instead.");
18304     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18305   }
18306 }
18307 @<Plug an opening in |right_type(pp)|, if possible@>;
18308 if ( d==ampersand ) {
18309   @<Splice independent paths together@>;
18310 } else  { 
18311   @<Plug an opening in |right_type(q)|, if possible@>;
18312   link(q)=pp; left_y(pp)=y;
18313   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18314 }
18315 q=qq;
18316 }
18317
18318 @ @<Plug an opening in |right_type(q)|...@>=
18319 if ( right_type(q)==mp_open ) {
18320   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18321     right_type(q)=left_type(q); right_given(q)=left_given(q);
18322   }
18323 }
18324
18325 @ @<Plug an opening in |right_type(pp)|...@>=
18326 if ( right_type(pp)==mp_open ) {
18327   if ( (t==mp_curl)||(t==mp_given) ) {
18328     right_type(pp)=t; right_given(pp)=x;
18329   }
18330 }
18331
18332 @ @<Splice independent paths together@>=
18333
18334   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18335     left_type(q)=mp_curl; left_curl(q)=unity;
18336   }
18337   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18338     right_type(pp)=mp_curl; right_curl(pp)=unity;
18339   }
18340   right_type(q)=right_type(pp); link(q)=link(pp);
18341   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18342   mp_free_node(mp, pp,knot_node_size);
18343   if ( qq==pp ) qq=q;
18344 }
18345
18346 @ @<Choose control points for the path...@>=
18347 if ( cycle_hit ) { 
18348   if ( d==ampersand ) p=q;
18349 } else  { 
18350   left_type(p)=mp_endpoint;
18351   if ( right_type(p)==mp_open ) { 
18352     right_type(p)=mp_curl; right_curl(p)=unity;
18353   }
18354   right_type(q)=mp_endpoint;
18355   if ( left_type(q)==mp_open ) { 
18356     left_type(q)=mp_curl; left_curl(q)=unity;
18357   }
18358   link(q)=p;
18359 }
18360 mp_make_choices(mp, p);
18361 mp->cur_type=mp_path_type; mp->cur_exp=p
18362
18363 @ Finally, we sometimes need to scan an expression whose value is
18364 supposed to be either |true_code| or |false_code|.
18365
18366 @<Declare the basic parsing subroutines@>=
18367 void mp_get_boolean (MP mp) { 
18368   mp_get_x_next(mp); mp_scan_expression(mp);
18369   if ( mp->cur_type!=mp_boolean_type ) {
18370     exp_err("Undefined condition will be treated as `false'");
18371 @.Undefined condition...@>
18372     help2("The expression shown above should have had a definite")
18373       ("true-or-false value. I'm changing it to `false'.");
18374     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18375   }
18376 }
18377
18378 @* \[39] Doing the operations.
18379 The purpose of parsing is primarily to permit people to avoid piles of
18380 parentheses. But the real work is done after the structure of an expression
18381 has been recognized; that's when new expressions are generated. We
18382 turn now to the guts of \MP, which handles individual operators that
18383 have come through the parsing mechanism.
18384
18385 We'll start with the easy ones that take no operands, then work our way
18386 up to operators with one and ultimately two arguments. In other words,
18387 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18388 that are invoked periodically by the expression scanners.
18389
18390 First let's make sure that all of the primitive operators are in the
18391 hash table. Although |scan_primary| and its relatives made use of the
18392 \\{cmd} code for these operators, the \\{do} routines base everything
18393 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18394 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18395
18396 @<Put each...@>=
18397 mp_primitive(mp, "true",nullary,true_code);
18398 @:true_}{\&{true} primitive@>
18399 mp_primitive(mp, "false",nullary,false_code);
18400 @:false_}{\&{false} primitive@>
18401 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18402 @:null_picture_}{\&{nullpicture} primitive@>
18403 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18404 @:null_pen_}{\&{nullpen} primitive@>
18405 mp_primitive(mp, "jobname",nullary,job_name_op);
18406 @:job_name_}{\&{jobname} primitive@>
18407 mp_primitive(mp, "readstring",nullary,read_string_op);
18408 @:read_string_}{\&{readstring} primitive@>
18409 mp_primitive(mp, "pencircle",nullary,pen_circle);
18410 @:pen_circle_}{\&{pencircle} primitive@>
18411 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18412 @:normal_deviate_}{\&{normaldeviate} primitive@>
18413 mp_primitive(mp, "readfrom",unary,read_from_op);
18414 @:read_from_}{\&{readfrom} primitive@>
18415 mp_primitive(mp, "closefrom",unary,close_from_op);
18416 @:close_from_}{\&{closefrom} primitive@>
18417 mp_primitive(mp, "odd",unary,odd_op);
18418 @:odd_}{\&{odd} primitive@>
18419 mp_primitive(mp, "known",unary,known_op);
18420 @:known_}{\&{known} primitive@>
18421 mp_primitive(mp, "unknown",unary,unknown_op);
18422 @:unknown_}{\&{unknown} primitive@>
18423 mp_primitive(mp, "not",unary,not_op);
18424 @:not_}{\&{not} primitive@>
18425 mp_primitive(mp, "decimal",unary,decimal);
18426 @:decimal_}{\&{decimal} primitive@>
18427 mp_primitive(mp, "reverse",unary,reverse);
18428 @:reverse_}{\&{reverse} primitive@>
18429 mp_primitive(mp, "makepath",unary,make_path_op);
18430 @:make_path_}{\&{makepath} primitive@>
18431 mp_primitive(mp, "makepen",unary,make_pen_op);
18432 @:make_pen_}{\&{makepen} primitive@>
18433 mp_primitive(mp, "oct",unary,oct_op);
18434 @:oct_}{\&{oct} primitive@>
18435 mp_primitive(mp, "hex",unary,hex_op);
18436 @:hex_}{\&{hex} primitive@>
18437 mp_primitive(mp, "ASCII",unary,ASCII_op);
18438 @:ASCII_}{\&{ASCII} primitive@>
18439 mp_primitive(mp, "char",unary,char_op);
18440 @:char_}{\&{char} primitive@>
18441 mp_primitive(mp, "length",unary,length_op);
18442 @:length_}{\&{length} primitive@>
18443 mp_primitive(mp, "turningnumber",unary,turning_op);
18444 @:turning_number_}{\&{turningnumber} primitive@>
18445 mp_primitive(mp, "xpart",unary,x_part);
18446 @:x_part_}{\&{xpart} primitive@>
18447 mp_primitive(mp, "ypart",unary,y_part);
18448 @:y_part_}{\&{ypart} primitive@>
18449 mp_primitive(mp, "xxpart",unary,xx_part);
18450 @:xx_part_}{\&{xxpart} primitive@>
18451 mp_primitive(mp, "xypart",unary,xy_part);
18452 @:xy_part_}{\&{xypart} primitive@>
18453 mp_primitive(mp, "yxpart",unary,yx_part);
18454 @:yx_part_}{\&{yxpart} primitive@>
18455 mp_primitive(mp, "yypart",unary,yy_part);
18456 @:yy_part_}{\&{yypart} primitive@>
18457 mp_primitive(mp, "redpart",unary,red_part);
18458 @:red_part_}{\&{redpart} primitive@>
18459 mp_primitive(mp, "greenpart",unary,green_part);
18460 @:green_part_}{\&{greenpart} primitive@>
18461 mp_primitive(mp, "bluepart",unary,blue_part);
18462 @:blue_part_}{\&{bluepart} primitive@>
18463 mp_primitive(mp, "cyanpart",unary,cyan_part);
18464 @:cyan_part_}{\&{cyanpart} primitive@>
18465 mp_primitive(mp, "magentapart",unary,magenta_part);
18466 @:magenta_part_}{\&{magentapart} primitive@>
18467 mp_primitive(mp, "yellowpart",unary,yellow_part);
18468 @:yellow_part_}{\&{yellowpart} primitive@>
18469 mp_primitive(mp, "blackpart",unary,black_part);
18470 @:black_part_}{\&{blackpart} primitive@>
18471 mp_primitive(mp, "greypart",unary,grey_part);
18472 @:grey_part_}{\&{greypart} primitive@>
18473 mp_primitive(mp, "colormodel",unary,color_model_part);
18474 @:color_model_part_}{\&{colormodel} primitive@>
18475 mp_primitive(mp, "fontpart",unary,font_part);
18476 @:font_part_}{\&{fontpart} primitive@>
18477 mp_primitive(mp, "textpart",unary,text_part);
18478 @:text_part_}{\&{textpart} primitive@>
18479 mp_primitive(mp, "pathpart",unary,path_part);
18480 @:path_part_}{\&{pathpart} primitive@>
18481 mp_primitive(mp, "penpart",unary,pen_part);
18482 @:pen_part_}{\&{penpart} primitive@>
18483 mp_primitive(mp, "dashpart",unary,dash_part);
18484 @:dash_part_}{\&{dashpart} primitive@>
18485 mp_primitive(mp, "sqrt",unary,sqrt_op);
18486 @:sqrt_}{\&{sqrt} primitive@>
18487 mp_primitive(mp, "mexp",unary,m_exp_op);
18488 @:m_exp_}{\&{mexp} primitive@>
18489 mp_primitive(mp, "mlog",unary,m_log_op);
18490 @:m_log_}{\&{mlog} primitive@>
18491 mp_primitive(mp, "sind",unary,sin_d_op);
18492 @:sin_d_}{\&{sind} primitive@>
18493 mp_primitive(mp, "cosd",unary,cos_d_op);
18494 @:cos_d_}{\&{cosd} primitive@>
18495 mp_primitive(mp, "floor",unary,floor_op);
18496 @:floor_}{\&{floor} primitive@>
18497 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18498 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18499 mp_primitive(mp, "charexists",unary,char_exists_op);
18500 @:char_exists_}{\&{charexists} primitive@>
18501 mp_primitive(mp, "fontsize",unary,font_size);
18502 @:font_size_}{\&{fontsize} primitive@>
18503 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18504 @:ll_corner_}{\&{llcorner} primitive@>
18505 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18506 @:lr_corner_}{\&{lrcorner} primitive@>
18507 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18508 @:ul_corner_}{\&{ulcorner} primitive@>
18509 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18510 @:ur_corner_}{\&{urcorner} primitive@>
18511 mp_primitive(mp, "arclength",unary,arc_length);
18512 @:arc_length_}{\&{arclength} primitive@>
18513 mp_primitive(mp, "angle",unary,angle_op);
18514 @:angle_}{\&{angle} primitive@>
18515 mp_primitive(mp, "cycle",cycle,cycle_op);
18516 @:cycle_}{\&{cycle} primitive@>
18517 mp_primitive(mp, "stroked",unary,stroked_op);
18518 @:stroked_}{\&{stroked} primitive@>
18519 mp_primitive(mp, "filled",unary,filled_op);
18520 @:filled_}{\&{filled} primitive@>
18521 mp_primitive(mp, "textual",unary,textual_op);
18522 @:textual_}{\&{textual} primitive@>
18523 mp_primitive(mp, "clipped",unary,clipped_op);
18524 @:clipped_}{\&{clipped} primitive@>
18525 mp_primitive(mp, "bounded",unary,bounded_op);
18526 @:bounded_}{\&{bounded} primitive@>
18527 mp_primitive(mp, "+",plus_or_minus,plus);
18528 @:+ }{\.{+} primitive@>
18529 mp_primitive(mp, "-",plus_or_minus,minus);
18530 @:- }{\.{-} primitive@>
18531 mp_primitive(mp, "*",secondary_binary,times);
18532 @:* }{\.{*} primitive@>
18533 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18534 @:/ }{\.{/} primitive@>
18535 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18536 @:++_}{\.{++} primitive@>
18537 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18538 @:+-+_}{\.{+-+} primitive@>
18539 mp_primitive(mp, "or",tertiary_binary,or_op);
18540 @:or_}{\&{or} primitive@>
18541 mp_primitive(mp, "and",and_command,and_op);
18542 @:and_}{\&{and} primitive@>
18543 mp_primitive(mp, "<",expression_binary,less_than);
18544 @:< }{\.{<} primitive@>
18545 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18546 @:<=_}{\.{<=} primitive@>
18547 mp_primitive(mp, ">",expression_binary,greater_than);
18548 @:> }{\.{>} primitive@>
18549 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18550 @:>=_}{\.{>=} primitive@>
18551 mp_primitive(mp, "=",equals,equal_to);
18552 @:= }{\.{=} primitive@>
18553 mp_primitive(mp, "<>",expression_binary,unequal_to);
18554 @:<>_}{\.{<>} primitive@>
18555 mp_primitive(mp, "substring",primary_binary,substring_of);
18556 @:substring_}{\&{substring} primitive@>
18557 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18558 @:subpath_}{\&{subpath} primitive@>
18559 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18560 @:direction_time_}{\&{directiontime} primitive@>
18561 mp_primitive(mp, "point",primary_binary,point_of);
18562 @:point_}{\&{point} primitive@>
18563 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18564 @:precontrol_}{\&{precontrol} primitive@>
18565 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18566 @:postcontrol_}{\&{postcontrol} primitive@>
18567 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18568 @:pen_offset_}{\&{penoffset} primitive@>
18569 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18570 @:arc_time_of_}{\&{arctime} primitive@>
18571 mp_primitive(mp, "mpversion",nullary,mp_version);
18572 @:mp_verison_}{\&{mpversion} primitive@>
18573 mp_primitive(mp, "&",ampersand,concatenate);
18574 @:!!!}{\.{\&} primitive@>
18575 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18576 @:rotated_}{\&{rotated} primitive@>
18577 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18578 @:slanted_}{\&{slanted} primitive@>
18579 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18580 @:scaled_}{\&{scaled} primitive@>
18581 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18582 @:shifted_}{\&{shifted} primitive@>
18583 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18584 @:transformed_}{\&{transformed} primitive@>
18585 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18586 @:x_scaled_}{\&{xscaled} primitive@>
18587 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18588 @:y_scaled_}{\&{yscaled} primitive@>
18589 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18590 @:z_scaled_}{\&{zscaled} primitive@>
18591 mp_primitive(mp, "infont",secondary_binary,in_font);
18592 @:in_font_}{\&{infont} primitive@>
18593 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18594 @:intersection_times_}{\&{intersectiontimes} primitive@>
18595 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18596 @:envelope_}{\&{envelope} primitive@>
18597
18598 @ @<Cases of |print_cmd...@>=
18599 case nullary:
18600 case unary:
18601 case primary_binary:
18602 case secondary_binary:
18603 case tertiary_binary:
18604 case expression_binary:
18605 case cycle:
18606 case plus_or_minus:
18607 case slash:
18608 case ampersand:
18609 case equals:
18610 case and_command:
18611   mp_print_op(mp, m);
18612   break;
18613
18614 @ OK, let's look at the simplest \\{do} procedure first.
18615
18616 @c @<Declare nullary action procedure@>;
18617 void mp_do_nullary (MP mp,quarterword c) { 
18618   check_arith;
18619   if ( mp->internal[mp_tracing_commands]>two )
18620     mp_show_cmd_mod(mp, nullary,c);
18621   switch (c) {
18622   case true_code: case false_code: 
18623     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18624     break;
18625   case null_picture_code: 
18626     mp->cur_type=mp_picture_type;
18627     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18628     mp_init_edges(mp, mp->cur_exp);
18629     break;
18630   case null_pen_code: 
18631     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18632     break;
18633   case normal_deviate: 
18634     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18635     break;
18636   case pen_circle: 
18637     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18638     break;
18639   case job_name_op:  
18640     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18641     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18642     break;
18643   case mp_version: 
18644     mp->cur_type=mp_string_type; 
18645     mp->cur_exp=intern(metapost_version) ;
18646     break;
18647   case read_string_op:
18648     @<Read a string from the terminal@>;
18649     break;
18650   } /* there are no other cases */
18651   check_arith;
18652 }
18653
18654 @ @<Read a string...@>=
18655
18656   if ( mp->interaction<=mp_nonstop_mode )
18657     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18658   mp_begin_file_reading(mp); name=is_read;
18659   limit=start; prompt_input("");
18660   mp_finish_read(mp);
18661 }
18662
18663 @ @<Declare nullary action procedure@>=
18664 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18665   size_t k;
18666   str_room((int)mp->last-start);
18667   for (k=start;k<=mp->last-1;k++) {
18668    append_char(mp->buffer[k]);
18669   }
18670   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18671   mp->cur_exp=mp_make_string(mp);
18672 }
18673
18674 @ Things get a bit more interesting when there's an operand. The
18675 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18676
18677 @c @<Declare unary action procedures@>;
18678 void mp_do_unary (MP mp,quarterword c) {
18679   pointer p,q,r; /* for list manipulation */
18680   integer x; /* a temporary register */
18681   check_arith;
18682   if ( mp->internal[mp_tracing_commands]>two )
18683     @<Trace the current unary operation@>;
18684   switch (c) {
18685   case plus:
18686     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18687     break;
18688   case minus:
18689     @<Negate the current expression@>;
18690     break;
18691   @<Additional cases of unary operators@>;
18692   } /* there are no other cases */
18693   check_arith;
18694 };
18695
18696 @ The |nice_pair| function returns |true| if both components of a pair
18697 are known.
18698
18699 @<Declare unary action procedures@>=
18700 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18701   if ( t==mp_pair_type ) {
18702     p=value(p);
18703     if ( type(x_part_loc(p))==mp_known )
18704       if ( type(y_part_loc(p))==mp_known )
18705         return true;
18706   }
18707   return false;
18708 }
18709
18710 @ The |nice_color_or_pair| function is analogous except that it also accepts
18711 fully known colors.
18712
18713 @<Declare unary action procedures@>=
18714 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18715   pointer q,r; /* for scanning the big node */
18716   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18717     return false;
18718   } else { 
18719     q=value(p);
18720     r=q+mp->big_node_size[type(p)];
18721     do {  
18722       r=r-2;
18723       if ( type(r)!=mp_known )
18724         return false;
18725     } while (r!=q);
18726     return true;
18727   }
18728 }
18729
18730 @ @<Declare unary action...@>=
18731 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18732   mp_print_char(mp, '(');
18733   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18734   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18735     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18736     mp_print_type(mp, t);
18737   }
18738   mp_print_char(mp, ')');
18739 }
18740
18741 @ @<Declare unary action...@>=
18742 void mp_bad_unary (MP mp,quarterword c) { 
18743   exp_err("Not implemented: "); mp_print_op(mp, c);
18744 @.Not implemented...@>
18745   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18746   help3("I'm afraid I don't know how to apply that operation to that")
18747     ("particular type. Continue, and I'll simply return the")
18748     ("argument (shown above) as the result of the operation.");
18749   mp_put_get_error(mp);
18750 }
18751
18752 @ @<Trace the current unary operation@>=
18753
18754   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18755   mp_print_op(mp, c); mp_print_char(mp, '(');
18756   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18757   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18758 }
18759
18760 @ Negation is easy except when the current expression
18761 is of type |independent|, or when it is a pair with one or more
18762 |independent| components.
18763
18764 It is tempting to argue that the negative of an independent variable
18765 is an independent variable, hence we don't have to do anything when
18766 negating it. The fallacy is that other dependent variables pointing
18767 to the current expression must change the sign of their
18768 coefficients if we make no change to the current expression.
18769
18770 Instead, we work around the problem by copying the current expression
18771 and recycling it afterwards (cf.~the |stash_in| routine).
18772
18773 @<Negate the current expression@>=
18774 switch (mp->cur_type) {
18775 case mp_color_type:
18776 case mp_cmykcolor_type:
18777 case mp_pair_type:
18778 case mp_independent: 
18779   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18780   if ( mp->cur_type==mp_dependent ) {
18781     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18782   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18783     p=value(mp->cur_exp);
18784     r=p+mp->big_node_size[mp->cur_type];
18785     do {  
18786       r=r-2;
18787       if ( type(r)==mp_known ) negate(value(r));
18788       else mp_negate_dep_list(mp, dep_list(r));
18789     } while (r!=p);
18790   } /* if |cur_type=mp_known| then |cur_exp=0| */
18791   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18792   break;
18793 case mp_dependent:
18794 case mp_proto_dependent:
18795   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18796   break;
18797 case mp_known:
18798   negate(mp->cur_exp);
18799   break;
18800 default:
18801   mp_bad_unary(mp, minus);
18802   break;
18803 }
18804
18805 @ @<Declare unary action...@>=
18806 void mp_negate_dep_list (MP mp,pointer p) { 
18807   while (1) { 
18808     negate(value(p));
18809     if ( info(p)==null ) return;
18810     p=link(p);
18811   }
18812 }
18813
18814 @ @<Additional cases of unary operators@>=
18815 case not_op: 
18816   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18817   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18818   break;
18819
18820 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18821 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18822
18823 @<Additional cases of unary operators@>=
18824 case sqrt_op:
18825 case m_exp_op:
18826 case m_log_op:
18827 case sin_d_op:
18828 case cos_d_op:
18829 case floor_op:
18830 case  uniform_deviate:
18831 case odd_op:
18832 case char_exists_op:
18833   if ( mp->cur_type!=mp_known ) {
18834     mp_bad_unary(mp, c);
18835   } else {
18836     switch (c) {
18837     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18838     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18839     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18840     case sin_d_op:
18841     case cos_d_op:
18842       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18843       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18844       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18845       break;
18846     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18847     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18848     case odd_op: 
18849       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18850       mp->cur_type=mp_boolean_type;
18851       break;
18852     case char_exists_op:
18853       @<Determine if a character has been shipped out@>;
18854       break;
18855     } /* there are no other cases */
18856   }
18857   break;
18858
18859 @ @<Additional cases of unary operators@>=
18860 case angle_op:
18861   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18862     p=value(mp->cur_exp);
18863     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18864     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18865     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18866   } else {
18867     mp_bad_unary(mp, angle_op);
18868   }
18869   break;
18870
18871 @ If the current expression is a pair, but the context wants it to
18872 be a path, we call |pair_to_path|.
18873
18874 @<Declare unary action...@>=
18875 void mp_pair_to_path (MP mp) { 
18876   mp->cur_exp=mp_new_knot(mp); 
18877   mp->cur_type=mp_path_type;
18878 };
18879
18880 @ @<Additional cases of unary operators@>=
18881 case x_part:
18882 case y_part:
18883   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18884     mp_take_part(mp, c);
18885   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18886   else mp_bad_unary(mp, c);
18887   break;
18888 case xx_part:
18889 case xy_part:
18890 case yx_part:
18891 case yy_part: 
18892   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18893   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18894   else mp_bad_unary(mp, c);
18895   break;
18896 case red_part:
18897 case green_part:
18898 case blue_part: 
18899   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18900   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18901   else mp_bad_unary(mp, c);
18902   break;
18903 case cyan_part:
18904 case magenta_part:
18905 case yellow_part:
18906 case black_part: 
18907   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18908   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18909   else mp_bad_unary(mp, c);
18910   break;
18911 case grey_part: 
18912   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18913   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18914   else mp_bad_unary(mp, c);
18915   break;
18916 case color_model_part: 
18917   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18918   else mp_bad_unary(mp, c);
18919   break;
18920
18921 @ In the following procedure, |cur_exp| points to a capsule, which points to
18922 a big node. We want to delete all but one part of the big node.
18923
18924 @<Declare unary action...@>=
18925 void mp_take_part (MP mp,quarterword c) {
18926   pointer p; /* the big node */
18927   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18928   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18929   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18930   mp_recycle_value(mp, temp_val);
18931 }
18932
18933 @ @<Initialize table entries...@>=
18934 name_type(temp_val)=mp_capsule;
18935
18936 @ @<Additional cases of unary operators@>=
18937 case font_part:
18938 case text_part:
18939 case path_part:
18940 case pen_part:
18941 case dash_part:
18942   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18943   else mp_bad_unary(mp, c);
18944   break;
18945
18946 @ @<Declarations@>=
18947 void mp_scale_edges (MP mp);
18948
18949 @ @<Declare unary action...@>=
18950 void mp_take_pict_part (MP mp,quarterword c) {
18951   pointer p; /* first graphical object in |cur_exp| */
18952   p=link(dummy_loc(mp->cur_exp));
18953   if ( p!=null ) {
18954     switch (c) {
18955     case x_part: case y_part: case xx_part:
18956     case xy_part: case yx_part: case yy_part:
18957       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18958       else goto NOT_FOUND;
18959       break;
18960     case red_part: case green_part: case blue_part:
18961       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18962       else goto NOT_FOUND;
18963       break;
18964     case cyan_part: case magenta_part: case yellow_part:
18965     case black_part:
18966       if ( has_color(p) ) {
18967         if ( color_model(p)==mp_uninitialized_model )
18968           mp_flush_cur_exp(mp, unity);
18969         else
18970           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18971       } else goto NOT_FOUND;
18972       break;
18973     case grey_part:
18974       if ( has_color(p) )
18975           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18976       else goto NOT_FOUND;
18977       break;
18978     case color_model_part:
18979       if ( has_color(p) ) {
18980         if ( color_model(p)==mp_uninitialized_model )
18981           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
18982         else
18983           mp_flush_cur_exp(mp, color_model(p)*unity);
18984       } else goto NOT_FOUND;
18985       break;
18986     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18987     } /* all cases have been enumerated */
18988     return;
18989   };
18990 NOT_FOUND:
18991   @<Convert the current expression to a null value appropriate
18992     for |c|@>;
18993 }
18994
18995 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18996 case text_part: 
18997   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18998   else { 
18999     mp_flush_cur_exp(mp, text_p(p));
19000     add_str_ref(mp->cur_exp);
19001     mp->cur_type=mp_string_type;
19002     };
19003   break;
19004 case font_part: 
19005   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19006   else { 
19007     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
19008     add_str_ref(mp->cur_exp);
19009     mp->cur_type=mp_string_type;
19010   };
19011   break;
19012 case path_part:
19013   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19014   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19015 @:this can't happen pict}{\quad pict@>
19016   else { 
19017     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19018     mp->cur_type=mp_path_type;
19019   }
19020   break;
19021 case pen_part: 
19022   if ( ! has_pen(p) ) goto NOT_FOUND;
19023   else {
19024     if ( pen_p(p)==null ) goto NOT_FOUND;
19025     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19026       mp->cur_type=mp_pen_type;
19027     };
19028   }
19029   break;
19030 case dash_part: 
19031   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19032   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19033     else { add_edge_ref(dash_p(p));
19034     mp->se_sf=dash_scale(p);
19035     mp->se_pic=dash_p(p);
19036     mp_scale_edges(mp);
19037     mp_flush_cur_exp(mp, mp->se_pic);
19038     mp->cur_type=mp_picture_type;
19039     };
19040   }
19041   break;
19042
19043 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19044 parameterless procedure even though it really takes two arguments and updates
19045 one of them.  Hence the following globals are needed.
19046
19047 @<Global...@>=
19048 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19049 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19050
19051 @ @<Convert the current expression to a null value appropriate...@>=
19052 switch (c) {
19053 case text_part: case font_part: 
19054   mp_flush_cur_exp(mp, rts(""));
19055   mp->cur_type=mp_string_type;
19056   break;
19057 case path_part: 
19058   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19059   left_type(mp->cur_exp)=mp_endpoint;
19060   right_type(mp->cur_exp)=mp_endpoint;
19061   link(mp->cur_exp)=mp->cur_exp;
19062   x_coord(mp->cur_exp)=0;
19063   y_coord(mp->cur_exp)=0;
19064   originator(mp->cur_exp)=mp_metapost_user;
19065   mp->cur_type=mp_path_type;
19066   break;
19067 case pen_part: 
19068   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19069   mp->cur_type=mp_pen_type;
19070   break;
19071 case dash_part: 
19072   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19073   mp_init_edges(mp, mp->cur_exp);
19074   mp->cur_type=mp_picture_type;
19075   break;
19076 default: 
19077    mp_flush_cur_exp(mp, 0);
19078   break;
19079 }
19080
19081 @ @<Additional cases of unary...@>=
19082 case char_op: 
19083   if ( mp->cur_type!=mp_known ) { 
19084     mp_bad_unary(mp, char_op);
19085   } else { 
19086     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19087     mp->cur_type=mp_string_type;
19088     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19089   }
19090   break;
19091 case decimal: 
19092   if ( mp->cur_type!=mp_known ) {
19093      mp_bad_unary(mp, decimal);
19094   } else { 
19095     mp->old_setting=mp->selector; mp->selector=new_string;
19096     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19097     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19098   }
19099   break;
19100 case oct_op:
19101 case hex_op:
19102 case ASCII_op: 
19103   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19104   else mp_str_to_num(mp, c);
19105   break;
19106 case font_size: 
19107   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19108   else @<Find the design size of the font whose name is |cur_exp|@>;
19109   break;
19110
19111 @ @<Declare unary action...@>=
19112 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19113   integer n; /* accumulator */
19114   ASCII_code m; /* current character */
19115   pool_pointer k; /* index into |str_pool| */
19116   int b; /* radix of conversion */
19117   boolean bad_char; /* did the string contain an invalid digit? */
19118   if ( c==ASCII_op ) {
19119     if ( length(mp->cur_exp)==0 ) n=-1;
19120     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19121   } else { 
19122     if ( c==oct_op ) b=8; else b=16;
19123     n=0; bad_char=false;
19124     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19125       m=mp->str_pool[k];
19126       if ( (m>='0')&&(m<='9') ) m=m-'0';
19127       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19128       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19129       else  { bad_char=true; m=0; };
19130       if ( m>=b ) { bad_char=true; m=0; };
19131       if ( n<32768 / b ) n=n*b+m; else n=32767;
19132     }
19133     @<Give error messages if |bad_char| or |n>=4096|@>;
19134   }
19135   mp_flush_cur_exp(mp, n*unity);
19136 }
19137
19138 @ @<Give error messages if |bad_char|...@>=
19139 if ( bad_char ) { 
19140   exp_err("String contains illegal digits");
19141 @.String contains illegal digits@>
19142   if ( c==oct_op ) {
19143     help1("I zeroed out characters that weren't in the range 0..7.");
19144   } else  {
19145     help1("I zeroed out characters that weren't hex digits.");
19146   }
19147   mp_put_get_error(mp);
19148 }
19149 if ( (n>4095) ) {
19150   if ( mp->internal[mp_warning_check]>0 ) {
19151     print_err("Number too large ("); 
19152     mp_print_int(mp, n); mp_print_char(mp, ')');
19153 @.Number too large@>
19154     help2("I have trouble with numbers greater than 4095; watch out.")
19155       ("(Set warningcheck:=0 to suppress this message.)");
19156     mp_put_get_error(mp);
19157   }
19158 }
19159
19160 @ The length operation is somewhat unusual in that it applies to a variety
19161 of different types of operands.
19162
19163 @<Additional cases of unary...@>=
19164 case length_op: 
19165   switch (mp->cur_type) {
19166   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19167   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19168   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19169   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19170   default: 
19171     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19172       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19173         value(x_part_loc(value(mp->cur_exp))),
19174         value(y_part_loc(value(mp->cur_exp)))));
19175     else mp_bad_unary(mp, c);
19176     break;
19177   }
19178   break;
19179
19180 @ @<Declare unary action...@>=
19181 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19182   scaled n; /* the path length so far */
19183   pointer p; /* traverser */
19184   p=mp->cur_exp;
19185   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19186   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19187   return n;
19188 }
19189
19190 @ @<Declare unary action...@>=
19191 scaled mp_pict_length (MP mp) { 
19192   /* counts interior components in picture |cur_exp| */
19193   scaled n; /* the count so far */
19194   pointer p; /* traverser */
19195   n=0;
19196   p=link(dummy_loc(mp->cur_exp));
19197   if ( p!=null ) {
19198     if ( is_start_or_stop(p) )
19199       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19200     while ( p!=null )  { 
19201       skip_component(p) return n; 
19202       n=n+unity;   
19203     }
19204   }
19205   return n;
19206 }
19207
19208 @ Implement |turningnumber|
19209
19210 @<Additional cases of unary...@>=
19211 case turning_op:
19212   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19213   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19214   else if ( left_type(mp->cur_exp)==mp_endpoint )
19215      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19216   else
19217     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19218   break;
19219
19220 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19221 argument is |origin|.
19222
19223 @<Declare unary action...@>=
19224 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19225   if ( (! ((xpar==0) && (ypar==0))) )
19226     return mp_n_arg(mp, xpar,ypar);
19227   return 0;
19228 }
19229
19230
19231 @ The actual turning number is (for the moment) computed in a C function
19232 that receives eight integers corresponding to the four controlling points,
19233 and returns a single angle.  Besides those, we have to account for discrete
19234 moves at the actual points.
19235
19236 @d floor(a) (a>=0 ? a : -(int)(-a))
19237 @d bezier_error (720<<20)+1
19238 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19239 @d print_roots(a) 
19240 @d out ((double)(xo>>20))
19241 @d mid ((double)(xm>>20))
19242 @d in  ((double)(xi>>20))
19243 @d divisor (256*256)
19244 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19245
19246 @<Declare unary action...@>=
19247 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19248             integer CX,integer CY,integer DX,integer DY);
19249
19250 @ @c 
19251 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19252             integer CX,integer CY,integer DX,integer DY) {
19253   double a, b, c;
19254   integer deltax,deltay;
19255   double ax,ay,bx,by,cx,cy,dx,dy;
19256   angle xi = 0, xo = 0, xm = 0;
19257   double res = 0;
19258   ax=AX/divisor;  ay=AY/divisor;
19259   bx=BX/divisor;  by=BY/divisor;
19260   cx=CX/divisor;  cy=CY/divisor;
19261   dx=DX/divisor;  dy=DY/divisor;
19262
19263   deltax = (BX-AX); deltay = (BY-AY);
19264   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19265   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19266   xi = mp_an_angle(mp,deltax,deltay);
19267
19268   deltax = (CX-BX); deltay = (CY-BY);
19269   xm = mp_an_angle(mp,deltax,deltay);
19270
19271   deltax = (DX-CX); deltay = (DY-CY);
19272   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19273   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19274   xo = mp_an_angle(mp,deltax,deltay);
19275
19276   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19277   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19278   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19279
19280   if ((a==0)&&(c==0)) {
19281     res = (b==0 ?  0 :  (out-in)); 
19282     print_roots("no roots (a)");
19283   } else if ((a==0)||(c==0)) {
19284     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19285       res = out-in; /* ? */
19286       if (res<-180.0) 
19287         res += 360.0;
19288       else if (res>180.0)
19289         res -= 360.0;
19290       print_roots("no roots (b)");
19291     } else {
19292       res = out-in; /* ? */
19293       print_roots("one root (a)");
19294     }
19295   } else if ((sign(a)*sign(c))<0) {
19296     res = out-in; /* ? */
19297       if (res<-180.0) 
19298         res += 360.0;
19299       else if (res>180.0)
19300         res -= 360.0;
19301     print_roots("one root (b)");
19302   } else {
19303     if (sign(a) == sign(b)) {
19304       res = out-in; /* ? */
19305       if (res<-180.0) 
19306         res += 360.0;
19307       else if (res>180.0)
19308         res -= 360.0;
19309       print_roots("no roots (d)");
19310     } else {
19311       if ((b*b) == (4*a*c)) {
19312         res = bezier_error;
19313         print_roots("double root"); /* cusp */
19314       } else if ((b*b) < (4*a*c)) {
19315         res = out-in; /* ? */
19316         if (res<=0.0 &&res>-180.0) 
19317           res += 360.0;
19318         else if (res>=0.0 && res<180.0)
19319           res -= 360.0;
19320         print_roots("no roots (e)");
19321       } else {
19322         res = out-in;
19323         if (res<-180.0) 
19324           res += 360.0;
19325         else if (res>180.0)
19326           res -= 360.0;
19327         print_roots("two roots"); /* two inflections */
19328       }
19329     }
19330   }
19331   return double2angle(res);
19332 }
19333
19334 @
19335 @d p_nextnext link(link(p))
19336 @d p_next link(p)
19337 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19338
19339 @<Declare unary action...@>=
19340 scaled mp_new_turn_cycles (MP mp,pointer c) {
19341   angle res,ang; /*  the angles of intermediate results  */
19342   scaled turns;  /*  the turn counter  */
19343   pointer p;     /*  for running around the path  */
19344   integer xp,yp;   /*  coordinates of next point  */
19345   integer x,y;   /*  helper coordinates  */
19346   angle in_angle,out_angle;     /*  helper angles */
19347   int old_setting; /* saved |selector| setting */
19348   res=0;
19349   turns= 0;
19350   p=c;
19351   old_setting = mp->selector; mp->selector=term_only;
19352   if ( mp->internal[mp_tracing_commands]>unity ) {
19353     mp_begin_diagnostic(mp);
19354     mp_print_nl(mp, "");
19355     mp_end_diagnostic(mp, false);
19356   }
19357   do { 
19358     xp = x_coord(p_next); yp = y_coord(p_next);
19359     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19360              left_x(p_next), left_y(p_next), xp, yp);
19361     if ( ang>seven_twenty_deg ) {
19362       print_err("Strange path");
19363       mp_error(mp);
19364       mp->selector=old_setting;
19365       return 0;
19366     }
19367     res  = res + ang;
19368     if ( res > one_eighty_deg ) {
19369       res = res - three_sixty_deg;
19370       turns = turns + unity;
19371     }
19372     if ( res <= -one_eighty_deg ) {
19373       res = res + three_sixty_deg;
19374       turns = turns - unity;
19375     }
19376     /*  incoming angle at next point  */
19377     x = left_x(p_next);  y = left_y(p_next);
19378     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19379     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19380     in_angle = mp_an_angle(mp, xp - x, yp - y);
19381     /*  outgoing angle at next point  */
19382     x = right_x(p_next);  y = right_y(p_next);
19383     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19384     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19385     out_angle = mp_an_angle(mp, x - xp, y- yp);
19386     ang  = (out_angle - in_angle);
19387     reduce_angle(ang);
19388     if ( ang!=0 ) {
19389       res  = res + ang;
19390       if ( res >= one_eighty_deg ) {
19391         res = res - three_sixty_deg;
19392         turns = turns + unity;
19393       };
19394       if ( res <= -one_eighty_deg ) {
19395         res = res + three_sixty_deg;
19396         turns = turns - unity;
19397       };
19398     };
19399     p = link(p);
19400   } while (p!=c);
19401   mp->selector=old_setting;
19402   return turns;
19403 }
19404
19405
19406 @ This code is based on Bogus\l{}av Jackowski's
19407 |emergency_turningnumber| macro, with some minor changes by Taco
19408 Hoekwater. The macro code looked more like this:
19409 {\obeylines
19410 vardef turning\_number primary p =
19411 ~~save res, ang, turns;
19412 ~~res := 0;
19413 ~~if length p <= 2:
19414 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19415 ~~else:
19416 ~~~~for t = 0 upto length p-1 :
19417 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19418 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19419 ~~~~~~if angc > 180: angc := angc - 360; fi;
19420 ~~~~~~if angc < -180: angc := angc + 360; fi;
19421 ~~~~~~res  := res + angc;
19422 ~~~~endfor;
19423 ~~res/360
19424 ~~fi
19425 enddef;}
19426 The general idea is to calculate only the sum of the angles of
19427 straight lines between the points, of a path, not worrying about cusps
19428 or self-intersections in the segments at all. If the segment is not
19429 well-behaved, the result is not necesarily correct. But the old code
19430 was not always correct either, and worse, it sometimes failed for
19431 well-behaved paths as well. All known bugs that were triggered by the
19432 original code no longer occur with this code, and it runs roughly 3
19433 times as fast because the algorithm is much simpler.
19434
19435 @ It is possible to overflow the return value of the |turn_cycles|
19436 function when the path is sufficiently long and winding, but I am not
19437 going to bother testing for that. In any case, it would only return
19438 the looped result value, which is not a big problem.
19439
19440 The macro code for the repeat loop was a bit nicer to look
19441 at than the pascal code, because it could use |point -1 of p|. In
19442 pascal, the fastest way to loop around the path is not to look
19443 backward once, but forward twice. These defines help hide the trick.
19444
19445 @d p_to link(link(p))
19446 @d p_here link(p)
19447 @d p_from p
19448
19449 @<Declare unary action...@>=
19450 scaled mp_turn_cycles (MP mp,pointer c) {
19451   angle res,ang; /*  the angles of intermediate results  */
19452   scaled turns;  /*  the turn counter  */
19453   pointer p;     /*  for running around the path  */
19454   res=0;  turns= 0; p=c;
19455   do { 
19456     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19457                             y_coord(p_to) - y_coord(p_here))
19458         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19459                            y_coord(p_here) - y_coord(p_from));
19460     reduce_angle(ang);
19461     res  = res + ang;
19462     if ( res >= three_sixty_deg )  {
19463       res = res - three_sixty_deg;
19464       turns = turns + unity;
19465     };
19466     if ( res <= -three_sixty_deg ) {
19467       res = res + three_sixty_deg;
19468       turns = turns - unity;
19469     };
19470     p = link(p);
19471   } while (p!=c);
19472   return turns;
19473 }
19474
19475 @ @<Declare unary action...@>=
19476 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19477   scaled nval,oval;
19478   scaled saved_t_o; /* tracing\_online saved  */
19479   if ( (link(c)==c)||(link(link(c))==c) ) {
19480     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19481       return unity;
19482     else
19483       return -unity;
19484   } else {
19485     nval = mp_new_turn_cycles(mp, c);
19486     oval = mp_turn_cycles(mp, c);
19487     if ( nval!=oval ) {
19488       saved_t_o=mp->internal[mp_tracing_online];
19489       mp->internal[mp_tracing_online]=unity;
19490       mp_begin_diagnostic(mp);
19491       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19492                        " The current computed value is ");
19493       mp_print_scaled(mp, nval);
19494       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19495       mp_print_scaled(mp, oval);
19496       mp_end_diagnostic(mp, false);
19497       mp->internal[mp_tracing_online]=saved_t_o;
19498     }
19499     return nval;
19500   }
19501 }
19502
19503 @ @<Declare unary action...@>=
19504 scaled mp_count_turns (MP mp,pointer c) {
19505   pointer p; /* a knot in envelope spec |c| */
19506   integer t; /* total pen offset changes counted */
19507   t=0; p=c;
19508   do {  
19509     t=t+info(p)-zero_off;
19510     p=link(p);
19511   } while (p!=c);
19512   return ((t / 3)*unity);
19513 }
19514
19515 @ @d type_range(A,B) { 
19516   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19517     mp_flush_cur_exp(mp, true_code);
19518   else mp_flush_cur_exp(mp, false_code);
19519   mp->cur_type=mp_boolean_type;
19520   }
19521 @d type_test(A) { 
19522   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19523   else mp_flush_cur_exp(mp, false_code);
19524   mp->cur_type=mp_boolean_type;
19525   }
19526
19527 @<Additional cases of unary operators@>=
19528 case mp_boolean_type: 
19529   type_range(mp_boolean_type,mp_unknown_boolean); break;
19530 case mp_string_type: 
19531   type_range(mp_string_type,mp_unknown_string); break;
19532 case mp_pen_type: 
19533   type_range(mp_pen_type,mp_unknown_pen); break;
19534 case mp_path_type: 
19535   type_range(mp_path_type,mp_unknown_path); break;
19536 case mp_picture_type: 
19537   type_range(mp_picture_type,mp_unknown_picture); break;
19538 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19539 case mp_pair_type: 
19540   type_test(c); break;
19541 case mp_numeric_type: 
19542   type_range(mp_known,mp_independent); break;
19543 case known_op: case unknown_op: 
19544   mp_test_known(mp, c); break;
19545
19546 @ @<Declare unary action procedures@>=
19547 void mp_test_known (MP mp,quarterword c) {
19548   int b; /* is the current expression known? */
19549   pointer p,q; /* locations in a big node */
19550   b=false_code;
19551   switch (mp->cur_type) {
19552   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19553   case mp_pen_type: case mp_path_type: case mp_picture_type:
19554   case mp_known: 
19555     b=true_code;
19556     break;
19557   case mp_transform_type:
19558   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19559     p=value(mp->cur_exp);
19560     q=p+mp->big_node_size[mp->cur_type];
19561     do {  
19562       q=q-2;
19563       if ( type(q)!=mp_known ) 
19564        goto DONE;
19565     } while (q!=p);
19566     b=true_code;
19567   DONE:  
19568     break;
19569   default: 
19570     break;
19571   }
19572   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19573   else mp_flush_cur_exp(mp, true_code+false_code-b);
19574   mp->cur_type=mp_boolean_type;
19575 }
19576
19577 @ @<Additional cases of unary operators@>=
19578 case cycle_op: 
19579   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19580   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19581   else mp_flush_cur_exp(mp, false_code);
19582   mp->cur_type=mp_boolean_type;
19583   break;
19584
19585 @ @<Additional cases of unary operators@>=
19586 case arc_length: 
19587   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19588   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19589   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19590   break;
19591
19592 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19593 object |type|.
19594 @^data structure assumptions@>
19595
19596 @<Additional cases of unary operators@>=
19597 case filled_op:
19598 case stroked_op:
19599 case textual_op:
19600 case clipped_op:
19601 case bounded_op:
19602   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19603   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19604   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19605     mp_flush_cur_exp(mp, true_code);
19606   else mp_flush_cur_exp(mp, false_code);
19607   mp->cur_type=mp_boolean_type;
19608   break;
19609
19610 @ @<Additional cases of unary operators@>=
19611 case make_pen_op: 
19612   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19613   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19614   else { 
19615     mp->cur_type=mp_pen_type;
19616     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19617   };
19618   break;
19619 case make_path_op: 
19620   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19621   else  { 
19622     mp->cur_type=mp_path_type;
19623     mp_make_path(mp, mp->cur_exp);
19624   };
19625   break;
19626 case reverse: 
19627   if ( mp->cur_type==mp_path_type ) {
19628     p=mp_htap_ypoc(mp, mp->cur_exp);
19629     if ( right_type(p)==mp_endpoint ) p=link(p);
19630     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19631   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19632   else mp_bad_unary(mp, reverse);
19633   break;
19634
19635 @ The |pair_value| routine changes the current expression to a
19636 given ordered pair of values.
19637
19638 @<Declare unary action procedures@>=
19639 void mp_pair_value (MP mp,scaled x, scaled y) {
19640   pointer p; /* a pair node */
19641   p=mp_get_node(mp, value_node_size); 
19642   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19643   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19644   p=value(p);
19645   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19646   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19647 }
19648
19649 @ @<Additional cases of unary operators@>=
19650 case ll_corner_op: 
19651   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19652   else mp_pair_value(mp, minx,miny);
19653   break;
19654 case lr_corner_op: 
19655   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19656   else mp_pair_value(mp, maxx,miny);
19657   break;
19658 case ul_corner_op: 
19659   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19660   else mp_pair_value(mp, minx,maxy);
19661   break;
19662 case ur_corner_op: 
19663   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19664   else mp_pair_value(mp, maxx,maxy);
19665   break;
19666
19667 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19668 box of the current expression.  The boolean result is |false| if the expression
19669 has the wrong type.
19670
19671 @<Declare unary action procedures@>=
19672 boolean mp_get_cur_bbox (MP mp) { 
19673   switch (mp->cur_type) {
19674   case mp_picture_type: 
19675     mp_set_bbox(mp, mp->cur_exp,true);
19676     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19677       minx=0; maxx=0; miny=0; maxy=0;
19678     } else { 
19679       minx=minx_val(mp->cur_exp);
19680       maxx=maxx_val(mp->cur_exp);
19681       miny=miny_val(mp->cur_exp);
19682       maxy=maxy_val(mp->cur_exp);
19683     }
19684     break;
19685   case mp_path_type: 
19686     mp_path_bbox(mp, mp->cur_exp);
19687     break;
19688   case mp_pen_type: 
19689     mp_pen_bbox(mp, mp->cur_exp);
19690     break;
19691   default: 
19692     return false;
19693   }
19694   return true;
19695 }
19696
19697 @ @<Additional cases of unary operators@>=
19698 case read_from_op:
19699 case close_from_op: 
19700   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19701   else mp_do_read_or_close(mp,c);
19702   break;
19703
19704 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19705 a line from the file or to close the file.
19706
19707 @<Declare unary action procedures@>=
19708 void mp_do_read_or_close (MP mp,quarterword c) {
19709   readf_index n,n0; /* indices for searching |rd_fname| */
19710   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19711     call |start_read_input| and |goto found| or |not_found|@>;
19712   mp_begin_file_reading(mp);
19713   name=is_read;
19714   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19715     goto FOUND;
19716   mp_end_file_reading(mp);
19717 NOT_FOUND:
19718   @<Record the end of file and set |cur_exp| to a dummy value@>;
19719   return;
19720 CLOSE_FILE:
19721   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19722   return;
19723 FOUND:
19724   mp_flush_cur_exp(mp, 0);
19725   mp_finish_read(mp);
19726 }
19727
19728 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19729 |rd_fname|.
19730
19731 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19732 {   
19733   char *fn;
19734   n=mp->read_files;
19735   n0=mp->read_files;
19736   fn = str(mp->cur_exp);
19737   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19738     if ( n>0 ) {
19739       decr(n);
19740     } else if ( c==close_from_op ) {
19741       goto CLOSE_FILE;
19742     } else {
19743       if ( n0==mp->read_files ) {
19744         if ( mp->read_files<mp->max_read_files ) {
19745           incr(mp->read_files);
19746         } else {
19747           void **rd_file;
19748           char **rd_fname;
19749               readf_index l,k;
19750           l = mp->max_read_files + (mp->max_read_files>>2);
19751           rd_file = xmalloc((l+1), sizeof(void *));
19752           rd_fname = xmalloc((l+1), sizeof(char *));
19753               for (k=0;k<=l;k++) {
19754             if (k<=mp->max_read_files) {
19755                   rd_file[k]=mp->rd_file[k]; 
19756               rd_fname[k]=mp->rd_fname[k];
19757             } else {
19758               rd_file[k]=0; 
19759               rd_fname[k]=NULL;
19760             }
19761           }
19762               xfree(mp->rd_file); xfree(mp->rd_fname);
19763           mp->max_read_files = l;
19764           mp->rd_file = rd_file;
19765           mp->rd_fname = rd_fname;
19766         }
19767       }
19768       n=n0;
19769       if ( mp_start_read_input(mp,fn,n) ) 
19770         goto FOUND;
19771       else 
19772         goto NOT_FOUND;
19773     }
19774     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19775   } 
19776   if ( c==close_from_op ) { 
19777     (mp->close_file)(mp->rd_file[n]); 
19778     goto NOT_FOUND; 
19779   }
19780 }
19781
19782 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19783 xfree(mp->rd_fname[n]);
19784 mp->rd_fname[n]=NULL;
19785 if ( n==mp->read_files-1 ) mp->read_files=n;
19786 if ( c==close_from_op ) 
19787   goto CLOSE_FILE;
19788 mp_flush_cur_exp(mp, mp->eof_line);
19789 mp->cur_type=mp_string_type
19790
19791 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19792
19793 @<Glob...@>=
19794 str_number eof_line;
19795
19796 @ @<Set init...@>=
19797 mp->eof_line=0;
19798
19799 @ Finally, we have the operations that combine a capsule~|p|
19800 with the current expression.
19801
19802 @c @<Declare binary action procedures@>;
19803 void mp_do_binary (MP mp,pointer p, quarterword c) {
19804   pointer q,r,rr; /* for list manipulation */
19805   pointer old_p,old_exp; /* capsules to recycle */
19806   integer v; /* for numeric manipulation */
19807   check_arith;
19808   if ( mp->internal[mp_tracing_commands]>two ) {
19809     @<Trace the current binary operation@>;
19810   }
19811   @<Sidestep |independent| cases in capsule |p|@>;
19812   @<Sidestep |independent| cases in the current expression@>;
19813   switch (c) {
19814   case plus: case minus:
19815     @<Add or subtract the current expression from |p|@>;
19816     break;
19817   @<Additional cases of binary operators@>;
19818   }; /* there are no other cases */
19819   mp_recycle_value(mp, p); 
19820   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19821   check_arith; 
19822   @<Recycle any sidestepped |independent| capsules@>;
19823 }
19824
19825 @ @<Declare binary action...@>=
19826 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19827   mp_disp_err(mp, p,"");
19828   exp_err("Not implemented: ");
19829 @.Not implemented...@>
19830   if ( c>=min_of ) mp_print_op(mp, c);
19831   mp_print_known_or_unknown_type(mp, type(p),p);
19832   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19833   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
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 void mp_bad_envelope_pen (MP mp) {
19840   mp_disp_err(mp, null,"");
19841   exp_err("Not implemented: envelope(elliptical pen)of(path)");
19842 @.Not implemented...@>
19843   help3("I'm afraid I don't know how to apply that operation to that")
19844        ("combination of types. Continue, and I'll return the second")
19845       ("argument (see above) as the result of the operation.");
19846   mp_put_get_error(mp);
19847 }
19848
19849 @ @<Trace the current binary operation@>=
19850
19851   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19852   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19853   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19854   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19855   mp_end_diagnostic(mp, false);
19856 }
19857
19858 @ Several of the binary operations are potentially complicated by the
19859 fact that |independent| values can sneak into capsules. For example,
19860 we've seen an instance of this difficulty in the unary operation
19861 of negation. In order to reduce the number of cases that need to be
19862 handled, we first change the two operands (if necessary)
19863 to rid them of |independent| components. The original operands are
19864 put into capsules called |old_p| and |old_exp|, which will be
19865 recycled after the binary operation has been safely carried out.
19866
19867 @<Recycle any sidestepped |independent| capsules@>=
19868 if ( old_p!=null ) { 
19869   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19870 }
19871 if ( old_exp!=null ) {
19872   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19873 }
19874
19875 @ A big node is considered to be ``tarnished'' if it contains at least one
19876 independent component. We will define a simple function called `|tarnished|'
19877 that returns |null| if and only if its argument is not tarnished.
19878
19879 @<Sidestep |independent| cases in capsule |p|@>=
19880 switch (type(p)) {
19881 case mp_transform_type:
19882 case mp_color_type:
19883 case mp_cmykcolor_type:
19884 case mp_pair_type: 
19885   old_p=mp_tarnished(mp, p);
19886   break;
19887 case mp_independent: old_p=mp_void; break;
19888 default: old_p=null; break;
19889 };
19890 if ( old_p!=null ) {
19891   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19892   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19893 }
19894
19895 @ @<Sidestep |independent| cases in the current expression@>=
19896 switch (mp->cur_type) {
19897 case mp_transform_type:
19898 case mp_color_type:
19899 case mp_cmykcolor_type:
19900 case mp_pair_type: 
19901   old_exp=mp_tarnished(mp, mp->cur_exp);
19902   break;
19903 case mp_independent:old_exp=mp_void; break;
19904 default: old_exp=null; break;
19905 };
19906 if ( old_exp!=null ) {
19907   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19908 }
19909
19910 @ @<Declare binary action...@>=
19911 pointer mp_tarnished (MP mp,pointer p) {
19912   pointer q; /* beginning of the big node */
19913   pointer r; /* current position in the big node */
19914   q=value(p); r=q+mp->big_node_size[type(p)];
19915   do {  
19916    r=r-2;
19917    if ( type(r)==mp_independent ) return mp_void; 
19918   } while (r!=q);
19919   return null;
19920 }
19921
19922 @ @<Add or subtract the current expression from |p|@>=
19923 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19924   mp_bad_binary(mp, p,c);
19925 } else  {
19926   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19927     mp_add_or_subtract(mp, p,null,c);
19928   } else {
19929     if ( mp->cur_type!=type(p) )  {
19930       mp_bad_binary(mp, p,c);
19931     } else { 
19932       q=value(p); r=value(mp->cur_exp);
19933       rr=r+mp->big_node_size[mp->cur_type];
19934       while ( r<rr ) { 
19935         mp_add_or_subtract(mp, q,r,c);
19936         q=q+2; r=r+2;
19937       }
19938     }
19939   }
19940 }
19941
19942 @ The first argument to |add_or_subtract| is the location of a value node
19943 in a capsule or pair node that will soon be recycled. The second argument
19944 is either a location within a pair or transform node of |cur_exp|,
19945 or it is null (which means that |cur_exp| itself should be the second
19946 argument).  The third argument is either |plus| or |minus|.
19947
19948 The sum or difference of the numeric quantities will replace the second
19949 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19950 be monkeying around with really big values.
19951
19952 @<Declare binary action...@>=
19953 @<Declare the procedure called |dep_finish|@>;
19954 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19955   small_number s,t; /* operand types */
19956   pointer r; /* list traverser */
19957   integer v; /* second operand value */
19958   if ( q==null ) { 
19959     t=mp->cur_type;
19960     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19961   } else { 
19962     t=type(q);
19963     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19964   }
19965   if ( t==mp_known ) {
19966     if ( c==minus ) negate(v);
19967     if ( type(p)==mp_known ) {
19968       v=mp_slow_add(mp, value(p),v);
19969       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19970       return;
19971     }
19972     @<Add a known value to the constant term of |dep_list(p)|@>;
19973   } else  { 
19974     if ( c==minus ) mp_negate_dep_list(mp, v);
19975     @<Add operand |p| to the dependency list |v|@>;
19976   }
19977 }
19978
19979 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19980 r=dep_list(p);
19981 while ( info(r)!=null ) r=link(r);
19982 value(r)=mp_slow_add(mp, value(r),v);
19983 if ( q==null ) {
19984   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19985   name_type(q)=mp_capsule;
19986 }
19987 dep_list(q)=dep_list(p); type(q)=type(p);
19988 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19989 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19990
19991 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19992 nice to retain the extra accuracy of |fraction| coefficients.
19993 But we have to handle both kinds, and mixtures too.
19994
19995 @<Add operand |p| to the dependency list |v|@>=
19996 if ( type(p)==mp_known ) {
19997   @<Add the known |value(p)| to the constant term of |v|@>;
19998 } else { 
19999   s=type(p); r=dep_list(p);
20000   if ( t==mp_dependent ) {
20001     if ( s==mp_dependent ) {
20002       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20003         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20004       } /* |fix_needed| will necessarily be false */
20005       t=mp_proto_dependent; 
20006       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20007     }
20008     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20009     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20010  DONE:  
20011     @<Output the answer, |v| (which might have become |known|)@>;
20012   }
20013
20014 @ @<Add the known |value(p)| to the constant term of |v|@>=
20015
20016   while ( info(v)!=null ) v=link(v);
20017   value(v)=mp_slow_add(mp, value(p),value(v));
20018 }
20019
20020 @ @<Output the answer, |v| (which might have become |known|)@>=
20021 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20022 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20023
20024 @ Here's the current situation: The dependency list |v| of type |t|
20025 should either be put into the current expression (if |q=null|) or
20026 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20027 or |q|) formerly held a dependency list with the same
20028 final pointer as the list |v|.
20029
20030 @<Declare the procedure called |dep_finish|@>=
20031 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20032   pointer p; /* the destination */
20033   scaled vv; /* the value, if it is |known| */
20034   if ( q==null ) p=mp->cur_exp; else p=q;
20035   dep_list(p)=v; type(p)=t;
20036   if ( info(v)==null ) { 
20037     vv=value(v);
20038     if ( q==null ) { 
20039       mp_flush_cur_exp(mp, vv);
20040     } else  { 
20041       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20042     }
20043   } else if ( q==null ) {
20044     mp->cur_type=t;
20045   }
20046   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20047 }
20048
20049 @ Let's turn now to the six basic relations of comparison.
20050
20051 @<Additional cases of binary operators@>=
20052 case less_than: case less_or_equal: case greater_than:
20053 case greater_or_equal: case equal_to: case unequal_to:
20054   check_arith; /* at this point |arith_error| should be |false|? */
20055   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20056     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20057   } else if ( mp->cur_type!=type(p) ) {
20058     mp_bad_binary(mp, p,c); goto DONE; 
20059   } else if ( mp->cur_type==mp_string_type ) {
20060     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20061   } else if ((mp->cur_type==mp_unknown_string)||
20062            (mp->cur_type==mp_unknown_boolean) ) {
20063     @<Check if unknowns have been equated@>;
20064   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20065     @<Reduce comparison of big nodes to comparison of scalars@>;
20066   } else if ( mp->cur_type==mp_boolean_type ) {
20067     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20068   } else { 
20069     mp_bad_binary(mp, p,c); goto DONE;
20070   }
20071   @<Compare the current expression with zero@>;
20072 DONE:  
20073   mp->arith_error=false; /* ignore overflow in comparisons */
20074   break;
20075
20076 @ @<Compare the current expression with zero@>=
20077 if ( mp->cur_type!=mp_known ) {
20078   if ( mp->cur_type<mp_known ) {
20079     mp_disp_err(mp, p,"");
20080     help1("The quantities shown above have not been equated.")
20081   } else  {
20082     help2("Oh dear. I can\'t decide if the expression above is positive,")
20083      ("negative, or zero. So this comparison test won't be `true'.");
20084   }
20085   exp_err("Unknown relation will be considered false");
20086 @.Unknown relation...@>
20087   mp_put_get_flush_error(mp, false_code);
20088 } else {
20089   switch (c) {
20090   case less_than: boolean_reset(mp->cur_exp<0); break;
20091   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20092   case greater_than: boolean_reset(mp->cur_exp>0); break;
20093   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20094   case equal_to: boolean_reset(mp->cur_exp==0); break;
20095   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20096   }; /* there are no other cases */
20097 }
20098 mp->cur_type=mp_boolean_type
20099
20100 @ When two unknown strings are in the same ring, we know that they are
20101 equal. Otherwise, we don't know whether they are equal or not, so we
20102 make no change.
20103
20104 @<Check if unknowns have been equated@>=
20105
20106   q=value(mp->cur_exp);
20107   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20108   if ( q==p ) mp_flush_cur_exp(mp, 0);
20109 }
20110
20111 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20112
20113   q=value(p); r=value(mp->cur_exp);
20114   rr=r+mp->big_node_size[mp->cur_type]-2;
20115   while (1) { mp_add_or_subtract(mp, q,r,minus);
20116     if ( type(r)!=mp_known ) break;
20117     if ( value(r)!=0 ) break;
20118     if ( r==rr ) break;
20119     q=q+2; r=r+2;
20120   }
20121   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20122 }
20123
20124 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20125
20126 @<Additional cases of binary operators@>=
20127 case and_op:
20128 case or_op: 
20129   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20130     mp_bad_binary(mp, p,c);
20131   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20132   break;
20133
20134 @ @<Additional cases of binary operators@>=
20135 case times: 
20136   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20137    mp_bad_binary(mp, p,times);
20138   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20139     @<Multiply when at least one operand is known@>;
20140   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20141       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20142           (type(p)>mp_pair_type)) ) {
20143     mp_hard_times(mp, p); return;
20144   } else {
20145     mp_bad_binary(mp, p,times);
20146   }
20147   break;
20148
20149 @ @<Multiply when at least one operand is known@>=
20150
20151   if ( type(p)==mp_known ) {
20152     v=value(p); mp_free_node(mp, p,value_node_size); 
20153   } else {
20154     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20155   }
20156   if ( mp->cur_type==mp_known ) {
20157     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20158   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20159               (mp->cur_type==mp_cmykcolor_type) ) {
20160     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20161     do {  
20162        p=p-2; mp_dep_mult(mp, p,v,true);
20163     } while (p!=value(mp->cur_exp));
20164   } else {
20165     mp_dep_mult(mp, null,v,true);
20166   }
20167   return;
20168 }
20169
20170 @ @<Declare binary action...@>=
20171 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20172   pointer q; /* the dependency list being multiplied by |v| */
20173   small_number s,t; /* its type, before and after */
20174   if ( p==null ) {
20175     q=mp->cur_exp;
20176   } else if ( type(p)!=mp_known ) {
20177     q=p;
20178   } else { 
20179     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20180     else value(p)=mp_take_fraction(mp, value(p),v);
20181     return;
20182   };
20183   t=type(q); q=dep_list(q); s=t;
20184   if ( t==mp_dependent ) if ( v_is_scaled )
20185     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20186       t=mp_proto_dependent;
20187   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20188   mp_dep_finish(mp, q,p,t);
20189 }
20190
20191 @ Here is a routine that is similar to |times|; but it is invoked only
20192 internally, when |v| is a |fraction| whose magnitude is at most~1,
20193 and when |cur_type>=mp_color_type|.
20194
20195 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20196   /* multiplies |cur_exp| by |n/d| */
20197   pointer p; /* a pair node */
20198   pointer old_exp; /* a capsule to recycle */
20199   fraction v; /* |n/d| */
20200   if ( mp->internal[mp_tracing_commands]>two ) {
20201     @<Trace the fraction multiplication@>;
20202   }
20203   switch (mp->cur_type) {
20204   case mp_transform_type:
20205   case mp_color_type:
20206   case mp_cmykcolor_type:
20207   case mp_pair_type:
20208    old_exp=mp_tarnished(mp, mp->cur_exp);
20209    break;
20210   case mp_independent: old_exp=mp_void; break;
20211   default: old_exp=null; break;
20212   }
20213   if ( old_exp!=null ) { 
20214      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20215   }
20216   v=mp_make_fraction(mp, n,d);
20217   if ( mp->cur_type==mp_known ) {
20218     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20219   } else if ( mp->cur_type<=mp_pair_type ) { 
20220     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20221     do {  
20222       p=p-2;
20223       mp_dep_mult(mp, p,v,false);
20224     } while (p!=value(mp->cur_exp));
20225   } else {
20226     mp_dep_mult(mp, null,v,false);
20227   }
20228   if ( old_exp!=null ) {
20229     mp_recycle_value(mp, old_exp); 
20230     mp_free_node(mp, old_exp,value_node_size);
20231   }
20232 }
20233
20234 @ @<Trace the fraction multiplication@>=
20235
20236   mp_begin_diagnostic(mp); 
20237   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20238   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20239   mp_print(mp,")}");
20240   mp_end_diagnostic(mp, false);
20241 }
20242
20243 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20244
20245 @<Declare binary action procedures@>=
20246 void mp_hard_times (MP mp,pointer p) {
20247   pointer q; /* a copy of the dependent variable |p| */
20248   pointer r; /* a component of the big node for the nice color or pair */
20249   scaled v; /* the known value for |r| */
20250   if ( type(p)<=mp_pair_type ) { 
20251      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20252   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20253   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20254   while (1) { 
20255     r=r-2;
20256     v=value(r);
20257     type(r)=type(p);
20258     if ( r==value(mp->cur_exp) ) 
20259       break;
20260     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20261     mp_dep_mult(mp, r,v,true);
20262   }
20263   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20264   link(prev_dep(p))=r;
20265   mp_free_node(mp, p,value_node_size);
20266   mp_dep_mult(mp, r,v,true);
20267 }
20268
20269 @ @<Additional cases of binary operators@>=
20270 case over: 
20271   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20272     mp_bad_binary(mp, p,over);
20273   } else { 
20274     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20275     if ( v==0 ) {
20276       @<Squeal about division by zero@>;
20277     } else { 
20278       if ( mp->cur_type==mp_known ) {
20279         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20280       } else if ( mp->cur_type<=mp_pair_type ) { 
20281         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20282         do {  
20283           p=p-2;  mp_dep_div(mp, p,v);
20284         } while (p!=value(mp->cur_exp));
20285       } else {
20286         mp_dep_div(mp, null,v);
20287       }
20288     }
20289     return;
20290   }
20291   break;
20292
20293 @ @<Declare binary action...@>=
20294 void mp_dep_div (MP mp,pointer p, scaled v) {
20295   pointer q; /* the dependency list being divided by |v| */
20296   small_number s,t; /* its type, before and after */
20297   if ( p==null ) q=mp->cur_exp;
20298   else if ( type(p)!=mp_known ) q=p;
20299   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20300   t=type(q); q=dep_list(q); s=t;
20301   if ( t==mp_dependent )
20302     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20303       t=mp_proto_dependent;
20304   q=mp_p_over_v(mp, q,v,s,t); 
20305   mp_dep_finish(mp, q,p,t);
20306 }
20307
20308 @ @<Squeal about division by zero@>=
20309
20310   exp_err("Division by zero");
20311 @.Division by zero@>
20312   help2("You're trying to divide the quantity shown above the error")
20313     ("message by zero. I'm going to divide it by one instead.");
20314   mp_put_get_error(mp);
20315 }
20316
20317 @ @<Additional cases of binary operators@>=
20318 case pythag_add:
20319 case pythag_sub: 
20320    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20321      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20322      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20323    } else mp_bad_binary(mp, p,c);
20324    break;
20325
20326 @ The next few sections of the program deal with affine transformations
20327 of coordinate data.
20328
20329 @<Additional cases of binary operators@>=
20330 case rotated_by: case slanted_by:
20331 case scaled_by: case shifted_by: case transformed_by:
20332 case x_scaled: case y_scaled: case z_scaled:
20333   if ( type(p)==mp_path_type ) { 
20334     path_trans(c,p); return;
20335   } else if ( type(p)==mp_pen_type ) { 
20336     pen_trans(c,p);
20337     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20338       /* rounding error could destroy convexity */
20339     return;
20340   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20341     mp_big_trans(mp, p,c);
20342   } else if ( type(p)==mp_picture_type ) {
20343     mp_do_edges_trans(mp, p,c); return;
20344   } else {
20345     mp_bad_binary(mp, p,c);
20346   }
20347   break;
20348
20349 @ Let |c| be one of the eight transform operators. The procedure call
20350 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20351 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20352 change at all if |c=transformed_by|.)
20353
20354 Then, if all components of the resulting transform are |known|, they are
20355 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20356 and |cur_exp| is changed to the known value zero.
20357
20358 @<Declare binary action...@>=
20359 void mp_set_up_trans (MP mp,quarterword c) {
20360   pointer p,q,r; /* list manipulation registers */
20361   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20362     @<Put the current transform into |cur_exp|@>;
20363   }
20364   @<If the current transform is entirely known, stash it in global variables;
20365     otherwise |return|@>;
20366 }
20367
20368 @ @<Glob...@>=
20369 scaled txx;
20370 scaled txy;
20371 scaled tyx;
20372 scaled tyy;
20373 scaled tx;
20374 scaled ty; /* current transform coefficients */
20375
20376 @ @<Put the current transform...@>=
20377
20378   p=mp_stash_cur_exp(mp); 
20379   mp->cur_exp=mp_id_transform(mp); 
20380   mp->cur_type=mp_transform_type;
20381   q=value(mp->cur_exp);
20382   switch (c) {
20383   @<For each of the eight cases, change the relevant fields of |cur_exp|
20384     and |goto done|;
20385     but do nothing if capsule |p| doesn't have the appropriate type@>;
20386   }; /* there are no other cases */
20387   mp_disp_err(mp, p,"Improper transformation argument");
20388 @.Improper transformation argument@>
20389   help3("The expression shown above has the wrong type,")
20390        ("so I can\'t transform anything using it.")
20391        ("Proceed, and I'll omit the transformation.");
20392   mp_put_get_error(mp);
20393 DONE: 
20394   mp_recycle_value(mp, p); 
20395   mp_free_node(mp, p,value_node_size);
20396 }
20397
20398 @ @<If the current transform is entirely known, ...@>=
20399 q=value(mp->cur_exp); r=q+transform_node_size;
20400 do {  
20401   r=r-2;
20402   if ( type(r)!=mp_known ) return;
20403 } while (r!=q);
20404 mp->txx=value(xx_part_loc(q));
20405 mp->txy=value(xy_part_loc(q));
20406 mp->tyx=value(yx_part_loc(q));
20407 mp->tyy=value(yy_part_loc(q));
20408 mp->tx=value(x_part_loc(q));
20409 mp->ty=value(y_part_loc(q));
20410 mp_flush_cur_exp(mp, 0)
20411
20412 @ @<For each of the eight cases...@>=
20413 case rotated_by:
20414   if ( type(p)==mp_known )
20415     @<Install sines and cosines, then |goto done|@>;
20416   break;
20417 case slanted_by:
20418   if ( type(p)>mp_pair_type ) { 
20419    mp_install(mp, xy_part_loc(q),p); goto DONE;
20420   };
20421   break;
20422 case scaled_by:
20423   if ( type(p)>mp_pair_type ) { 
20424     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20425     goto DONE;
20426   };
20427   break;
20428 case shifted_by:
20429   if ( type(p)==mp_pair_type ) {
20430     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20431     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20432   };
20433   break;
20434 case x_scaled:
20435   if ( type(p)>mp_pair_type ) {
20436     mp_install(mp, xx_part_loc(q),p); goto DONE;
20437   };
20438   break;
20439 case y_scaled:
20440   if ( type(p)>mp_pair_type ) {
20441     mp_install(mp, yy_part_loc(q),p); goto DONE;
20442   };
20443   break;
20444 case z_scaled:
20445   if ( type(p)==mp_pair_type )
20446     @<Install a complex multiplier, then |goto done|@>;
20447   break;
20448 case transformed_by:
20449   break;
20450   
20451
20452 @ @<Install sines and cosines, then |goto done|@>=
20453 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20454   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20455   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20456   value(xy_part_loc(q))=-value(yx_part_loc(q));
20457   value(yy_part_loc(q))=value(xx_part_loc(q));
20458   goto DONE;
20459 }
20460
20461 @ @<Install a complex multiplier, then |goto done|@>=
20462
20463   r=value(p);
20464   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20465   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20466   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20467   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20468   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20469   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20470   goto DONE;
20471 }
20472
20473 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20474 insists that the transformation be entirely known.
20475
20476 @<Declare binary action...@>=
20477 void mp_set_up_known_trans (MP mp,quarterword c) { 
20478   mp_set_up_trans(mp, c);
20479   if ( mp->cur_type!=mp_known ) {
20480     exp_err("Transform components aren't all known");
20481 @.Transform components...@>
20482     help3("I'm unable to apply a partially specified transformation")
20483       ("except to a fully known pair or transform.")
20484       ("Proceed, and I'll omit the transformation.");
20485     mp_put_get_flush_error(mp, 0);
20486     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20487     mp->tx=0; mp->ty=0;
20488   }
20489 }
20490
20491 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20492 coordinates in locations |p| and~|q|.
20493
20494 @<Declare binary action...@>= 
20495 void mp_trans (MP mp,pointer p, pointer q) {
20496   scaled v; /* the new |x| value */
20497   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20498   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20499   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20500   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20501   mp->mem[p].sc=v;
20502 }
20503
20504 @ The simplest transformation procedure applies a transform to all
20505 coordinates of a path.  The |path_trans(c)(p)| macro applies
20506 a transformation defined by |cur_exp| and the transform operator |c|
20507 to the path~|p|.
20508
20509 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20510                      mp_unstash_cur_exp(mp, (B)); 
20511                      mp_do_path_trans(mp, mp->cur_exp); }
20512
20513 @<Declare binary action...@>=
20514 void mp_do_path_trans (MP mp,pointer p) {
20515   pointer q; /* list traverser */
20516   q=p;
20517   do { 
20518     if ( left_type(q)!=mp_endpoint ) 
20519       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20520     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20521     if ( right_type(q)!=mp_endpoint ) 
20522       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20523 @^data structure assumptions@>
20524     q=link(q);
20525   } while (q!=p);
20526 }
20527
20528 @ Transforming a pen is very similar, except that there are no |left_type|
20529 and |right_type| fields.
20530
20531 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20532                     mp_unstash_cur_exp(mp, (B)); 
20533                     mp_do_pen_trans(mp, mp->cur_exp); }
20534
20535 @<Declare binary action...@>=
20536 void mp_do_pen_trans (MP mp,pointer p) {
20537   pointer q; /* list traverser */
20538   if ( pen_is_elliptical(p) ) {
20539     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20540     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20541   };
20542   q=p;
20543   do { 
20544     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20545 @^data structure assumptions@>
20546     q=link(q);
20547   } while (q!=p);
20548 }
20549
20550 @ The next transformation procedure applies to edge structures. It will do
20551 any transformation, but the results may be substandard if the picture contains
20552 text that uses downloaded bitmap fonts.  The binary action procedure is
20553 |do_edges_trans|, but we also need a function that just scales a picture.
20554 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20555 should be thought of as procedures that update an edge structure |h|, except
20556 that they have to return a (possibly new) structure because of the need to call
20557 |private_edges|.
20558
20559 @<Declare binary action...@>=
20560 pointer mp_edges_trans (MP mp, pointer h) {
20561   pointer q; /* the object being transformed */
20562   pointer r,s; /* for list manipulation */
20563   scaled sx,sy; /* saved transformation parameters */
20564   scaled sqdet; /* square root of determinant for |dash_scale| */
20565   integer sgndet; /* sign of the determinant */
20566   scaled v; /* a temporary value */
20567   h=mp_private_edges(mp, h);
20568   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20569   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20570   if ( dash_list(h)!=null_dash ) {
20571     @<Try to transform the dash list of |h|@>;
20572   }
20573   @<Make the bounding box of |h| unknown if it can't be updated properly
20574     without scanning the whole structure@>;  
20575   q=link(dummy_loc(h));
20576   while ( q!=null ) { 
20577     @<Transform graphical object |q|@>;
20578     q=link(q);
20579   }
20580   return h;
20581 }
20582 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20583   mp_set_up_known_trans(mp, c);
20584   value(p)=mp_edges_trans(mp, value(p));
20585   mp_unstash_cur_exp(mp, p);
20586 }
20587 void mp_scale_edges (MP mp) { 
20588   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20589   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20590   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20591 }
20592
20593 @ @<Try to transform the dash list of |h|@>=
20594 if ( (mp->txy!=0)||(mp->tyx!=0)||
20595      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20596   mp_flush_dash_list(mp, h);
20597 } else { 
20598   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20599   @<Scale the dash list by |txx| and shift it by |tx|@>;
20600   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20601 }
20602
20603 @ @<Reverse the dash list of |h|@>=
20604
20605   r=dash_list(h);
20606   dash_list(h)=null_dash;
20607   while ( r!=null_dash ) {
20608     s=r; r=link(r);
20609     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20610     link(s)=dash_list(h);
20611     dash_list(h)=s;
20612   }
20613 }
20614
20615 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20616 r=dash_list(h);
20617 while ( r!=null_dash ) {
20618   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20619   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20620   r=link(r);
20621 }
20622
20623 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20624 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20625   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20626 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20627   mp_init_bbox(mp, h);
20628   goto DONE1;
20629 }
20630 if ( minx_val(h)<=maxx_val(h) ) {
20631   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20632    |(tx,ty)|@>;
20633 }
20634 DONE1:
20635
20636
20637
20638 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20639
20640   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20641   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20642 }
20643
20644 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20645 sum is similar.
20646
20647 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20648
20649   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20650   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20651   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20652   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20653   if ( mp->txx+mp->txy<0 ) {
20654     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20655   }
20656   if ( mp->tyx+mp->tyy<0 ) {
20657     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20658   }
20659 }
20660
20661 @ Now we ready for the main task of transforming the graphical objects in edge
20662 structure~|h|.
20663
20664 @<Transform graphical object |q|@>=
20665 switch (type(q)) {
20666 case mp_fill_code: case mp_stroked_code: 
20667   mp_do_path_trans(mp, path_p(q));
20668   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20669   break;
20670 case mp_start_clip_code: case mp_start_bounds_code: 
20671   mp_do_path_trans(mp, path_p(q));
20672   break;
20673 case mp_text_code: 
20674   r=text_tx_loc(q);
20675   @<Transform the compact transformation starting at |r|@>;
20676   break;
20677 case mp_stop_clip_code: case mp_stop_bounds_code: 
20678   break;
20679 } /* there are no other cases */
20680
20681 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20682 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20683 since the \ps\ output procedures will try to compensate for the transformation
20684 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20685 root of the determinant, |sqdet| is the appropriate factor.
20686
20687 @<Transform |pen_p(q)|, making sure...@>=
20688 if ( pen_p(q)!=null ) {
20689   sx=mp->tx; sy=mp->ty;
20690   mp->tx=0; mp->ty=0;
20691   mp_do_pen_trans(mp, pen_p(q));
20692   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20693     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20694   if ( ! pen_is_elliptical(pen_p(q)) )
20695     if ( sgndet<0 )
20696       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20697          /* this unreverses the pen */
20698   mp->tx=sx; mp->ty=sy;
20699 }
20700
20701 @ This uses the fact that transformations are stored in the order
20702 |(tx,ty,txx,txy,tyx,tyy)|.
20703 @^data structure assumptions@>
20704
20705 @<Transform the compact transformation starting at |r|@>=
20706 mp_trans(mp, r,r+1);
20707 sx=mp->tx; sy=mp->ty;
20708 mp->tx=0; mp->ty=0;
20709 mp_trans(mp, r+2,r+4);
20710 mp_trans(mp, r+3,r+5);
20711 mp->tx=sx; mp->ty=sy
20712
20713 @ The hard cases of transformation occur when big nodes are involved,
20714 and when some of their components are unknown.
20715
20716 @<Declare binary action...@>=
20717 @<Declare subroutines needed by |big_trans|@>;
20718 void mp_big_trans (MP mp,pointer p, quarterword c) {
20719   pointer q,r,pp,qq; /* list manipulation registers */
20720   small_number s; /* size of a big node */
20721   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20722   do {  
20723     r=r-2;
20724     if ( type(r)!=mp_known ) {
20725       @<Transform an unknown big node and |return|@>;
20726     }
20727   } while (r!=q);
20728   @<Transform a known big node@>;
20729 }; /* node |p| will now be recycled by |do_binary| */
20730
20731 @ @<Transform an unknown big node and |return|@>=
20732
20733   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20734   r=value(mp->cur_exp);
20735   if ( mp->cur_type==mp_transform_type ) {
20736     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20737     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20738     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20739     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20740   }
20741   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20742   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20743   return;
20744 }
20745
20746 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20747 and let |q| point to a another value field. The |bilin1| procedure
20748 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20749
20750 @<Declare subroutines needed by |big_trans|@>=
20751 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20752                 scaled u, scaled delta) {
20753   pointer r; /* list traverser */
20754   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20755   if ( u!=0 ) {
20756     if ( type(q)==mp_known ) {
20757       delta+=mp_take_scaled(mp, value(q),u);
20758     } else { 
20759       @<Ensure that |type(p)=mp_proto_dependent|@>;
20760       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20761                                mp_proto_dependent,type(q));
20762     }
20763   }
20764   if ( type(p)==mp_known ) {
20765     value(p)+=delta;
20766   } else {
20767     r=dep_list(p);
20768     while ( info(r)!=null ) r=link(r);
20769     delta+=value(r);
20770     if ( r!=dep_list(p) ) value(r)=delta;
20771     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20772   }
20773   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20774 }
20775
20776 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20777 if ( type(p)!=mp_proto_dependent ) {
20778   if ( type(p)==mp_known ) 
20779     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20780   else 
20781     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20782                              mp_proto_dependent,true);
20783   type(p)=mp_proto_dependent;
20784 }
20785
20786 @ @<Transform a known big node@>=
20787 mp_set_up_trans(mp, c);
20788 if ( mp->cur_type==mp_known ) {
20789   @<Transform known by known@>;
20790 } else { 
20791   pp=mp_stash_cur_exp(mp); qq=value(pp);
20792   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20793   if ( mp->cur_type==mp_transform_type ) {
20794     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20795       value(xy_part_loc(q)),yx_part_loc(qq),null);
20796     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20797       value(xx_part_loc(q)),yx_part_loc(qq),null);
20798     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20799       value(yy_part_loc(q)),xy_part_loc(qq),null);
20800     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20801       value(yx_part_loc(q)),xy_part_loc(qq),null);
20802   };
20803   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20804     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20805   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20806     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20807   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20808 }
20809
20810 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20811 at |dep_final|. The following procedure adds |v| times another
20812 numeric quantity to~|p|.
20813
20814 @<Declare subroutines needed by |big_trans|@>=
20815 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20816   if ( type(r)==mp_known ) {
20817     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20818   } else  { 
20819     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20820                                                          mp_proto_dependent,type(r));
20821     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20822   }
20823 }
20824
20825 @ The |bilin2| procedure is something like |bilin1|, but with known
20826 and unknown quantities reversed. Parameter |p| points to a value field
20827 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20828 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20829 unless it is |null| (which stands for zero). Location~|p| will be
20830 replaced by $p\cdot t+v\cdot u+q$.
20831
20832 @<Declare subroutines needed by |big_trans|@>=
20833 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20834                 pointer u, pointer q) {
20835   scaled vv; /* temporary storage for |value(p)| */
20836   vv=value(p); type(p)=mp_proto_dependent;
20837   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20838   if ( vv!=0 ) 
20839     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20840   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20841   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20842   if ( dep_list(p)==mp->dep_final ) {
20843     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20844     type(p)=mp_known; value(p)=vv;
20845   }
20846 }
20847
20848 @ @<Transform known by known@>=
20849
20850   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20851   if ( mp->cur_type==mp_transform_type ) {
20852     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20853     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20854     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20855     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20856   }
20857   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20858   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20859 }
20860
20861 @ Finally, in |bilin3| everything is |known|.
20862
20863 @<Declare subroutines needed by |big_trans|@>=
20864 void mp_bilin3 (MP mp,pointer p, scaled t, 
20865                scaled v, scaled u, scaled delta) { 
20866   if ( t!=unity )
20867     delta+=mp_take_scaled(mp, value(p),t);
20868   else 
20869     delta+=value(p);
20870   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20871   else value(p)=delta;
20872 }
20873
20874 @ @<Additional cases of binary operators@>=
20875 case concatenate: 
20876   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20877   else mp_bad_binary(mp, p,concatenate);
20878   break;
20879 case substring_of: 
20880   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20881     mp_chop_string(mp, value(p));
20882   else mp_bad_binary(mp, p,substring_of);
20883   break;
20884 case subpath_of: 
20885   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20886   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20887     mp_chop_path(mp, value(p));
20888   else mp_bad_binary(mp, p,subpath_of);
20889   break;
20890
20891 @ @<Declare binary action...@>=
20892 void mp_cat (MP mp,pointer p) {
20893   str_number a,b; /* the strings being concatenated */
20894   pool_pointer k; /* index into |str_pool| */
20895   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20896   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20897     append_char(mp->str_pool[k]);
20898   }
20899   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20900     append_char(mp->str_pool[k]);
20901   }
20902   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20903 }
20904
20905 @ @<Declare binary action...@>=
20906 void mp_chop_string (MP mp,pointer p) {
20907   integer a, b; /* start and stop points */
20908   integer l; /* length of the original string */
20909   integer k; /* runs from |a| to |b| */
20910   str_number s; /* the original string */
20911   boolean reversed; /* was |a>b|? */
20912   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20913   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20914   if ( a<=b ) reversed=false;
20915   else  { reversed=true; k=a; a=b; b=k; };
20916   s=mp->cur_exp; l=length(s);
20917   if ( a<0 ) { 
20918     a=0;
20919     if ( b<0 ) b=0;
20920   }
20921   if ( b>l ) { 
20922     b=l;
20923     if ( a>l ) a=l;
20924   }
20925   str_room(b-a);
20926   if ( reversed ) {
20927     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20928       append_char(mp->str_pool[k]);
20929     }
20930   } else  {
20931     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20932       append_char(mp->str_pool[k]);
20933     }
20934   }
20935   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20936 }
20937
20938 @ @<Declare binary action...@>=
20939 void mp_chop_path (MP mp,pointer p) {
20940   pointer q; /* a knot in the original path */
20941   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20942   scaled a,b,k,l; /* indices for chopping */
20943   boolean reversed; /* was |a>b|? */
20944   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20945   if ( a<=b ) reversed=false;
20946   else  { reversed=true; k=a; a=b; b=k; };
20947   @<Dispense with the cases |a<0| and/or |b>l|@>;
20948   q=mp->cur_exp;
20949   while ( a>=unity ) {
20950     q=link(q); a=a-unity; b=b-unity;
20951   }
20952   if ( b==a ) {
20953     @<Construct a path from |pp| to |qq| of length zero@>; 
20954   } else { 
20955     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20956   }
20957   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
20958   mp_toss_knot_list(mp, mp->cur_exp);
20959   if ( reversed ) {
20960     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20961   } else {
20962     mp->cur_exp=pp;
20963   }
20964 }
20965
20966 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20967 if ( a<0 ) {
20968   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20969     a=0; if ( b<0 ) b=0;
20970   } else  {
20971     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20972   }
20973 }
20974 if ( b>l ) {
20975   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20976     b=l; if ( a>l ) a=l;
20977   } else {
20978     while ( a>=l ) { 
20979       a=a-l; b=b-l;
20980     }
20981   }
20982 }
20983
20984 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20985
20986   pp=mp_copy_knot(mp, q); qq=pp;
20987   do {  
20988     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20989   } while (b>0);
20990   if ( a>0 ) {
20991     ss=pp; pp=link(pp);
20992     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20993     mp_free_node(mp, ss,knot_node_size);
20994     if ( rr==ss ) {
20995       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20996     }
20997   }
20998   if ( b<0 ) {
20999     mp_split_cubic(mp, rr,(b+unity)*010000);
21000     mp_free_node(mp, qq,knot_node_size);
21001     qq=link(rr);
21002   }
21003 }
21004
21005 @ @<Construct a path from |pp| to |qq| of length zero@>=
21006
21007   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
21008   pp=mp_copy_knot(mp, q); qq=pp;
21009 }
21010
21011 @ @<Additional cases of binary operators@>=
21012 case point_of: case precontrol_of: case postcontrol_of: 
21013   if ( mp->cur_type==mp_pair_type )
21014      mp_pair_to_path(mp);
21015   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21016     mp_find_point(mp, value(p),c);
21017   else 
21018     mp_bad_binary(mp, p,c);
21019   break;
21020 case pen_offset_of: 
21021   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21022     mp_set_up_offset(mp, value(p));
21023   else 
21024     mp_bad_binary(mp, p,pen_offset_of);
21025   break;
21026 case direction_time_of: 
21027   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21028   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21029     mp_set_up_direction_time(mp, value(p));
21030   else 
21031     mp_bad_binary(mp, p,direction_time_of);
21032   break;
21033 case envelope_of:
21034   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21035     mp_bad_binary(mp, p,envelope_of);
21036   else
21037     mp_set_up_envelope(mp, p);
21038   break;
21039
21040 @ @<Declare binary action...@>=
21041 void mp_set_up_offset (MP mp,pointer p) { 
21042   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21043   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21044 }
21045 void mp_set_up_direction_time (MP mp,pointer p) { 
21046   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21047   value(y_part_loc(p)),mp->cur_exp));
21048 }
21049 void mp_set_up_envelope (MP mp,pointer p) {
21050   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21051   /* TODO: accept elliptical pens for straight paths */
21052   if (pen_is_elliptical(value(p))) {
21053     mp_bad_envelope_pen(mp);
21054     mp->cur_exp = q;
21055     mp->cur_type = mp_path_type;
21056     return;
21057   }
21058   small_number ljoin, lcap;
21059   scaled miterlim;
21060   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21061   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21062   else ljoin=0;
21063   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21064   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21065   else lcap=0;
21066   if ( mp->internal[mp_miterlimit]<unity )
21067     miterlim=unity;
21068   else
21069     miterlim=mp->internal[mp_miterlimit];
21070   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21071   mp->cur_type = mp_path_type;
21072 }
21073
21074 @ @<Declare binary action...@>=
21075 void mp_find_point (MP mp,scaled v, quarterword c) {
21076   pointer p; /* the path */
21077   scaled n; /* its length */
21078   p=mp->cur_exp;
21079   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21080   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21081   if ( n==0 ) { 
21082     v=0; 
21083   } else if ( v<0 ) {
21084     if ( left_type(p)==mp_endpoint ) v=0;
21085     else v=n-1-((-v-1) % n);
21086   } else if ( v>n ) {
21087     if ( left_type(p)==mp_endpoint ) v=n;
21088     else v=v % n;
21089   }
21090   p=mp->cur_exp;
21091   while ( v>=unity ) { p=link(p); v=v-unity;  };
21092   if ( v!=0 ) {
21093      @<Insert a fractional node by splitting the cubic@>;
21094   }
21095   @<Set the current expression to the desired path coordinates@>;
21096 }
21097
21098 @ @<Insert a fractional node...@>=
21099 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21100
21101 @ @<Set the current expression to the desired path coordinates...@>=
21102 switch (c) {
21103 case point_of: 
21104   mp_pair_value(mp, x_coord(p),y_coord(p));
21105   break;
21106 case precontrol_of: 
21107   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21108   else mp_pair_value(mp, left_x(p),left_y(p));
21109   break;
21110 case postcontrol_of: 
21111   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21112   else mp_pair_value(mp, right_x(p),right_y(p));
21113   break;
21114 } /* there are no other cases */
21115
21116 @ @<Additional cases of binary operators@>=
21117 case arc_time_of: 
21118   if ( mp->cur_type==mp_pair_type )
21119      mp_pair_to_path(mp);
21120   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21121     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21122   else 
21123     mp_bad_binary(mp, p,c);
21124   break;
21125
21126 @ @<Additional cases of bin...@>=
21127 case intersect: 
21128   if ( type(p)==mp_pair_type ) {
21129     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21130     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21131   };
21132   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21133   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21134     mp_path_intersection(mp, value(p),mp->cur_exp);
21135     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21136   } else {
21137     mp_bad_binary(mp, p,intersect);
21138   }
21139   break;
21140
21141 @ @<Additional cases of bin...@>=
21142 case in_font:
21143   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21144     mp_bad_binary(mp, p,in_font);
21145   else { mp_do_infont(mp, p); return; }
21146   break;
21147
21148 @ Function |new_text_node| owns the reference count for its second argument
21149 (the text string) but not its first (the font name).
21150
21151 @<Declare binary action...@>=
21152 void mp_do_infont (MP mp,pointer p) {
21153   pointer q;
21154   q=mp_get_node(mp, edge_header_size);
21155   mp_init_edges(mp, q);
21156   link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21157   obj_tail(q)=link(obj_tail(q));
21158   mp_free_node(mp, p,value_node_size);
21159   mp_flush_cur_exp(mp, q);
21160   mp->cur_type=mp_picture_type;
21161 }
21162
21163 @* \[40] Statements and commands.
21164 The chief executive of \MP\ is the |do_statement| routine, which
21165 contains the master switch that causes all the various pieces of \MP\
21166 to do their things, in the right order.
21167
21168 In a sense, this is the grand climax of the program: It applies all the
21169 tools that we have worked so hard to construct. In another sense, this is
21170 the messiest part of the program: It necessarily refers to other pieces
21171 of code all over the place, so that a person can't fully understand what is
21172 going on without paging back and forth to be reminded of conventions that
21173 are defined elsewhere. We are now at the hub of the web.
21174
21175 The structure of |do_statement| itself is quite simple.  The first token
21176 of the statement is fetched using |get_x_next|.  If it can be the first
21177 token of an expression, we look for an equation, an assignment, or a
21178 title. Otherwise we use a \&{case} construction to branch at high speed to
21179 the appropriate routine for various and sundry other types of commands,
21180 each of which has an ``action procedure'' that does the necessary work.
21181
21182 The program uses the fact that
21183 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21184 to interpret a statement that starts with, e.g., `\&{string}',
21185 as a type declaration rather than a boolean expression.
21186
21187 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21188   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21189   if ( mp->cur_cmd>max_primary_command ) {
21190     @<Worry about bad statement@>;
21191   } else if ( mp->cur_cmd>max_statement_command ) {
21192     @<Do an equation, assignment, title, or
21193      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21194   } else {
21195     @<Do a statement that doesn't begin with an expression@>;
21196   }
21197   if ( mp->cur_cmd<semicolon )
21198     @<Flush unparsable junk that was found after the statement@>;
21199   mp->error_count=0;
21200 }
21201
21202 @ @<Declarations@>=
21203 @<Declare action procedures for use by |do_statement|@>;
21204
21205 @ The only command codes |>max_primary_command| that can be present
21206 at the beginning of a statement are |semicolon| and higher; these
21207 occur when the statement is null.
21208
21209 @<Worry about bad statement@>=
21210
21211   if ( mp->cur_cmd<semicolon ) {
21212     print_err("A statement can't begin with `");
21213 @.A statement can't begin with x@>
21214     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21215     help5("I was looking for the beginning of a new statement.")
21216       ("If you just proceed without changing anything, I'll ignore")
21217       ("everything up to the next `;'. Please insert a semicolon")
21218       ("now in front of anything that you don't want me to delete.")
21219       ("(See Chapter 27 of The METAFONTbook for an example.)");
21220 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21221     mp_back_error(mp); mp_get_x_next(mp);
21222   }
21223 }
21224
21225 @ The help message printed here says that everything is flushed up to
21226 a semicolon, but actually the commands |end_group| and |stop| will
21227 also terminate a statement.
21228
21229 @<Flush unparsable junk that was found after the statement@>=
21230
21231   print_err("Extra tokens will be flushed");
21232 @.Extra tokens will be flushed@>
21233   help6("I've just read as much of that statement as I could fathom,")
21234        ("so a semicolon should have been next. It's very puzzling...")
21235        ("but I'll try to get myself back together, by ignoring")
21236        ("everything up to the next `;'. Please insert a semicolon")
21237        ("now in front of anything that you don't want me to delete.")
21238        ("(See Chapter 27 of The METAFONTbook for an example.)");
21239 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21240   mp_back_error(mp); mp->scanner_status=flushing;
21241   do {  
21242     get_t_next;
21243     @<Decrease the string reference count...@>;
21244   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21245   mp->scanner_status=normal;
21246 }
21247
21248 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21249 |cur_type=mp_vacuous| unless the statement was simply an expression;
21250 in the latter case, |cur_type| and |cur_exp| should represent that
21251 expression.
21252
21253 @<Do a statement that doesn't...@>=
21254
21255   if ( mp->internal[mp_tracing_commands]>0 ) 
21256     show_cur_cmd_mod;
21257   switch (mp->cur_cmd ) {
21258   case type_name:mp_do_type_declaration(mp); break;
21259   case macro_def:
21260     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21261     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21262      break;
21263   @<Cases of |do_statement| that invoke particular commands@>;
21264   } /* there are no other cases */
21265   mp->cur_type=mp_vacuous;
21266 }
21267
21268 @ The most important statements begin with expressions.
21269
21270 @<Do an equation, assignment, title, or...@>=
21271
21272   mp->var_flag=assignment; mp_scan_expression(mp);
21273   if ( mp->cur_cmd<end_group ) {
21274     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21275     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21276     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21277     else if ( mp->cur_type!=mp_vacuous ){ 
21278       exp_err("Isolated expression");
21279 @.Isolated expression@>
21280       help3("I couldn't find an `=' or `:=' after the")
21281         ("expression that is shown above this error message,")
21282         ("so I guess I'll just ignore it and carry on.");
21283       mp_put_get_error(mp);
21284     }
21285     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21286   }
21287 }
21288
21289 @ @<Do a title@>=
21290
21291   if ( mp->internal[mp_tracing_titles]>0 ) {
21292     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21293   }
21294 }
21295
21296 @ Equations and assignments are performed by the pair of mutually recursive
21297 @^recursion@>
21298 routines |do_equation| and |do_assignment|. These routines are called when
21299 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21300 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21301 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21302 will be equal to the right-hand side (which will normally be equal
21303 to the left-hand side).
21304
21305 @<Declare action procedures for use by |do_statement|@>=
21306 @<Declare the procedure called |try_eq|@>;
21307 @<Declare the procedure called |make_eq|@>;
21308 void mp_do_equation (MP mp) ;
21309
21310 @ @c
21311 void mp_do_equation (MP mp) {
21312   pointer lhs; /* capsule for the left-hand side */
21313   pointer p; /* temporary register */
21314   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21315   mp->var_flag=assignment; mp_scan_expression(mp);
21316   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21317   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21318   if ( mp->internal[mp_tracing_commands]>two ) 
21319     @<Trace the current equation@>;
21320   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21321     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21322   }; /* in this case |make_eq| will change the pair to a path */
21323   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21324 }
21325
21326 @ And |do_assignment| is similar to |do_expression|:
21327
21328 @<Declarations@>=
21329 void mp_do_assignment (MP mp);
21330
21331 @ @<Declare action procedures for use by |do_statement|@>=
21332 void mp_do_assignment (MP mp) ;
21333
21334 @ @c
21335 void mp_do_assignment (MP mp) {
21336   pointer lhs; /* token list for the left-hand side */
21337   pointer p; /* where the left-hand value is stored */
21338   pointer q; /* temporary capsule for the right-hand value */
21339   if ( mp->cur_type!=mp_token_list ) { 
21340     exp_err("Improper `:=' will be changed to `='");
21341 @.Improper `:='@>
21342     help2("I didn't find a variable name at the left of the `:=',")
21343       ("so I'm going to pretend that you said `=' instead.");
21344     mp_error(mp); mp_do_equation(mp);
21345   } else { 
21346     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21347     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21348     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21349     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21350     if ( mp->internal[mp_tracing_commands]>two ) 
21351       @<Trace the current assignment@>;
21352     if ( info(lhs)>hash_end ) {
21353       @<Assign the current expression to an internal variable@>;
21354     } else  {
21355       @<Assign the current expression to the variable |lhs|@>;
21356     }
21357     mp_flush_node_list(mp, lhs);
21358   }
21359 }
21360
21361 @ @<Trace the current equation@>=
21362
21363   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21364   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21365   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21366 }
21367
21368 @ @<Trace the current assignment@>=
21369
21370   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21371   if ( info(lhs)>hash_end ) 
21372      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21373   else 
21374      mp_show_token_list(mp, lhs,null,1000,0);
21375   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21376   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21377 }
21378
21379 @ @<Assign the current expression to an internal variable@>=
21380 if ( mp->cur_type==mp_known )  {
21381   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21382 } else { 
21383   exp_err("Internal quantity `");
21384 @.Internal quantity...@>
21385   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21386   mp_print(mp, "' must receive a known value");
21387   help2("I can\'t set an internal quantity to anything but a known")
21388     ("numeric value, so I'll have to ignore this assignment.");
21389   mp_put_get_error(mp);
21390 }
21391
21392 @ @<Assign the current expression to the variable |lhs|@>=
21393
21394   p=mp_find_variable(mp, lhs);
21395   if ( p!=null ) {
21396     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21397     mp_recycle_value(mp, p);
21398     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21399     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21400   } else  { 
21401     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21402   }
21403 }
21404
21405
21406 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21407 a pointer to a capsule that is to be equated to the current expression.
21408
21409 @<Declare the procedure called |make_eq|@>=
21410 void mp_make_eq (MP mp,pointer lhs) ;
21411
21412
21413
21414 @c void mp_make_eq (MP mp,pointer lhs) {
21415   small_number t; /* type of the left-hand side */
21416   pointer p,q; /* pointers inside of big nodes */
21417   integer v=0; /* value of the left-hand side */
21418 RESTART: 
21419   t=type(lhs);
21420   if ( t<=mp_pair_type ) v=value(lhs);
21421   switch (t) {
21422   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21423     is incompatible with~|t|@>;
21424   } /* all cases have been listed */
21425   @<Announce that the equation cannot be performed@>;
21426 DONE:
21427   check_arith; mp_recycle_value(mp, lhs); 
21428   mp_free_node(mp, lhs,value_node_size);
21429 }
21430
21431 @ @<Announce that the equation cannot be performed@>=
21432 mp_disp_err(mp, lhs,""); 
21433 exp_err("Equation cannot be performed (");
21434 @.Equation cannot be performed@>
21435 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21436 else mp_print(mp, "numeric");
21437 mp_print_char(mp, '=');
21438 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21439 else mp_print(mp, "numeric");
21440 mp_print_char(mp, ')');
21441 help2("I'm sorry, but I don't know how to make such things equal.")
21442      ("(See the two expressions just above the error message.)");
21443 mp_put_get_error(mp)
21444
21445 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21446 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21447 case mp_path_type: case mp_picture_type:
21448   if ( mp->cur_type==t+unknown_tag ) { 
21449     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21450   } else if ( mp->cur_type==t ) {
21451     @<Report redundant or inconsistent equation and |goto done|@>;
21452   }
21453   break;
21454 case unknown_types:
21455   if ( mp->cur_type==t-unknown_tag ) { 
21456     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21457   } else if ( mp->cur_type==t ) { 
21458     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21459   } else if ( mp->cur_type==mp_pair_type ) {
21460     if ( t==mp_unknown_path ) { 
21461      mp_pair_to_path(mp); goto RESTART;
21462     };
21463   }
21464   break;
21465 case mp_transform_type: case mp_color_type:
21466 case mp_cmykcolor_type: case mp_pair_type:
21467   if ( mp->cur_type==t ) {
21468     @<Do multiple equations and |goto done|@>;
21469   }
21470   break;
21471 case mp_known: case mp_dependent:
21472 case mp_proto_dependent: case mp_independent:
21473   if ( mp->cur_type>=mp_known ) { 
21474     mp_try_eq(mp, lhs,null); goto DONE;
21475   };
21476   break;
21477 case mp_vacuous:
21478   break;
21479
21480 @ @<Report redundant or inconsistent equation and |goto done|@>=
21481
21482   if ( mp->cur_type<=mp_string_type ) {
21483     if ( mp->cur_type==mp_string_type ) {
21484       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21485         goto NOT_FOUND;
21486       }
21487     } else if ( v!=mp->cur_exp ) {
21488       goto NOT_FOUND;
21489     }
21490     @<Exclaim about a redundant equation@>; goto DONE;
21491   }
21492   print_err("Redundant or inconsistent equation");
21493 @.Redundant or inconsistent equation@>
21494   help2("An equation between already-known quantities can't help.")
21495        ("But don't worry; continue and I'll just ignore it.");
21496   mp_put_get_error(mp); goto DONE;
21497 NOT_FOUND: 
21498   print_err("Inconsistent equation");
21499 @.Inconsistent equation@>
21500   help2("The equation I just read contradicts what was said before.")
21501        ("But don't worry; continue and I'll just ignore it.");
21502   mp_put_get_error(mp); goto DONE;
21503 }
21504
21505 @ @<Do multiple equations and |goto done|@>=
21506
21507   p=v+mp->big_node_size[t]; 
21508   q=value(mp->cur_exp)+mp->big_node_size[t];
21509   do {  
21510     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21511   } while (p!=v);
21512   goto DONE;
21513 }
21514
21515 @ The first argument to |try_eq| is the location of a value node
21516 in a capsule that will soon be recycled. The second argument is
21517 either a location within a pair or transform node pointed to by
21518 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21519 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21520 but to equate the two operands.
21521
21522 @<Declare the procedure called |try_eq|@>=
21523 void mp_try_eq (MP mp,pointer l, pointer r) ;
21524
21525
21526 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21527   pointer p; /* dependency list for right operand minus left operand */
21528   int t; /* the type of list |p| */
21529   pointer q; /* the constant term of |p| is here */
21530   pointer pp; /* dependency list for right operand */
21531   int tt; /* the type of list |pp| */
21532   boolean copied; /* have we copied a list that ought to be recycled? */
21533   @<Remove the left operand from its container, negate it, and
21534     put it into dependency list~|p| with constant term~|q|@>;
21535   @<Add the right operand to list |p|@>;
21536   if ( info(p)==null ) {
21537     @<Deal with redundant or inconsistent equation@>;
21538   } else { 
21539     mp_linear_eq(mp, p,t);
21540     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21541       if ( type(mp->cur_exp)==mp_known ) {
21542         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21543         mp_free_node(mp, pp,value_node_size);
21544       }
21545     }
21546   }
21547 }
21548
21549 @ @<Remove the left operand from its container, negate it, and...@>=
21550 t=type(l);
21551 if ( t==mp_known ) { 
21552   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21553 } else if ( t==mp_independent ) {
21554   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21555   q=mp->dep_final;
21556 } else { 
21557   p=dep_list(l); q=p;
21558   while (1) { 
21559     negate(value(q));
21560     if ( info(q)==null ) break;
21561     q=link(q);
21562   }
21563   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21564   type(l)=mp_known;
21565 }
21566
21567 @ @<Deal with redundant or inconsistent equation@>=
21568
21569   if ( abs(value(p))>64 ) { /* off by .001 or more */
21570     print_err("Inconsistent equation");
21571 @.Inconsistent equation@>
21572     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21573     mp_print_char(mp, ')');
21574     help2("The equation I just read contradicts what was said before.")
21575       ("But don't worry; continue and I'll just ignore it.");
21576     mp_put_get_error(mp);
21577   } else if ( r==null ) {
21578     @<Exclaim about a redundant equation@>;
21579   }
21580   mp_free_node(mp, p,dep_node_size);
21581 }
21582
21583 @ @<Add the right operand to list |p|@>=
21584 if ( r==null ) {
21585   if ( mp->cur_type==mp_known ) {
21586     value(q)=value(q)+mp->cur_exp; goto DONE1;
21587   } else { 
21588     tt=mp->cur_type;
21589     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21590     else pp=dep_list(mp->cur_exp);
21591   } 
21592 } else {
21593   if ( type(r)==mp_known ) {
21594     value(q)=value(q)+value(r); goto DONE1;
21595   } else { 
21596     tt=type(r);
21597     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21598     else pp=dep_list(r);
21599   }
21600 }
21601 if ( tt!=mp_independent ) copied=false;
21602 else  { copied=true; tt=mp_dependent; };
21603 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21604 if ( copied ) mp_flush_node_list(mp, pp);
21605 DONE1:
21606
21607 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21608 mp->watch_coefs=false;
21609 if ( t==tt ) {
21610   p=mp_p_plus_q(mp, p,pp,t);
21611 } else if ( t==mp_proto_dependent ) {
21612   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21613 } else { 
21614   q=p;
21615   while ( info(q)!=null ) {
21616     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21617   }
21618   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21619 }
21620 mp->watch_coefs=true;
21621
21622 @ Our next goal is to process type declarations. For this purpose it's
21623 convenient to have a procedure that scans a $\langle\,$declared
21624 variable$\,\rangle$ and returns the corresponding token list. After the
21625 following procedure has acted, the token after the declared variable
21626 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21627 and~|cur_sym|.
21628
21629 @<Declare the function called |scan_declared_variable|@>=
21630 pointer mp_scan_declared_variable (MP mp) {
21631   pointer x; /* hash address of the variable's root */
21632   pointer h,t; /* head and tail of the token list to be returned */
21633   pointer l; /* hash address of left bracket */
21634   mp_get_symbol(mp); x=mp->cur_sym;
21635   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21636   h=mp_get_avail(mp); info(h)=x; t=h;
21637   while (1) { 
21638     mp_get_x_next(mp);
21639     if ( mp->cur_sym==0 ) break;
21640     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21641       if ( mp->cur_cmd==left_bracket ) {
21642         @<Descend past a collective subscript@>;
21643       } else {
21644         break;
21645       }
21646     }
21647     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21648   }
21649   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21650   if ( equiv(x)==null ) mp_new_root(mp, x);
21651   return h;
21652 }
21653
21654 @ If the subscript isn't collective, we don't accept it as part of the
21655 declared variable.
21656
21657 @<Descend past a collective subscript@>=
21658
21659   l=mp->cur_sym; mp_get_x_next(mp);
21660   if ( mp->cur_cmd!=right_bracket ) {
21661     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21662   } else {
21663     mp->cur_sym=collective_subscript;
21664   }
21665 }
21666
21667 @ Type declarations are introduced by the following primitive operations.
21668
21669 @<Put each...@>=
21670 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21671 @:numeric_}{\&{numeric} primitive@>
21672 mp_primitive(mp, "string",type_name,mp_string_type);
21673 @:string_}{\&{string} primitive@>
21674 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21675 @:boolean_}{\&{boolean} primitive@>
21676 mp_primitive(mp, "path",type_name,mp_path_type);
21677 @:path_}{\&{path} primitive@>
21678 mp_primitive(mp, "pen",type_name,mp_pen_type);
21679 @:pen_}{\&{pen} primitive@>
21680 mp_primitive(mp, "picture",type_name,mp_picture_type);
21681 @:picture_}{\&{picture} primitive@>
21682 mp_primitive(mp, "transform",type_name,mp_transform_type);
21683 @:transform_}{\&{transform} primitive@>
21684 mp_primitive(mp, "color",type_name,mp_color_type);
21685 @:color_}{\&{color} primitive@>
21686 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21687 @:color_}{\&{rgbcolor} primitive@>
21688 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21689 @:color_}{\&{cmykcolor} primitive@>
21690 mp_primitive(mp, "pair",type_name,mp_pair_type);
21691 @:pair_}{\&{pair} primitive@>
21692
21693 @ @<Cases of |print_cmd...@>=
21694 case type_name: mp_print_type(mp, m); break;
21695
21696 @ Now we are ready to handle type declarations, assuming that a
21697 |type_name| has just been scanned.
21698
21699 @<Declare action procedures for use by |do_statement|@>=
21700 void mp_do_type_declaration (MP mp) ;
21701
21702 @ @c
21703 void mp_do_type_declaration (MP mp) {
21704   small_number t; /* the type being declared */
21705   pointer p; /* token list for a declared variable */
21706   pointer q; /* value node for the variable */
21707   if ( mp->cur_mod>=mp_transform_type ) 
21708     t=mp->cur_mod;
21709   else 
21710     t=mp->cur_mod+unknown_tag;
21711   do {  
21712     p=mp_scan_declared_variable(mp);
21713     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21714     q=mp_find_variable(mp, p);
21715     if ( q!=null ) { 
21716       type(q)=t; value(q)=null; 
21717     } else  { 
21718       print_err("Declared variable conflicts with previous vardef");
21719 @.Declared variable conflicts...@>
21720       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21721            ("Proceed, and I'll ignore the illegal redeclaration.");
21722       mp_put_get_error(mp);
21723     }
21724     mp_flush_list(mp, p);
21725     if ( mp->cur_cmd<comma ) {
21726       @<Flush spurious symbols after the declared variable@>;
21727     }
21728   } while (! end_of_statement);
21729 }
21730
21731 @ @<Flush spurious symbols after the declared variable@>=
21732
21733   print_err("Illegal suffix of declared variable will be flushed");
21734 @.Illegal suffix...flushed@>
21735   help5("Variables in declarations must consist entirely of")
21736     ("names and collective subscripts, e.g., `x[]a'.")
21737     ("Are you trying to use a reserved word in a variable name?")
21738     ("I'm going to discard the junk I found here,")
21739     ("up to the next comma or the end of the declaration.");
21740   if ( mp->cur_cmd==numeric_token )
21741     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21742   mp_put_get_error(mp); mp->scanner_status=flushing;
21743   do {  
21744     get_t_next;
21745     @<Decrease the string reference count...@>;
21746   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21747   mp->scanner_status=normal;
21748 }
21749
21750 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21751 until coming to the end of the user's program.
21752 Each execution of |do_statement| concludes with
21753 |cur_cmd=semicolon|, |end_group|, or |stop|.
21754
21755 @c void mp_main_control (MP mp) { 
21756   do {  
21757     mp_do_statement(mp);
21758     if ( mp->cur_cmd==end_group ) {
21759       print_err("Extra `endgroup'");
21760 @.Extra `endgroup'@>
21761       help2("I'm not currently working on a `begingroup',")
21762         ("so I had better not try to end anything.");
21763       mp_flush_error(mp, 0);
21764     }
21765   } while (mp->cur_cmd!=stop);
21766 }
21767 int __attribute__((noinline)) 
21768 mp_run (MP mp) {
21769   if (mp->history < mp_fatal_error_stop ) {
21770     @<Install and test the non-local jump buffer@>;
21771     mp_main_control(mp); /* come to life */
21772     mp_final_cleanup(mp); /* prepare for death */
21773     mp_close_files_and_terminate(mp);
21774   }
21775   return mp->history;
21776 }
21777 int __attribute__((noinline)) 
21778 mp_execute (MP mp) {
21779   if (mp->history < mp_fatal_error_stop ) {
21780     mp->history = mp_spotless;
21781     mp->file_offset = 0;
21782     mp->term_offset = 0;
21783     mp->tally = 0; 
21784     @<Install and test the non-local jump buffer@>;
21785     mp_input_ln(mp,mp->term_in);
21786     mp_firm_up_the_line(mp);
21787     mp->buffer[limit]='%';
21788     mp->first=limit+1; 
21789     loc=start;
21790     mp_main_control(mp); /* come to life */ 
21791   }
21792   return mp->history;
21793 }
21794 int __attribute__((noinline)) 
21795 mp_finish (MP mp) {
21796   if (mp->history < mp_fatal_error_stop ) {
21797     @<Install and test the non-local jump buffer@>;
21798     mp_final_cleanup(mp); /* prepare for death */
21799     mp_close_files_and_terminate(mp);
21800   }
21801   return mp->history;
21802 }
21803 char * mp_mplib_version (MP mp) {
21804   assert(mp);
21805   return mplib_version;
21806 }
21807 char * mp_metapost_version (MP mp) {
21808   assert(mp);
21809   return metapost_version;
21810 }
21811
21812 @ @<Exported function headers@>=
21813 int mp_run (MP mp);
21814 int mp_execute (MP mp);
21815 int mp_finish (MP mp);
21816 char * mp_mplib_version (MP mp);
21817 char * mp_metapost_version (MP mp);
21818
21819 @ @<Put each...@>=
21820 mp_primitive(mp, "end",stop,0);
21821 @:end_}{\&{end} primitive@>
21822 mp_primitive(mp, "dump",stop,1);
21823 @:dump_}{\&{dump} primitive@>
21824
21825 @ @<Cases of |print_cmd...@>=
21826 case stop:
21827   if ( m==0 ) mp_print(mp, "end");
21828   else mp_print(mp, "dump");
21829   break;
21830
21831 @* \[41] Commands.
21832 Let's turn now to statements that are classified as ``commands'' because
21833 of their imperative nature. We'll begin with simple ones, so that it
21834 will be clear how to hook command processing into the |do_statement| routine;
21835 then we'll tackle the tougher commands.
21836
21837 Here's one of the simplest:
21838
21839 @<Cases of |do_statement|...@>=
21840 case mp_random_seed: mp_do_random_seed(mp);  break;
21841
21842 @ @<Declare action procedures for use by |do_statement|@>=
21843 void mp_do_random_seed (MP mp) ;
21844
21845 @ @c void mp_do_random_seed (MP mp) { 
21846   mp_get_x_next(mp);
21847   if ( mp->cur_cmd!=assignment ) {
21848     mp_missing_err(mp, ":=");
21849 @.Missing `:='@>
21850     help1("Always say `randomseed:=<numeric expression>'.");
21851     mp_back_error(mp);
21852   };
21853   mp_get_x_next(mp); mp_scan_expression(mp);
21854   if ( mp->cur_type!=mp_known ) {
21855     exp_err("Unknown value will be ignored");
21856 @.Unknown value...ignored@>
21857     help2("Your expression was too random for me to handle,")
21858       ("so I won't change the random seed just now.");
21859     mp_put_get_flush_error(mp, 0);
21860   } else {
21861    @<Initialize the random seed to |cur_exp|@>;
21862   }
21863 }
21864
21865 @ @<Initialize the random seed to |cur_exp|@>=
21866
21867   mp_init_randoms(mp, mp->cur_exp);
21868   if ( mp->selector>=log_only && mp->selector<write_file) {
21869     mp->old_setting=mp->selector; mp->selector=log_only;
21870     mp_print_nl(mp, "{randomseed:="); 
21871     mp_print_scaled(mp, mp->cur_exp); 
21872     mp_print_char(mp, '}');
21873     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21874   }
21875 }
21876
21877 @ And here's another simple one (somewhat different in flavor):
21878
21879 @<Cases of |do_statement|...@>=
21880 case mode_command: 
21881   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21882   @<Initialize the print |selector| based on |interaction|@>;
21883   if ( mp->log_opened ) mp->selector=mp->selector+2;
21884   mp_get_x_next(mp);
21885   break;
21886
21887 @ @<Put each...@>=
21888 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21889 @:mp_batch_mode_}{\&{batchmode} primitive@>
21890 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21891 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21892 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21893 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21894 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21895 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21896
21897 @ @<Cases of |print_cmd_mod|...@>=
21898 case mode_command: 
21899   switch (m) {
21900   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21901   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21902   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21903   default: mp_print(mp, "errorstopmode"); break;
21904   }
21905   break;
21906
21907 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21908
21909 @<Cases of |do_statement|...@>=
21910 case protection_command: mp_do_protection(mp); break;
21911
21912 @ @<Put each...@>=
21913 mp_primitive(mp, "inner",protection_command,0);
21914 @:inner_}{\&{inner} primitive@>
21915 mp_primitive(mp, "outer",protection_command,1);
21916 @:outer_}{\&{outer} primitive@>
21917
21918 @ @<Cases of |print_cmd...@>=
21919 case protection_command: 
21920   if ( m==0 ) mp_print(mp, "inner");
21921   else mp_print(mp, "outer");
21922   break;
21923
21924 @ @<Declare action procedures for use by |do_statement|@>=
21925 void mp_do_protection (MP mp) ;
21926
21927 @ @c void mp_do_protection (MP mp) {
21928   int m; /* 0 to unprotect, 1 to protect */
21929   halfword t; /* the |eq_type| before we change it */
21930   m=mp->cur_mod;
21931   do {  
21932     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21933     if ( m==0 ) { 
21934       if ( t>=outer_tag ) 
21935         eq_type(mp->cur_sym)=t-outer_tag;
21936     } else if ( t<outer_tag ) {
21937       eq_type(mp->cur_sym)=t+outer_tag;
21938     }
21939     mp_get_x_next(mp);
21940   } while (mp->cur_cmd==comma);
21941 }
21942
21943 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21944 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21945 declaration assigns the command code |left_delimiter| to `\.{(}' and
21946 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21947 hash address of its mate.
21948
21949 @<Cases of |do_statement|...@>=
21950 case delimiters: mp_def_delims(mp); break;
21951
21952 @ @<Declare action procedures for use by |do_statement|@>=
21953 void mp_def_delims (MP mp) ;
21954
21955 @ @c void mp_def_delims (MP mp) {
21956   pointer l_delim,r_delim; /* the new delimiter pair */
21957   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21958   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21959   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21960   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21961   mp_get_x_next(mp);
21962 }
21963
21964 @ Here is a procedure that is called when \MP\ has reached a point
21965 where some right delimiter is mandatory.
21966
21967 @<Declare the procedure called |check_delimiter|@>=
21968 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21969   if ( mp->cur_cmd==right_delimiter ) 
21970     if ( mp->cur_mod==l_delim ) 
21971       return;
21972   if ( mp->cur_sym!=r_delim ) {
21973      mp_missing_err(mp, str(text(r_delim)));
21974 @.Missing `)'@>
21975     help2("I found no right delimiter to match a left one. So I've")
21976       ("put one in, behind the scenes; this may fix the problem.");
21977     mp_back_error(mp);
21978   } else { 
21979     print_err("The token `"); mp_print_text(r_delim);
21980 @.The token...delimiter@>
21981     mp_print(mp, "' is no longer a right delimiter");
21982     help3("Strange: This token has lost its former meaning!")
21983       ("I'll read it as a right delimiter this time;")
21984       ("but watch out, I'll probably miss it later.");
21985     mp_error(mp);
21986   }
21987 }
21988
21989 @ The next four commands save or change the values associated with tokens.
21990
21991 @<Cases of |do_statement|...@>=
21992 case save_command: 
21993   do {  
21994     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21995   } while (mp->cur_cmd==comma);
21996   break;
21997 case interim_command: mp_do_interim(mp); break;
21998 case let_command: mp_do_let(mp); break;
21999 case new_internal: mp_do_new_internal(mp); break;
22000
22001 @ @<Declare action procedures for use by |do_statement|@>=
22002 void mp_do_statement (MP mp);
22003 void mp_do_interim (MP mp);
22004
22005 @ @c void mp_do_interim (MP mp) { 
22006   mp_get_x_next(mp);
22007   if ( mp->cur_cmd!=internal_quantity ) {
22008      print_err("The token `");
22009 @.The token...quantity@>
22010     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22011     else mp_print_text(mp->cur_sym);
22012     mp_print(mp, "' isn't an internal quantity");
22013     help1("Something like `tracingonline' should follow `interim'.");
22014     mp_back_error(mp);
22015   } else { 
22016     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22017   }
22018   mp_do_statement(mp);
22019 }
22020
22021 @ The following procedure is careful not to undefine the left-hand symbol
22022 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22023
22024 @<Declare action procedures for use by |do_statement|@>=
22025 void mp_do_let (MP mp) ;
22026
22027 @ @c void mp_do_let (MP mp) {
22028   pointer l; /* hash location of the left-hand symbol */
22029   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22030   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22031      mp_missing_err(mp, "=");
22032 @.Missing `='@>
22033     help3("You should have said `let symbol = something'.")
22034       ("But don't worry; I'll pretend that an equals sign")
22035       ("was present. The next token I read will be `something'.");
22036     mp_back_error(mp);
22037   }
22038   mp_get_symbol(mp);
22039   switch (mp->cur_cmd) {
22040   case defined_macro: case secondary_primary_macro:
22041   case tertiary_secondary_macro: case expression_tertiary_macro: 
22042     add_mac_ref(mp->cur_mod);
22043     break;
22044   default: 
22045     break;
22046   }
22047   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22048   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22049   else equiv(l)=mp->cur_mod;
22050   mp_get_x_next(mp);
22051 }
22052
22053 @ @<Declarations@>=
22054 void mp_grow_internals (MP mp, int l);
22055 void mp_do_new_internal (MP mp) ;
22056
22057 @ @c
22058 void mp_grow_internals (MP mp, int l) {
22059   scaled *internal;
22060   char * *int_name; 
22061   int k;
22062   if ( hash_end+l>max_halfword ) {
22063     mp_confusion(mp, "out of memory space"); /* can't be reached */
22064   }
22065   int_name = xmalloc ((l+1),sizeof(char *));
22066   internal = xmalloc ((l+1),sizeof(scaled));
22067   for (k=0;k<=l; k++ ) { 
22068     if (k<=mp->max_internal) {
22069       internal[k]=mp->internal[k]; 
22070       int_name[k]=mp->int_name[k]; 
22071     } else {
22072       internal[k]=0; 
22073       int_name[k]=NULL; 
22074     }
22075   }
22076   xfree(mp->internal); xfree(mp->int_name);
22077   mp->int_name = int_name;
22078   mp->internal = internal;
22079   mp->max_internal = l;
22080 }
22081
22082
22083 void mp_do_new_internal (MP mp) { 
22084   do {  
22085     if ( mp->int_ptr==mp->max_internal ) {
22086       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22087     }
22088     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22089     eq_type(mp->cur_sym)=internal_quantity; 
22090     equiv(mp->cur_sym)=mp->int_ptr;
22091     if(mp->int_name[mp->int_ptr]!=NULL)
22092       xfree(mp->int_name[mp->int_ptr]);
22093     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22094     mp->internal[mp->int_ptr]=0;
22095     mp_get_x_next(mp);
22096   } while (mp->cur_cmd==comma);
22097 }
22098
22099 @ @<Dealloc variables@>=
22100 for (k=0;k<=mp->max_internal;k++) {
22101    xfree(mp->int_name[k]);
22102 }
22103 xfree(mp->internal); 
22104 xfree(mp->int_name); 
22105
22106
22107 @ The various `\&{show}' commands are distinguished by modifier fields
22108 in the usual way.
22109
22110 @d show_token_code 0 /* show the meaning of a single token */
22111 @d show_stats_code 1 /* show current memory and string usage */
22112 @d show_code 2 /* show a list of expressions */
22113 @d show_var_code 3 /* show a variable and its descendents */
22114 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22115
22116 @<Put each...@>=
22117 mp_primitive(mp, "showtoken",show_command,show_token_code);
22118 @:show_token_}{\&{showtoken} primitive@>
22119 mp_primitive(mp, "showstats",show_command,show_stats_code);
22120 @:show_stats_}{\&{showstats} primitive@>
22121 mp_primitive(mp, "show",show_command,show_code);
22122 @:show_}{\&{show} primitive@>
22123 mp_primitive(mp, "showvariable",show_command,show_var_code);
22124 @:show_var_}{\&{showvariable} primitive@>
22125 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22126 @:show_dependencies_}{\&{showdependencies} primitive@>
22127
22128 @ @<Cases of |print_cmd...@>=
22129 case show_command: 
22130   switch (m) {
22131   case show_token_code:mp_print(mp, "showtoken"); break;
22132   case show_stats_code:mp_print(mp, "showstats"); break;
22133   case show_code:mp_print(mp, "show"); break;
22134   case show_var_code:mp_print(mp, "showvariable"); break;
22135   default: mp_print(mp, "showdependencies"); break;
22136   }
22137   break;
22138
22139 @ @<Cases of |do_statement|...@>=
22140 case show_command:mp_do_show_whatever(mp); break;
22141
22142 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22143 if it's |show_code|, complicated structures are abbreviated, otherwise
22144 they aren't.
22145
22146 @<Declare action procedures for use by |do_statement|@>=
22147 void mp_do_show (MP mp) ;
22148
22149 @ @c void mp_do_show (MP mp) { 
22150   do {  
22151     mp_get_x_next(mp); mp_scan_expression(mp);
22152     mp_print_nl(mp, ">> ");
22153 @.>>@>
22154     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22155   } while (mp->cur_cmd==comma);
22156 }
22157
22158 @ @<Declare action procedures for use by |do_statement|@>=
22159 void mp_disp_token (MP mp) ;
22160
22161 @ @c void mp_disp_token (MP mp) { 
22162   mp_print_nl(mp, "> ");
22163 @.>\relax@>
22164   if ( mp->cur_sym==0 ) {
22165     @<Show a numeric or string or capsule token@>;
22166   } else { 
22167     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22168     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22169     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22170     if ( mp->cur_cmd==defined_macro ) {
22171       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22172     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22173 @^recursion@>
22174   }
22175 }
22176
22177 @ @<Show a numeric or string or capsule token@>=
22178
22179   if ( mp->cur_cmd==numeric_token ) {
22180     mp_print_scaled(mp, mp->cur_mod);
22181   } else if ( mp->cur_cmd==capsule_token ) {
22182     mp_print_capsule(mp,mp->cur_mod);
22183   } else  { 
22184     mp_print_char(mp, '"'); 
22185     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22186     delete_str_ref(mp->cur_mod);
22187   }
22188 }
22189
22190 @ The following cases of |print_cmd_mod| might arise in connection
22191 with |disp_token|, although they don't correspond to any
22192 primitive tokens.
22193
22194 @<Cases of |print_cmd_...@>=
22195 case left_delimiter:
22196 case right_delimiter: 
22197   if ( c==left_delimiter ) mp_print(mp, "left");
22198   else mp_print(mp, "right");
22199   mp_print(mp, " delimiter that matches "); 
22200   mp_print_text(m);
22201   break;
22202 case tag_token:
22203   if ( m==null ) mp_print(mp, "tag");
22204    else mp_print(mp, "variable");
22205    break;
22206 case defined_macro: 
22207    mp_print(mp, "macro:");
22208    break;
22209 case secondary_primary_macro:
22210 case tertiary_secondary_macro:
22211 case expression_tertiary_macro:
22212   mp_print_cmd_mod(mp, macro_def,c); 
22213   mp_print(mp, "'d macro:");
22214   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22215   break;
22216 case repeat_loop:
22217   mp_print(mp, "[repeat the loop]");
22218   break;
22219 case internal_quantity:
22220   mp_print(mp, mp->int_name[m]);
22221   break;
22222
22223 @ @<Declare action procedures for use by |do_statement|@>=
22224 void mp_do_show_token (MP mp) ;
22225
22226 @ @c void mp_do_show_token (MP mp) { 
22227   do {  
22228     get_t_next; mp_disp_token(mp);
22229     mp_get_x_next(mp);
22230   } while (mp->cur_cmd==comma);
22231 }
22232
22233 @ @<Declare action procedures for use by |do_statement|@>=
22234 void mp_do_show_stats (MP mp) ;
22235
22236 @ @c void mp_do_show_stats (MP mp) { 
22237   mp_print_nl(mp, "Memory usage ");
22238 @.Memory usage...@>
22239   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22240   if ( false )
22241     mp_print(mp, "unknown");
22242   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22243   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22244   mp_print_nl(mp, "String usage ");
22245   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22246   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22247   if ( false )
22248     mp_print(mp, "unknown");
22249   mp_print(mp, " (");
22250   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22251   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22252   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22253   mp_get_x_next(mp);
22254 }
22255
22256 @ Here's a recursive procedure that gives an abbreviated account
22257 of a variable, for use by |do_show_var|.
22258
22259 @<Declare action procedures for use by |do_statement|@>=
22260 void mp_disp_var (MP mp,pointer p) ;
22261
22262 @ @c void mp_disp_var (MP mp,pointer p) {
22263   pointer q; /* traverses attributes and subscripts */
22264   int n; /* amount of macro text to show */
22265   if ( type(p)==mp_structured )  {
22266     @<Descend the structure@>;
22267   } else if ( type(p)>=mp_unsuffixed_macro ) {
22268     @<Display a variable macro@>;
22269   } else if ( type(p)!=undefined ){ 
22270     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22271     mp_print_char(mp, '=');
22272     mp_print_exp(mp, p,0);
22273   }
22274 }
22275
22276 @ @<Descend the structure@>=
22277
22278   q=attr_head(p);
22279   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22280   q=subscr_head(p);
22281   while ( name_type(q)==mp_subscr ) { 
22282     mp_disp_var(mp, q); q=link(q);
22283   }
22284 }
22285
22286 @ @<Display a variable macro@>=
22287
22288   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22289   if ( type(p)>mp_unsuffixed_macro ) 
22290     mp_print(mp, "@@#"); /* |suffixed_macro| */
22291   mp_print(mp, "=macro:");
22292   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22293   else n=mp->max_print_line-mp->file_offset-15;
22294   mp_show_macro(mp, value(p),null,n);
22295 }
22296
22297 @ @<Declare action procedures for use by |do_statement|@>=
22298 void mp_do_show_var (MP mp) ;
22299
22300 @ @c void mp_do_show_var (MP mp) { 
22301   do {  
22302     get_t_next;
22303     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22304       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22305       mp_disp_var(mp, mp->cur_mod); goto DONE;
22306     }
22307    mp_disp_token(mp);
22308   DONE:
22309    mp_get_x_next(mp);
22310   } while (mp->cur_cmd==comma);
22311 }
22312
22313 @ @<Declare action procedures for use by |do_statement|@>=
22314 void mp_do_show_dependencies (MP mp) ;
22315
22316 @ @c void mp_do_show_dependencies (MP mp) {
22317   pointer p; /* link that runs through all dependencies */
22318   p=link(dep_head);
22319   while ( p!=dep_head ) {
22320     if ( mp_interesting(mp, p) ) {
22321       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22322       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22323       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22324       mp_print_dependency(mp, dep_list(p),type(p));
22325     }
22326     p=dep_list(p);
22327     while ( info(p)!=null ) p=link(p);
22328     p=link(p);
22329   }
22330   mp_get_x_next(mp);
22331 }
22332
22333 @ Finally we are ready for the procedure that governs all of the
22334 show commands.
22335
22336 @<Declare action procedures for use by |do_statement|@>=
22337 void mp_do_show_whatever (MP mp) ;
22338
22339 @ @c void mp_do_show_whatever (MP mp) { 
22340   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22341   switch (mp->cur_mod) {
22342   case show_token_code:mp_do_show_token(mp); break;
22343   case show_stats_code:mp_do_show_stats(mp); break;
22344   case show_code:mp_do_show(mp); break;
22345   case show_var_code:mp_do_show_var(mp); break;
22346   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22347   } /* there are no other cases */
22348   if ( mp->internal[mp_showstopping]>0 ){ 
22349     print_err("OK");
22350 @.OK@>
22351     if ( mp->interaction<mp_error_stop_mode ) { 
22352       help0; decr(mp->error_count);
22353     } else {
22354       help1("This isn't an error message; I'm just showing something.");
22355     }
22356     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22357      else mp_put_get_error(mp);
22358   }
22359 }
22360
22361 @ The `\&{addto}' command needs the following additional primitives:
22362
22363 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22364 @d contour_code 1 /* command modifier for `\&{contour}' */
22365 @d also_code 2 /* command modifier for `\&{also}' */
22366
22367 @ Pre and postscripts need two new identifiers:
22368
22369 @d with_pre_script 11
22370 @d with_post_script 13
22371
22372 @<Put each...@>=
22373 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22374 @:double_path_}{\&{doublepath} primitive@>
22375 mp_primitive(mp, "contour",thing_to_add,contour_code);
22376 @:contour_}{\&{contour} primitive@>
22377 mp_primitive(mp, "also",thing_to_add,also_code);
22378 @:also_}{\&{also} primitive@>
22379 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22380 @:with_pen_}{\&{withpen} primitive@>
22381 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22382 @:dashed_}{\&{dashed} primitive@>
22383 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22384 @:with_pre_script_}{\&{withprescript} primitive@>
22385 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22386 @:with_post_script_}{\&{withpostscript} primitive@>
22387 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22388 @:with_color_}{\&{withoutcolor} primitive@>
22389 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22390 @:with_color_}{\&{withgreyscale} primitive@>
22391 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22392 @:with_color_}{\&{withcolor} primitive@>
22393 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22394 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22395 @:with_color_}{\&{withrgbcolor} primitive@>
22396 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22397 @:with_color_}{\&{withcmykcolor} primitive@>
22398
22399 @ @<Cases of |print_cmd...@>=
22400 case thing_to_add:
22401   if ( m==contour_code ) mp_print(mp, "contour");
22402   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22403   else mp_print(mp, "also");
22404   break;
22405 case with_option:
22406   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22407   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22408   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22409   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22410   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22411   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22412   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22413   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22414   else mp_print(mp, "dashed");
22415   break;
22416
22417 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22418 updates the list of graphical objects starting at |p|.  Each $\langle$with
22419 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22420 Other objects are ignored.
22421
22422 @<Declare action procedures for use by |do_statement|@>=
22423 void mp_scan_with_list (MP mp,pointer p) ;
22424
22425 @ @c void mp_scan_with_list (MP mp,pointer p) {
22426   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22427   pointer q; /* for list manipulation */
22428   int old_setting; /* saved |selector| setting */
22429   pointer k; /* for finding the near-last item in a list  */
22430   str_number s; /* for string cleanup after combining  */
22431   pointer cp,pp,dp,ap,bp;
22432     /* objects being updated; |void| initially; |null| to suppress update */
22433   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22434   k=0;
22435   while ( mp->cur_cmd==with_option ){ 
22436     t=mp->cur_mod;
22437     mp_get_x_next(mp);
22438     if ( t!=mp_no_model ) mp_scan_expression(mp);
22439     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22440      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22441      ((t==mp_uninitialized_model)&&
22442         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22443           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22444      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22445      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22446      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22447      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22448      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22449       @<Complain about improper type@>;
22450     } else if ( t==mp_uninitialized_model ) {
22451       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22452       if ( cp!=null )
22453         @<Transfer a color from the current expression to object~|cp|@>;
22454       mp_flush_cur_exp(mp, 0);
22455     } else if ( t==mp_rgb_model ) {
22456       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22457       if ( cp!=null )
22458         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22459       mp_flush_cur_exp(mp, 0);
22460     } else if ( t==mp_cmyk_model ) {
22461       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22462       if ( cp!=null )
22463         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22464       mp_flush_cur_exp(mp, 0);
22465     } else if ( t==mp_grey_model ) {
22466       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22467       if ( cp!=null )
22468         @<Transfer a greyscale from the current expression to object~|cp|@>;
22469       mp_flush_cur_exp(mp, 0);
22470     } else if ( t==mp_no_model ) {
22471       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22472       if ( cp!=null )
22473         @<Transfer a noncolor from the current expression to object~|cp|@>;
22474     } else if ( t==mp_pen_type ) {
22475       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22476       if ( pp!=null ) {
22477         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22478         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22479       }
22480     } else if ( t==with_pre_script ) {
22481       if ( ap==mp_void )
22482         ap=p;
22483       while ( (ap!=null)&&(! has_color(ap)) )
22484          ap=link(ap);
22485       if ( ap!=null ) {
22486         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22487           s=pre_script(ap);
22488           old_setting=mp->selector;
22489               mp->selector=new_string;
22490           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22491               mp_print_str(mp, mp->cur_exp);
22492           append_char(13);  /* a forced \ps\ newline  */
22493           mp_print_str(mp, pre_script(ap));
22494           pre_script(ap)=mp_make_string(mp);
22495           delete_str_ref(s);
22496           mp->selector=old_setting;
22497         } else {
22498           pre_script(ap)=mp->cur_exp;
22499         }
22500         mp->cur_type=mp_vacuous;
22501       }
22502     } else if ( t==with_post_script ) {
22503       if ( bp==mp_void )
22504         k=p; 
22505       bp=k;
22506       while ( link(k)!=null ) {
22507         k=link(k);
22508         if ( has_color(k) ) bp=k;
22509       }
22510       if ( bp!=null ) {
22511          if ( post_script(bp)!=null ) {
22512            s=post_script(bp);
22513            old_setting=mp->selector;
22514                mp->selector=new_string;
22515            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22516            mp_print_str(mp, post_script(bp));
22517            append_char(13); /* a forced \ps\ newline  */
22518            mp_print_str(mp, mp->cur_exp);
22519            post_script(bp)=mp_make_string(mp);
22520            delete_str_ref(s);
22521            mp->selector=old_setting;
22522          } else {
22523            post_script(bp)=mp->cur_exp;
22524          }
22525          mp->cur_type=mp_vacuous;
22526        }
22527     } else { 
22528       if ( dp==mp_void ) {
22529         @<Make |dp| a stroked node in list~|p|@>;
22530       }
22531       if ( dp!=null ) {
22532         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22533         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22534         dash_scale(dp)=unity;
22535         mp->cur_type=mp_vacuous;
22536       }
22537     }
22538   }
22539   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22540     of the list@>;
22541 };
22542
22543 @ @<Complain about improper type@>=
22544 { exp_err("Improper type");
22545 @.Improper type@>
22546 help2("Next time say `withpen <known pen expression>';")
22547   ("I'll ignore the bad `with' clause and look for another.");
22548 if ( t==with_pre_script )
22549   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22550 else if ( t==with_post_script )
22551   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22552 else if ( t==mp_picture_type )
22553   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22554 else if ( t==mp_uninitialized_model )
22555   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22556 else if ( t==mp_rgb_model )
22557   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22558 else if ( t==mp_cmyk_model )
22559   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22560 else if ( t==mp_grey_model )
22561   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22562 mp_put_get_flush_error(mp, 0);
22563 }
22564
22565 @ Forcing the color to be between |0| and |unity| here guarantees that no
22566 picture will ever contain a color outside the legal range for \ps\ graphics.
22567
22568 @<Transfer a color from the current expression to object~|cp|@>=
22569 { if ( mp->cur_type==mp_color_type )
22570    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22571 else if ( mp->cur_type==mp_cmykcolor_type )
22572    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22573 else if ( mp->cur_type==mp_known )
22574    @<Transfer a greyscale from the current expression to object~|cp|@>
22575 else if ( mp->cur_exp==false_code )
22576    @<Transfer a noncolor from the current expression to object~|cp|@>;
22577 }
22578
22579 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22580 { q=value(mp->cur_exp);
22581 cyan_val(cp)=0;
22582 magenta_val(cp)=0;
22583 yellow_val(cp)=0;
22584 black_val(cp)=0;
22585 red_val(cp)=value(red_part_loc(q));
22586 green_val(cp)=value(green_part_loc(q));
22587 blue_val(cp)=value(blue_part_loc(q));
22588 color_model(cp)=mp_rgb_model;
22589 if ( red_val(cp)<0 ) red_val(cp)=0;
22590 if ( green_val(cp)<0 ) green_val(cp)=0;
22591 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22592 if ( red_val(cp)>unity ) red_val(cp)=unity;
22593 if ( green_val(cp)>unity ) green_val(cp)=unity;
22594 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22595 }
22596
22597 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22598 { q=value(mp->cur_exp);
22599 cyan_val(cp)=value(cyan_part_loc(q));
22600 magenta_val(cp)=value(magenta_part_loc(q));
22601 yellow_val(cp)=value(yellow_part_loc(q));
22602 black_val(cp)=value(black_part_loc(q));
22603 color_model(cp)=mp_cmyk_model;
22604 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22605 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22606 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22607 if ( black_val(cp)<0 ) black_val(cp)=0;
22608 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22609 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22610 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22611 if ( black_val(cp)>unity ) black_val(cp)=unity;
22612 }
22613
22614 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22615 { q=mp->cur_exp;
22616 cyan_val(cp)=0;
22617 magenta_val(cp)=0;
22618 yellow_val(cp)=0;
22619 black_val(cp)=0;
22620 grey_val(cp)=q;
22621 color_model(cp)=mp_grey_model;
22622 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22623 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22624 }
22625
22626 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22627 {
22628 cyan_val(cp)=0;
22629 magenta_val(cp)=0;
22630 yellow_val(cp)=0;
22631 black_val(cp)=0;
22632 grey_val(cp)=0;
22633 color_model(cp)=mp_no_model;
22634 }
22635
22636 @ @<Make |cp| a colored object in object list~|p|@>=
22637 { cp=p;
22638   while ( cp!=null ){ 
22639     if ( has_color(cp) ) break;
22640     cp=link(cp);
22641   }
22642 }
22643
22644 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22645 { pp=p;
22646   while ( pp!=null ) {
22647     if ( has_pen(pp) ) break;
22648     pp=link(pp);
22649   }
22650 }
22651
22652 @ @<Make |dp| a stroked node in list~|p|@>=
22653 { dp=p;
22654   while ( dp!=null ) {
22655     if ( type(dp)==mp_stroked_code ) break;
22656     dp=link(dp);
22657   }
22658 }
22659
22660 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22661 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22662 if ( pp>mp_void ) {
22663   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22664 }
22665 if ( dp>mp_void ) {
22666   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22667 }
22668
22669
22670 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22671 { q=link(cp);
22672   while ( q!=null ) { 
22673     if ( has_color(q) ) {
22674       red_val(q)=red_val(cp);
22675       green_val(q)=green_val(cp);
22676       blue_val(q)=blue_val(cp);
22677       black_val(q)=black_val(cp);
22678       color_model(q)=color_model(cp);
22679     }
22680     q=link(q);
22681   }
22682 }
22683
22684 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22685 { q=link(pp);
22686   while ( q!=null ) {
22687     if ( has_pen(q) ) {
22688       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22689       pen_p(q)=copy_pen(pen_p(pp));
22690     }
22691     q=link(q);
22692   }
22693 }
22694
22695 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22696 { q=link(dp);
22697   while ( q!=null ) {
22698     if ( type(q)==mp_stroked_code ) {
22699       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22700       dash_p(q)=dash_p(dp);
22701       dash_scale(q)=unity;
22702       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22703     }
22704     q=link(q);
22705   }
22706 }
22707
22708 @ One of the things we need to do when we've parsed an \&{addto} or
22709 similar command is find the header of a supposed \&{picture} variable, given
22710 a token list for that variable.  Since the edge structure is about to be
22711 updated, we use |private_edges| to make sure that this is possible.
22712
22713 @<Declare action procedures for use by |do_statement|@>=
22714 pointer mp_find_edges_var (MP mp, pointer t) ;
22715
22716 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22717   pointer p;
22718   pointer cur_edges; /* the return value */
22719   p=mp_find_variable(mp, t); cur_edges=null;
22720   if ( p==null ) { 
22721     mp_obliterated(mp, t); mp_put_get_error(mp);
22722   } else if ( type(p)!=mp_picture_type )  { 
22723     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22724 @.Variable x is the wrong type@>
22725     mp_print(mp, " is the wrong type ("); 
22726     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22727     help2("I was looking for a \"known\" picture variable.")
22728          ("So I'll not change anything just now."); 
22729     mp_put_get_error(mp);
22730   } else { 
22731     value(p)=mp_private_edges(mp, value(p));
22732     cur_edges=value(p);
22733   }
22734   mp_flush_node_list(mp, t);
22735   return cur_edges;
22736 };
22737
22738 @ @<Cases of |do_statement|...@>=
22739 case add_to_command: mp_do_add_to(mp); break;
22740 case bounds_command:mp_do_bounds(mp); break;
22741
22742 @ @<Put each...@>=
22743 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22744 @:clip_}{\&{clip} primitive@>
22745 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22746 @:set_bounds_}{\&{setbounds} primitive@>
22747
22748 @ @<Cases of |print_cmd...@>=
22749 case bounds_command: 
22750   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22751   else mp_print(mp, "setbounds");
22752   break;
22753
22754 @ The following function parses the beginning of an \&{addto} or \&{clip}
22755 command: it expects a variable name followed by a token with |cur_cmd=sep|
22756 and then an expression.  The function returns the token list for the variable
22757 and stores the command modifier for the separator token in the global variable
22758 |last_add_type|.  We must be careful because this variable might get overwritten
22759 any time we call |get_x_next|.
22760
22761 @<Glob...@>=
22762 quarterword last_add_type;
22763   /* command modifier that identifies the last \&{addto} command */
22764
22765 @ @<Declare action procedures for use by |do_statement|@>=
22766 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22767
22768 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22769   pointer lhv; /* variable to add to left */
22770   quarterword add_type=0; /* value to be returned in |last_add_type| */
22771   lhv=null;
22772   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22773   if ( mp->cur_type!=mp_token_list ) {
22774     @<Abandon edges command because there's no variable@>;
22775   } else  { 
22776     lhv=mp->cur_exp; add_type=mp->cur_mod;
22777     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22778   }
22779   mp->last_add_type=add_type;
22780   return lhv;
22781 }
22782
22783 @ @<Abandon edges command because there's no variable@>=
22784 { exp_err("Not a suitable variable");
22785 @.Not a suitable variable@>
22786   help4("At this point I needed to see the name of a picture variable.")
22787     ("(Or perhaps you have indeed presented me with one; I might")
22788     ("have missed it, if it wasn't followed by the proper token.)")
22789     ("So I'll not change anything just now.");
22790   mp_put_get_flush_error(mp, 0);
22791 }
22792
22793 @ Here is an example of how to use |start_draw_cmd|.
22794
22795 @<Declare action procedures for use by |do_statement|@>=
22796 void mp_do_bounds (MP mp) ;
22797
22798 @ @c void mp_do_bounds (MP mp) {
22799   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22800   pointer p; /* for list manipulation */
22801   integer m; /* initial value of |cur_mod| */
22802   m=mp->cur_mod;
22803   lhv=mp_start_draw_cmd(mp, to_token);
22804   if ( lhv!=null ) {
22805     lhe=mp_find_edges_var(mp, lhv);
22806     if ( lhe==null ) {
22807       mp_flush_cur_exp(mp, 0);
22808     } else if ( mp->cur_type!=mp_path_type ) {
22809       exp_err("Improper `clip'");
22810 @.Improper `addto'@>
22811       help2("This expression should have specified a known path.")
22812         ("So I'll not change anything just now."); 
22813       mp_put_get_flush_error(mp, 0);
22814     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22815       @<Complain about a non-cycle@>;
22816     } else {
22817       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22818     }
22819   }
22820 }
22821
22822 @ @<Complain about a non-cycle@>=
22823 { print_err("Not a cycle");
22824 @.Not a cycle@>
22825   help2("That contour should have ended with `..cycle' or `&cycle'.")
22826     ("So I'll not change anything just now."); mp_put_get_error(mp);
22827 }
22828
22829 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22830 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22831   link(p)=link(dummy_loc(lhe));
22832   link(dummy_loc(lhe))=p;
22833   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22834   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22835   type(p)=stop_type(m);
22836   link(obj_tail(lhe))=p;
22837   obj_tail(lhe)=p;
22838   mp_init_bbox(mp, lhe);
22839 }
22840
22841 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22842 cases to deal with.
22843
22844 @<Declare action procedures for use by |do_statement|@>=
22845 void mp_do_add_to (MP mp) ;
22846
22847 @ @c void mp_do_add_to (MP mp) {
22848   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22849   pointer p; /* the graphical object or list for |scan_with_list| to update */
22850   pointer e; /* an edge structure to be merged */
22851   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22852   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22853   if ( lhv!=null ) {
22854     if ( add_type==also_code ) {
22855       @<Make sure the current expression is a suitable picture and set |e| and |p|
22856        appropriately@>;
22857     } else {
22858       @<Create a graphical object |p| based on |add_type| and the current
22859         expression@>;
22860     }
22861     mp_scan_with_list(mp, p);
22862     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22863   }
22864 }
22865
22866 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22867 setting |e:=null| prevents anything from being added to |lhe|.
22868
22869 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22870
22871   p=null; e=null;
22872   if ( mp->cur_type!=mp_picture_type ) {
22873     exp_err("Improper `addto'");
22874 @.Improper `addto'@>
22875     help2("This expression should have specified a known picture.")
22876       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22877   } else { 
22878     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22879     p=link(dummy_loc(e));
22880   }
22881 }
22882
22883 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22884 attempts to add to the edge structure.
22885
22886 @<Create a graphical object |p| based on |add_type| and the current...@>=
22887 { e=null; p=null;
22888   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22889   if ( mp->cur_type!=mp_path_type ) {
22890     exp_err("Improper `addto'");
22891 @.Improper `addto'@>
22892     help2("This expression should have specified a known path.")
22893       ("So I'll not change anything just now."); 
22894     mp_put_get_flush_error(mp, 0);
22895   } else if ( add_type==contour_code ) {
22896     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22897       @<Complain about a non-cycle@>;
22898     } else { 
22899       p=mp_new_fill_node(mp, mp->cur_exp);
22900       mp->cur_type=mp_vacuous;
22901     }
22902   } else { 
22903     p=mp_new_stroked_node(mp, mp->cur_exp);
22904     mp->cur_type=mp_vacuous;
22905   }
22906 }
22907
22908 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22909 lhe=mp_find_edges_var(mp, lhv);
22910 if ( lhe==null ) {
22911   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22912   if ( e!=null ) delete_edge_ref(e);
22913 } else if ( add_type==also_code ) {
22914   if ( e!=null ) {
22915     @<Merge |e| into |lhe| and delete |e|@>;
22916   } else { 
22917     do_nothing;
22918   }
22919 } else if ( p!=null ) {
22920   link(obj_tail(lhe))=p;
22921   obj_tail(lhe)=p;
22922   if ( add_type==double_path_code )
22923     if ( pen_p(p)==null ) 
22924       pen_p(p)=mp_get_pen_circle(mp, 0);
22925 }
22926
22927 @ @<Merge |e| into |lhe| and delete |e|@>=
22928 { if ( link(dummy_loc(e))!=null ) {
22929     link(obj_tail(lhe))=link(dummy_loc(e));
22930     obj_tail(lhe)=obj_tail(e);
22931     obj_tail(e)=dummy_loc(e);
22932     link(dummy_loc(e))=null;
22933     mp_flush_dash_list(mp, lhe);
22934   }
22935   mp_toss_edges(mp, e);
22936 }
22937
22938 @ @<Cases of |do_statement|...@>=
22939 case ship_out_command: mp_do_ship_out(mp); break;
22940
22941 @ @<Declare action procedures for use by |do_statement|@>=
22942 @<Declare the function called |tfm_check|@>;
22943 @<Declare the \ps\ output procedures@>;
22944 void mp_do_ship_out (MP mp) ;
22945
22946 @ @c void mp_do_ship_out (MP mp) {
22947   integer c; /* the character code */
22948   mp_get_x_next(mp); mp_scan_expression(mp);
22949   if ( mp->cur_type!=mp_picture_type ) {
22950     @<Complain that it's not a known picture@>;
22951   } else { 
22952     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
22953     if ( c<0 ) c=c+256;
22954     @<Store the width information for character code~|c|@>;
22955     mp_ship_out(mp, mp->cur_exp);
22956     mp_flush_cur_exp(mp, 0);
22957   }
22958 }
22959
22960 @ @<Complain that it's not a known picture@>=
22961
22962   exp_err("Not a known picture");
22963   help1("I can only output known pictures.");
22964   mp_put_get_flush_error(mp, 0);
22965 }
22966
22967 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22968 |start_sym|.
22969
22970 @<Cases of |do_statement|...@>=
22971 case every_job_command: 
22972   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22973   break;
22974
22975 @ @<Glob...@>=
22976 halfword start_sym; /* a symbolic token to insert at beginning of job */
22977
22978 @ @<Set init...@>=
22979 mp->start_sym=0;
22980
22981 @ Finally, we have only the ``message'' commands remaining.
22982
22983 @d message_code 0
22984 @d err_message_code 1
22985 @d err_help_code 2
22986 @d filename_template_code 3
22987 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22988               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22989               if ( f>g ) {
22990                 mp->pool_ptr = mp->pool_ptr - g;
22991                 while ( f>g ) {
22992                   mp_print_char(mp, '0');
22993                   decr(f);
22994                   };
22995                 mp_print_int(mp, (A));
22996               };
22997               f = 0
22998
22999 @<Put each...@>=
23000 mp_primitive(mp, "message",message_command,message_code);
23001 @:message_}{\&{message} primitive@>
23002 mp_primitive(mp, "errmessage",message_command,err_message_code);
23003 @:err_message_}{\&{errmessage} primitive@>
23004 mp_primitive(mp, "errhelp",message_command,err_help_code);
23005 @:err_help_}{\&{errhelp} primitive@>
23006 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23007 @:filename_template_}{\&{filenametemplate} primitive@>
23008
23009 @ @<Cases of |print_cmd...@>=
23010 case message_command: 
23011   if ( m<err_message_code ) mp_print(mp, "message");
23012   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23013   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23014   else mp_print(mp, "errhelp");
23015   break;
23016
23017 @ @<Cases of |do_statement|...@>=
23018 case message_command: mp_do_message(mp); break;
23019
23020 @ @<Declare action procedures for use by |do_statement|@>=
23021 @<Declare a procedure called |no_string_err|@>;
23022 void mp_do_message (MP mp) ;
23023
23024
23025 @c void mp_do_message (MP mp) {
23026   int m; /* the type of message */
23027   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23028   if ( mp->cur_type!=mp_string_type )
23029     mp_no_string_err(mp, "A message should be a known string expression.");
23030   else {
23031     switch (m) {
23032     case message_code: 
23033       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23034       break;
23035     case err_message_code:
23036       @<Print string |cur_exp| as an error message@>;
23037       break;
23038     case err_help_code:
23039       @<Save string |cur_exp| as the |err_help|@>;
23040       break;
23041     case filename_template_code:
23042       @<Save the filename template@>;
23043       break;
23044     } /* there are no other cases */
23045   }
23046   mp_flush_cur_exp(mp, 0);
23047 }
23048
23049 @ @<Declare a procedure called |no_string_err|@>=
23050 void mp_no_string_err (MP mp,char *s) { 
23051    exp_err("Not a string");
23052 @.Not a string@>
23053   help1(s);
23054   mp_put_get_error(mp);
23055 }
23056
23057 @ The global variable |err_help| is zero when the user has most recently
23058 given an empty help string, or if none has ever been given.
23059
23060 @<Save string |cur_exp| as the |err_help|@>=
23061
23062   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23063   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23064   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23065 }
23066
23067 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23068 \&{errhelp}, we don't want to give a long help message each time. So we
23069 give a verbose explanation only once.
23070
23071 @<Glob...@>=
23072 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23073
23074 @ @<Set init...@>=mp->long_help_seen=false;
23075
23076 @ @<Print string |cur_exp| as an error message@>=
23077
23078   print_err(""); mp_print_str(mp, mp->cur_exp);
23079   if ( mp->err_help!=0 ) {
23080     mp->use_err_help=true;
23081   } else if ( mp->long_help_seen ) { 
23082     help1("(That was another `errmessage'.)") ; 
23083   } else  { 
23084    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23085     help4("This error message was generated by an `errmessage'")
23086      ("command, so I can\'t give any explicit help.")
23087      ("Pretend that you're Miss Marple: Examine all clues,")
23088 @^Marple, Jane@>
23089      ("and deduce the truth by inspired guesses.");
23090   }
23091   mp_put_get_error(mp); mp->use_err_help=false;
23092 }
23093
23094 @ @<Cases of |do_statement|...@>=
23095 case write_command: mp_do_write(mp); break;
23096
23097 @ @<Declare action procedures for use by |do_statement|@>=
23098 void mp_do_write (MP mp) ;
23099
23100 @ @c void mp_do_write (MP mp) {
23101   str_number t; /* the line of text to be written */
23102   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23103   int old_setting; /* for saving |selector| during output */
23104   mp_get_x_next(mp);
23105   mp_scan_expression(mp);
23106   if ( mp->cur_type!=mp_string_type ) {
23107     mp_no_string_err(mp, "The text to be written should be a known string expression");
23108   } else if ( mp->cur_cmd!=to_token ) { 
23109     print_err("Missing `to' clause");
23110     help1("A write command should end with `to <filename>'");
23111     mp_put_get_error(mp);
23112   } else { 
23113     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23114     mp_get_x_next(mp);
23115     mp_scan_expression(mp);
23116     if ( mp->cur_type!=mp_string_type )
23117       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23118     else {
23119       @<Write |t| to the file named by |cur_exp|@>;
23120     }
23121     delete_str_ref(t);
23122   }
23123   mp_flush_cur_exp(mp, 0);
23124 }
23125
23126 @ @<Write |t| to the file named by |cur_exp|@>=
23127
23128   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23129     |cur_exp| must be inserted@>;
23130   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23131     @<Record the end of file on |wr_file[n]|@>;
23132   } else { 
23133     old_setting=mp->selector;
23134     mp->selector=n+write_file;
23135     mp_print_str(mp, t); mp_print_ln(mp);
23136     mp->selector = old_setting;
23137   }
23138 }
23139
23140 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23141 {
23142   char *fn = str(mp->cur_exp);
23143   n=mp->write_files;
23144   n0=mp->write_files;
23145   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23146     if ( n==0 ) { /* bottom reached */
23147           if ( n0==mp->write_files ) {
23148         if ( mp->write_files<mp->max_write_files ) {
23149           incr(mp->write_files);
23150         } else {
23151           void **wr_file;
23152           char **wr_fname;
23153               write_index l,k;
23154           l = mp->max_write_files + (mp->max_write_files>>2);
23155           wr_file = xmalloc((l+1),sizeof(void *));
23156           wr_fname = xmalloc((l+1),sizeof(char *));
23157               for (k=0;k<=l;k++) {
23158             if (k<=mp->max_write_files) {
23159                   wr_file[k]=mp->wr_file[k]; 
23160               wr_fname[k]=mp->wr_fname[k];
23161             } else {
23162                   wr_file[k]=0; 
23163               wr_fname[k]=NULL;
23164             }
23165           }
23166               xfree(mp->wr_file); xfree(mp->wr_fname);
23167           mp->max_write_files = l;
23168           mp->wr_file = wr_file;
23169           mp->wr_fname = wr_fname;
23170         }
23171       }
23172       n=n0;
23173       mp_open_write_file(mp, fn ,n);
23174     } else { 
23175       decr(n);
23176           if ( mp->wr_fname[n]==NULL )  n0=n; 
23177     }
23178   }
23179 }
23180
23181 @ @<Record the end of file on |wr_file[n]|@>=
23182 { (mp->close_file)(mp->wr_file[n]);
23183   xfree(mp->wr_fname[n]);
23184   mp->wr_fname[n]=NULL;
23185   if ( n==mp->write_files-1 ) mp->write_files=n;
23186 }
23187
23188
23189 @* \[42] Writing font metric data.
23190 \TeX\ gets its knowledge about fonts from font metric files, also called
23191 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23192 but other programs know about them too. One of \MP's duties is to
23193 write \.{TFM} files so that the user's fonts can readily be
23194 applied to typesetting.
23195 @:TFM files}{\.{TFM} files@>
23196 @^font metric files@>
23197
23198 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23199 Since the number of bytes is always a multiple of~4, we could
23200 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23201 byte interpretation. The format of \.{TFM} files was designed by
23202 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23203 @^Ramshaw, Lyle Harold@>
23204 of information in a compact but useful form.
23205
23206 @<Glob...@>=
23207 void * tfm_file; /* the font metric output goes here */
23208 char * metric_file_name; /* full name of the font metric file */
23209
23210 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23211 integers that give the lengths of the various subsequent portions
23212 of the file. These twelve integers are, in order:
23213 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23214 |lf|&length of the entire file, in words;\cr
23215 |lh|&length of the header data, in words;\cr
23216 |bc|&smallest character code in the font;\cr
23217 |ec|&largest character code in the font;\cr
23218 |nw|&number of words in the width table;\cr
23219 |nh|&number of words in the height table;\cr
23220 |nd|&number of words in the depth table;\cr
23221 |ni|&number of words in the italic correction table;\cr
23222 |nl|&number of words in the lig/kern table;\cr
23223 |nk|&number of words in the kern table;\cr
23224 |ne|&number of words in the extensible character table;\cr
23225 |np|&number of font parameter words.\cr}}$$
23226 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23227 |ne<=256|, and
23228 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23229 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23230 and as few as 0 characters (if |bc=ec+1|).
23231
23232 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23233 16 or more bits, the most significant bytes appear first in the file.
23234 This is called BigEndian order.
23235 @^BigEndian order@>
23236
23237 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23238 arrays.
23239
23240 The most important data type used here is a |fix_word|, which is
23241 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23242 quantity, with the two's complement of the entire word used to represent
23243 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23244 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23245 the smallest is $-2048$. We will see below, however, that all but two of
23246 the |fix_word| values must lie between $-16$ and $+16$.
23247
23248 @ The first data array is a block of header information, which contains
23249 general facts about the font. The header must contain at least two words,
23250 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23251 header information of use to other software routines might also be
23252 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23253 For example, 16 more words of header information are in use at the Xerox
23254 Palo Alto Research Center; the first ten specify the character coding
23255 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23256 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23257 last gives the ``face byte.''
23258
23259 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23260 the \.{GF} output file. This helps ensure consistency between files,
23261 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23262 should match the check sums on actual fonts that are used.  The actual
23263 relation between this check sum and the rest of the \.{TFM} file is not
23264 important; the check sum is simply an identification number with the
23265 property that incompatible fonts almost always have distinct check sums.
23266 @^check sum@>
23267
23268 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23269 font, in units of \TeX\ points. This number must be at least 1.0; it is
23270 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23271 font, i.e., a font that was designed to look best at a 10-point size,
23272 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23273 $\delta$ \.{pt}', the effect is to override the design size and replace it
23274 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23275 the font image by a factor of $\delta$ divided by the design size.  {\sl
23276 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23277 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23278 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23279 since many fonts have a design size equal to one em.  The other dimensions
23280 must be less than 16 design-size units in absolute value; thus,
23281 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23282 \.{TFM} file whose first byte might be something besides 0 or 255.
23283
23284 @ Next comes the |char_info| array, which contains one |char_info_word|
23285 per character. Each word in this part of the file contains six fields
23286 packed into four bytes as follows.
23287
23288 \yskip\hang first byte: |width_index| (8 bits)\par
23289 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23290   (4~bits)\par
23291 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23292   (2~bits)\par
23293 \hang fourth byte: |remainder| (8 bits)\par
23294 \yskip\noindent
23295 The actual width of a character is \\{width}|[width_index]|, in design-size
23296 units; this is a device for compressing information, since many characters
23297 have the same width. Since it is quite common for many characters
23298 to have the same height, depth, or italic correction, the \.{TFM} format
23299 imposes a limit of 16 different heights, 16 different depths, and
23300 64 different italic corrections.
23301
23302 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23303 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23304 value of zero.  The |width_index| should never be zero unless the
23305 character does not exist in the font, since a character is valid if and
23306 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23307
23308 @ The |tag| field in a |char_info_word| has four values that explain how to
23309 interpret the |remainder| field.
23310
23311 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23312 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23313 program starting at location |remainder| in the |lig_kern| array.\par
23314 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23315 characters of ascending sizes, and not the largest in the chain.  The
23316 |remainder| field gives the character code of the next larger character.\par
23317 \hang|tag=3| (|ext_tag|) means that this character code represents an
23318 extensible character, i.e., a character that is built up of smaller pieces
23319 so that it can be made arbitrarily large. The pieces are specified in
23320 |exten[remainder]|.\par
23321 \yskip\noindent
23322 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23323 unless they are used in special circumstances in math formulas. For example,
23324 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23325 operation looks for both |list_tag| and |ext_tag|.
23326
23327 @d no_tag 0 /* vanilla character */
23328 @d lig_tag 1 /* character has a ligature/kerning program */
23329 @d list_tag 2 /* character has a successor in a charlist */
23330 @d ext_tag 3 /* character is extensible */
23331
23332 @ The |lig_kern| array contains instructions in a simple programming language
23333 that explains what to do for special letter pairs. Each word in this array is a
23334 |lig_kern_command| of four bytes.
23335
23336 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23337   step if the byte is 128 or more, otherwise the next step is obtained by
23338   skipping this number of intervening steps.\par
23339 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23340   then perform the operation and stop, otherwise continue.''\par
23341 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23342   a kern step otherwise.\par
23343 \hang fourth byte: |remainder|.\par
23344 \yskip\noindent
23345 In a kern step, an
23346 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23347 between the current character and |next_char|. This amount is
23348 often negative, so that the characters are brought closer together
23349 by kerning; but it might be positive.
23350
23351 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23352 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23353 |remainder| is inserted between the current character and |next_char|;
23354 then the current character is deleted if $b=0$, and |next_char| is
23355 deleted if $c=0$; then we pass over $a$~characters to reach the next
23356 current character (which may have a ligature/kerning program of its own).
23357
23358 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23359 the |next_char| byte is the so-called right boundary character of this font;
23360 the value of |next_char| need not lie between |bc| and~|ec|.
23361 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23362 there is a special ligature/kerning program for a left boundary character,
23363 beginning at location |256*op_byte+remainder|.
23364 The interpretation is that \TeX\ puts implicit boundary characters
23365 before and after each consecutive string of characters from the same font.
23366 These implicit characters do not appear in the output, but they can affect
23367 ligatures and kerning.
23368
23369 If the very first instruction of a character's |lig_kern| program has
23370 |skip_byte>128|, the program actually begins in location
23371 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23372 arrays, because the first instruction must otherwise
23373 appear in a location |<=255|.
23374
23375 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23376 the condition
23377 $$\hbox{|256*op_byte+remainder<nl|.}$$
23378 If such an instruction is encountered during
23379 normal program execution, it denotes an unconditional halt; no ligature
23380 command is performed.
23381
23382 @d stop_flag (128)
23383   /* value indicating `\.{STOP}' in a lig/kern program */
23384 @d kern_flag (128) /* op code for a kern step */
23385 @d skip_byte(A) mp->lig_kern[(A)].b0
23386 @d next_char(A) mp->lig_kern[(A)].b1
23387 @d op_byte(A) mp->lig_kern[(A)].b2
23388 @d rem_byte(A) mp->lig_kern[(A)].b3
23389
23390 @ Extensible characters are specified by an |extensible_recipe|, which
23391 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23392 order). These bytes are the character codes of individual pieces used to
23393 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23394 present in the built-up result. For example, an extensible vertical line is
23395 like an extensible bracket, except that the top and bottom pieces are missing.
23396
23397 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23398 if the piece isn't present. Then the extensible characters have the form
23399 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23400 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23401 The width of the extensible character is the width of $R$; and the
23402 height-plus-depth is the sum of the individual height-plus-depths of the
23403 components used, since the pieces are butted together in a vertical list.
23404
23405 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23406 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23407 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23408 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23409
23410 @ The final portion of a \.{TFM} file is the |param| array, which is another
23411 sequence of |fix_word| values.
23412
23413 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23414 to help position accents. For example, |slant=.25| means that when you go
23415 up one unit, you also go .25 units to the right. The |slant| is a pure
23416 number; it is the only |fix_word| other than the design size itself that is
23417 not scaled by the design size.
23418
23419 \hang|param[2]=space| is the normal spacing between words in text.
23420 Note that character 040 in the font need not have anything to do with
23421 blank spaces.
23422
23423 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23424
23425 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23426
23427 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23428 the height of letters for which accents don't have to be raised or lowered.
23429
23430 \hang|param[6]=quad| is the size of one em in the font.
23431
23432 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23433 ends of sentences.
23434
23435 \yskip\noindent
23436 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23437 to zero.
23438
23439 @d slant_code 1
23440 @d space_code 2
23441 @d space_stretch_code 3
23442 @d space_shrink_code 4
23443 @d x_height_code 5
23444 @d quad_code 6
23445 @d extra_space_code 7
23446
23447 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23448 information, and it does this all at once at the end of a job.
23449 In order to prepare for such frenetic activity, it squirrels away the
23450 necessary facts in various arrays as information becomes available.
23451
23452 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23453 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23454 |tfm_ital_corr|. Other information about a character (e.g., about
23455 its ligatures or successors) is accessible via the |char_tag| and
23456 |char_remainder| arrays. Other information about the font as a whole
23457 is kept in additional arrays called |header_byte|, |lig_kern|,
23458 |kern|, |exten|, and |param|.
23459
23460 @d max_tfm_int 32510
23461 @d undefined_label max_tfm_int /* an undefined local label */
23462
23463 @<Glob...@>=
23464 #define TFM_ITEMS 257
23465 eight_bits bc;
23466 eight_bits ec; /* smallest and largest character codes shipped out */
23467 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23468 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23469 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23470 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23471 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23472 int char_tag[TFM_ITEMS]; /* |remainder| category */
23473 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23474 char *header_byte; /* bytes of the \.{TFM} header */
23475 int header_last; /* last initialized \.{TFM} header byte */
23476 int header_size; /* size of the \.{TFM} header */
23477 four_quarters *lig_kern; /* the ligature/kern table */
23478 short nl; /* the number of ligature/kern steps so far */
23479 scaled *kern; /* distinct kerning amounts */
23480 short nk; /* the number of distinct kerns so far */
23481 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23482 short ne; /* the number of extensible characters so far */
23483 scaled *param; /* \&{fontinfo} parameters */
23484 short np; /* the largest \&{fontinfo} parameter specified so far */
23485 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23486 short skip_table[TFM_ITEMS]; /* local label status */
23487 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23488 integer bchar; /* right boundary character */
23489 short bch_label; /* left boundary starting location */
23490 short ll;short lll; /* registers used for lig/kern processing */
23491 short label_loc[257]; /* lig/kern starting addresses */
23492 eight_bits label_char[257]; /* characters for |label_loc| */
23493 short label_ptr; /* highest position occupied in |label_loc| */
23494
23495 @ @<Allocate or initialize ...@>=
23496 mp->header_last = 0; mp->header_size = 128; /* just for init */
23497 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23498 mp->lig_kern = NULL; /* allocated when needed */
23499 mp->kern = NULL; /* allocated when needed */ 
23500 mp->param = NULL; /* allocated when needed */
23501
23502 @ @<Dealloc variables@>=
23503 xfree(mp->header_byte);
23504 xfree(mp->lig_kern);
23505 xfree(mp->kern);
23506 xfree(mp->param);
23507
23508 @ @<Set init...@>=
23509 for (k=0;k<= 255;k++ ) {
23510   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23511   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23512   mp->skip_table[k]=undefined_label;
23513 };
23514 memset(mp->header_byte,0,mp->header_size);
23515 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23516 mp->internal[mp_boundary_char]=-unity;
23517 mp->bch_label=undefined_label;
23518 mp->label_loc[0]=-1; mp->label_ptr=0;
23519
23520 @ @<Declarations@>=
23521 scaled mp_tfm_check (MP mp,small_number m) ;
23522
23523 @ @<Declare the function called |tfm_check|@>=
23524 scaled mp_tfm_check (MP mp,small_number m) {
23525   if ( abs(mp->internal[m])>=fraction_half ) {
23526     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23527 @.Enormous charwd...@>
23528 @.Enormous chardp...@>
23529 @.Enormous charht...@>
23530 @.Enormous charic...@>
23531 @.Enormous designsize...@>
23532     mp_print(mp, " has been reduced");
23533     help1("Font metric dimensions must be less than 2048pt.");
23534     mp_put_get_error(mp);
23535     if ( mp->internal[m]>0 ) return (fraction_half-1);
23536     else return (1-fraction_half);
23537   } else {
23538     return mp->internal[m];
23539   }
23540 }
23541
23542 @ @<Store the width information for character code~|c|@>=
23543 if ( c<mp->bc ) mp->bc=c;
23544 if ( c>mp->ec ) mp->ec=c;
23545 mp->char_exists[c]=true;
23546 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23547 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23548 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23549 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23550
23551 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23552
23553 @<Cases of |do_statement|...@>=
23554 case tfm_command: mp_do_tfm_command(mp); break;
23555
23556 @ @d char_list_code 0
23557 @d lig_table_code 1
23558 @d extensible_code 2
23559 @d header_byte_code 3
23560 @d font_dimen_code 4
23561
23562 @<Put each...@>=
23563 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23564 @:char_list_}{\&{charlist} primitive@>
23565 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23566 @:lig_table_}{\&{ligtable} primitive@>
23567 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23568 @:extensible_}{\&{extensible} primitive@>
23569 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23570 @:header_byte_}{\&{headerbyte} primitive@>
23571 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23572 @:font_dimen_}{\&{fontdimen} primitive@>
23573
23574 @ @<Cases of |print_cmd...@>=
23575 case tfm_command: 
23576   switch (m) {
23577   case char_list_code:mp_print(mp, "charlist"); break;
23578   case lig_table_code:mp_print(mp, "ligtable"); break;
23579   case extensible_code:mp_print(mp, "extensible"); break;
23580   case header_byte_code:mp_print(mp, "headerbyte"); break;
23581   default: mp_print(mp, "fontdimen"); break;
23582   }
23583   break;
23584
23585 @ @<Declare action procedures for use by |do_statement|@>=
23586 eight_bits mp_get_code (MP mp) ;
23587
23588 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23589   integer c; /* the code value found */
23590   mp_get_x_next(mp); mp_scan_expression(mp);
23591   if ( mp->cur_type==mp_known ) { 
23592     c=mp_round_unscaled(mp, mp->cur_exp);
23593     if ( c>=0 ) if ( c<256 ) return c;
23594   } else if ( mp->cur_type==mp_string_type ) {
23595     if ( length(mp->cur_exp)==1 )  { 
23596       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23597       return c;
23598     }
23599   }
23600   exp_err("Invalid code has been replaced by 0");
23601 @.Invalid code...@>
23602   help2("I was looking for a number between 0 and 255, or for a")
23603        ("string of length 1. Didn't find it; will use 0 instead.");
23604   mp_put_get_flush_error(mp, 0); c=0;
23605   return c;
23606 };
23607
23608 @ @<Declare action procedures for use by |do_statement|@>=
23609 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23610
23611 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23612   if ( mp->char_tag[c]==no_tag ) {
23613     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23614     if ( t==lig_tag ){ 
23615       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23616       mp->label_char[mp->label_ptr]=c;
23617     }
23618   } else {
23619     @<Complain about a character tag conflict@>;
23620   }
23621 }
23622
23623 @ @<Complain about a character tag conflict@>=
23624
23625   print_err("Character ");
23626   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23627   else if ( c==256 ) mp_print(mp, "||");
23628   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23629   mp_print(mp, " is already ");
23630 @.Character c is already...@>
23631   switch (mp->char_tag[c]) {
23632   case lig_tag: mp_print(mp, "in a ligtable"); break;
23633   case list_tag: mp_print(mp, "in a charlist"); break;
23634   case ext_tag: mp_print(mp, "extensible"); break;
23635   } /* there are no other cases */
23636   help2("It's not legal to label a character more than once.")
23637     ("So I'll not change anything just now.");
23638   mp_put_get_error(mp); 
23639 }
23640
23641 @ @<Declare action procedures for use by |do_statement|@>=
23642 void mp_do_tfm_command (MP mp) ;
23643
23644 @ @c void mp_do_tfm_command (MP mp) {
23645   int c,cc; /* character codes */
23646   int k; /* index into the |kern| array */
23647   int j; /* index into |header_byte| or |param| */
23648   switch (mp->cur_mod) {
23649   case char_list_code: 
23650     c=mp_get_code(mp);
23651      /* we will store a list of character successors */
23652     while ( mp->cur_cmd==colon )   { 
23653       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23654     };
23655     break;
23656   case lig_table_code: 
23657     if (mp->lig_kern==NULL) 
23658        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23659     if (mp->kern==NULL) 
23660        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23661     @<Store a list of ligature/kern steps@>;
23662     break;
23663   case extensible_code: 
23664     @<Define an extensible recipe@>;
23665     break;
23666   case header_byte_code: 
23667   case font_dimen_code: 
23668     c=mp->cur_mod; mp_get_x_next(mp);
23669     mp_scan_expression(mp);
23670     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23671       exp_err("Improper location");
23672 @.Improper location@>
23673       help2("I was looking for a known, positive number.")
23674        ("For safety's sake I'll ignore the present command.");
23675       mp_put_get_error(mp);
23676     } else  { 
23677       j=mp_round_unscaled(mp, mp->cur_exp);
23678       if ( mp->cur_cmd!=colon ) {
23679         mp_missing_err(mp, ":");
23680 @.Missing `:'@>
23681         help1("A colon should follow a headerbyte or fontinfo location.");
23682         mp_back_error(mp);
23683       }
23684       if ( c==header_byte_code ) { 
23685         @<Store a list of header bytes@>;
23686       } else {     
23687         if (mp->param==NULL) 
23688           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23689         @<Store a list of font dimensions@>;
23690       }
23691     }
23692     break;
23693   } /* there are no other cases */
23694 };
23695
23696 @ @<Store a list of ligature/kern steps@>=
23697
23698   mp->lk_started=false;
23699 CONTINUE: 
23700   mp_get_x_next(mp);
23701   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23702     @<Process a |skip_to| command and |goto done|@>;
23703   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23704   else { mp_back_input(mp); c=mp_get_code(mp); };
23705   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23706     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23707   }
23708   if ( mp->cur_cmd==lig_kern_token ) { 
23709     @<Compile a ligature/kern command@>; 
23710   } else  { 
23711     print_err("Illegal ligtable step");
23712 @.Illegal ligtable step@>
23713     help1("I was looking for `=:' or `kern' here.");
23714     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23715     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23716     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23717   }
23718   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23719   incr(mp->nl);
23720   if ( mp->cur_cmd==comma ) goto CONTINUE;
23721   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23722 }
23723 DONE:
23724
23725 @ @<Put each...@>=
23726 mp_primitive(mp, "=:",lig_kern_token,0);
23727 @:=:_}{\.{=:} primitive@>
23728 mp_primitive(mp, "=:|",lig_kern_token,1);
23729 @:=:/_}{\.{=:\char'174} primitive@>
23730 mp_primitive(mp, "=:|>",lig_kern_token,5);
23731 @:=:/>_}{\.{=:\char'174>} primitive@>
23732 mp_primitive(mp, "|=:",lig_kern_token,2);
23733 @:=:/_}{\.{\char'174=:} primitive@>
23734 mp_primitive(mp, "|=:>",lig_kern_token,6);
23735 @:=:/>_}{\.{\char'174=:>} primitive@>
23736 mp_primitive(mp, "|=:|",lig_kern_token,3);
23737 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23738 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23739 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23740 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23741 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23742 mp_primitive(mp, "kern",lig_kern_token,128);
23743 @:kern_}{\&{kern} primitive@>
23744
23745 @ @<Cases of |print_cmd...@>=
23746 case lig_kern_token: 
23747   switch (m) {
23748   case 0:mp_print(mp, "=:"); break;
23749   case 1:mp_print(mp, "=:|"); break;
23750   case 2:mp_print(mp, "|=:"); break;
23751   case 3:mp_print(mp, "|=:|"); break;
23752   case 5:mp_print(mp, "=:|>"); break;
23753   case 6:mp_print(mp, "|=:>"); break;
23754   case 7:mp_print(mp, "|=:|>"); break;
23755   case 11:mp_print(mp, "|=:|>>"); break;
23756   default: mp_print(mp, "kern"); break;
23757   }
23758   break;
23759
23760 @ Local labels are implemented by maintaining the |skip_table| array,
23761 where |skip_table[c]| is either |undefined_label| or the address of the
23762 most recent lig/kern instruction that skips to local label~|c|. In the
23763 latter case, the |skip_byte| in that instruction will (temporarily)
23764 be zero if there were no prior skips to this label, or it will be the
23765 distance to the prior skip.
23766
23767 We may need to cancel skips that span more than 127 lig/kern steps.
23768
23769 @d cancel_skips(A) mp->ll=(A);
23770   do {  
23771     mp->lll=qo(skip_byte(mp->ll)); 
23772     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23773   } while (mp->lll!=0)
23774 @d skip_error(A) { print_err("Too far to skip");
23775 @.Too far to skip@>
23776   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23777   mp_error(mp); cancel_skips((A));
23778   }
23779
23780 @<Process a |skip_to| command and |goto done|@>=
23781
23782   c=mp_get_code(mp);
23783   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23784     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23785   }
23786   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23787   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23788   mp->skip_table[c]=mp->nl-1; goto DONE;
23789 }
23790
23791 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23792
23793   if ( mp->cur_cmd==colon ) {
23794     if ( c==256 ) mp->bch_label=mp->nl;
23795     else mp_set_tag(mp, c,lig_tag,mp->nl);
23796   } else if ( mp->skip_table[c]<undefined_label ) {
23797     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23798     do {  
23799       mp->lll=qo(skip_byte(mp->ll));
23800       if ( mp->nl-mp->ll>128 ) {
23801         skip_error(mp->ll); goto CONTINUE;
23802       }
23803       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23804     } while (mp->lll!=0);
23805   }
23806   goto CONTINUE;
23807 }
23808
23809 @ @<Compile a ligature/kern...@>=
23810
23811   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23812   if ( mp->cur_mod<128 ) { /* ligature op */
23813     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23814   } else { 
23815     mp_get_x_next(mp); mp_scan_expression(mp);
23816     if ( mp->cur_type!=mp_known ) {
23817       exp_err("Improper kern");
23818 @.Improper kern@>
23819       help2("The amount of kern should be a known numeric value.")
23820         ("I'm zeroing this one. Proceed, with fingers crossed.");
23821       mp_put_get_flush_error(mp, 0);
23822     }
23823     mp->kern[mp->nk]=mp->cur_exp;
23824     k=0; 
23825     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23826     if ( k==mp->nk ) {
23827       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23828       incr(mp->nk);
23829     }
23830     op_byte(mp->nl)=kern_flag+(k / 256);
23831     rem_byte(mp->nl)=qi((k % 256));
23832   }
23833   mp->lk_started=true;
23834 }
23835
23836 @ @d missing_extensible_punctuation(A) 
23837   { mp_missing_err(mp, (A));
23838 @.Missing `\char`\#'@>
23839   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23840   }
23841
23842 @<Define an extensible recipe@>=
23843
23844   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23845   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23846   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23847   ext_top(mp->ne)=qi(mp_get_code(mp));
23848   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23849   ext_mid(mp->ne)=qi(mp_get_code(mp));
23850   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23851   ext_bot(mp->ne)=qi(mp_get_code(mp));
23852   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23853   ext_rep(mp->ne)=qi(mp_get_code(mp));
23854   incr(mp->ne);
23855 }
23856
23857 @ The header could contain ASCII zeroes, so can't use |strdup|.
23858
23859 @<Store a list of header bytes@>=
23860 do {  
23861   if ( j>=mp->header_size ) {
23862     int l = mp->header_size + (mp->header_size >> 2);
23863     char *t = xmalloc(l,sizeof(char));
23864     memset(t,0,l); 
23865     memcpy(t,mp->header_byte,mp->header_size);
23866     xfree (mp->header_byte);
23867     mp->header_byte = t;
23868     mp->header_size = l;
23869   }
23870   mp->header_byte[j]=mp_get_code(mp); 
23871   incr(j); incr(mp->header_last);
23872 } while (mp->cur_cmd==comma)
23873
23874 @ @<Store a list of font dimensions@>=
23875 do {  
23876   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23877   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23878   mp_get_x_next(mp); mp_scan_expression(mp);
23879   if ( mp->cur_type!=mp_known ){ 
23880     exp_err("Improper font parameter");
23881 @.Improper font parameter@>
23882     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23883     mp_put_get_flush_error(mp, 0);
23884   }
23885   mp->param[j]=mp->cur_exp; incr(j);
23886 } while (mp->cur_cmd==comma)
23887
23888 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23889 All that remains is to output it in the correct format.
23890
23891 An interesting problem needs to be solved in this connection, because
23892 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23893 and 64~italic corrections. If the data has more distinct values than
23894 this, we want to meet the necessary restrictions by perturbing the
23895 given values as little as possible.
23896
23897 \MP\ solves this problem in two steps. First the values of a given
23898 kind (widths, heights, depths, or italic corrections) are sorted;
23899 then the list of sorted values is perturbed, if necessary.
23900
23901 The sorting operation is facilitated by having a special node of
23902 essentially infinite |value| at the end of the current list.
23903
23904 @<Initialize table entries...@>=
23905 value(inf_val)=fraction_four;
23906
23907 @ Straight linear insertion is good enough for sorting, since the lists
23908 are usually not terribly long. As we work on the data, the current list
23909 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23910 list will be in increasing order of their |value| fields.
23911
23912 Given such a list, the |sort_in| function takes a value and returns a pointer
23913 to where that value can be found in the list. The value is inserted in
23914 the proper place, if necessary.
23915
23916 At the time we need to do these operations, most of \MP's work has been
23917 completed, so we will have plenty of memory to play with. The value nodes
23918 that are allocated for sorting will never be returned to free storage.
23919
23920 @d clear_the_list link(temp_head)=inf_val
23921
23922 @c pointer mp_sort_in (MP mp,scaled v) {
23923   pointer p,q,r; /* list manipulation registers */
23924   p=temp_head;
23925   while (1) { 
23926     q=link(p);
23927     if ( v<=value(q) ) break;
23928     p=q;
23929   }
23930   if ( v<value(q) ) {
23931     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23932   }
23933   return link(p);
23934 }
23935
23936 @ Now we come to the interesting part, where we reduce the list if necessary
23937 until it has the required size. The |min_cover| routine is basic to this
23938 process; it computes the minimum number~|m| such that the values of the
23939 current sorted list can be covered by |m|~intervals of width~|d|. It
23940 also sets the global value |perturbation| to the smallest value $d'>d$
23941 such that the covering found by this algorithm would be different.
23942
23943 In particular, |min_cover(0)| returns the number of distinct values in the
23944 current list and sets |perturbation| to the minimum distance between
23945 adjacent values.
23946
23947 @c integer mp_min_cover (MP mp,scaled d) {
23948   pointer p; /* runs through the current list */
23949   scaled l; /* the least element covered by the current interval */
23950   integer m; /* lower bound on the size of the minimum cover */
23951   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23952   while ( p!=inf_val ){ 
23953     incr(m); l=value(p);
23954     do {  p=link(p); } while (value(p)<=l+d);
23955     if ( value(p)-l<mp->perturbation ) 
23956       mp->perturbation=value(p)-l;
23957   }
23958   return m;
23959 }
23960
23961 @ @<Glob...@>=
23962 scaled perturbation; /* quantity related to \.{TFM} rounding */
23963 integer excess; /* the list is this much too long */
23964
23965 @ The smallest |d| such that a given list can be covered with |m| intervals
23966 is determined by the |threshold| routine, which is sort of an inverse
23967 to |min_cover|. The idea is to increase the interval size rapidly until
23968 finding the range, then to go sequentially until the exact borderline has
23969 been discovered.
23970
23971 @c scaled mp_threshold (MP mp,integer m) {
23972   scaled d; /* lower bound on the smallest interval size */
23973   mp->excess=mp_min_cover(mp, 0)-m;
23974   if ( mp->excess<=0 ) {
23975     return 0;
23976   } else  { 
23977     do {  
23978       d=mp->perturbation;
23979     } while (mp_min_cover(mp, d+d)>m);
23980     while ( mp_min_cover(mp, d)>m ) 
23981       d=mp->perturbation;
23982     return d;
23983   }
23984 }
23985
23986 @ The |skimp| procedure reduces the current list to at most |m| entries,
23987 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23988 is the |k|th distinct value on the resulting list, and it sets
23989 |perturbation| to the maximum amount by which a |value| field has
23990 been changed. The size of the resulting list is returned as the
23991 value of |skimp|.
23992
23993 @c integer mp_skimp (MP mp,integer m) {
23994   scaled d; /* the size of intervals being coalesced */
23995   pointer p,q,r; /* list manipulation registers */
23996   scaled l; /* the least value in the current interval */
23997   scaled v; /* a compromise value */
23998   d=mp_threshold(mp, m); mp->perturbation=0;
23999   q=temp_head; m=0; p=link(temp_head);
24000   while ( p!=inf_val ) {
24001     incr(m); l=value(p); info(p)=m;
24002     if ( value(link(p))<=l+d ) {
24003       @<Replace an interval of values by its midpoint@>;
24004     }
24005     q=p; p=link(p);
24006   }
24007   return m;
24008 }
24009
24010 @ @<Replace an interval...@>=
24011
24012   do {  
24013     p=link(p); info(p)=m;
24014     decr(mp->excess); if ( mp->excess==0 ) d=0;
24015   } while (value(link(p))<=l+d);
24016   v=l+halfp(value(p)-l);
24017   if ( value(p)-v>mp->perturbation ) 
24018     mp->perturbation=value(p)-v;
24019   r=q;
24020   do {  
24021     r=link(r); value(r)=v;
24022   } while (r!=p);
24023   link(q)=p; /* remove duplicate values from the current list */
24024 }
24025
24026 @ A warning message is issued whenever something is perturbed by
24027 more than 1/16\thinspace pt.
24028
24029 @c void mp_tfm_warning (MP mp,small_number m) { 
24030   mp_print_nl(mp, "(some "); 
24031   mp_print(mp, mp->int_name[m]);
24032 @.some charwds...@>
24033 @.some chardps...@>
24034 @.some charhts...@>
24035 @.some charics...@>
24036   mp_print(mp, " values had to be adjusted by as much as ");
24037   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24038 }
24039
24040 @ Here's an example of how we use these routines.
24041 The width data needs to be perturbed only if there are 256 distinct
24042 widths, but \MP\ must check for this case even though it is
24043 highly unusual.
24044
24045 An integer variable |k| will be defined when we use this code.
24046 The |dimen_head| array will contain pointers to the sorted
24047 lists of dimensions.
24048
24049 @<Massage the \.{TFM} widths@>=
24050 clear_the_list;
24051 for (k=mp->bc;k<=mp->ec;k++)  {
24052   if ( mp->char_exists[k] )
24053     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24054 }
24055 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24056 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24057
24058 @ @<Glob...@>=
24059 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24060
24061 @ Heights, depths, and italic corrections are different from widths
24062 not only because their list length is more severely restricted, but
24063 also because zero values do not need to be put into the lists.
24064
24065 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24066 clear_the_list;
24067 for (k=mp->bc;k<=mp->ec;k++) {
24068   if ( mp->char_exists[k] ) {
24069     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24070     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24071   }
24072 }
24073 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24074 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24075 clear_the_list;
24076 for (k=mp->bc;k<=mp->ec;k++) {
24077   if ( mp->char_exists[k] ) {
24078     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24079     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24080   }
24081 }
24082 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24083 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24084 clear_the_list;
24085 for (k=mp->bc;k<=mp->ec;k++) {
24086   if ( mp->char_exists[k] ) {
24087     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24088     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24089   }
24090 }
24091 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24092 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24093
24094 @ @<Initialize table entries...@>=
24095 value(zero_val)=0; info(zero_val)=0;
24096
24097 @ Bytes 5--8 of the header are set to the design size, unless the user has
24098 some crazy reason for specifying them differently.
24099
24100 Error messages are not allowed at the time this procedure is called,
24101 so a warning is printed instead.
24102
24103 The value of |max_tfm_dimen| is calculated so that
24104 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24105  < \\{three\_bytes}.$$
24106
24107 @d three_bytes 0100000000 /* $2^{24}$ */
24108
24109 @c 
24110 void mp_fix_design_size (MP mp) {
24111   scaled d; /* the design size */
24112   d=mp->internal[mp_design_size];
24113   if ( (d<unity)||(d>=fraction_half) ) {
24114     if ( d!=0 )
24115       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24116 @.illegal design size...@>
24117     d=040000000; mp->internal[mp_design_size]=d;
24118   }
24119   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24120     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24121      mp->header_byte[4]=d / 04000000;
24122      mp->header_byte[5]=(d / 4096) % 256;
24123      mp->header_byte[6]=(d / 16) % 256;
24124      mp->header_byte[7]=(d % 16)*16;
24125   };
24126   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24127   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24128 }
24129
24130 @ The |dimen_out| procedure computes a |fix_word| relative to the
24131 design size. If the data was out of range, it is corrected and the
24132 global variable |tfm_changed| is increased by~one.
24133
24134 @c integer mp_dimen_out (MP mp,scaled x) { 
24135   if ( abs(x)>mp->max_tfm_dimen ) {
24136     incr(mp->tfm_changed);
24137     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24138   } else {
24139     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24140   }
24141   return x;
24142 }
24143
24144 @ @<Glob...@>=
24145 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24146 integer tfm_changed; /* the number of data entries that were out of bounds */
24147
24148 @ If the user has not specified any of the first four header bytes,
24149 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24150 from the |tfm_width| data relative to the design size.
24151 @^check sum@>
24152
24153 @c void mp_fix_check_sum (MP mp) {
24154   eight_bits k; /* runs through character codes */
24155   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24156   integer x;  /* hash value used in check sum computation */
24157   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24158        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24159     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24160     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24161     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24162     return;
24163   }
24164 }
24165
24166 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24167 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24168 for (k=mp->bc;k<=mp->ec;k++) { 
24169   if ( mp->char_exists[k] ) {
24170     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24171     B1=(B1+B1+x) % 255;
24172     B2=(B2+B2+x) % 253;
24173     B3=(B3+B3+x) % 251;
24174     B4=(B4+B4+x) % 247;
24175   }
24176 }
24177
24178 @ Finally we're ready to actually write the \.{TFM} information.
24179 Here are some utility routines for this purpose.
24180
24181 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24182   unsigned char s=(A); 
24183   (mp->write_binary_file)(mp->tfm_file,(void *)&s,1); 
24184   } while (0)
24185
24186 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24187   tfm_out(x / 256); tfm_out(x % 256);
24188 }
24189 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24190   if ( x>=0 ) tfm_out(x / three_bytes);
24191   else { 
24192     x=x+010000000000; /* use two's complement for negative values */
24193     x=x+010000000000;
24194     tfm_out((x / three_bytes) + 128);
24195   };
24196   x=x % three_bytes; tfm_out(x / unity);
24197   x=x % unity; tfm_out(x / 0400);
24198   tfm_out(x % 0400);
24199 }
24200 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24201   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24202   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24203 }
24204
24205 @ @<Finish the \.{TFM} file@>=
24206 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24207 mp_pack_job_name(mp, ".tfm");
24208 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24209   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24210 mp->metric_file_name=xstrdup(mp->name_of_file);
24211 @<Output the subfile sizes and header bytes@>;
24212 @<Output the character information bytes, then
24213   output the dimensions themselves@>;
24214 @<Output the ligature/kern program@>;
24215 @<Output the extensible character recipes and the font metric parameters@>;
24216   if ( mp->internal[mp_tracing_stats]>0 )
24217   @<Log the subfile sizes of the \.{TFM} file@>;
24218 mp_print_nl(mp, "Font metrics written on "); 
24219 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24220 @.Font metrics written...@>
24221 (mp->close_file)(mp->tfm_file)
24222
24223 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24224 this code.
24225
24226 @<Output the subfile sizes and header bytes@>=
24227 k=mp->header_last;
24228 LH=(k+3) / 4; /* this is the number of header words */
24229 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24230 @<Compute the ligature/kern program offset and implant the
24231   left boundary label@>;
24232 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24233      +lk_offset+mp->nk+mp->ne+mp->np);
24234   /* this is the total number of file words that will be output */
24235 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24236 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24237 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24238 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24239 mp_tfm_two(mp, mp->np);
24240 for (k=0;k< 4*LH;k++)   { 
24241   tfm_out(mp->header_byte[k]);
24242 }
24243
24244 @ @<Output the character information bytes...@>=
24245 for (k=mp->bc;k<=mp->ec;k++) {
24246   if ( ! mp->char_exists[k] ) {
24247     mp_tfm_four(mp, 0);
24248   } else { 
24249     tfm_out(info(mp->tfm_width[k])); /* the width index */
24250     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24251     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24252     tfm_out(mp->char_remainder[k]);
24253   };
24254 }
24255 mp->tfm_changed=0;
24256 for (k=1;k<=4;k++) { 
24257   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24258   while ( p!=inf_val ) {
24259     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24260   }
24261 }
24262
24263
24264 @ We need to output special instructions at the beginning of the
24265 |lig_kern| array in order to specify the right boundary character
24266 and/or to handle starting addresses that exceed 255. The |label_loc|
24267 and |label_char| arrays have been set up to record all the
24268 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24269 \le|label_loc|[|label_ptr]|$.
24270
24271 @<Compute the ligature/kern program offset...@>=
24272 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24273 if ((mp->bchar<0)||(mp->bchar>255))
24274   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24275 else { mp->lk_started=true; lk_offset=1; };
24276 @<Find the minimum |lk_offset| and adjust all remainders@>;
24277 if ( mp->bch_label<undefined_label )
24278   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24279   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24280   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24281   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24282   }
24283
24284 @ @<Find the minimum |lk_offset|...@>=
24285 k=mp->label_ptr; /* pointer to the largest unallocated label */
24286 if ( mp->label_loc[k]+lk_offset>255 ) {
24287   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24288   do {  
24289     mp->char_remainder[mp->label_char[k]]=lk_offset;
24290     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24291        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24292     }
24293     incr(lk_offset); decr(k);
24294   } while (! (lk_offset+mp->label_loc[k]<256));
24295     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24296 };
24297 if ( lk_offset>0 ) {
24298   while ( k>0 ) {
24299     mp->char_remainder[mp->label_char[k]]
24300      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24301     decr(k);
24302   }
24303 }
24304
24305 @ @<Output the ligature/kern program@>=
24306 for (k=0;k<= 255;k++ ) {
24307   if ( mp->skip_table[k]<undefined_label ) {
24308      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24309 @.local label l:: was missing@>
24310     cancel_skips(mp->skip_table[k]);
24311   }
24312 }
24313 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24314   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24315 } else {
24316   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24317     mp->ll=mp->label_loc[mp->label_ptr];
24318     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24319     else { tfm_out(255); tfm_out(mp->bchar);   };
24320     mp_tfm_two(mp, mp->ll+lk_offset);
24321     do {  
24322       decr(mp->label_ptr);
24323     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24324   }
24325 }
24326 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24327 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24328
24329 @ @<Output the extensible character recipes...@>=
24330 for (k=0;k<=mp->ne-1;k++) 
24331   mp_tfm_qqqq(mp, mp->exten[k]);
24332 for (k=1;k<=mp->np;k++) {
24333   if ( k==1 ) {
24334     if ( abs(mp->param[1])<fraction_half ) {
24335       mp_tfm_four(mp, mp->param[1]*16);
24336     } else  { 
24337       incr(mp->tfm_changed);
24338       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24339       else mp_tfm_four(mp, -el_gordo);
24340     }
24341   } else {
24342     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24343   }
24344 }
24345 if ( mp->tfm_changed>0 )  { 
24346   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24347 @.a font metric dimension...@>
24348   else  { 
24349     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24350 @.font metric dimensions...@>
24351     mp_print(mp, " font metric dimensions");
24352   }
24353   mp_print(mp, " had to be decreased)");
24354 }
24355
24356 @ @<Log the subfile sizes of the \.{TFM} file@>=
24357
24358   char s[200];
24359   wlog_ln(" ");
24360   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24361   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24362                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24363   wlog_ln(s);
24364 }
24365
24366 @* \[43] Reading font metric data.
24367
24368 \MP\ isn't a typesetting program but it does need to find the bounding box
24369 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24370 well as write them.
24371
24372 @<Glob...@>=
24373 void * tfm_infile;
24374
24375 @ All the width, height, and depth information is stored in an array called
24376 |font_info|.  This array is allocated sequentially and each font is stored
24377 as a series of |char_info| words followed by the width, height, and depth
24378 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24379 set to |max_str_ref|.
24380
24381 @<Types...@>=
24382 typedef unsigned int font_number; /* |0..font_max| */
24383
24384 @ The |font_info| array is indexed via a group directory arrays.
24385 For example, the |char_info| data for character~|c| in font~|f| will be
24386 in |font_info[char_base[f]+c].qqqq|.
24387
24388 @<Glob...@>=
24389 font_number font_max; /* maximum font number for included text fonts */
24390 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24391 memory_word *font_info; /* height, width, and depth data */
24392 char        **font_enc_name; /* encoding names, if any */
24393 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24394 int         next_fmem; /* next unused entry in |font_info| */
24395 font_number last_fnum; /* last font number used so far */
24396 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24397 char        **font_name;  /* name as specified in the \&{infont} command */
24398 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24399 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24400 eight_bits  *font_bc;
24401 eight_bits  *font_ec;  /* first and last character code */
24402 int         *char_base;  /* base address for |char_info| */
24403 int         *width_base; /* index for zeroth character width */
24404 int         *height_base; /* index for zeroth character height */
24405 int         *depth_base; /* index for zeroth character depth */
24406 pointer     *font_sizes;
24407
24408 @ @<Allocate or initialize ...@>=
24409 mp->font_mem_size = 10000; 
24410 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24411 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24412 mp->font_enc_name = NULL;
24413 mp->font_ps_name_fixed = NULL;
24414 mp->font_dsize = NULL;
24415 mp->font_name = NULL;
24416 mp->font_ps_name = NULL;
24417 mp->font_bc = NULL;
24418 mp->font_ec = NULL;
24419 mp->last_fnum = null_font;
24420 mp->char_base = NULL;
24421 mp->width_base = NULL;
24422 mp->height_base = NULL;
24423 mp->depth_base = NULL;
24424 mp->font_sizes = null;
24425
24426 @ @<Dealloc variables@>=
24427 for (k=1;k<=(int)mp->last_fnum;k++) {
24428   xfree(mp->font_enc_name[k]);
24429   xfree(mp->font_name[k]);
24430   xfree(mp->font_ps_name[k]);
24431 }
24432 xfree(mp->font_info);
24433 xfree(mp->font_enc_name);
24434 xfree(mp->font_ps_name_fixed);
24435 xfree(mp->font_dsize);
24436 xfree(mp->font_name);
24437 xfree(mp->font_ps_name);
24438 xfree(mp->font_bc);
24439 xfree(mp->font_ec);
24440 xfree(mp->char_base);
24441 xfree(mp->width_base);
24442 xfree(mp->height_base);
24443 xfree(mp->depth_base);
24444 xfree(mp->font_sizes);
24445
24446
24447 @c 
24448 void mp_reallocate_fonts (MP mp, font_number l) {
24449   font_number f;
24450   XREALLOC(mp->font_enc_name,      l, char *);
24451   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24452   XREALLOC(mp->font_dsize,         l, scaled);
24453   XREALLOC(mp->font_name,          l, char *);
24454   XREALLOC(mp->font_ps_name,       l, char *);
24455   XREALLOC(mp->font_bc,            l, eight_bits);
24456   XREALLOC(mp->font_ec,            l, eight_bits);
24457   XREALLOC(mp->char_base,          l, int);
24458   XREALLOC(mp->width_base,         l, int);
24459   XREALLOC(mp->height_base,        l, int);
24460   XREALLOC(mp->depth_base,         l, int);
24461   XREALLOC(mp->font_sizes,         l, pointer);
24462   for (f=(mp->last_fnum+1);f<=l;f++) {
24463     mp->font_enc_name[f]=NULL;
24464     mp->font_ps_name_fixed[f] = false;
24465     mp->font_name[f]=NULL;
24466     mp->font_ps_name[f]=NULL;
24467     mp->font_sizes[f]=null;
24468   }
24469   mp->font_max = l;
24470 }
24471
24472 @ @<Declare |mp_reallocate| functions@>=
24473 void mp_reallocate_fonts (MP mp, font_number l);
24474
24475
24476 @ A |null_font| containing no characters is useful for error recovery.  Its
24477 |font_name| entry starts out empty but is reset each time an erroneous font is
24478 found.  This helps to cut down on the number of duplicate error messages without
24479 wasting a lot of space.
24480
24481 @d null_font 0 /* the |font_number| for an empty font */
24482
24483 @<Set initial...@>=
24484 mp->font_dsize[null_font]=0;
24485 mp->font_bc[null_font]=1;
24486 mp->font_ec[null_font]=0;
24487 mp->char_base[null_font]=0;
24488 mp->width_base[null_font]=0;
24489 mp->height_base[null_font]=0;
24490 mp->depth_base[null_font]=0;
24491 mp->next_fmem=0;
24492 mp->last_fnum=null_font;
24493 mp->last_ps_fnum=null_font;
24494 mp->font_name[null_font]="nullfont";
24495 mp->font_ps_name[null_font]="";
24496 mp->font_ps_name_fixed[null_font] = false;
24497 mp->font_enc_name[null_font]=NULL;
24498 mp->font_sizes[null_font]=null;
24499
24500 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24501 the |width index|; the |b1| field contains the height
24502 index; the |b2| fields contains the depth index, and the |b3| field used only
24503 for temporary storage. (It is used to keep track of which characters occur in
24504 an edge structure that is being shipped out.)
24505 The corresponding words in the width, height, and depth tables are stored as
24506 |scaled| values in units of \ps\ points.
24507
24508 With the macros below, the |char_info| word for character~|c| in font~|f| is
24509 |char_info(f)(c)| and the width is
24510 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24511
24512 @d char_info_end(A) (A)].qqqq
24513 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24514 @d char_width_end(A) (A).b0].sc
24515 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24516 @d char_height_end(A) (A).b1].sc
24517 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24518 @d char_depth_end(A) (A).b2].sc
24519 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24520 @d ichar_exists(A) ((A).b0>0)
24521
24522 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24523 A preliminary name is obtained here from the \.{TFM} name as given in the
24524 |fname| argument.  This gets updated later from an external table if necessary.
24525
24526 @<Declare text measuring subroutines@>=
24527 @<Declare subroutines for parsing file names@>;
24528 font_number mp_read_font_info (MP mp, char *fname) {
24529   boolean file_opened; /* has |tfm_infile| been opened? */
24530   font_number n; /* the number to return */
24531   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24532   size_t whd_size; /* words needed for heights, widths, and depths */
24533   int i,ii; /* |font_info| indices */
24534   int jj; /* counts bytes to be ignored */
24535   scaled z; /* used to compute the design size */
24536   fraction d;
24537   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24538   eight_bits h_and_d; /* height and depth indices being unpacked */
24539   unsigned char tfbyte; /* a byte read from the file */
24540   n=null_font;
24541   @<Open |tfm_infile| for input@>;
24542   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24543     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24544 BAD_TFM:
24545   @<Complain that the \.{TFM} file is bad@>;
24546 DONE:
24547   if ( file_opened ) (mp->close_file)(mp->tfm_infile);
24548   if ( n!=null_font ) { 
24549     mp->font_ps_name[n]=mp_xstrdup(mp,fname);
24550     mp->font_name[n]=mp_xstrdup(mp,fname);
24551   }
24552   return n;
24553 }
24554
24555 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24556 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24557 @.TFtoPL@> @.PLtoTF@>
24558 and \.{PLtoTF} can be used to debug \.{TFM} files.
24559
24560 @<Complain that the \.{TFM} file is bad@>=
24561 print_err("Font ");
24562 mp_print(mp, fname);
24563 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24564 else mp_print(mp, " not usable: TFM file not found");
24565 help3("I wasn't able to read the size data for this font so this")
24566   ("`infont' operation won't produce anything. If the font name")
24567   ("is right, you might ask an expert to make a TFM file");
24568 if ( file_opened )
24569   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24570 mp_error(mp)
24571
24572 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24573 @<Read the \.{TFM} size fields@>;
24574 @<Use the size fields to allocate space in |font_info|@>;
24575 @<Read the \.{TFM} header@>;
24576 @<Read the character data and the width, height, and depth tables and
24577   |goto done|@>
24578
24579 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24580 might try to read past the end of the file if this happens.  Changes will be
24581 needed if it causes a system error to refer to |tfm_infile^| or call
24582 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24583 @^system dependencies@>
24584 of |tfget| could be changed to
24585 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24586
24587 @d tfget do { 
24588   size_t wanted=1; 
24589   void *tfbyte_ptr = &tfbyte;
24590   (mp->read_binary_file)(mp->tfm_infile,&tfbyte_ptr,&wanted); 
24591   if (wanted==0) goto BAD_TFM; 
24592 } while (0)
24593 @d read_two(A) { (A)=tfbyte;
24594   if ( (A)>127 ) goto BAD_TFM;
24595   tfget; (A)=(A)*0400+tfbyte;
24596 }
24597 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24598
24599 @<Read the \.{TFM} size fields@>=
24600 tfget; read_two(lf);
24601 tfget; read_two(tfm_lh);
24602 tfget; read_two(bc);
24603 tfget; read_two(ec);
24604 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24605 tfget; read_two(nw);
24606 tfget; read_two(nh);
24607 tfget; read_two(nd);
24608 whd_size=(ec+1-bc)+nw+nh+nd;
24609 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24610 tf_ignore(10)
24611
24612 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24613 necessary to apply the |so|  and |qo| macros when looking up the width of a
24614 character in the string pool.  In order to ensure nonnegative |char_base|
24615 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24616 elements.
24617
24618 @<Use the size fields to allocate space in |font_info|@>=
24619 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24620 if (mp->last_fnum==mp->font_max)
24621   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24622 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24623   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24624   memory_word *font_info;
24625   font_info = xmalloc ((l+1),sizeof(memory_word));
24626   memset (font_info,0,sizeof(memory_word)*(l+1));
24627   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24628   xfree(mp->font_info);
24629   mp->font_info = font_info;
24630   mp->font_mem_size = l;
24631 }
24632 incr(mp->last_fnum);
24633 n=mp->last_fnum;
24634 mp->font_bc[n]=bc;
24635 mp->font_ec[n]=ec;
24636 mp->char_base[n]=mp->next_fmem-bc;
24637 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24638 mp->height_base[n]=mp->width_base[n]+nw;
24639 mp->depth_base[n]=mp->height_base[n]+nh;
24640 mp->next_fmem=mp->next_fmem+whd_size;
24641
24642
24643 @ @<Read the \.{TFM} header@>=
24644 if ( tfm_lh<2 ) goto BAD_TFM;
24645 tf_ignore(4);
24646 tfget; read_two(z);
24647 tfget; z=z*0400+tfbyte;
24648 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24649 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24650   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24651 tf_ignore(4*(tfm_lh-2))
24652
24653 @ @<Read the character data and the width, height, and depth tables...@>=
24654 ii=mp->width_base[n];
24655 i=mp->char_base[n]+bc;
24656 while ( i<ii ) { 
24657   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24658   tfget; h_and_d=tfbyte;
24659   mp->font_info[i].qqqq.b1=h_and_d / 16;
24660   mp->font_info[i].qqqq.b2=h_and_d % 16;
24661   tfget; tfget;
24662   incr(i);
24663 }
24664 while ( i<mp->next_fmem ) {
24665   @<Read a four byte dimension, scale it by the design size, store it in
24666     |font_info[i]|, and increment |i|@>;
24667 }
24668 goto DONE
24669
24670 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24671 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24672 we can multiply it by sixteen and think of it as a |fraction| that has been
24673 divided by sixteen.  This cancels the extra scale factor contained in
24674 |font_dsize[n|.
24675
24676 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24677
24678 tfget; d=tfbyte;
24679 if ( d>=0200 ) d=d-0400;
24680 tfget; d=d*0400+tfbyte;
24681 tfget; d=d*0400+tfbyte;
24682 tfget; d=d*0400+tfbyte;
24683 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24684 incr(i);
24685 }
24686
24687 @ This function does no longer use the file name parser, because |fname| is
24688 a C string already.
24689 @<Open |tfm_infile| for input@>=
24690 file_opened=false;
24691 mp_ptr_scan_file(mp, fname);
24692 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24693 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24694 pack_cur_name;
24695 mp->tfm_infile = (mp->open_file)( mp->name_of_file, "rb",mp_filetype_metrics);
24696 if ( !mp->tfm_infile  ) goto BAD_TFM;
24697 file_opened=true
24698
24699 @ When we have a font name and we don't know whether it has been loaded yet,
24700 we scan the |font_name| array before calling |read_font_info|.
24701
24702 @<Declare text measuring subroutines@>=
24703 font_number mp_find_font (MP mp, char *f) {
24704   font_number n;
24705   for (n=0;n<=mp->last_fnum;n++) {
24706     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
24707       mp_xfree(f);
24708       return n;
24709     }
24710   }
24711   n = mp_read_font_info(mp, f);
24712   mp_xfree(f);
24713   return n;
24714 }
24715
24716 @ One simple application of |find_font| is the implementation of the |font_size|
24717 operator that gets the design size for a given font name.
24718
24719 @<Find the design size of the font whose name is |cur_exp|@>=
24720 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24721
24722 @ If we discover that the font doesn't have a requested character, we omit it
24723 from the bounding box computation and expect the \ps\ interpreter to drop it.
24724 This routine issues a warning message if the user has asked for it.
24725
24726 @<Declare text measuring subroutines@>=
24727 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24728   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24729     mp_begin_diagnostic(mp);
24730     if ( mp->selector==log_only ) incr(mp->selector);
24731     mp_print_nl(mp, "Missing character: There is no ");
24732 @.Missing character@>
24733     mp_print_str(mp, mp->str_pool[k]); 
24734     mp_print(mp, " in font ");
24735     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24736     mp_end_diagnostic(mp, false);
24737   }
24738 }
24739
24740 @ The whole purpose of saving the height, width, and depth information is to be
24741 able to find the bounding box of an item of text in an edge structure.  The
24742 |set_text_box| procedure takes a text node and adds this information.
24743
24744 @<Declare text measuring subroutines@>=
24745 void mp_set_text_box (MP mp,pointer p) {
24746   font_number f; /* |font_n(p)| */
24747   ASCII_code bc,ec; /* range of valid characters for font |f| */
24748   pool_pointer k,kk; /* current character and character to stop at */
24749   four_quarters cc; /* the |char_info| for the current character */
24750   scaled h,d; /* dimensions of the current character */
24751   width_val(p)=0;
24752   height_val(p)=-el_gordo;
24753   depth_val(p)=-el_gordo;
24754   f=font_n(p);
24755   bc=mp->font_bc[f];
24756   ec=mp->font_ec[f];
24757   kk=str_stop(text_p(p));
24758   k=mp->str_start[text_p(p)];
24759   while ( k<kk ) {
24760     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24761   }
24762   @<Set the height and depth to zero if the bounding box is empty@>;
24763 }
24764
24765 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24766
24767   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24768     mp_lost_warning(mp, f,k);
24769   } else { 
24770     cc=char_info(f)(mp->str_pool[k]);
24771     if ( ! ichar_exists(cc) ) {
24772       mp_lost_warning(mp, f,k);
24773     } else { 
24774       width_val(p)=width_val(p)+char_width(f)(cc);
24775       h=char_height(f)(cc);
24776       d=char_depth(f)(cc);
24777       if ( h>height_val(p) ) height_val(p)=h;
24778       if ( d>depth_val(p) ) depth_val(p)=d;
24779     }
24780   }
24781   incr(k);
24782 }
24783
24784 @ Let's hope modern compilers do comparisons correctly when the difference would
24785 overflow.
24786
24787 @<Set the height and depth to zero if the bounding box is empty@>=
24788 if ( height_val(p)<-depth_val(p) ) { 
24789   height_val(p)=0;
24790   depth_val(p)=0;
24791 }
24792
24793 @ The new primitives fontmapfile and fontmapline.
24794
24795 @<Declare action procedures for use by |do_statement|@>=
24796 void mp_do_mapfile (MP mp) ;
24797 void mp_do_mapline (MP mp) ;
24798
24799 @ @c void mp_do_mapfile (MP mp) { 
24800   mp_get_x_next(mp); mp_scan_expression(mp);
24801   if ( mp->cur_type!=mp_string_type ) {
24802     @<Complain about improper map operation@>;
24803   } else {
24804     mp_map_file(mp,mp->cur_exp);
24805   }
24806 }
24807 void mp_do_mapline (MP mp) { 
24808   mp_get_x_next(mp); mp_scan_expression(mp);
24809   if ( mp->cur_type!=mp_string_type ) {
24810      @<Complain about improper map operation@>;
24811   } else { 
24812      mp_map_line(mp,mp->cur_exp);
24813   }
24814 }
24815
24816 @ @<Complain about improper map operation@>=
24817
24818   exp_err("Unsuitable expression");
24819   help1("Only known strings can be map files or map lines.");
24820   mp_put_get_error(mp);
24821 }
24822
24823 @ To print |scaled| value to PDF output we need some subroutines to ensure
24824 accurary.
24825
24826 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24827
24828 @<Glob...@>=
24829 scaled one_bp; /* scaled value corresponds to 1bp */
24830 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24831 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24832 integer ten_pow[10]; /* $10^0..10^9$ */
24833 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24834
24835 @ @<Set init...@>=
24836 mp->one_bp = 65782; /* 65781.76 */
24837 mp->one_hundred_bp = 6578176;
24838 mp->one_hundred_inch = 473628672;
24839 mp->ten_pow[0] = 1;
24840 for (i = 1;i<= 9; i++ ) {
24841   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24842 }
24843
24844 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24845
24846 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24847   scaled q,r;
24848   integer sign,i;
24849   sign = 1;
24850   if ( s < 0 ) { sign = -sign; s = -s; }
24851   if ( m < 0 ) { sign = -sign; m = -m; }
24852   if ( m == 0 )
24853     mp_confusion(mp, "arithmetic: divided by zero");
24854   else if ( m >= (max_integer / 10) )
24855     mp_confusion(mp, "arithmetic: number too big");
24856   q = s / m;
24857   r = s % m;
24858   for (i = 1;i<=dd;i++) {
24859     q = 10*q + (10*r) / m;
24860     r = (10*r) % m;
24861   }
24862   if ( 2*r >= m ) { incr(q); r = r - m; }
24863   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24864   return (sign*q);
24865 }
24866
24867 @* \[44] Shipping pictures out.
24868 The |ship_out| procedure, to be described below, is given a pointer to
24869 an edge structure. Its mission is to output a file containing the \ps\
24870 description of an edge structure.
24871
24872 @ Each time an edge structure is shipped out we write a new \ps\ output
24873 file named according to the current \&{charcode}.
24874 @:char_code_}{\&{charcode} primitive@>
24875
24876 This is the only backend function that remains in the main |mpost.w| file. 
24877 There are just too many variable accesses needed for status reporting 
24878 etcetera to make it worthwile to move the code to |psout.w|.
24879
24880 @<Internal library declarations@>=
24881 void mp_open_output_file (MP mp) ;
24882
24883 @ @c void mp_open_output_file (MP mp) {
24884   integer c; /* \&{charcode} rounded to the nearest integer */
24885   int old_setting; /* previous |selector| setting */
24886   pool_pointer i; /*  indexes into |filename_template|  */
24887   integer cc; /* a temporary integer for template building  */
24888   integer f,g=0; /* field widths */
24889   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24890   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24891   if ( mp->filename_template==0 ) {
24892     char *s; /* a file extension derived from |c| */
24893     if ( c<0 ) 
24894       s=xstrdup(".ps");
24895     else 
24896       @<Use |c| to compute the file extension |s|@>;
24897     mp_pack_job_name(mp, s);
24898     xfree(s);
24899     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24900       mp_prompt_file_name(mp, "file name for output",s);
24901   } else { /* initializations */
24902     str_number s, n; /* a file extension derived from |c| */
24903     old_setting=mp->selector; 
24904     mp->selector=new_string;
24905     f = 0;
24906     i = mp->str_start[mp->filename_template];
24907     n = rts(""); /* initialize */
24908     while ( i<str_stop(mp->filename_template) ) {
24909        if ( mp->str_pool[i]=='%' ) {
24910       CONTINUE:
24911         incr(i);
24912         if ( i<str_stop(mp->filename_template) ) {
24913           if ( mp->str_pool[i]=='j' ) {
24914             mp_print(mp, mp->job_name);
24915           } else if ( mp->str_pool[i]=='d' ) {
24916              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24917              print_with_leading_zeroes(cc);
24918           } else if ( mp->str_pool[i]=='m' ) {
24919              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24920              print_with_leading_zeroes(cc);
24921           } else if ( mp->str_pool[i]=='y' ) {
24922              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24923              print_with_leading_zeroes(cc);
24924           } else if ( mp->str_pool[i]=='H' ) {
24925              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24926              print_with_leading_zeroes(cc);
24927           }  else if ( mp->str_pool[i]=='M' ) {
24928              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24929              print_with_leading_zeroes(cc);
24930           } else if ( mp->str_pool[i]=='c' ) {
24931             if ( c<0 ) mp_print(mp, "ps");
24932             else print_with_leading_zeroes(c);
24933           } else if ( (mp->str_pool[i]>='0') && 
24934                       (mp->str_pool[i]<='9') ) {
24935             if ( (f<10)  )
24936               f = (f*10) + mp->str_pool[i]-'0';
24937             goto CONTINUE;
24938           } else {
24939             mp_print_str(mp, mp->str_pool[i]);
24940           }
24941         }
24942       } else {
24943         if ( mp->str_pool[i]=='.' )
24944           if (length(n)==0)
24945             n = mp_make_string(mp);
24946         mp_print_str(mp, mp->str_pool[i]);
24947       };
24948       incr(i);
24949     };
24950     s = mp_make_string(mp);
24951     mp->selector= old_setting;
24952     if (length(n)==0) {
24953        n=s;
24954        s=rts("");
24955     };
24956     mp_pack_file_name(mp, str(n),"",str(s));
24957     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24958       mp_prompt_file_name(mp, "file name for output",str(s));
24959     delete_str_ref(n);
24960     delete_str_ref(s);
24961   }
24962   @<Store the true output file name if appropriate@>;
24963 }
24964
24965 @ The file extension created here could be up to five characters long in
24966 extreme cases so it may have to be shortened on some systems.
24967 @^system dependencies@>
24968
24969 @<Use |c| to compute the file extension |s|@>=
24970
24971   s = xmalloc(7,1);
24972   snprintf(s,7,".%i",(int)c);
24973 }
24974
24975 @ The user won't want to see all the output file names so we only save the
24976 first and last ones and a count of how many there were.  For this purpose
24977 files are ordered primarily by \&{charcode} and secondarily by order of
24978 creation.
24979 @:char_code_}{\&{charcode} primitive@>
24980
24981 @<Store the true output file name if appropriate@>=
24982 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24983   mp->first_output_code=c;
24984   xfree(mp->first_file_name);
24985   mp->first_file_name=xstrdup(mp->name_of_file);
24986 }
24987 if ( c>=mp->last_output_code ) {
24988   mp->last_output_code=c;
24989   xfree(mp->last_file_name);
24990   mp->last_file_name=xstrdup(mp->name_of_file);
24991 }
24992
24993 @ @<Glob...@>=
24994 char * first_file_name;
24995 char * last_file_name; /* full file names */
24996 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24997 @:char_code_}{\&{charcode} primitive@>
24998 integer total_shipped; /* total number of |ship_out| operations completed */
24999
25000 @ @<Set init...@>=
25001 mp->first_file_name=xstrdup("");
25002 mp->last_file_name=xstrdup("");
25003 mp->first_output_code=32768;
25004 mp->last_output_code=-32768;
25005 mp->total_shipped=0;
25006
25007 @ @<Dealloc variables@>=
25008 xfree(mp->first_file_name);
25009 xfree(mp->last_file_name);
25010
25011 @ @<Begin the progress report for the output of picture~|c|@>=
25012 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25013 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25014 mp_print_char(mp, '[');
25015 if ( c>=0 ) mp_print_int(mp, c)
25016
25017 @ @<End progress report@>=
25018 mp_print_char(mp, ']');
25019 update_terminal;
25020 incr(mp->total_shipped)
25021
25022 @ @<Explain what output files were written@>=
25023 if ( mp->total_shipped>0 ) { 
25024   mp_print_nl(mp, "");
25025   mp_print_int(mp, mp->total_shipped);
25026   mp_print(mp, " output file");
25027   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25028   mp_print(mp, " written: ");
25029   mp_print(mp, mp->first_file_name);
25030   if ( mp->total_shipped>1 ) {
25031     if ( 31+strlen(mp->first_file_name)+
25032          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25033       mp_print_ln(mp);
25034     mp_print(mp, " .. ");
25035     mp_print(mp, mp->last_file_name);
25036   }
25037 }
25038
25039 @ @<Internal library declarations@>=
25040 boolean mp_has_font_size(MP mp, font_number f );
25041
25042 @ @c 
25043 boolean mp_has_font_size(MP mp, font_number f ) {
25044   return (mp->font_sizes[f]!=null);
25045 }
25046
25047 @ The \&{special} command saves up lines of text to be printed during the next
25048 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25049
25050 @<Glob...@>=
25051 pointer last_pending; /* the last token in a list of pending specials */
25052
25053 @ @<Set init...@>=
25054 mp->last_pending=spec_head;
25055
25056 @ @<Cases of |do_statement|...@>=
25057 case special_command: 
25058   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25059   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25060   mp_do_mapline(mp);
25061   break;
25062
25063 @ @<Declare action procedures for use by |do_statement|@>=
25064 void mp_do_special (MP mp) ;
25065
25066 @ @c void mp_do_special (MP mp) { 
25067   mp_get_x_next(mp); mp_scan_expression(mp);
25068   if ( mp->cur_type!=mp_string_type ) {
25069     @<Complain about improper special operation@>;
25070   } else { 
25071     link(mp->last_pending)=mp_stash_cur_exp(mp);
25072     mp->last_pending=link(mp->last_pending);
25073     link(mp->last_pending)=null;
25074   }
25075 }
25076
25077 @ @<Complain about improper special operation@>=
25078
25079   exp_err("Unsuitable expression");
25080   help1("Only known strings are allowed for output as specials.");
25081   mp_put_get_error(mp);
25082 }
25083
25084 @ On the export side, we need an extra object type for special strings.
25085
25086 @<Graphical object codes@>=
25087 mp_special_code=8, 
25088
25089 @ @<Export pending specials@>=
25090 p=link(spec_head);
25091 while ( p!=null ) {
25092   hq = mp_new_graphic_object(mp,mp_special_code);
25093   gr_pre_script(hq)  = str(value(p));
25094   if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25095   hp = hq;
25096   p=link(p);
25097 }
25098 mp_flush_token_list(mp, link(spec_head));
25099 link(spec_head)=null;
25100 mp->last_pending=spec_head
25101
25102 @ We are now ready for the main output procedure.  Note that the |selector|
25103 setting is saved in a global variable so that |begin_diagnostic| can access it.
25104
25105 @<Declare the \ps\ output procedures@>=
25106 void mp_ship_out (MP mp, pointer h) ;
25107
25108 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25109
25110 @c
25111 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25112   pointer p; /* the current graphical object */
25113   integer t; /* a temporary value */
25114   struct mp_edge_object *hh; /* the first graphical object */
25115   struct mp_graphic_object *hp; /* the current graphical object */
25116   struct mp_graphic_object *hq; /* something |hp| points to  */
25117   mp_set_bbox(mp, h, true);
25118   hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25119   hh->body = NULL;
25120   hh->_next = NULL;
25121   hh->_parent = mp;
25122   hh->_minx = minx_val(h);
25123   hh->_miny = miny_val(h);
25124   hh->_maxx = maxx_val(h);
25125   hh->_maxy = maxy_val(h);
25126   @<Export pending specials@>;
25127   p=link(dummy_loc(h));
25128   while ( p!=null ) { 
25129     hq = mp_new_graphic_object(mp,type(p));
25130     switch (type(p)) {
25131     case mp_fill_code:
25132       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25133       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25134           gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25135       } else {
25136         pointer pc, pp;
25137         pc = mp_copy_path(mp, path_p(p));
25138         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25139         gr_path_p(hq)       = mp_export_knot_list(mp,pp);
25140         mp_toss_knot_list(mp, pp);
25141         pc = mp_htap_ypoc(mp, path_p(p));
25142         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25143         gr_htap_p(hq)       = mp_export_knot_list(mp,pp);
25144         mp_toss_knot_list(mp, pp);
25145       }
25146       @<Export object color@>;
25147       @<Export object scripts@>;
25148       gr_ljoin_val(hq)    = ljoin_val(p);
25149       gr_miterlim_val(hq) = miterlim_val(p);
25150       break;
25151     case mp_stroked_code:
25152       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25153       if (pen_is_elliptical(pen_p(p)))  {
25154               gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25155       } else {
25156         pointer pc;
25157         pc=mp_copy_path(mp, path_p(p));
25158         t=lcap_val(p);
25159         if ( left_type(pc)!=mp_endpoint ) { 
25160           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25161           right_type(pc)=mp_endpoint;
25162           pc=link(pc);
25163           t=1;
25164         }
25165         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25166         gr_path_p(hq)       = mp_export_knot_list(mp,pc);
25167         mp_toss_knot_list(mp, pc);
25168       }
25169       @<Export object color@>;
25170       @<Export object scripts@>;
25171       gr_ljoin_val(hq)    = ljoin_val(p);
25172       gr_miterlim_val(hq) = miterlim_val(p);
25173       gr_lcap_val(hq)     = lcap_val(p);
25174       gr_dash_scale(hq)   = dash_scale(p);
25175       gr_dash_p(hq)       = mp_export_dashes(mp,dash_p(p));
25176       break;
25177     case mp_text_code:
25178       gr_text_p(hq)       = str(text_p(p));
25179       gr_font_n(hq)       = font_n(p);
25180       gr_font_name(hq)    = mp_xstrdup(mp,mp->font_name[font_n(p)]);
25181       gr_font_dsize(hq)   = mp->font_dsize[font_n(p)];
25182       @<Export object color@>;
25183       @<Export object scripts@>;
25184       gr_width_val(hq)    = width_val(p);
25185       gr_height_val(hq)   = height_val(p);
25186       gr_depth_val(hq)    = depth_val(p);
25187       gr_tx_val(hq)       = tx_val(p);
25188       gr_ty_val(hq)       = ty_val(p);
25189       gr_txx_val(hq)      = txx_val(p);
25190       gr_txy_val(hq)      = txy_val(p);
25191       gr_tyx_val(hq)      = tyx_val(p);
25192       gr_tyy_val(hq)      = tyy_val(p);
25193       break;
25194     case mp_start_clip_code: 
25195     case mp_start_bounds_code:
25196       gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25197       break;
25198     case mp_stop_clip_code: 
25199     case mp_stop_bounds_code:
25200       /* nothing to do here */
25201       break;
25202     } 
25203     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25204     hp = hq;
25205     p=link(p);
25206   }
25207   return hh;
25208 }
25209
25210 @ @<Exported function ...@>=
25211 struct mp_edge_object *mp_gr_export(MP mp, int h);
25212
25213 @ This function is now nearly trivial.
25214
25215 @c
25216 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25217   integer c; /* \&{charcode} rounded to the nearest integer */
25218   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25219   @<Begin the progress report for the output of picture~|c|@>;
25220   (mp->shipout_backend) (mp, h);
25221   @<End progress report@>;
25222   if ( mp->internal[mp_tracing_output]>0 ) 
25223    mp_print_edges(mp, h," (just shipped out)",true);
25224 }
25225
25226 @ @<Declarations@>=
25227 void mp_shipout_backend (MP mp, pointer h);
25228
25229 @ @c
25230 void mp_shipout_backend (MP mp, pointer h) {
25231   struct mp_edge_object *hh; /* the first graphical object */
25232   hh = mp_gr_export(mp,h);
25233   mp_gr_ship_out (hh,
25234                  (mp->internal[mp_prologues]>>16),
25235                  (mp->internal[mp_procset]>>16));
25236   mp_gr_toss_objects(hh);
25237 }
25238
25239 @ @<Exported types@>=
25240 typedef void (*mp_backend_writer)(MP, int);
25241
25242 @ @<Option variables@>=
25243 mp_backend_writer shipout_backend;
25244
25245 @ @<Allocate or initialize ...@>=
25246 set_callback_option(shipout_backend);
25247
25248
25249
25250 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25251
25252 @<Export object color@>=
25253 gr_color_model(hq)  = color_model(p);
25254 gr_cyan_val(hq)     = cyan_val(p);
25255 gr_magenta_val(hq)  = magenta_val(p);
25256 gr_yellow_val(hq)   = yellow_val(p);
25257 gr_black_val(hq)    = black_val(p);
25258 gr_red_val(hq)      = red_val(p);
25259 gr_green_val(hq)    = green_val(p);
25260 gr_blue_val(hq)     = blue_val(p);
25261 gr_grey_val(hq)     = grey_val(p)
25262
25263
25264 @ @<Export object scripts@>=
25265 if (pre_script(p)!=null)
25266   gr_pre_script(hq)   = str(pre_script(p));
25267 if (post_script(p)!=null)
25268   gr_post_script(hq)  = str(post_script(p));
25269
25270 @ Now that we've finished |ship_out|, let's look at the other commands
25271 by which a user can send things to the \.{GF} file.
25272
25273 @ @<Determine if a character has been shipped out@>=
25274
25275   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25276   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25277   boolean_reset(mp->char_exists[mp->cur_exp]);
25278   mp->cur_type=mp_boolean_type;
25279 }
25280
25281 @ @<Glob...@>=
25282 psout_data ps;
25283
25284 @ @<Allocate or initialize ...@>=
25285 mp_backend_initialize(mp);
25286
25287 @ @<Dealloc...@>=
25288 mp_backend_free(mp);
25289
25290
25291 @* \[45] Dumping and undumping the tables.
25292 After \.{INIMP} has seen a collection of macros, it
25293 can write all the necessary information on an auxiliary file so
25294 that production versions of \MP\ are able to initialize their
25295 memory at high speed. The present section of the program takes
25296 care of such output and input. We shall consider simultaneously
25297 the processes of storing and restoring,
25298 so that the inverse relation between them is clear.
25299 @.INIMP@>
25300
25301 The global variable |mem_ident| is a string that is printed right
25302 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25303 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25304 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25305 month, and day that the mem file was created. We have |mem_ident=0|
25306 before \MP's tables are loaded.
25307
25308 @<Glob...@>=
25309 char * mem_ident;
25310
25311 @ @<Set init...@>=
25312 mp->mem_ident=NULL;
25313
25314 @ @<Initialize table entries...@>=
25315 mp->mem_ident=xstrdup(" (INIMP)");
25316
25317 @ @<Declare act...@>=
25318 void mp_store_mem_file (MP mp) ;
25319
25320 @ @c void mp_store_mem_file (MP mp) {
25321   integer k;  /* all-purpose index */
25322   pointer p,q; /* all-purpose pointers */
25323   integer x; /* something to dump */
25324   four_quarters w; /* four ASCII codes */
25325   memory_word WW;
25326   @<Create the |mem_ident|, open the mem file,
25327     and inform the user that dumping has begun@>;
25328   @<Dump constants for consistency check@>;
25329   @<Dump the string pool@>;
25330   @<Dump the dynamic memory@>;
25331   @<Dump the table of equivalents and the hash table@>;
25332   @<Dump a few more things and the closing check word@>;
25333   @<Close the mem file@>;
25334 }
25335
25336 @ Corresponding to the procedure that dumps a mem file, we also have a function
25337 that reads~one~in. The function returns |false| if the dumped mem is
25338 incompatible with the present \MP\ table sizes, etc.
25339
25340 @d off_base 6666 /* go here if the mem file is unacceptable */
25341 @d too_small(A) { wake_up_terminal;
25342   wterm_ln("---! Must increase the "); wterm((A));
25343 @.Must increase the x@>
25344   goto OFF_BASE;
25345   }
25346
25347 @c 
25348 boolean mp_load_mem_file (MP mp) {
25349   integer k; /* all-purpose index */
25350   pointer p,q; /* all-purpose pointers */
25351   integer x; /* something undumped */
25352   str_number s; /* some temporary string */
25353   four_quarters w; /* four ASCII codes */
25354   memory_word WW;
25355   @<Undump constants for consistency check@>;
25356   @<Undump the string pool@>;
25357   @<Undump the dynamic memory@>;
25358   @<Undump the table of equivalents and the hash table@>;
25359   @<Undump a few more things and the closing check word@>;
25360   return true; /* it worked! */
25361 OFF_BASE: 
25362   wake_up_terminal;
25363   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25364 @.Fatal mem file error@>
25365    return false;
25366 }
25367
25368 @ @<Declarations@>=
25369 boolean mp_load_mem_file (MP mp) ;
25370
25371 @ Mem files consist of |memory_word| items, and we use the following
25372 macros to dump words of different types:
25373
25374 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25375 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp->mem_file,&cint,sizeof(cint)); }
25376 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25377 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25378 @d dump_string(A) { dump_int(strlen(A)+1);
25379                     (mp->write_binary_file)(mp->mem_file,A,strlen(A)+1); }
25380
25381 @<Glob...@>=
25382 void * mem_file; /* for input or output of mem information */
25383
25384 @ The inverse macros are slightly more complicated, since we need to check
25385 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25386 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25387
25388 @d mgeti(A) do {
25389   size_t wanted = sizeof(A);
25390   void *A_ptr = &A;
25391   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25392   if (wanted!=sizeof(A)) goto OFF_BASE;
25393 } while (0)
25394
25395 @d mgetw(A) do {
25396   size_t wanted = sizeof(A);
25397   void *A_ptr = &A;
25398   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25399   if (wanted!=sizeof(A)) goto OFF_BASE;
25400 } while (0)
25401
25402 @d undump_wd(A)   { mgetw(WW); A=WW; }
25403 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25404 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25405 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25406 @d undump_strings(A,B,C) { 
25407    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25408 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25409 @d undump_size(A,B,C,D) { undump_int(x);
25410                           if (x<(A)) goto OFF_BASE; 
25411                           if (x>(B)) { too_small((C)); } else { D=x;} }
25412 @d undump_string(A) do { 
25413   size_t wanted; 
25414   integer XX=0; 
25415   undump_int(XX);
25416   wanted = XX;
25417   A = xmalloc(XX,sizeof(char));
25418   (mp->read_binary_file)(mp->mem_file,(void **)&A,&wanted);
25419   if (wanted!=(size_t)XX) goto OFF_BASE;
25420 } while (0)
25421
25422 @ The next few sections of the program should make it clear how we use the
25423 dump/undump macros.
25424
25425 @<Dump constants for consistency check@>=
25426 dump_int(mp->mem_top);
25427 dump_int(mp->hash_size);
25428 dump_int(mp->hash_prime)
25429 dump_int(mp->param_size);
25430 dump_int(mp->max_in_open);
25431
25432 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25433 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25434 the same strings. (And it is, of course, a good thing that they do.)
25435 @.WEB@>
25436 @^string pool@>
25437
25438 @<Undump constants for consistency check@>=
25439 undump_int(x); mp->mem_top = x;
25440 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25441 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25442 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25443 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25444
25445 @ We do string pool compaction to avoid dumping unused strings.
25446
25447 @d dump_four_ASCII 
25448   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25449   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25450   dump_qqqq(w)
25451
25452 @<Dump the string pool@>=
25453 mp_do_compaction(mp, mp->pool_size);
25454 dump_int(mp->pool_ptr);
25455 dump_int(mp->max_str_ptr);
25456 dump_int(mp->str_ptr);
25457 k=0;
25458 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25459   incr(k);
25460 dump_int(k);
25461 while ( k<=mp->max_str_ptr ) { 
25462   dump_int(mp->next_str[k]); incr(k);
25463 }
25464 k=0;
25465 while (1)  { 
25466   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25467   if ( k==mp->str_ptr ) {
25468     break;
25469   } else { 
25470     k=mp->next_str[k]; 
25471   }
25472 };
25473 k=0;
25474 while (k+4<mp->pool_ptr ) { 
25475   dump_four_ASCII; k=k+4; 
25476 }
25477 k=mp->pool_ptr-4; dump_four_ASCII;
25478 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25479 mp_print(mp, " strings of total length ");
25480 mp_print_int(mp, mp->pool_ptr)
25481
25482 @ @d undump_four_ASCII 
25483   undump_qqqq(w);
25484   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25485   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25486
25487 @<Undump the string pool@>=
25488 undump_int(mp->pool_ptr);
25489 mp_reallocate_pool(mp, mp->pool_ptr) ;
25490 undump_int(mp->max_str_ptr);
25491 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25492 undump(0,mp->max_str_ptr,mp->str_ptr);
25493 undump(0,mp->max_str_ptr+1,s);
25494 for (k=0;k<=s-1;k++) 
25495   mp->next_str[k]=k+1;
25496 for (k=s;k<=mp->max_str_ptr;k++) 
25497   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25498 mp->fixed_str_use=0;
25499 k=0;
25500 while (1) { 
25501   undump(0,mp->pool_ptr,mp->str_start[k]);
25502   if ( k==mp->str_ptr ) break;
25503   mp->str_ref[k]=max_str_ref;
25504   incr(mp->fixed_str_use);
25505   mp->last_fixed_str=k; k=mp->next_str[k];
25506 }
25507 k=0;
25508 while ( k+4<mp->pool_ptr ) { 
25509   undump_four_ASCII; k=k+4;
25510 }
25511 k=mp->pool_ptr-4; undump_four_ASCII;
25512 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25513 mp->max_pool_ptr=mp->pool_ptr;
25514 mp->strs_used_up=mp->fixed_str_use;
25515 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25516 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25517 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25518
25519 @ By sorting the list of available spaces in the variable-size portion of
25520 |mem|, we are usually able to get by without having to dump very much
25521 of the dynamic memory.
25522
25523 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25524 information even when it has not been gathering statistics.
25525
25526 @<Dump the dynamic memory@>=
25527 mp_sort_avail(mp); mp->var_used=0;
25528 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25529 p=0; q=mp->rover; x=0;
25530 do {  
25531   for (k=p;k<= q+1;k++) 
25532     dump_wd(mp->mem[k]);
25533   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25534   p=q+node_size(q); q=rlink(q);
25535 } while (q!=mp->rover);
25536 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25537 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25538 for (k=p;k<= mp->lo_mem_max;k++ ) 
25539   dump_wd(mp->mem[k]);
25540 x=x+mp->lo_mem_max+1-p;
25541 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25542 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25543   dump_wd(mp->mem[k]);
25544 x=x+mp->mem_end+1-mp->hi_mem_min;
25545 p=mp->avail;
25546 while ( p!=null ) { 
25547   decr(mp->dyn_used); p=link(p);
25548 }
25549 dump_int(mp->var_used); dump_int(mp->dyn_used);
25550 mp_print_ln(mp); mp_print_int(mp, x);
25551 mp_print(mp, " memory locations dumped; current usage is ");
25552 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25553
25554 @ @<Undump the dynamic memory@>=
25555 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25556 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25557 p=0; q=mp->rover;
25558 do {  
25559   for (k=p;k<= q+1; k++) 
25560     undump_wd(mp->mem[k]);
25561   p=q+node_size(q);
25562   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25563     goto OFF_BASE;
25564   q=rlink(q);
25565 } while (q!=mp->rover);
25566 for (k=p;k<=mp->lo_mem_max;k++ ) 
25567   undump_wd(mp->mem[k]);
25568 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25569 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25570 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25571   undump_wd(mp->mem[k]);
25572 undump_int(mp->var_used); undump_int(mp->dyn_used)
25573
25574 @ A different scheme is used to compress the hash table, since its lower region
25575 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25576 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25577 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25578
25579 @<Dump the table of equivalents and the hash table@>=
25580 dump_int(mp->hash_used); 
25581 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25582 for (p=1;p<=mp->hash_used;p++) {
25583   if ( text(p)!=0 ) {
25584      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25585   }
25586 }
25587 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25588   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25589 }
25590 dump_int(mp->st_count);
25591 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25592
25593 @ @<Undump the table of equivalents and the hash table@>=
25594 undump(1,frozen_inaccessible,mp->hash_used); 
25595 p=0;
25596 do {  
25597   undump(p+1,mp->hash_used,p); 
25598   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25599 } while (p!=mp->hash_used);
25600 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25601   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25602 }
25603 undump_int(mp->st_count)
25604
25605 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25606 to prevent them appearing again.
25607
25608 @<Dump a few more things and the closing check word@>=
25609 dump_int(mp->max_internal);
25610 dump_int(mp->int_ptr);
25611 for (k=1;k<= mp->int_ptr;k++ ) { 
25612   dump_int(mp->internal[k]); 
25613   dump_string(mp->int_name[k]);
25614 }
25615 dump_int(mp->start_sym); 
25616 dump_int(mp->interaction); 
25617 dump_string(mp->mem_ident);
25618 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25619 mp->internal[mp_tracing_stats]=0
25620
25621 @ @<Undump a few more things and the closing check word@>=
25622 undump_int(x);
25623 if (x>mp->max_internal) mp_grow_internals(mp,x);
25624 undump_int(mp->int_ptr);
25625 for (k=1;k<= mp->int_ptr;k++) { 
25626   undump_int(mp->internal[k]);
25627   undump_string(mp->int_name[k]);
25628 }
25629 undump(0,frozen_inaccessible,mp->start_sym);
25630 if (mp->interaction==mp_unspecified_mode) {
25631   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25632 } else {
25633   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25634 }
25635 undump_string(mp->mem_ident);
25636 undump(1,hash_end,mp->bg_loc);
25637 undump(1,hash_end,mp->eg_loc);
25638 undump_int(mp->serial_no);
25639 undump_int(x); 
25640 if (x!=69073) goto OFF_BASE
25641
25642 @ @<Create the |mem_ident|...@>=
25643
25644   xfree(mp->mem_ident);
25645   mp->mem_ident = xmalloc(256,1);
25646   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25647            mp->job_name,
25648            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25649            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25650            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25651   mp_pack_job_name(mp, mem_extension);
25652   while (! mp_w_open_out(mp, &mp->mem_file) )
25653     mp_prompt_file_name(mp, "mem file name", mem_extension);
25654   mp_print_nl(mp, "Beginning to dump on file ");
25655 @.Beginning to dump...@>
25656   mp_print(mp, mp->name_of_file); 
25657   mp_print_nl(mp, mp->mem_ident);
25658 }
25659
25660 @ @<Dealloc variables@>=
25661 xfree(mp->mem_ident);
25662
25663 @ @<Close the mem file@>=
25664 (mp->close_file)(mp->mem_file)
25665
25666 @* \[46] The main program.
25667 This is it: the part of \MP\ that executes all those procedures we have
25668 written.
25669
25670 Well---almost. We haven't put the parsing subroutines into the
25671 program yet; and we'd better leave space for a few more routines that may
25672 have been forgotten.
25673
25674 @c @<Declare the basic parsing subroutines@>;
25675 @<Declare miscellaneous procedures that were declared |forward|@>;
25676 @<Last-minute procedures@>
25677
25678 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25679 @.INIMP@>
25680 has to be run first; it initializes everything from scratch, without
25681 reading a mem file, and it has the capability of dumping a mem file.
25682 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25683 @.VIRMP@>
25684 to input a mem file in order to get started. \.{VIRMP} typically has
25685 a bit more memory capacity than \.{INIMP}, because it does not need the
25686 space consumed by the dumping/undumping routines and the numerous calls on
25687 |primitive|, etc.
25688
25689 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25690 the best implementations therefore allow for production versions of \MP\ that
25691 not only avoid the loading routine for object code, they also have
25692 a mem file pre-loaded. 
25693
25694 @ @<Option variables@>=
25695 int ini_version; /* are we iniMP? */
25696
25697 @ @<Set |ini_version|@>=
25698 mp->ini_version = (opt->ini_version ? true : false);
25699
25700 @ Here we do whatever is needed to complete \MP's job gracefully on the
25701 local operating system. The code here might come into play after a fatal
25702 error; it must therefore consist entirely of ``safe'' operations that
25703 cannot produce error messages. For example, it would be a mistake to call
25704 |str_room| or |make_string| at this time, because a call on |overflow|
25705 might lead to an infinite loop.
25706 @^system dependencies@>
25707
25708 This program doesn't bother to close the input files that may still be open.
25709
25710 @<Last-minute...@>=
25711 void mp_close_files_and_terminate (MP mp) {
25712   integer k; /* all-purpose index */
25713   integer LH; /* the length of the \.{TFM} header, in words */
25714   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25715   pointer p; /* runs through a list of \.{TFM} dimensions */
25716   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25717   if ( mp->internal[mp_tracing_stats]>0 )
25718     @<Output statistics about this job@>;
25719   wake_up_terminal; 
25720   @<Do all the finishing work on the \.{TFM} file@>;
25721   @<Explain what output files were written@>;
25722   if ( mp->log_opened ){ 
25723     wlog_cr;
25724     (mp->close_file)(mp->log_file); 
25725     mp->selector=mp->selector-2;
25726     if ( mp->selector==term_only ) {
25727       mp_print_nl(mp, "Transcript written on ");
25728 @.Transcript written...@>
25729       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25730     }
25731   }
25732   mp_print_ln(mp);
25733   t_close_out;
25734   t_close_in;
25735 }
25736
25737 @ @<Declarations@>=
25738 void mp_close_files_and_terminate (MP mp) ;
25739
25740 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25741 if (mp->rd_fname!=NULL) {
25742   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25743     if ( mp->rd_fname[k]!=NULL ) {
25744       (mp->close_file)(mp->rd_file[k]);
25745    }
25746  }
25747 }
25748 if (mp->wr_fname!=NULL) {
25749   for (k=0;k<=(int)mp->write_files-1;k++) {
25750     if ( mp->wr_fname[k]!=NULL ) {
25751      (mp->close_file)(mp->wr_file[k]);
25752     }
25753   }
25754 }
25755
25756 @ @<Dealloc ...@>=
25757 for (k=0;k<(int)mp->max_read_files;k++ ) {
25758   if ( mp->rd_fname[k]!=NULL ) {
25759     (mp->close_file)(mp->rd_file[k]);
25760     mp_xfree(mp->rd_fname[k]); 
25761   }
25762 }
25763 mp_xfree(mp->rd_file);
25764 mp_xfree(mp->rd_fname);
25765 for (k=0;k<(int)mp->max_write_files;k++) {
25766   if ( mp->wr_fname[k]!=NULL ) {
25767     (mp->close_file)(mp->wr_file[k]);
25768     mp_xfree(mp->wr_fname[k]); 
25769   }
25770 }
25771 mp_xfree(mp->wr_file);
25772 mp_xfree(mp->wr_fname);
25773
25774
25775 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25776
25777 We reclaim all of the variable-size memory at this point, so that
25778 there is no chance of another memory overflow after the memory capacity
25779 has already been exceeded.
25780
25781 @<Do all the finishing work on the \.{TFM} file@>=
25782 if ( mp->internal[mp_fontmaking]>0 ) {
25783   @<Make the dynamic memory into one big available node@>;
25784   @<Massage the \.{TFM} widths@>;
25785   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25786   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25787   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25788   @<Finish the \.{TFM} file@>;
25789 }
25790
25791 @ @<Make the dynamic memory into one big available node@>=
25792 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25793 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25794 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25795 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25796 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25797
25798 @ The present section goes directly to the log file instead of using
25799 |print| commands, because there's no need for these strings to take
25800 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25801
25802 @<Output statistics...@>=
25803 if ( mp->log_opened ) { 
25804   char s[128];
25805   wlog_ln(" ");
25806   wlog_ln("Here is how much of MetaPost's memory you used:");
25807 @.Here is how much...@>
25808   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25809           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25810           (int)(mp->max_strings-1-mp->init_str_use));
25811   wlog_ln(s);
25812   snprintf(s,128," %i string characters out of %i",
25813            (int)mp->max_pl_used-mp->init_pool_ptr,
25814            (int)mp->pool_size-mp->init_pool_ptr);
25815   wlog_ln(s);
25816   snprintf(s,128," %i words of memory out of %i",
25817            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25818            (int)mp->mem_end+1);
25819   wlog_ln(s);
25820   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25821   wlog_ln(s);
25822   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25823            (int)mp->max_in_stack,(int)mp->int_ptr,
25824            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25825            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25826   wlog_ln(s);
25827   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25828           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25829   wlog_ln(s);
25830 }
25831
25832 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25833 been scanned.
25834
25835 @<Last-minute...@>=
25836 void mp_final_cleanup (MP mp) {
25837   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25838   c=mp->cur_mod;
25839   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25840   while ( mp->input_ptr>0 ) {
25841     if ( token_state ) mp_end_token_list(mp);
25842     else  mp_end_file_reading(mp);
25843   }
25844   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25845   while ( mp->open_parens>0 ) { 
25846     mp_print(mp, " )"); decr(mp->open_parens);
25847   };
25848   while ( mp->cond_ptr!=null ) {
25849     mp_print_nl(mp, "(end occurred when ");
25850 @.end occurred...@>
25851     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25852     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25853     if ( mp->if_line!=0 ) {
25854       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25855     }
25856     mp_print(mp, " was incomplete)");
25857     mp->if_line=if_line_field(mp->cond_ptr);
25858     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25859   }
25860   if ( mp->history!=mp_spotless )
25861     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25862       if ( mp->selector==term_and_log ) {
25863     mp->selector=term_only;
25864     mp_print_nl(mp, "(see the transcript file for additional information)");
25865 @.see the transcript file...@>
25866     mp->selector=term_and_log;
25867   }
25868   if ( c==1 ) {
25869     if (mp->ini_version) {
25870       mp_store_mem_file(mp); return;
25871     }
25872     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
25873 @.dump...only by INIMP@>
25874   }
25875 }
25876
25877 @ @<Declarations@>=
25878 void mp_final_cleanup (MP mp) ;
25879 void mp_init_prim (MP mp) ;
25880 void mp_init_tab (MP mp) ;
25881
25882 @ @<Last-minute...@>=
25883 void mp_init_prim (MP mp) { /* initialize all the primitives */
25884   @<Put each...@>;
25885 }
25886 @#
25887 void mp_init_tab (MP mp) { /* initialize other tables */
25888   integer k; /* all-purpose index */
25889   @<Initialize table entries (done by \.{INIMP} only)@>;
25890 }
25891
25892
25893 @ When we begin the following code, \MP's tables may still contain garbage;
25894 the strings might not even be present. Thus we must proceed cautiously to get
25895 bootstrapped in.
25896
25897 But when we finish this part of the program, \MP\ is ready to call on the
25898 |main_control| routine to do its work.
25899
25900 @<Get the first line...@>=
25901
25902   @<Initialize the input routines@>;
25903   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
25904     if ( mp->mem_ident!=NULL ) {
25905       mp_do_initialize(mp); /* erase preloaded mem */
25906     }
25907     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
25908     if ( ! mp_load_mem_file(mp) ) {
25909       (mp->close_file)(mp->mem_file); 
25910       return mp_fatal_error_stop;
25911     }
25912     (mp->close_file)( mp->mem_file);
25913     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
25914   }
25915   mp->buffer[limit]='%';
25916   mp_fix_date_and_time(mp);
25917   if (mp->random_seed==0)
25918     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
25919   mp_init_randoms(mp, mp->random_seed);
25920   @<Initialize the print |selector|...@>;
25921   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
25922     mp_start_input(mp); /* \&{input} assumed */
25923 }
25924
25925 @ @<Run inimpost commands@>=
25926 {
25927   mp_get_strings_started(mp);
25928   mp_init_tab(mp); /* initialize the tables */
25929   mp_init_prim(mp); /* call |primitive| for each primitive */
25930   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
25931   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
25932   mp_fix_date_and_time(mp);
25933 }
25934
25935
25936 @* \[47] Debugging.
25937 Once \MP\ is working, you should be able to diagnose most errors with
25938 the \.{show} commands and other diagnostic features. But for the initial
25939 stages of debugging, and for the revelation of really deep mysteries, you
25940 can compile \MP\ with a few more aids. An additional routine called |debug_help|
25941 will also come into play when you type `\.D' after an error message;
25942 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
25943 @^debugging@>
25944 @^system dependencies@>
25945
25946 The interface to |debug_help| is primitive, but it is good enough when used
25947 with a debugger that allows you to set breakpoints and to read
25948 variables and change their values. After getting the prompt `\.{debug \#}', you
25949 type either a negative number (this exits |debug_help|), or zero (this
25950 goes to a location where you can set a breakpoint, thereby entering into
25951 dialog with the debugger), or a positive number |m| followed by
25952 an argument |n|. The meaning of |m| and |n| will be clear from the
25953 program below. (If |m=13|, there is an additional argument, |l|.)
25954 @.debug \#@>
25955
25956 @<Last-minute...@>=
25957 void mp_debug_help (MP mp) { /* routine to display various things */
25958   integer k;
25959   int l,m,n;
25960   char *aline;
25961   size_t len;
25962   while (1) { 
25963     wake_up_terminal;
25964     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
25965 @.debug \#@>
25966     m = 0;
25967     aline = (mp->read_ascii_file)(mp->term_in, &len);
25968     if (len) { sscanf(aline,"%i",&m); xfree(aline); }
25969     if ( m<=0 )
25970       return;
25971     n = 0 ;
25972     aline = (mp->read_ascii_file)(mp->term_in, &len);
25973     if (len) { sscanf(aline,"%i",&n); xfree(aline); }
25974     switch (m) {
25975     @<Numbered cases for |debug_help|@>;
25976     default: mp_print(mp, "?"); break;
25977     }
25978   }
25979 }
25980
25981 @ @<Numbered cases...@>=
25982 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
25983   break;
25984 case 2: mp_print_int(mp, info(n));
25985   break;
25986 case 3: mp_print_int(mp, link(n));
25987   break;
25988 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
25989   break;
25990 case 5: mp_print_variable_name(mp, n);
25991   break;
25992 case 6: mp_print_int(mp, mp->internal[n]);
25993   break;
25994 case 7: mp_do_show_dependencies(mp);
25995   break;
25996 case 9: mp_show_token_list(mp, n,null,100000,0);
25997   break;
25998 case 10: mp_print_str(mp, n);
25999   break;
26000 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26001   break;
26002 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26003   break;
26004 case 13: 
26005   l = 0;  
26006   aline = (mp->read_ascii_file)(mp->term_in, &len);
26007   if (len) { sscanf(aline,"%i",&l); xfree(aline); }
26008   mp_print_cmd_mod(mp, n,l); 
26009   break;
26010 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26011   break;
26012 case 15: mp->panicking=! mp->panicking;
26013   break;
26014
26015
26016 @ Saving the filename template
26017
26018 @<Save the filename template@>=
26019
26020   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26021   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26022   else { 
26023     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26024   }
26025 }
26026
26027 @* \[48] System-dependent changes.
26028 This section should be replaced, if necessary, by any special
26029 modification of the program
26030 that are necessary to make \MP\ work at a particular installation.
26031 It is usually best to design your change file so that all changes to
26032 previous sections preserve the section numbering; then everybody's version
26033 will be consistent with the published program. More extensive changes,
26034 which introduce new sections, can be inserted here; then only the index
26035 itself will get a new section number.
26036 @^system dependencies@>
26037
26038 @* \[49] Index.
26039 Here is where you can find all uses of each identifier in the program,
26040 with underlined entries pointing to where the identifier was defined.
26041 If the identifier is only one letter long, however, you get to see only
26042 the underlined entries. {\sl All references are to section numbers instead of
26043 page numbers.}
26044
26045 This index also lists error messages and other aspects of the program
26046 that you might want to look up some day. For example, the entry
26047 for ``system dependencies'' lists all sections that should receive
26048 special attention from people who are installing \MP\ in a new
26049 operating environment. A list of various things that can't happen appears
26050 under ``this can't happen''.
26051 Approximately 25 sections are listed under ``inner loop''; these account
26052 for more than 60\pct! of \MP's running time, exclusive of input and output.