some progress on graphic object access
[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 *f, size_t *size) {
647   int c;
648   size_t len = 0, lim = 128;
649   char *s = NULL;
650   *size = 0;
651 #if NOTTESTING
652   c = fgetc(f);
653   if (c==EOF)
654     return NULL;
655   s = malloc(lim); 
656   if (s==NULL) return NULL;
657   while (c!=EOF && c!='\n' && c!='\r') { 
658     if (len==lim) {
659       s =realloc(s, (lim+(lim>>2)));
660       if (s==NULL) return NULL;
661       lim+=(lim>>2);
662     }
663         s[len++] = c;
664     c =fgetc(f);
665   }
666   if (c=='\r') {
667     c = fgetc(f);
668     if (c!=EOF && c!='\n')
669        ungetc(c,f);
670   }
671   s[len] = 0;
672   *size = len;
673 #endif
674   return s;
675 }
676
677 @ @c
678 void mp_write_ascii_file (void *f, char *s) {
679 #if NOTTESTING
680   if (f!=NULL) {
681     fputs(s,f);
682   }
683 #endif
684 }
685
686 @ @c
687 void mp_read_binary_file (void *f, void **data, size_t *size) {
688   size_t len = 0;
689 #if NOTTESTING
690   len = fread(*data,1,*size,f);
691 #endif
692   *size = len;
693 }
694
695 @ @c
696 void mp_write_binary_file (void *f, void *s, size_t size) {
697 #if NOTTESTING
698   if (f!=NULL)
699     fwrite(s,size,1,f);
700 #endif
701 }
702
703
704 @ @c
705 void mp_close_file (void *f) {
706 #if NOTTESTING
707   fclose(f);
708 #endif
709 }
710
711 @ @c
712 int mp_eof_file (void *f) {
713 #if NOTTESTING
714   return feof(f);
715 #else
716   return 0;
717 #endif
718 }
719
720 @ @c
721 void mp_flush_file (void *f) {
722 #if NOTTESTING
723   fflush(f);
724 #endif
725 }
726
727 @ Input from text files is read one line at a time, using a routine called
728 |input_ln|. This function is defined in terms of global variables called
729 |buffer|, |first|, and |last| that will be described in detail later; for
730 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
731 values, and that |first| and |last| are indices into this array
732 representing the beginning and ending of a line of text.
733
734 @<Glob...@>=
735 size_t buf_size; /* maximum number of characters simultaneously present in
736                     current lines of open files */
737 ASCII_code *buffer; /* lines of characters being read */
738 size_t first; /* the first unused position in |buffer| */
739 size_t last; /* end of the line just input to |buffer| */
740 size_t max_buf_stack; /* largest index used in |buffer| */
741
742 @ @<Allocate or initialize ...@>=
743 mp->buf_size = 200;
744 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
745
746 @ @<Dealloc variables@>=
747 xfree(mp->buffer);
748
749 @ @c
750 void mp_reallocate_buffer(MP mp, size_t l) {
751   ASCII_code *buffer;
752   if (l>max_halfword) {
753     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
754   }
755   buffer = xmalloc((l+1),sizeof(ASCII_code));
756   memcpy(buffer,mp->buffer,(mp->buf_size+1));
757   xfree(mp->buffer);
758   mp->buffer = buffer ;
759   mp->buf_size = l;
760 }
761
762 @ The |input_ln| function brings the next line of input from the specified
763 field into available positions of the buffer array and returns the value
764 |true|, unless the file has already been entirely read, in which case it
765 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
766 numbers that represent the next line of the file are input into
767 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
768 global variable |last| is set equal to |first| plus the length of the
769 line. Trailing blanks are removed from the line; thus, either |last=first|
770 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
771 @^inner loop@>
772
773 The variable |max_buf_stack|, which is used to keep track of how large
774 the |buf_size| parameter must be to accommodate the present job, is
775 also kept up to date by |input_ln|.
776
777 @c 
778 boolean mp_input_ln (MP mp, void *f ) {
779   /* inputs the next line or returns |false| */
780   char *s;
781   size_t size = 0; 
782   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
783   s = (mp->read_ascii_file)(f, &size);
784   if (s==NULL)
785         return false;
786   if (size>0) {
787     mp->last = mp->first+size;
788     if ( mp->last>=mp->max_buf_stack ) { 
789       mp->max_buf_stack=mp->last+1;
790       while ( mp->max_buf_stack>=mp->buf_size ) {
791         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
792       }
793     }
794     memcpy((mp->buffer+mp->first),s,size);
795     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
796   } 
797   free(s);
798   return true;
799 }
800
801 @ The user's terminal acts essentially like other files of text, except
802 that it is used both for input and for output. When the terminal is
803 considered an input file, the file variable is called |term_in|, and when it
804 is considered an output file the file variable is |term_out|.
805 @^system dependencies@>
806
807 @<Glob...@>=
808 void * term_in; /* the terminal as an input file */
809 void * term_out; /* the terminal as an output file */
810 void * err_out; /* the terminal as an output file */
811
812 @ Here is how to open the terminal files. In the default configuration,
813 nothing happens except that the command line (if there is one) is copied
814 to the input buffer.  The variable |command_line| will be filled by the 
815 |main| procedure. The copying can not be done earlier in the program 
816 logic because in the |INI| version, the |buffer| is also used for primitive 
817 initialization.
818
819 @^system dependencies@>
820
821 @d t_open_out  do {/* open the terminal for text output */
822     mp->term_out = (mp->open_file)("terminal", "w", mp_filetype_terminal);
823     mp->err_out = (mp->open_file)("error", "w", mp_filetype_error);
824 } while (0)
825 @d t_open_in  do { /* open the terminal for text input */
826     mp->term_in = (mp->open_file)("terminal", "r", mp_filetype_terminal);
827     if (mp->command_line!=NULL) {
828       mp->last = strlen(mp->command_line);
829       strncpy((char *)mp->buffer,mp->command_line,mp->last);
830       xfree(mp->command_line);
831     }
832 } while (0)
833
834 @d t_close_out do { /* close the terminal */
835   (mp->close_file)(mp->term_out);
836   (mp->close_file)(mp->err_out);
837 } while (0)
838
839 @d t_close_in do { /* close the terminal */
840   (mp->close_file)(mp->term_in);
841 } while (0)
842
843 @<Option variables@>=
844 char *command_line;
845
846 @ @<Allocate or initialize ...@>=
847 mp->command_line = xstrdup(opt->command_line);
848
849 @ Sometimes it is necessary to synchronize the input/output mixture that
850 happens on the user's terminal, and three system-dependent
851 procedures are used for this
852 purpose. The first of these, |update_terminal|, is called when we want
853 to make sure that everything we have output to the terminal so far has
854 actually left the computer's internal buffers and been sent.
855 The second, |clear_terminal|, is called when we wish to cancel any
856 input that the user may have typed ahead (since we are about to
857 issue an unexpected error message). The third, |wake_up_terminal|,
858 is supposed to revive the terminal if the user has disabled it by
859 some instruction to the operating system.  The following macros show how
860 these operations can be specified:
861 @^system dependencies@>
862
863 @d update_terminal   (mp->flush_file)(mp->term_out) /* empty the terminal output buffer */
864 @d clear_terminal   do_nothing /* clear the terminal input buffer */
865 @d wake_up_terminal  (mp->flush_file)(mp->term_out) /* cancel the user's cancellation of output */
866
867 @ We need a special routine to read the first line of \MP\ input from
868 the user's terminal. This line is different because it is read before we
869 have opened the transcript file; there is sort of a ``chicken and
870 egg'' problem here. If the user types `\.{input cmr10}' on the first
871 line, or if some macro invoked by that line does such an \.{input},
872 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
873 commands are performed during the first line of terminal input, the transcript
874 file will acquire its default name `\.{mpout.log}'. (The transcript file
875 will not contain error messages generated by the first line before the
876 first \.{input} command.)
877
878 The first line is even more special. It's nice to let the user start
879 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
880 such a case, \MP\ will operate as if the first line of input were
881 `\.{cmr10}', i.e., the first line will consist of the remainder of the
882 command line, after the part that invoked \MP.
883
884 @ Different systems have different ways to get started. But regardless of
885 what conventions are adopted, the routine that initializes the terminal
886 should satisfy the following specifications:
887
888 \yskip\textindent{1)}It should open file |term_in| for input from the
889   terminal. (The file |term_out| will already be open for output to the
890   terminal.)
891
892 \textindent{2)}If the user has given a command line, this line should be
893   considered the first line of terminal input. Otherwise the
894   user should be prompted with `\.{**}', and the first line of input
895   should be whatever is typed in response.
896
897 \textindent{3)}The first line of input, which might or might not be a
898   command line, should appear in locations |first| to |last-1| of the
899   |buffer| array.
900
901 \textindent{4)}The global variable |loc| should be set so that the
902   character to be read next by \MP\ is in |buffer[loc]|. This
903   character should not be blank, and we should have |loc<last|.
904
905 \yskip\noindent(It may be necessary to prompt the user several times
906 before a non-blank line comes in. The prompt is `\.{**}' instead of the
907 later `\.*' because the meaning is slightly different: `\.{input}' need
908 not be typed immediately after~`\.{**}'.)
909
910 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
911
912 @ The following program does the required initialization
913 without retrieving a possible command line.
914 It should be clear how to modify this routine to deal with command lines,
915 if the system permits them.
916 @^system dependencies@>
917
918 @c 
919 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
920   t_open_in; 
921   if (mp->last!=0) {
922     loc = mp->first = 0;
923         return true;
924   }
925   while (1) { 
926     wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
927 @.**@>
928     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
929       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
930 @.End of file on the terminal@>
931       return false;
932     }
933     loc=mp->first;
934     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
935       incr(loc);
936     if ( loc<(int)mp->last ) { 
937       return true; /* return unless the line was all blank */
938     };
939     do_fprintf(mp->term_out,"Please type the name of your input file.\n");
940   }
941 }
942
943 @ @<Declarations@>=
944 boolean mp_init_terminal (MP mp) ;
945
946
947 @* \[4] String handling.
948 Symbolic token names and diagnostic messages are variable-length strings
949 of eight-bit characters. Many strings \MP\ uses are simply literals
950 in the compiled source, like the error messages and the names of the
951 internal parameters. Other strings are used or defined from the \MP\ input 
952 language, and these have to be interned.
953
954 \MP\ uses strings more extensively than \MF\ does, but the necessary
955 operations can still be handled with a fairly simple data structure.
956 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
957 of the strings, and the array |str_start| contains indices of the starting
958 points of each string. Strings are referred to by integer numbers, so that
959 string number |s| comprises the characters |str_pool[j]| for
960 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
961 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
962 location.  The first string number not currently in use is |str_ptr|
963 and |next_str[str_ptr]| begins a list of free string numbers.  String
964 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
965 string currently being constructed.
966
967 String numbers 0 to 255 are reserved for strings that correspond to single
968 ASCII characters. This is in accordance with the conventions of \.{WEB},
969 @.WEB@>
970 which converts single-character strings into the ASCII code number of the
971 single character involved, while it converts other strings into integers
972 and builds a string pool file. Thus, when the string constant \.{"."} appears
973 in the program below, \.{WEB} converts it into the integer 46, which is the
974 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
975 into some integer greater than~255. String number 46 will presumably be the
976 single character `\..'\thinspace; but some ASCII codes have no standard visible
977 representation, and \MP\ may need to be able to print an arbitrary
978 ASCII character, so the first 256 strings are used to specify exactly what
979 should be printed for each of the 256 possibilities.
980
981 @<Types...@>=
982 typedef int pool_pointer; /* for variables that point into |str_pool| */
983 typedef int str_number; /* for variables that point into |str_start| */
984
985 @ @<Glob...@>=
986 ASCII_code *str_pool; /* the characters */
987 pool_pointer *str_start; /* the starting pointers */
988 str_number *next_str; /* for linking strings in order */
989 pool_pointer pool_ptr; /* first unused position in |str_pool| */
990 str_number str_ptr; /* number of the current string being created */
991 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
992 str_number init_str_use; /* the initial number of strings in use */
993 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
994 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
995
996 @ @<Allocate or initialize ...@>=
997 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
998 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
999 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1000
1001 @ @<Dealloc variables@>=
1002 xfree(mp->str_pool);
1003 xfree(mp->str_start);
1004 xfree(mp->next_str);
1005
1006 @ Most printing is done from |char *|s, but sometimes not. Here are
1007 functions that convert an internal string into a |char *| for use
1008 by the printing routines, and vice versa.
1009
1010 @d str(A) mp_str(mp,A)
1011 @d rts(A) mp_rts(mp,A)
1012
1013 @<Internal ...@>=
1014 int mp_xstrcmp (const char *a, const char *b);
1015 char * mp_str (MP mp, str_number s);
1016
1017 @ @<Declarations@>=
1018 str_number mp_rts (MP mp, char *s);
1019 str_number mp_make_string (MP mp);
1020
1021 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1022 very good: it does not handle nesting over more than one level.
1023
1024 @c 
1025 int mp_xstrcmp (const char *a, const char *b) {
1026         if (a==NULL && b==NULL) 
1027           return 0;
1028     if (a==NULL)
1029       return -1;
1030     if (b==NULL)
1031       return 1;
1032     return strcmp(a,b);
1033 }
1034
1035 @ @c
1036 char * mp_str (MP mp, str_number ss) {
1037   char *s;
1038   int len;
1039   if (ss==mp->str_ptr) {
1040     return NULL;
1041   } else {
1042     len = length(ss);
1043     s = xmalloc(len+1,sizeof(char));
1044     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1045     s[len] = 0;
1046     return (char *)s;
1047   }
1048 }
1049 str_number mp_rts (MP mp, char *s) {
1050   int r; /* the new string */ 
1051   int old; /* a possible string in progress */
1052   int i=0;
1053   if (strlen(s)==0) {
1054     return 256;
1055   } else if (strlen(s)==1) {
1056     return s[0];
1057   } else {
1058    old=0;
1059    str_room((integer)strlen(s));
1060    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1061      old = mp_make_string(mp);
1062    while (*s) {
1063      append_char(*s);
1064      s++;
1065    }
1066    r = mp_make_string(mp);
1067    if (old!=0) {
1068       str_room(length(old));
1069       while (i<length(old)) {
1070         append_char((mp->str_start[old]+i));
1071       } 
1072       mp_flush_string(mp,old);
1073     }
1074     return r;
1075   }
1076 }
1077
1078 @ Except for |strs_used_up|, the following string statistics are only
1079 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1080 commented out:
1081
1082 @<Glob...@>=
1083 integer strs_used_up; /* strings in use or unused but not reclaimed */
1084 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1085 integer strs_in_use; /* total number of strings actually in use */
1086 integer max_pl_used; /* maximum |pool_in_use| so far */
1087 integer max_strs_used; /* maximum |strs_in_use| so far */
1088
1089 @ Several of the elementary string operations are performed using \.{WEB}
1090 macros instead of functions, because many of the
1091 operations are done quite frequently and we want to avoid the
1092 overhead of procedure calls. For example, here is
1093 a simple macro that computes the length of a string.
1094 @.WEB@>
1095
1096 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1097   number \# */
1098 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1099
1100 @ The length of the current string is called |cur_length|.  If we decide that
1101 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1102 |cur_length| becomes zero.
1103
1104 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1105 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1106
1107 @ Strings are created by appending character codes to |str_pool|.
1108 The |append_char| macro, defined here, does not check to see if the
1109 value of |pool_ptr| has gotten too high; this test is supposed to be
1110 made before |append_char| is used.
1111
1112 To test if there is room to append |l| more characters to |str_pool|,
1113 we shall write |str_room(l)|, which tries to make sure there is enough room
1114 by compacting the string pool if necessary.  If this does not work,
1115 |do_compaction| aborts \MP\ and gives an apologetic error message.
1116
1117 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1118 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1119 }
1120 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1121   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1122     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1123     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1124   }
1125
1126 @ The following routine is similar to |str_room(1)| but it uses the
1127 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1128 string space is exhausted.
1129
1130 @<Declare the procedure called |unit_str_room|@>=
1131 void mp_unit_str_room (MP mp);
1132
1133 @ @c
1134 void mp_unit_str_room (MP mp) { 
1135   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1136   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1137 }
1138
1139 @ \MP's string expressions are implemented in a brute-force way: Every
1140 new string or substring that is needed is simply copied into the string pool.
1141 Space is eventually reclaimed by a procedure called |do_compaction| with
1142 the aid of a simple system system of reference counts.
1143 @^reference counts@>
1144
1145 The number of references to string number |s| will be |str_ref[s]|. The
1146 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1147 positive number of references; such strings will never be recycled. If
1148 a string is ever referred to more than 126 times, simultaneously, we
1149 put it in this category. Hence a single byte suffices to store each |str_ref|.
1150
1151 @d max_str_ref 127 /* ``infinite'' number of references */
1152 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1153   }
1154
1155 @<Glob...@>=
1156 int *str_ref;
1157
1158 @ @<Allocate or initialize ...@>=
1159 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1160
1161 @ @<Dealloc variables@>=
1162 xfree(mp->str_ref);
1163
1164 @ Here's what we do when a string reference disappears:
1165
1166 @d delete_str_ref(A)  { 
1167     if ( mp->str_ref[(A)]<max_str_ref ) {
1168        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1169        else mp_flush_string(mp, (A));
1170     }
1171   }
1172
1173 @<Declare the procedure called |flush_string|@>=
1174 void mp_flush_string (MP mp,str_number s) ;
1175
1176
1177 @ We can't flush the first set of static strings at all, so there 
1178 is no point in trying
1179
1180 @c
1181 void mp_flush_string (MP mp,str_number s) { 
1182   if (length(s)>1) {
1183     mp->pool_in_use=mp->pool_in_use-length(s);
1184     decr(mp->strs_in_use);
1185     if ( mp->next_str[s]!=mp->str_ptr ) {
1186       mp->str_ref[s]=0;
1187     } else { 
1188       mp->str_ptr=s;
1189       decr(mp->strs_used_up);
1190     }
1191     mp->pool_ptr=mp->str_start[mp->str_ptr];
1192   }
1193 }
1194
1195 @ C literals cannot be simply added, they need to be set so they can't
1196 be flushed.
1197
1198 @d intern(A) mp_intern(mp,(A))
1199
1200 @c
1201 str_number mp_intern (MP mp, char *s) {
1202   str_number r ;
1203   r = rts(s);
1204   mp->str_ref[r] = max_str_ref;
1205   return r;
1206 }
1207
1208 @ @<Declarations@>=
1209 str_number mp_intern (MP mp, char *s);
1210
1211
1212 @ Once a sequence of characters has been appended to |str_pool|, it
1213 officially becomes a string when the function |make_string| is called.
1214 This function returns the identification number of the new string as its
1215 value.
1216
1217 When getting the next unused string number from the linked list, we pretend
1218 that
1219 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1220 are linked sequentially even though the |next_str| entries have not been
1221 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1222 |do_compaction| is responsible for making sure of this.
1223
1224 @<Declarations@>=
1225 @<Declare the procedure called |do_compaction|@>;
1226 @<Declare the procedure called |unit_str_room|@>;
1227 str_number mp_make_string (MP mp);
1228
1229 @ @c 
1230 str_number mp_make_string (MP mp) { /* current string enters the pool */
1231   str_number s; /* the new string */
1232 RESTART: 
1233   s=mp->str_ptr;
1234   mp->str_ptr=mp->next_str[s];
1235   if ( mp->str_ptr>mp->max_str_ptr ) {
1236     if ( mp->str_ptr==mp->max_strings ) { 
1237       mp->str_ptr=s;
1238       mp_do_compaction(mp, 0);
1239       goto RESTART;
1240     } else {
1241 #ifdef DEBUG 
1242       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1243 @:this can't happen s}{\quad \.s@>
1244 #endif
1245       mp->max_str_ptr=mp->str_ptr;
1246       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1247     }
1248   }
1249   mp->str_ref[s]=1;
1250   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1251   incr(mp->strs_used_up);
1252   incr(mp->strs_in_use);
1253   mp->pool_in_use=mp->pool_in_use+length(s);
1254   if ( mp->pool_in_use>mp->max_pl_used ) 
1255     mp->max_pl_used=mp->pool_in_use;
1256   if ( mp->strs_in_use>mp->max_strs_used ) 
1257     mp->max_strs_used=mp->strs_in_use;
1258   return s;
1259 }
1260
1261 @ The most interesting string operation is string pool compaction.  The idea
1262 is to recover unused space in the |str_pool| array by recopying the strings
1263 to close the gaps created when some strings become unused.  All string
1264 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1265 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1266 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1267 with |needed=mp->pool_size| supresses all overflow tests.
1268
1269 The compaction process starts with |last_fixed_str| because all lower numbered
1270 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1271
1272 @<Glob...@>=
1273 str_number last_fixed_str; /* last permanently allocated string */
1274 str_number fixed_str_use; /* number of permanently allocated strings */
1275
1276 @ @<Declare the procedure called |do_compaction|@>=
1277 void mp_do_compaction (MP mp, pool_pointer needed) ;
1278
1279 @ @c
1280 void mp_do_compaction (MP mp, pool_pointer needed) {
1281   str_number str_use; /* a count of strings in use */
1282   str_number r,s,t; /* strings being manipulated */
1283   pool_pointer p,q; /* destination and source for copying string characters */
1284   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1285   r=mp->last_fixed_str;
1286   s=mp->next_str[r];
1287   p=mp->str_start[s];
1288   while ( s!=mp->str_ptr ) { 
1289     while ( mp->str_ref[s]==0 ) {
1290       @<Advance |s| and add the old |s| to the list of free string numbers;
1291         then |break| if |s=str_ptr|@>;
1292     }
1293     r=s; s=mp->next_str[s];
1294     incr(str_use);
1295     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1296      after the end of the string@>;
1297   }
1298   @<Move the current string back so that it starts at |p|@>;
1299   if ( needed<mp->pool_size ) {
1300     @<Make sure that there is room for another string with |needed| characters@>;
1301   }
1302   @<Account for the compaction and make sure the statistics agree with the
1303      global versions@>;
1304   mp->strs_used_up=str_use;
1305 }
1306
1307 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1308 t=mp->next_str[mp->last_fixed_str];
1309 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1310   incr(mp->fixed_str_use);
1311   mp->last_fixed_str=t;
1312   t=mp->next_str[t];
1313 }
1314 str_use=mp->fixed_str_use
1315
1316 @ Because of the way |flush_string| has been written, it should never be
1317 necessary to |break| here.  The extra line of code seems worthwhile to
1318 preserve the generality of |do_compaction|.
1319
1320 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1321 {
1322 t=s;
1323 s=mp->next_str[s];
1324 mp->next_str[r]=s;
1325 mp->next_str[t]=mp->next_str[mp->str_ptr];
1326 mp->next_str[mp->str_ptr]=t;
1327 if ( s==mp->str_ptr ) break;
1328 }
1329
1330 @ The string currently starts at |str_start[r]| and ends just before
1331 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1332 to locate the next string.
1333
1334 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1335 q=mp->str_start[r];
1336 mp->str_start[r]=p;
1337 while ( q<mp->str_start[s] ) { 
1338   mp->str_pool[p]=mp->str_pool[q];
1339   incr(p); incr(q);
1340 }
1341
1342 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1343 we do this, anything between them should be moved.
1344
1345 @ @<Move the current string back so that it starts at |p|@>=
1346 q=mp->str_start[mp->str_ptr];
1347 mp->str_start[mp->str_ptr]=p;
1348 while ( q<mp->pool_ptr ) { 
1349   mp->str_pool[p]=mp->str_pool[q];
1350   incr(p); incr(q);
1351 }
1352 mp->pool_ptr=p
1353
1354 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1355
1356 @<Make sure that there is room for another string with |needed| char...@>=
1357 if ( str_use>=mp->max_strings-1 )
1358   mp_reallocate_strings (mp,str_use);
1359 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1360   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1361   mp->max_pool_ptr=mp->pool_ptr+needed;
1362 }
1363
1364 @ @<Declarations@>=
1365 void mp_reallocate_strings (MP mp, str_number str_use) ;
1366 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1367
1368 @ @c 
1369 void mp_reallocate_strings (MP mp, str_number str_use) { 
1370   while ( str_use>=mp->max_strings-1 ) {
1371     int l = mp->max_strings + (mp->max_strings>>2);
1372     XREALLOC (mp->str_ref,   l, int);
1373     XREALLOC (mp->str_start, l, pool_pointer);
1374     XREALLOC (mp->next_str,  l, str_number);
1375     mp->max_strings = l;
1376   }
1377 }
1378 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1379   while ( needed>mp->pool_size ) {
1380     int l = mp->pool_size + (mp->pool_size>>2);
1381         XREALLOC (mp->str_pool, l, ASCII_code);
1382     mp->pool_size = l;
1383   }
1384 }
1385
1386 @ @<Account for the compaction and make sure the statistics agree with...@>=
1387 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1388   mp_confusion(mp, "string");
1389 @:this can't happen string}{\quad string@>
1390 incr(mp->pact_count);
1391 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1392 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1393 #ifdef DEBUG
1394 s=mp->str_ptr; t=str_use;
1395 while ( s<=mp->max_str_ptr ){
1396   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1397   incr(t); s=mp->next_str[s];
1398 };
1399 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1400 #endif
1401
1402 @ A few more global variables are needed to keep track of statistics when
1403 |stat| $\ldots$ |tats| blocks are not commented out.
1404
1405 @<Glob...@>=
1406 integer pact_count; /* number of string pool compactions so far */
1407 integer pact_chars; /* total number of characters moved during compactions */
1408 integer pact_strs; /* total number of strings moved during compactions */
1409
1410 @ @<Initialize compaction statistics@>=
1411 mp->pact_count=0;
1412 mp->pact_chars=0;
1413 mp->pact_strs=0;
1414
1415 @ The following subroutine compares string |s| with another string of the
1416 same length that appears in |buffer| starting at position |k|;
1417 the result is |true| if and only if the strings are equal.
1418
1419 @c 
1420 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1421   /* test equality of strings */
1422   pool_pointer j; /* running index */
1423   j=mp->str_start[s];
1424   while ( j<str_stop(s) ) { 
1425     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1426       return false;
1427   }
1428   return true;
1429 }
1430
1431 @ Here is a similar routine, but it compares two strings in the string pool,
1432 and it does not assume that they have the same length. If the first string
1433 is lexicographically greater than, less than, or equal to the second,
1434 the result is respectively positive, negative, or zero.
1435
1436 @c 
1437 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1438   /* test equality of strings */
1439   pool_pointer j,k; /* running indices */
1440   integer ls,lt; /* lengths */
1441   integer l; /* length remaining to test */
1442   ls=length(s); lt=length(t);
1443   if ( ls<=lt ) l=ls; else l=lt;
1444   j=mp->str_start[s]; k=mp->str_start[t];
1445   while ( l-->0 ) { 
1446     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1447        return (mp->str_pool[j]-mp->str_pool[k]); 
1448     }
1449     incr(j); incr(k);
1450   }
1451   return (ls-lt);
1452 }
1453
1454 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1455 and |str_ptr| are computed by the \.{INIMP} program, based in part
1456 on the information that \.{WEB} has output while processing \MP.
1457 @.INIMP@>
1458 @^string pool@>
1459
1460 @c 
1461 void mp_get_strings_started (MP mp) { 
1462   /* initializes the string pool,
1463     but returns |false| if something goes wrong */
1464   int k; /* small indices or counters */
1465   str_number g; /* a new string */
1466   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1467   mp->str_start[0]=0;
1468   mp->next_str[0]=1;
1469   mp->pool_in_use=0; mp->strs_in_use=0;
1470   mp->max_pl_used=0; mp->max_strs_used=0;
1471   @<Initialize compaction statistics@>;
1472   mp->strs_used_up=0;
1473   @<Make the first 256 strings@>;
1474   g=mp_make_string(mp); /* string 256 == "" */
1475   mp->str_ref[g]=max_str_ref;
1476   mp->last_fixed_str=mp->str_ptr-1;
1477   mp->fixed_str_use=mp->str_ptr;
1478   return;
1479 }
1480
1481 @ @<Declarations@>=
1482 void mp_get_strings_started (MP mp);
1483
1484 @ The first 256 strings will consist of a single character only.
1485
1486 @<Make the first 256...@>=
1487 for (k=0;k<=255;k++) { 
1488   append_char(k);
1489   g=mp_make_string(mp); 
1490   mp->str_ref[g]=max_str_ref;
1491 }
1492
1493 @ The first 128 strings will contain 95 standard ASCII characters, and the
1494 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1495 unless a system-dependent change is made here. Installations that have
1496 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1497 would like string 032 to be printed as the single character 032 instead
1498 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1499 even people with an extended character set will want to represent string
1500 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1501 to produce visible strings instead of tabs or line-feeds or carriage-returns
1502 or bell-rings or characters that are treated anomalously in text files.
1503
1504 Unprintable characters of codes 128--255 are, similarly, rendered
1505 \.{\^\^80}--\.{\^\^ff}.
1506
1507 The boolean expression defined here should be |true| unless \MP\ internal
1508 code number~|k| corresponds to a non-troublesome visible symbol in the
1509 local character set.
1510 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1511 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1512 must be printable.
1513 @^character set dependencies@>
1514 @^system dependencies@>
1515
1516 @<Character |k| cannot be printed@>=
1517   (k<' ')||(k>'~')
1518
1519 @* \[5] On-line and off-line printing.
1520 Messages that are sent to a user's terminal and to the transcript-log file
1521 are produced by several `|print|' procedures. These procedures will
1522 direct their output to a variety of places, based on the setting of
1523 the global variable |selector|, which has the following possible
1524 values:
1525
1526 \yskip
1527 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1528   transcript file.
1529
1530 \hang |log_only|, prints only on the transcript file.
1531
1532 \hang |term_only|, prints only on the terminal.
1533
1534 \hang |no_print|, doesn't print at all. This is used only in rare cases
1535   before the transcript file is open.
1536
1537 \hang |pseudo|, puts output into a cyclic buffer that is used
1538   by the |show_context| routine; when we get to that routine we shall discuss
1539   the reasoning behind this curious mode.
1540
1541 \hang |new_string|, appends the output to the current string in the
1542   string pool.
1543
1544 \hang |>=write_file| prints on one of the files used for the \&{write}
1545 @:write_}{\&{write} primitive@>
1546   command.
1547
1548 \yskip
1549 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1550 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1551 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1552 relations are not used when |selector| could be |pseudo|, or |new_string|.
1553 We need not check for unprintable characters when |selector<pseudo|.
1554
1555 Three additional global variables, |tally|, |term_offset| and |file_offset|
1556 record the number of characters that have been printed
1557 since they were most recently cleared to zero. We use |tally| to record
1558 the length of (possibly very long) stretches of printing; |term_offset|,
1559 and |file_offset|, on the other hand, keep track of how many
1560 characters have appeared so far on the current line that has been output
1561 to the terminal, the transcript file, or the \ps\ output file, respectively.
1562
1563 @d new_string 0 /* printing is deflected to the string pool */
1564 @d pseudo 2 /* special |selector| setting for |show_context| */
1565 @d no_print 3 /* |selector| setting that makes data disappear */
1566 @d term_only 4 /* printing is destined for the terminal only */
1567 @d log_only 5 /* printing is destined for the transcript file only */
1568 @d term_and_log 6 /* normal |selector| setting */
1569 @d write_file 7 /* first write file selector */
1570
1571 @<Glob...@>=
1572 void * log_file; /* transcript of \MP\ session */
1573 void * ps_file; /* the generic font output goes here */
1574 unsigned int selector; /* where to print a message */
1575 unsigned char dig[23]; /* digits in a number being output */
1576 integer tally; /* the number of characters recently printed */
1577 unsigned int term_offset;
1578   /* the number of characters on the current terminal line */
1579 unsigned int file_offset;
1580   /* the number of characters on the current file line */
1581 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1582 integer trick_count; /* threshold for pseudoprinting, explained later */
1583 integer first_count; /* another variable for pseudoprinting */
1584
1585 @ @<Allocate or initialize ...@>=
1586 memset(mp->dig,0,23);
1587 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1588
1589 @ @<Dealloc variables@>=
1590 xfree(mp->trick_buf);
1591
1592 @ @<Initialize the output routines@>=
1593 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1594
1595 @ Macro abbreviations for output to the terminal and to the log file are
1596 defined here for convenience. Some systems need special conventions
1597 for terminal output, and it is possible to adhere to those conventions
1598 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1599 @^system dependencies@>
1600
1601 @d do_fprintf(f,b) (mp->write_ascii_file)(f,b)
1602 @d wterm(A)     do_fprintf(mp->term_out,(A))
1603 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->term_out,(char *)ss); }
1604 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1605 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1606 @d wlog(A)      do_fprintf(mp->log_file,(A))
1607 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->log_file,(char *)ss); }
1608 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1609 @d wlog_ln(A)   {wlog_cr; do_fprintf(mp->log_file,(A)); }
1610
1611
1612 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1613 use an array |wr_file| that will be declared later.
1614
1615 @d mp_print_text(A) mp_print_str(mp,text((A)))
1616
1617 @<Internal ...@>=
1618 void mp_print_ln (MP mp);
1619 void mp_print_visible_char (MP mp, ASCII_code s); 
1620 void mp_print_char (MP mp, ASCII_code k);
1621 void mp_print (MP mp, char *s);
1622 void mp_print_str (MP mp, str_number s);
1623 void mp_print_nl (MP mp, char *s);
1624 void mp_print_two (MP mp,scaled x, scaled y) ;
1625 void mp_print_scaled (MP mp,scaled s);
1626
1627 @ @<Basic print...@>=
1628 void mp_print_ln (MP mp) { /* prints an end-of-line */
1629  switch (mp->selector) {
1630   case term_and_log: 
1631     wterm_cr; wlog_cr;
1632     mp->term_offset=0;  mp->file_offset=0;
1633     break;
1634   case log_only: 
1635     wlog_cr; mp->file_offset=0;
1636     break;
1637   case term_only: 
1638     wterm_cr; mp->term_offset=0;
1639     break;
1640   case no_print:
1641   case pseudo: 
1642   case new_string: 
1643     break;
1644   default: 
1645     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1646   }
1647 } /* note that |tally| is not affected */
1648
1649 @ The |print_visible_char| procedure sends one character to the desired
1650 destination, using the |xchr| array to map it into an external character
1651 compatible with |input_ln|.  (It assumes that it is always called with
1652 a visible ASCII character.)  All printing comes through |print_ln| or
1653 |print_char|, which ultimately calls |print_visible_char|, hence these
1654 routines are the ones that limit lines to at most |max_print_line| characters.
1655 But we must make an exception for the \ps\ output file since it is not safe
1656 to cut up lines arbitrarily in \ps.
1657
1658 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1659 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1660 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1661
1662 @<Basic printing...@>=
1663 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1664   switch (mp->selector) {
1665   case term_and_log: 
1666     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1667     incr(mp->term_offset); incr(mp->file_offset);
1668     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1669        wterm_cr; mp->term_offset=0;
1670     };
1671     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1672        wlog_cr; mp->file_offset=0;
1673     };
1674     break;
1675   case log_only: 
1676     wlog_chr(xchr(s)); incr(mp->file_offset);
1677     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1678     break;
1679   case term_only: 
1680     wterm_chr(xchr(s)); incr(mp->term_offset);
1681     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1682     break;
1683   case no_print: 
1684     break;
1685   case pseudo: 
1686     if ( mp->tally<mp->trick_count ) 
1687       mp->trick_buf[mp->tally % mp->error_line]=s;
1688     break;
1689   case new_string: 
1690     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1691       mp_unit_str_room(mp);
1692       if ( mp->pool_ptr>=mp->pool_size ) 
1693         goto DONE; /* drop characters if string space is full */
1694     };
1695     append_char(s);
1696     break;
1697   default:
1698     { char ss[2]; ss[0] = xchr(s); ss[1]=0;
1699       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1700     }
1701   }
1702 DONE:
1703   incr(mp->tally);
1704 }
1705
1706 @ The |print_char| procedure sends one character to the desired destination.
1707 File names and string expressions might contain |ASCII_code| values that
1708 can't be printed using |print_visible_char|.  These characters will be
1709 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1710 (This procedure assumes that it is safe to bypass all checks for unprintable
1711 characters when |selector| is in the range |0..max_write_files-1|.
1712 The user might want to write unprintable characters.
1713
1714 @d print_lc_hex(A) do { l=(A);
1715     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1716   } while (0)
1717
1718 @<Basic printing...@>=
1719 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1720   int l; /* small index or counter */
1721   if ( mp->selector<pseudo || mp->selector>=write_file) {
1722     mp_print_visible_char(mp, k);
1723   } else if ( @<Character |k| cannot be printed@> ) { 
1724     mp_print(mp, "^^"); 
1725     if ( k<0100 ) { 
1726       mp_print_visible_char(mp, k+0100); 
1727     } else if ( k<0200 ) { 
1728       mp_print_visible_char(mp, k-0100); 
1729     } else { 
1730       print_lc_hex(k / 16);  
1731       print_lc_hex(k % 16); 
1732     }
1733   } else {
1734     mp_print_visible_char(mp, k);
1735   }
1736 };
1737
1738 @ An entire string is output by calling |print|. Note that if we are outputting
1739 the single standard ASCII character \.c, we could call |print("c")|, since
1740 |"c"=99| is the number of a single-character string, as explained above. But
1741 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1742 routine when it knows that this is safe. (The present implementation
1743 assumes that it is always safe to print a visible ASCII character.)
1744 @^system dependencies@>
1745
1746 @<Basic print...@>=
1747 void mp_do_print (MP mp, char *ss, unsigned int len) { /* prints string |s| */
1748   unsigned int j = 0;
1749   while ( j<len ){ 
1750     mp_print_char(mp, ss[j]); incr(j);
1751   }
1752 }
1753
1754
1755 @<Basic print...@>=
1756 void mp_print (MP mp, char *ss) {
1757   mp_do_print(mp, ss, strlen(ss));
1758 }
1759 void mp_print_str (MP mp, str_number s) {
1760   pool_pointer j; /* current character code position */
1761   if ( (s<0)||(s>mp->max_str_ptr) ) {
1762      mp_do_print(mp,"???",3); /* this can't happen */
1763 @.???@>
1764   }
1765   j=mp->str_start[s];
1766   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1767 }
1768
1769
1770 @ Here is the very first thing that \MP\ prints: a headline that identifies
1771 the version number and base name. The |term_offset| variable is temporarily
1772 incorrect, but the discrepancy is not serious since we assume that the banner
1773 and mem identifier together will occupy at most |max_print_line|
1774 character positions.
1775
1776 @<Initialize the output...@>=
1777 wterm (banner);
1778 wterm (version_string);
1779 if (mp->mem_ident!=NULL) 
1780   mp_print(mp,mp->mem_ident); 
1781 mp_print_ln(mp);
1782 update_terminal;
1783
1784 @ The procedure |print_nl| is like |print|, but it makes sure that the
1785 string appears at the beginning of a new line.
1786
1787 @<Basic print...@>=
1788 void mp_print_nl (MP mp, char *s) { /* prints string |s| at beginning of line */
1789   switch(mp->selector) {
1790   case term_and_log: 
1791     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1792     break;
1793   case log_only: 
1794     if ( mp->file_offset>0 ) mp_print_ln(mp);
1795     break;
1796   case term_only: 
1797     if ( mp->term_offset>0 ) mp_print_ln(mp);
1798     break;
1799   case no_print:
1800   case pseudo:
1801   case new_string: 
1802         break;
1803   } /* there are no other cases */
1804   mp_print(mp, s);
1805 }
1806
1807 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1808
1809 @<Basic print...@>=
1810 void mp_print_the_digs (MP mp, eight_bits k) {
1811   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1812   while ( k>0 ){ 
1813     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1814   }
1815 };
1816
1817 @ The following procedure, which prints out the decimal representation of a
1818 given integer |n|, has been written carefully so that it works properly
1819 if |n=0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1820 to negative arguments, since such operations are not implemented consistently
1821 on all platforms.
1822
1823 @<Basic print...@>=
1824 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1825   integer m; /* used to negate |n| in possibly dangerous cases */
1826   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1827   if ( n<0 ) { 
1828     mp_print_char(mp, '-');
1829     if ( n>-100000000 ) {
1830           negate(n);
1831     } else  { 
1832           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1833       if ( m<10 ) {
1834         mp->dig[0]=m;
1835       } else { 
1836         mp->dig[0]=0; incr(n);
1837       }
1838     }
1839   }
1840   do {  
1841     mp->dig[k]=n % 10; n=n / 10; incr(k);
1842   } while (n!=0);
1843   mp_print_the_digs(mp, k);
1844 };
1845
1846 @ @<Internal ...@>=
1847 void mp_print_int (MP mp,integer n);
1848
1849 @ \MP\ also makes use of a trivial procedure to print two digits. The
1850 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1851
1852 @c 
1853 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1854   n=abs(n) % 100; 
1855   mp_print_char(mp, '0'+(n / 10));
1856   mp_print_char(mp, '0'+(n % 10));
1857 }
1858
1859
1860 @ @<Internal ...@>=
1861 void mp_print_dd (MP mp,integer n);
1862
1863 @ Here is a procedure that asks the user to type a line of input,
1864 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1865 The input is placed into locations |first| through |last-1| of the
1866 |buffer| array, and echoed on the transcript file if appropriate.
1867
1868 This procedure is never called when |interaction<mp_scroll_mode|.
1869
1870 @d prompt_input(A) do { 
1871     if (!mp->noninteractive) {
1872       wake_up_terminal; mp_print(mp, (A)); 
1873     }
1874     mp_term_input(mp);
1875   } while (0) /* prints a string and gets a line of input */
1876
1877 @c 
1878 void mp_term_input (MP mp) { /* gets a line from the terminal */
1879   size_t k; /* index into |buffer| */
1880   update_terminal; /* Now the user sees the prompt for sure */
1881   if (!mp_input_ln(mp, mp->term_in )) {
1882     if (!mp->noninteractive) {
1883           mp_fatal_error(mp, "End of file on the terminal!");
1884 @.End of file on the terminal@>
1885     } else { /* we are done with this input chunk */
1886           longjmp(mp->jump_buf,1);      
1887     }
1888   }
1889   if (!mp->noninteractive) {
1890     mp->term_offset=0; /* the user's line ended with \<\rm return> */
1891     decr(mp->selector); /* prepare to echo the input */
1892     if ( mp->last!=mp->first ) {
1893       for (k=mp->first;k<=mp->last-1;k++) {
1894         mp_print_char(mp, mp->buffer[k]);
1895       }
1896     }
1897     mp_print_ln(mp); 
1898     mp->buffer[mp->last]='%'; 
1899     incr(mp->selector); /* restore previous status */
1900   }
1901 }
1902
1903 @* \[6] Reporting errors.
1904 When something anomalous is detected, \MP\ typically does something like this:
1905 $$\vbox{\halign{#\hfil\cr
1906 |print_err("Something anomalous has been detected");|\cr
1907 |help3("This is the first line of my offer to help.")|\cr
1908 |("This is the second line. I'm trying to")|\cr
1909 |("explain the best way for you to proceed.");|\cr
1910 |error;|\cr}}$$
1911 A two-line help message would be given using |help2|, etc.; these informal
1912 helps should use simple vocabulary that complements the words used in the
1913 official error message that was printed. (Outside the U.S.A., the help
1914 messages should preferably be translated into the local vernacular. Each
1915 line of help is at most 60 characters long, in the present implementation,
1916 so that |max_print_line| will not be exceeded.)
1917
1918 The |print_err| procedure supplies a `\.!' before the official message,
1919 and makes sure that the terminal is awake if a stop is going to occur.
1920 The |error| procedure supplies a `\..' after the official message, then it
1921 shows the location of the error; and if |interaction=error_stop_mode|,
1922 it also enters into a dialog with the user, during which time the help
1923 message may be printed.
1924 @^system dependencies@>
1925
1926 @ The global variable |interaction| has four settings, representing increasing
1927 amounts of user interaction:
1928
1929 @<Exported types@>=
1930 enum mp_interaction_mode { 
1931  mp_unspecified_mode=0, /* extra value for command-line switch */
1932  mp_batch_mode, /* omits all stops and omits terminal output */
1933  mp_nonstop_mode, /* omits all stops */
1934  mp_scroll_mode, /* omits error stops */
1935  mp_error_stop_mode, /* stops at every opportunity to interact */
1936 };
1937
1938 @ @<Option variables@>=
1939 int interaction; /* current level of interaction */
1940 int noninteractive; /* do we have a terminal? */
1941
1942 @ Set it here so it can be overwritten by the commandline
1943
1944 @<Allocate or initialize ...@>=
1945 mp->interaction=opt->interaction;
1946 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1947   mp->interaction=mp_error_stop_mode;
1948 if (mp->interaction<mp_unspecified_mode) 
1949   mp->interaction=mp_batch_mode;
1950 mp->noninteractive=opt->noninteractive;
1951
1952
1953
1954 @d print_err(A) mp_print_err(mp,(A))
1955
1956 @<Internal ...@>=
1957 void mp_print_err(MP mp, char * A);
1958
1959 @ @c
1960 void mp_print_err(MP mp, char * A) { 
1961   if ( mp->interaction==mp_error_stop_mode ) 
1962     wake_up_terminal;
1963   mp_print_nl(mp, "! "); 
1964   mp_print(mp, A);
1965 @.!\relax@>
1966 }
1967
1968
1969 @ \MP\ is careful not to call |error| when the print |selector| setting
1970 might be unusual. The only possible values of |selector| at the time of
1971 error messages are
1972
1973 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1974   and |log_file| not yet open);
1975
1976 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1977
1978 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1979
1980 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1981
1982 @<Initialize the print |selector| based on |interaction|@>=
1983 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1984
1985 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1986 routine is active when |error| is called; this ensures that |get_next|
1987 will never be called recursively.
1988 @^recursion@>
1989
1990 The global variable |history| records the worst level of error that
1991 has been detected. It has four possible values: |spotless|, |warning_issued|,
1992 |error_message_issued|, and |fatal_error_stop|.
1993
1994 Another global variable, |error_count|, is increased by one when an
1995 |error| occurs without an interactive dialog, and it is reset to zero at
1996 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1997 that there is no point in continuing further.
1998
1999 @<Types...@>=
2000 enum mp_history_states {
2001   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2002   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2003   mp_error_message_issued, /* |history| value when |error| has been called */
2004   mp_fatal_error_stop, /* |history| value when termination was premature */
2005 };
2006
2007 @ @<Glob...@>=
2008 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2009 int history; /* has the source input been clean so far? */
2010 int error_count; /* the number of scrolled errors since the last statement ended */
2011
2012 @ The value of |history| is initially |fatal_error_stop|, but it will
2013 be changed to |spotless| if \MP\ survives the initialization process.
2014
2015 @<Allocate or ...@>=
2016 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2017
2018 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2019 error procedures near the beginning of the program. But the error procedures
2020 in turn use some other procedures, which need to be declared |forward|
2021 before we get to |error| itself.
2022
2023 It is possible for |error| to be called recursively if some error arises
2024 when |get_next| is being used to delete a token, and/or if some fatal error
2025 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2026 @^recursion@>
2027 is never more than two levels deep.
2028
2029 @<Declarations@>=
2030 void mp_get_next (MP mp);
2031 void mp_term_input (MP mp);
2032 void mp_show_context (MP mp);
2033 void mp_begin_file_reading (MP mp);
2034 void mp_open_log_file (MP mp);
2035 void mp_clear_for_error_prompt (MP mp);
2036 void mp_debug_help (MP mp);
2037 @<Declare the procedure called |flush_string|@>
2038
2039 @ @<Internal ...@>=
2040 void mp_normalize_selector (MP mp);
2041
2042 @ Individual lines of help are recorded in the array |help_line|, which
2043 contains entries in positions |0..(help_ptr-1)|. They should be printed
2044 in reverse order, i.e., with |help_line[0]| appearing last.
2045
2046 @d hlp1(A) mp->help_line[0]=(A); }
2047 @d hlp2(A) mp->help_line[1]=(A); hlp1
2048 @d hlp3(A) mp->help_line[2]=(A); hlp2
2049 @d hlp4(A) mp->help_line[3]=(A); hlp3
2050 @d hlp5(A) mp->help_line[4]=(A); hlp4
2051 @d hlp6(A) mp->help_line[5]=(A); hlp5
2052 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2053 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2054 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2055 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2056 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2057 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2058 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2059
2060 @<Glob...@>=
2061 char * help_line[6]; /* helps for the next |error| */
2062 unsigned int help_ptr; /* the number of help lines present */
2063 boolean use_err_help; /* should the |err_help| string be shown? */
2064 str_number err_help; /* a string set up by \&{errhelp} */
2065 str_number filename_template; /* a string set up by \&{filenametemplate} */
2066
2067 @ @<Allocate or ...@>=
2068 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2069
2070 @ The |jump_out| procedure just cuts across all active procedure levels and
2071 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2072 whole program. It is used when there is no recovery from a particular error.
2073
2074 The program uses a |jump_buf| to handle this, this is initialized at three
2075 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2076 of |mp_run|. Those are the only library enty points.
2077
2078 @^system dependencies@>
2079
2080 @<Glob...@>=
2081 jmp_buf jump_buf;
2082
2083 @ @<Install and test the non-local jump buffer@>=
2084 if (setjmp(mp->jump_buf) != 0) { return mp->history; }
2085
2086
2087 @ @<Setup the non-local jump buffer in |mp_new|@>=
2088 if (setjmp(mp->jump_buf) != 0) return NULL;
2089
2090 @ If the array of internals is still |NULL| when |jump_out| is called, a
2091 crash occured during initialization, and it is not safe to run the normal
2092 cleanup routine.
2093
2094 @<Error hand...@>=
2095 void mp_jump_out (MP mp) { 
2096   if(mp->internal!=NULL)
2097     mp_close_files_and_terminate(mp);
2098   longjmp(mp->jump_buf,1);
2099 }
2100
2101 @ Here now is the general |error| routine.
2102
2103 @<Error hand...@>=
2104 void mp_error (MP mp) { /* completes the job of error reporting */
2105   ASCII_code c; /* what the user types */
2106   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2107   pool_pointer j; /* character position being printed */
2108   if ( mp->history<mp_error_message_issued ) 
2109         mp->history=mp_error_message_issued;
2110   mp_print_char(mp, '.'); mp_show_context(mp);
2111   if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2112     @<Get user's advice and |return|@>;
2113   }
2114   incr(mp->error_count);
2115   if ( mp->error_count==100 ) { 
2116     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2117 @.That makes 100 errors...@>
2118     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2119   }
2120   @<Put help message on the transcript file@>;
2121 }
2122 void mp_warn (MP mp, char *msg) {
2123   int saved_selector = mp->selector;
2124   mp_normalize_selector(mp);
2125   mp_print_nl(mp,"Warning: ");
2126   mp_print(mp,msg);
2127   mp->selector = saved_selector;
2128 }
2129
2130 @ @<Exported function ...@>=
2131 void mp_error (MP mp);
2132 void mp_warn (MP mp, char *msg);
2133
2134
2135 @ @<Get user's advice...@>=
2136 while (1) { 
2137 CONTINUE:
2138   mp_clear_for_error_prompt(mp); prompt_input("? ");
2139 @.?\relax@>
2140   if ( mp->last==mp->first ) return;
2141   c=mp->buffer[mp->first];
2142   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2143   @<Interpret code |c| and |return| if done@>;
2144 }
2145
2146 @ It is desirable to provide an `\.E' option here that gives the user
2147 an easy way to return from \MP\ to the system editor, with the offending
2148 line ready to be edited. But such an extension requires some system
2149 wizardry, so the present implementation simply types out the name of the
2150 file that should be
2151 edited and the relevant line number.
2152 @^system dependencies@>
2153
2154 @<Exported types@>=
2155 typedef void (*mp_run_editor_command)(MP, char *, int);
2156
2157 @ @<Option variables@>=
2158 mp_run_editor_command run_editor;
2159
2160 @ @<Allocate or initialize ...@>=
2161 set_callback_option(run_editor);
2162
2163 @ @<Declarations@>=
2164 void mp_run_editor (MP mp, char *fname, int fline);
2165
2166 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2167     mp_print_nl(mp, "You want to edit file ");
2168 @.You want to edit file x@>
2169     mp_print(mp, fname);
2170     mp_print(mp, " at line "); 
2171     mp_print_int(mp, fline);
2172     mp->interaction=mp_scroll_mode; 
2173     mp_jump_out(mp);
2174 }
2175
2176
2177 There is a secret `\.D' option available when the debugging routines haven't
2178 been commented~out.
2179 @^debugging@>
2180
2181 @<Interpret code |c| and |return| if done@>=
2182 switch (c) {
2183 case '0': case '1': case '2': case '3': case '4':
2184 case '5': case '6': case '7': case '8': case '9': 
2185   if ( mp->deletions_allowed ) {
2186     @<Delete |c-"0"| tokens and |continue|@>;
2187   }
2188   break;
2189 #ifdef DEBUG
2190 case 'D': 
2191   mp_debug_help(mp); continue; 
2192   break;
2193 #endif
2194 case 'E': 
2195   if ( mp->file_ptr>0 ){ 
2196     (mp->run_editor)(mp, 
2197                      str(mp->input_stack[mp->file_ptr].name_field), 
2198                      mp_true_line(mp));
2199   }
2200   break;
2201 case 'H': 
2202   @<Print the help information and |continue|@>;
2203   break;
2204 case 'I':
2205   @<Introduce new material from the terminal and |return|@>;
2206   break;
2207 case 'Q': case 'R': case 'S':
2208   @<Change the interaction level and |return|@>;
2209   break;
2210 case 'X':
2211   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2212   break;
2213 default:
2214   break;
2215 }
2216 @<Print the menu of available options@>
2217
2218 @ @<Print the menu...@>=
2219
2220   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2221 @.Type <return> to proceed...@>
2222   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2223   mp_print_nl(mp, "I to insert something, ");
2224   if ( mp->file_ptr>0 ) 
2225     mp_print(mp, "E to edit your file,");
2226   if ( mp->deletions_allowed )
2227     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2228   mp_print_nl(mp, "H for help, X to quit.");
2229 }
2230
2231 @ Here the author of \MP\ apologizes for making use of the numerical
2232 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2233 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2234 @^Knuth, Donald Ervin@>
2235
2236 @<Change the interaction...@>=
2237
2238   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2239   mp_print(mp, "OK, entering ");
2240   switch (c) {
2241   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2242   case 'R': mp_print(mp, "nonstopmode"); break;
2243   case 'S': mp_print(mp, "scrollmode"); break;
2244   } /* there are no other cases */
2245   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2246 }
2247
2248 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2249 contain the material inserted by the user; otherwise another prompt will
2250 be given. In order to understand this part of the program fully, you need
2251 to be familiar with \MP's input stacks.
2252
2253 @<Introduce new material...@>=
2254
2255   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2256   if ( mp->last>mp->first+1 ) { 
2257     loc=mp->first+1; mp->buffer[mp->first]=' ';
2258   } else { 
2259    prompt_input("insert>"); loc=mp->first;
2260 @.insert>@>
2261   };
2262   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2263 }
2264
2265 @ We allow deletion of up to 99 tokens at a time.
2266
2267 @<Delete |c-"0"| tokens...@>=
2268
2269   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2270   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2271     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2272   else 
2273     c=c-'0';
2274   while ( c>0 ) { 
2275     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2276     @<Decrease the string reference count, if the current token is a string@>;
2277     decr(c);
2278   };
2279   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2280   help2("I have just deleted some text, as you asked.")
2281        ("You can now delete more, or insert, or whatever.");
2282   mp_show_context(mp); 
2283   goto CONTINUE;
2284 }
2285
2286 @ @<Print the help info...@>=
2287
2288   if ( mp->use_err_help ) { 
2289     @<Print the string |err_help|, possibly on several lines@>;
2290     mp->use_err_help=false;
2291   } else { 
2292     if ( mp->help_ptr==0 ) {
2293       help2("Sorry, I don't know how to help in this situation.")
2294            ("Maybe you should try asking a human?");
2295      }
2296     do { 
2297       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2298     } while (mp->help_ptr!=0);
2299   };
2300   help4("Sorry, I already gave what help I could...")
2301        ("Maybe you should try asking a human?")
2302        ("An error might have occurred before I noticed any problems.")
2303        ("``If all else fails, read the instructions.''");
2304   goto CONTINUE;
2305 }
2306
2307 @ @<Print the string |err_help|, possibly on several lines@>=
2308 j=mp->str_start[mp->err_help];
2309 while ( j<str_stop(mp->err_help) ) { 
2310   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2311   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2312   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2313   else  { incr(j); mp_print_char(mp, '%'); };
2314   incr(j);
2315 }
2316
2317 @ @<Put help message on the transcript file@>=
2318 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2319 if ( mp->use_err_help ) { 
2320   mp_print_nl(mp, "");
2321   @<Print the string |err_help|, possibly on several lines@>;
2322 } else { 
2323   while ( mp->help_ptr>0 ){ 
2324     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2325   };
2326 }
2327 mp_print_ln(mp);
2328 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2329 mp_print_ln(mp)
2330
2331 @ In anomalous cases, the print selector might be in an unknown state;
2332 the following subroutine is called to fix things just enough to keep
2333 running a bit longer.
2334
2335 @c 
2336 void mp_normalize_selector (MP mp) { 
2337   if ( mp->log_opened ) mp->selector=term_and_log;
2338   else mp->selector=term_only;
2339   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2340   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2341 }
2342
2343 @ The following procedure prints \MP's last words before dying.
2344
2345 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2346     mp->interaction=mp_scroll_mode; /* no more interaction */
2347   if ( mp->log_opened ) mp_error(mp);
2348   /*| if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); |*/
2349   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2350   }
2351
2352 @<Error hand...@>=
2353 void mp_fatal_error (MP mp, char *s) { /* prints |s|, and that's it */
2354   mp_normalize_selector(mp);
2355   print_err("Emergency stop"); help1(s); succumb;
2356 @.Emergency stop@>
2357 }
2358
2359 @ @<Exported function ...@>=
2360 void mp_fatal_error (MP mp, char *s);
2361
2362
2363 @ Here is the most dreaded error message.
2364
2365 @<Error hand...@>=
2366 void mp_overflow (MP mp, char *s, integer n) { /* stop due to finiteness */
2367   mp_normalize_selector(mp);
2368   print_err("MetaPost capacity exceeded, sorry [");
2369 @.MetaPost capacity exceeded ...@>
2370   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2371   help2("If you really absolutely need more capacity,")
2372        ("you can ask a wizard to enlarge me.");
2373   succumb;
2374 }
2375
2376 @ @<Internal library declarations@>=
2377 void mp_overflow (MP mp, char *s, integer n);
2378
2379 @ The program might sometime run completely amok, at which point there is
2380 no choice but to stop. If no previous error has been detected, that's bad
2381 news; a message is printed that is really intended for the \MP\
2382 maintenance person instead of the user (unless the user has been
2383 particularly diabolical).  The index entries for `this can't happen' may
2384 help to pinpoint the problem.
2385 @^dry rot@>
2386
2387 @<Internal library ...@>=
2388 void mp_confusion (MP mp,char *s);
2389
2390 @ @<Error hand...@>=
2391 void mp_confusion (MP mp,char *s) {
2392   /* consistency check violated; |s| tells where */
2393   mp_normalize_selector(mp);
2394   if ( mp->history<mp_error_message_issued ) { 
2395     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2396 @.This can't happen@>
2397     help1("I'm broken. Please show this to someone who can fix can fix");
2398   } else { 
2399     print_err("I can\'t go on meeting you like this");
2400 @.I can't go on...@>
2401     help2("One of your faux pas seems to have wounded me deeply...")
2402          ("in fact, I'm barely conscious. Please fix it and try again.");
2403   }
2404   succumb;
2405 }
2406
2407 @ Users occasionally want to interrupt \MP\ while it's running.
2408 If the runtime system allows this, one can implement
2409 a routine that sets the global variable |interrupt| to some nonzero value
2410 when such an interrupt is signaled. Otherwise there is probably at least
2411 a way to make |interrupt| nonzero using the C debugger.
2412 @^system dependencies@>
2413 @^debugging@>
2414
2415 @d check_interrupt { if ( mp->interrupt!=0 )
2416    mp_pause_for_instructions(mp); }
2417
2418 @<Global...@>=
2419 integer interrupt; /* should \MP\ pause for instructions? */
2420 boolean OK_to_interrupt; /* should interrupts be observed? */
2421
2422 @ @<Allocate or ...@>=
2423 mp->interrupt=0; mp->OK_to_interrupt=true;
2424
2425 @ When an interrupt has been detected, the program goes into its
2426 highest interaction level and lets the user have the full flexibility of
2427 the |error| routine.  \MP\ checks for interrupts only at times when it is
2428 safe to do this.
2429
2430 @c 
2431 void mp_pause_for_instructions (MP mp) { 
2432   if ( mp->OK_to_interrupt ) { 
2433     mp->interaction=mp_error_stop_mode;
2434     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2435       incr(mp->selector);
2436     print_err("Interruption");
2437 @.Interruption@>
2438     help3("You rang?")
2439          ("Try to insert some instructions for me (e.g.,`I show x'),")
2440          ("unless you just want to quit by typing `X'.");
2441     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2442     mp->interrupt=0;
2443   }
2444 }
2445
2446 @ Many of \MP's error messages state that a missing token has been
2447 inserted behind the scenes. We can save string space and program space
2448 by putting this common code into a subroutine.
2449
2450 @c 
2451 void mp_missing_err (MP mp, char *s) { 
2452   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2453 @.Missing...inserted@>
2454 }
2455
2456 @* \[7] Arithmetic with scaled numbers.
2457 The principal computations performed by \MP\ are done entirely in terms of
2458 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2459 program can be carried out in exactly the same way on a wide variety of
2460 computers, including some small ones.
2461 @^small computers@>
2462
2463 But C does not rigidly define the |/| operation in the case of negative
2464 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2465 computers and |-n| on others (is this true ?).  There are two principal
2466 types of arithmetic: ``translation-preserving,'' in which the identity
2467 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2468 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2469 different results, although the differences should be negligible when the
2470 language is being used properly.  The \TeX\ processor has been defined
2471 carefully so that both varieties of arithmetic will produce identical
2472 output, but it would be too inefficient to constrain \MP\ in a similar way.
2473
2474 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2475
2476 @ One of \MP's most common operations is the calculation of
2477 $\lfloor{a+b\over2}\rfloor$,
2478 the midpoint of two given integers |a| and~|b|. The most decent way to do
2479 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2480 to calculate `|(a+b)>>1|'.
2481
2482 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2483 in this program. If \MP\ is being implemented with languages that permit
2484 binary shifting, the |half| macro should be changed to make this operation
2485 as efficient as possible.  Since some systems have shift operators that can
2486 only be trusted to work on positive numbers, there is also a macro |halfp|
2487 that is used only when the quantity being halved is known to be positive
2488 or zero.
2489
2490 @d half(A) ((A) / 2)
2491 @d halfp(A) ((A) >> 1)
2492
2493 @ A single computation might use several subroutine calls, and it is
2494 desirable to avoid producing multiple error messages in case of arithmetic
2495 overflow. So the routines below set the global variable |arith_error| to |true|
2496 instead of reporting errors directly to the user.
2497
2498 @<Glob...@>=
2499 boolean arith_error; /* has arithmetic overflow occurred recently? */
2500
2501 @ @<Allocate or ...@>=
2502 mp->arith_error=false;
2503
2504 @ At crucial points the program will say |check_arith|, to test if
2505 an arithmetic error has been detected.
2506
2507 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2508
2509 @c 
2510 void mp_clear_arith (MP mp) { 
2511   print_err("Arithmetic overflow");
2512 @.Arithmetic overflow@>
2513   help4("Uh, oh. A little while ago one of the quantities that I was")
2514        ("computing got too large, so I'm afraid your answers will be")
2515        ("somewhat askew. You'll probably have to adopt different")
2516        ("tactics next time. But I shall try to carry on anyway.");
2517   mp_error(mp); 
2518   mp->arith_error=false;
2519 }
2520
2521 @ Addition is not always checked to make sure that it doesn't overflow,
2522 but in places where overflow isn't too unlikely the |slow_add| routine
2523 is used.
2524
2525 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2526   if ( x>=0 )  {
2527     if ( y<=el_gordo-x ) { 
2528       return x+y;
2529     } else  { 
2530       mp->arith_error=true; 
2531           return el_gordo;
2532     }
2533   } else  if ( -y<=el_gordo+x ) {
2534     return x+y;
2535   } else { 
2536     mp->arith_error=true; 
2537         return -el_gordo;
2538   }
2539 }
2540
2541 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2542 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2543 positions from the right end of a binary computer word.
2544
2545 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2546 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2547 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2548 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2549 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2550 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2551
2552 @<Types...@>=
2553 typedef integer scaled; /* this type is used for scaled integers */
2554 typedef unsigned char small_number; /* this type is self-explanatory */
2555
2556 @ The following function is used to create a scaled integer from a given decimal
2557 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2558 given in |dig[i]|, and the calculation produces a correctly rounded result.
2559
2560 @c 
2561 scaled mp_round_decimals (MP mp,small_number k) {
2562   /* converts a decimal fraction */
2563  integer a = 0; /* the accumulator */
2564  while ( k-->0 ) { 
2565     a=(a+mp->dig[k]*two) / 10;
2566   }
2567   return halfp(a+1);
2568 }
2569
2570 @ Conversely, here is a procedure analogous to |print_int|. If the output
2571 of this procedure is subsequently read by \MP\ and converted by the
2572 |round_decimals| routine above, it turns out that the original value will
2573 be reproduced exactly. A decimal point is printed only if the value is
2574 not an integer. If there is more than one way to print the result with
2575 the optimum number of digits following the decimal point, the closest
2576 possible value is given.
2577
2578 The invariant relation in the \&{repeat} loop is that a sequence of
2579 decimal digits yet to be printed will yield the original number if and only if
2580 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2581 We can stop if and only if $f=0$ satisfies this condition; the loop will
2582 terminate before $s$ can possibly become zero.
2583
2584 @<Basic printing...@>=
2585 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2586   scaled delta; /* amount of allowable inaccuracy */
2587   if ( s<0 ) { 
2588         mp_print_char(mp, '-'); 
2589     negate(s); /* print the sign, if negative */
2590   }
2591   mp_print_int(mp, s / unity); /* print the integer part */
2592   s=10*(s % unity)+5;
2593   if ( s!=5 ) { 
2594     delta=10; 
2595     mp_print_char(mp, '.');
2596     do {  
2597       if ( delta>unity )
2598         s=s+0100000-(delta / 2); /* round the final digit */
2599       mp_print_char(mp, '0'+(s / unity)); 
2600       s=10*(s % unity); 
2601       delta=delta*10;
2602     } while (s>delta);
2603   }
2604 }
2605
2606 @ We often want to print two scaled quantities in parentheses,
2607 separated by a comma.
2608
2609 @<Basic printing...@>=
2610 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2611   mp_print_char(mp, '('); 
2612   mp_print_scaled(mp, x); 
2613   mp_print_char(mp, ','); 
2614   mp_print_scaled(mp, y);
2615   mp_print_char(mp, ')');
2616 }
2617
2618 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2619 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2620 arithmetic with 28~significant bits of precision. A |fraction| denotes
2621 a scaled integer whose binary point is assumed to be 28 bit positions
2622 from the right.
2623
2624 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2625 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2626 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2627 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2628 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2629
2630 @<Types...@>=
2631 typedef integer fraction; /* this type is used for scaled fractions */
2632
2633 @ In fact, the two sorts of scaling discussed above aren't quite
2634 sufficient; \MP\ has yet another, used internally to keep track of angles
2635 in units of $2^{-20}$ degrees.
2636
2637 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2638 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2639 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2640 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2641
2642 @<Types...@>=
2643 typedef integer angle; /* this type is used for scaled angles */
2644
2645 @ The |make_fraction| routine produces the |fraction| equivalent of
2646 |p/q|, given integers |p| and~|q|; it computes the integer
2647 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2648 positive. If |p| and |q| are both of the same scaled type |t|,
2649 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2650 and it's also possible to use the subroutine ``backwards,'' using
2651 the relation |make_fraction(t,fraction)=t| between scaled types.
2652
2653 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2654 sets |arith_error:=true|. Most of \MP's internal computations have
2655 been designed to avoid this sort of error.
2656
2657 If this subroutine were programmed in assembly language on a typical
2658 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2659 double-precision product can often be input to a fixed-point division
2660 instruction. But when we are restricted to int-eger arithmetic it
2661 is necessary either to resort to multiple-precision maneuvering
2662 or to use a simple but slow iteration. The multiple-precision technique
2663 would be about three times faster than the code adopted here, but it
2664 would be comparatively long and tricky, involving about sixteen
2665 additional multiplications and divisions.
2666
2667 This operation is part of \MP's ``inner loop''; indeed, it will
2668 consume nearly 10\pct! of the running time (exclusive of input and output)
2669 if the code below is left unchanged. A machine-dependent recoding
2670 will therefore make \MP\ run faster. The present implementation
2671 is highly portable, but slow; it avoids multiplication and division
2672 except in the initial stage. System wizards should be careful to
2673 replace it with a routine that is guaranteed to produce identical
2674 results in all cases.
2675 @^system dependencies@>
2676
2677 As noted below, a few more routines should also be replaced by machine-dependent
2678 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2679 such changes aren't advisable; simplicity and robustness are
2680 preferable to trickery, unless the cost is too high.
2681 @^inner loop@>
2682
2683 @<Internal ...@>=
2684 fraction mp_make_fraction (MP mp,integer p, integer q);
2685 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2686
2687 @ If FIXPT is not defined, we need these preprocessor values
2688
2689 @d ELGORDO  0x7fffffff
2690 @d TWEXP31  2147483648.0
2691 @d TWEXP28  268435456.0
2692 @d TWEXP16 65536.0
2693 @d TWEXP_16 (1.0/65536.0)
2694 @d TWEXP_28 (1.0/268435456.0)
2695
2696
2697 @c 
2698 fraction mp_make_fraction (MP mp,integer p, integer q) {
2699 #ifdef FIXPT
2700   integer f; /* the fraction bits, with a leading 1 bit */
2701   integer n; /* the integer part of $\vert p/q\vert$ */
2702   integer be_careful; /* disables certain compiler optimizations */
2703   boolean negative = false; /* should the result be negated? */
2704   if ( p<0 ) {
2705     negate(p); negative=true;
2706   }
2707   if ( q<=0 ) { 
2708 #ifdef DEBUG
2709     if ( q==0 ) mp_confusion(mp, '/');
2710 #endif
2711 @:this can't happen /}{\quad \./@>
2712     negate(q); negative = ! negative;
2713   };
2714   n=p / q; p=p % q;
2715   if ( n>=8 ){ 
2716     mp->arith_error=true;
2717     return ( negative ? -el_gordo : el_gordo);
2718   } else { 
2719     n=(n-1)*fraction_one;
2720     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2721     return (negative ? (-(f+n)) : (f+n));
2722   }
2723 #else /* FIXPT */
2724     register double d;
2725         register integer i;
2726 #ifdef DEBUG
2727         if (q==0) mp_confusion(mp,'/'); 
2728 #endif /* DEBUG */
2729         d = TWEXP28 * (double)p /(double)q;
2730         if ((p^q) >= 0) {
2731                 d += 0.5;
2732                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2733                 i = (integer) d;
2734                 if (d==i && ( ((q>0 ? -q : q)&077777)
2735                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2736         } else {
2737                 d -= 0.5;
2738                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2739                 i = (integer) d;
2740                 if (d==i && ( ((q>0 ? q : -q)&077777)
2741                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2742         }
2743         return i;
2744 #endif /* FIXPT */
2745 }
2746
2747 @ The |repeat| loop here preserves the following invariant relations
2748 between |f|, |p|, and~|q|:
2749 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2750 $p_0$ is the original value of~$p$.
2751
2752 Notice that the computation specifies
2753 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2754 Let us hope that optimizing compilers do not miss this point; a
2755 special variable |be_careful| is used to emphasize the necessary
2756 order of computation. Optimizing compilers should keep |be_careful|
2757 in a register, not store it in memory.
2758 @^inner loop@>
2759
2760 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2761 {
2762   f=1;
2763   do {  
2764     be_careful=p-q; p=be_careful+p;
2765     if ( p>=0 ) { 
2766       f=f+f+1;
2767     } else  { 
2768       f+=f; p=p+q;
2769     }
2770   } while (f<fraction_one);
2771   be_careful=p-q;
2772   if ( be_careful+p>=0 ) incr(f);
2773 }
2774
2775 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2776 given integer~|q| by a fraction~|f|. When the operands are positive, it
2777 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2778 of |q| and~|f|.
2779
2780 This routine is even more ``inner loopy'' than |make_fraction|;
2781 the present implementation consumes almost 20\pct! of \MP's computation
2782 time during typical jobs, so a machine-language substitute is advisable.
2783 @^inner loop@> @^system dependencies@>
2784
2785 @<Declarations@>=
2786 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2787
2788 @ @c 
2789 #ifdef FIXPT
2790 integer mp_take_fraction (MP mp,integer q, fraction f) {
2791   integer p; /* the fraction so far */
2792   boolean negative; /* should the result be negated? */
2793   integer n; /* additional multiple of $q$ */
2794   integer be_careful; /* disables certain compiler optimizations */
2795   @<Reduce to the case that |f>=0| and |q>0|@>;
2796   if ( f<fraction_one ) { 
2797     n=0;
2798   } else { 
2799     n=f / fraction_one; f=f % fraction_one;
2800     if ( q<=el_gordo / n ) { 
2801       n=n*q ; 
2802     } else { 
2803       mp->arith_error=true; n=el_gordo;
2804     }
2805   }
2806   f=f+fraction_one;
2807   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2808   be_careful=n-el_gordo;
2809   if ( be_careful+p>0 ){ 
2810     mp->arith_error=true; n=el_gordo-p;
2811   }
2812   if ( negative ) 
2813         return (-(n+p));
2814   else 
2815     return (n+p);
2816 #else /* FIXPT */
2817 integer mp_take_fraction (MP mp,integer p, fraction q) {
2818     register double d;
2819         register integer i;
2820         d = (double)p * (double)q * TWEXP_28;
2821         if ((p^q) >= 0) {
2822                 d += 0.5;
2823                 if (d>=TWEXP31) {
2824                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2825                                 mp->arith_error = true;
2826                         return ELGORDO;
2827                 }
2828                 i = (integer) d;
2829                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2830         } else {
2831                 d -= 0.5;
2832                 if (d<= -TWEXP31) {
2833                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2834                                 mp->arith_error = true;
2835                         return -ELGORDO;
2836                 }
2837                 i = (integer) d;
2838                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2839         }
2840         return i;
2841 #endif /* FIXPT */
2842 }
2843
2844 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2845 if ( f>=0 ) {
2846   negative=false;
2847 } else { 
2848   negate( f); negative=true;
2849 }
2850 if ( q<0 ) { 
2851   negate(q); negative=! negative;
2852 }
2853
2854 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2855 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2856 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2857 @^inner loop@>
2858
2859 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2860 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2861 if ( q<fraction_four ) {
2862   do {  
2863     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2864     f=halfp(f);
2865   } while (f!=1);
2866 } else  {
2867   do {  
2868     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2869     f=halfp(f);
2870   } while (f!=1);
2871 }
2872
2873
2874 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2875 analogous to |take_fraction| but with a different scaling.
2876 Given positive operands, |take_scaled|
2877 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2878
2879 Once again it is a good idea to use a machine-language replacement if
2880 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2881 when the Computer Modern fonts are being generated.
2882 @^inner loop@>
2883
2884 @c 
2885 #ifdef FIXPT
2886 integer mp_take_scaled (MP mp,integer q, scaled f) {
2887   integer p; /* the fraction so far */
2888   boolean negative; /* should the result be negated? */
2889   integer n; /* additional multiple of $q$ */
2890   integer be_careful; /* disables certain compiler optimizations */
2891   @<Reduce to the case that |f>=0| and |q>0|@>;
2892   if ( f<unity ) { 
2893     n=0;
2894   } else  { 
2895     n=f / unity; f=f % unity;
2896     if ( q<=el_gordo / n ) {
2897       n=n*q;
2898     } else  { 
2899       mp->arith_error=true; n=el_gordo;
2900     }
2901   }
2902   f=f+unity;
2903   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2904   be_careful=n-el_gordo;
2905   if ( be_careful+p>0 ) { 
2906     mp->arith_error=true; n=el_gordo-p;
2907   }
2908   return ( negative ?(-(n+p)) :(n+p));
2909 #else /* FIXPT */
2910 integer mp_take_scaled (MP mp,integer p, scaled q) {
2911     register double d;
2912         register integer i;
2913         d = (double)p * (double)q * TWEXP_16;
2914         if ((p^q) >= 0) {
2915                 d += 0.5;
2916                 if (d>=TWEXP31) {
2917                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2918                                 mp->arith_error = true;
2919                         return ELGORDO;
2920                 }
2921                 i = (integer) d;
2922                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2923         } else {
2924                 d -= 0.5;
2925                 if (d<= -TWEXP31) {
2926                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2927                                 mp->arith_error = true;
2928                         return -ELGORDO;
2929                 }
2930                 i = (integer) d;
2931                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2932         }
2933         return i;
2934 #endif /* FIXPT */
2935 }
2936
2937 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2938 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2939 @^inner loop@>
2940 if ( q<fraction_four ) {
2941   do {  
2942     p = (odd(f) ? halfp(p+q) : halfp(p));
2943     f=halfp(f);
2944   } while (f!=1);
2945 } else {
2946   do {  
2947     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2948     f=halfp(f);
2949   } while (f!=1);
2950 }
2951
2952 @ For completeness, there's also |make_scaled|, which computes a
2953 quotient as a |scaled| number instead of as a |fraction|.
2954 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2955 operands are positive. \ (This procedure is not used especially often,
2956 so it is not part of \MP's inner loop.)
2957
2958 @<Internal library ...@>=
2959 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2960
2961 @ @c 
2962 scaled mp_make_scaled (MP mp,integer p, integer q) {
2963 #ifdef FIXPT 
2964   integer f; /* the fraction bits, with a leading 1 bit */
2965   integer n; /* the integer part of $\vert p/q\vert$ */
2966   boolean negative; /* should the result be negated? */
2967   integer be_careful; /* disables certain compiler optimizations */
2968   if ( p>=0 ) negative=false;
2969   else  { negate(p); negative=true; };
2970   if ( q<=0 ) { 
2971 #ifdef DEBUG 
2972     if ( q==0 ) mp_confusion(mp, "/");
2973 @:this can't happen /}{\quad \./@>
2974 #endif
2975     negate(q); negative=! negative;
2976   }
2977   n=p / q; p=p % q;
2978   if ( n>=0100000 ) { 
2979     mp->arith_error=true;
2980     return (negative ? (-el_gordo) : el_gordo);
2981   } else  { 
2982     n=(n-1)*unity;
2983     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2984     return ( negative ? (-(f+n)) :(f+n));
2985   }
2986 #else /* FIXPT */
2987     register double d;
2988         register integer i;
2989 #ifdef DEBUG
2990         if (q==0) mp_confusion(mp,"/"); 
2991 #endif /* DEBUG */
2992         d = TWEXP16 * (double)p /(double)q;
2993         if ((p^q) >= 0) {
2994                 d += 0.5;
2995                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2996                 i = (integer) d;
2997                 if (d==i && ( ((q>0 ? -q : q)&077777)
2998                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2999         } else {
3000                 d -= 0.5;
3001                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3002                 i = (integer) d;
3003                 if (d==i && ( ((q>0 ? q : -q)&077777)
3004                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3005         }
3006         return i;
3007 #endif /* FIXPT */
3008 }
3009
3010 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3011 f=1;
3012 do {  
3013   be_careful=p-q; p=be_careful+p;
3014   if ( p>=0 ) f=f+f+1;
3015   else  { f+=f; p=p+q; };
3016 } while (f<unity);
3017 be_careful=p-q;
3018 if ( be_careful+p>=0 ) incr(f)
3019
3020 @ Here is a typical example of how the routines above can be used.
3021 It computes the function
3022 $${1\over3\tau}f(\theta,\phi)=
3023 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3024  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3025 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3026 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3027 fudge factor for placing the first control point of a curve that starts
3028 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3029 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3030
3031 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3032 (It's a sum of eight terms whose absolute values can be bounded using
3033 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3034 is positive; and since the tension $\tau$ is constrained to be at least
3035 $3\over4$, the numerator is less than $16\over3$. The denominator is
3036 nonnegative and at most~6.  Hence the fixed-point calculations below
3037 are guaranteed to stay within the bounds of a 32-bit computer word.
3038
3039 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3040 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3041 $\sin\phi$, and $\cos\phi$, respectively.
3042
3043 @c 
3044 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3045                       fraction cf, scaled t) {
3046   integer acc,num,denom; /* registers for intermediate calculations */
3047   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3048   acc=mp_take_fraction(mp, acc,ct-cf);
3049   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3050                    /* $2^{28}\sqrt2\approx379625062.497$ */
3051   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3052                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3053                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3054   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3055   /* |make_scaled(fraction,scaled)=fraction| */
3056   if ( num / 4>=denom ) 
3057     return fraction_four;
3058   else 
3059     return mp_make_fraction(mp, num, denom);
3060 }
3061
3062 @ The following somewhat different subroutine tests rigorously if $ab$ is
3063 greater than, equal to, or less than~$cd$,
3064 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3065 The result is $+1$, 0, or~$-1$ in the three respective cases.
3066
3067 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3068
3069 @c 
3070 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3071   integer q,r; /* temporary registers */
3072   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3073   while (1) { 
3074     q = a / d; r = c / b;
3075     if ( q!=r )
3076       return ( q>r ? 1 : -1);
3077     q = a % d; r = c % b;
3078     if ( r==0 )
3079       return (q ? 1 : 0);
3080     if ( q==0 ) return -1;
3081     a=b; b=q; c=d; d=r;
3082   } /* now |a>d>0| and |c>b>0| */
3083 }
3084
3085 @ @<Reduce to the case that |a...@>=
3086 if ( a<0 ) { negate(a); negate(b);  };
3087 if ( c<0 ) { negate(c); negate(d);  };
3088 if ( d<=0 ) { 
3089   if ( b>=0 ) {
3090     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3091     else return 1;
3092   }
3093   if ( d==0 )
3094     return ( a==0 ? 0 : -1);
3095   q=a; a=c; c=q; q=-b; b=-d; d=q;
3096 } else if ( b<=0 ) { 
3097   if ( b<0 ) if ( a>0 ) return -1;
3098   return (c==0 ? 0 : -1);
3099 }
3100
3101 @ We conclude this set of elementary routines with some simple rounding
3102 and truncation operations.
3103
3104 @<Internal library declarations@>=
3105 #define mp_floor_scaled(M,i) ((i)&(-65536))
3106 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3107 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3108
3109
3110 @* \[8] Algebraic and transcendental functions.
3111 \MP\ computes all of the necessary special functions from scratch, without
3112 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3113
3114 @ To get the square root of a |scaled| number |x|, we want to calculate
3115 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3116 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3117 determines $s$ by an iterative method that maintains the invariant
3118 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3119 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3120 might, however, be zero at the start of the first iteration.
3121
3122 @<Declarations@>=
3123 scaled mp_square_rt (MP mp,scaled x) ;
3124
3125 @ @c 
3126 scaled mp_square_rt (MP mp,scaled x) {
3127   small_number k; /* iteration control counter */
3128   integer y,q; /* registers for intermediate calculations */
3129   if ( x<=0 ) { 
3130     @<Handle square root of zero or negative argument@>;
3131   } else { 
3132     k=23; q=2;
3133     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3134       decr(k); x=x+x+x+x;
3135     }
3136     if ( x<fraction_four ) y=0;
3137     else  { x=x-fraction_four; y=1; };
3138     do {  
3139       @<Decrease |k| by 1, maintaining the invariant
3140       relations between |x|, |y|, and~|q|@>;
3141     } while (k!=0);
3142     return (halfp(q));
3143   }
3144 }
3145
3146 @ @<Handle square root of zero...@>=
3147
3148   if ( x<0 ) { 
3149     print_err("Square root of ");
3150 @.Square root...replaced by 0@>
3151     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3152     help2("Since I don't take square roots of negative numbers,")
3153          ("I'm zeroing this one. Proceed, with fingers crossed.");
3154     mp_error(mp);
3155   };
3156   return 0;
3157 }
3158
3159 @ @<Decrease |k| by 1, maintaining...@>=
3160 x+=x; y+=y;
3161 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3162   x=x-fraction_four; incr(y);
3163 };
3164 x+=x; y=y+y-q; q+=q;
3165 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3166 if ( y>q ){ y=y-q; q=q+2; }
3167 else if ( y<=0 )  { q=q-2; y=y+q;  };
3168 decr(k)
3169
3170 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3171 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3172 @^Moler, Cleve Barry@>
3173 @^Morrison, Donald Ross@>
3174 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3175 in such a way that their Pythagorean sum remains invariant, while the
3176 smaller argument decreases.
3177
3178 @<Internal library ...@>=
3179 integer mp_pyth_add (MP mp,integer a, integer b);
3180
3181
3182 @ @c 
3183 integer mp_pyth_add (MP mp,integer a, integer b) {
3184   fraction r; /* register used to transform |a| and |b| */
3185   boolean big; /* is the result dangerously near $2^{31}$? */
3186   a=abs(a); b=abs(b);
3187   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3188   if ( b>0 ) {
3189     if ( a<fraction_two ) {
3190       big=false;
3191     } else { 
3192       a=a / 4; b=b / 4; big=true;
3193     }; /* we reduced the precision to avoid arithmetic overflow */
3194     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3195     if ( big ) {
3196       if ( a<fraction_two ) {
3197         a=a+a+a+a;
3198       } else  { 
3199         mp->arith_error=true; a=el_gordo;
3200       };
3201     }
3202   }
3203   return a;
3204 }
3205
3206 @ The key idea here is to reflect the vector $(a,b)$ about the
3207 line through $(a,b/2)$.
3208
3209 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3210 while (1) {  
3211   r=mp_make_fraction(mp, b,a);
3212   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3213   if ( r==0 ) break;
3214   r=mp_make_fraction(mp, r,fraction_four+r);
3215   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3216 }
3217
3218
3219 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3220 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3221
3222 @c 
3223 integer mp_pyth_sub (MP mp,integer a, integer b) {
3224   fraction r; /* register used to transform |a| and |b| */
3225   boolean big; /* is the input dangerously near $2^{31}$? */
3226   a=abs(a); b=abs(b);
3227   if ( a<=b ) {
3228     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3229   } else { 
3230     if ( a<fraction_four ) {
3231       big=false;
3232     } else  { 
3233       a=halfp(a); b=halfp(b); big=true;
3234     }
3235     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3236     if ( big ) double(a);
3237   }
3238   return a;
3239 }
3240
3241 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3242 while (1) { 
3243   r=mp_make_fraction(mp, b,a);
3244   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3245   if ( r==0 ) break;
3246   r=mp_make_fraction(mp, r,fraction_four-r);
3247   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3248 }
3249
3250 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3251
3252   if ( a<b ){ 
3253     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3254     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3255     mp_print(mp, " has been replaced by 0");
3256 @.Pythagorean...@>
3257     help2("Since I don't take square roots of negative numbers,")
3258          ("I'm zeroing this one. Proceed, with fingers crossed.");
3259     mp_error(mp);
3260   }
3261   a=0;
3262 }
3263
3264 @ The subroutines for logarithm and exponential involve two tables.
3265 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3266 a bit more calculation, which the author claims to have done correctly:
3267 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3268 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3269 nearest integer.
3270
3271 @d two_to_the(A) (1<<(A))
3272
3273 @<Constants ...@>=
3274 static const integer spec_log[29] = { 0, /* special logarithms */
3275 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3276 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3277 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3278
3279 @ @<Local variables for initialization@>=
3280 integer k; /* all-purpose loop index */
3281
3282
3283 @ Here is the routine that calculates $2^8$ times the natural logarithm
3284 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3285 when |x| is a given positive integer.
3286
3287 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3288 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3289 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3290 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3291 during the calculation, and sixteen auxiliary bits to extend |y| are
3292 kept in~|z| during the initial argument reduction. (We add
3293 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3294 not become negative; also, the actual amount subtracted from~|y| is~96,
3295 not~100, because we want to add~4 for rounding before the final division by~8.)
3296
3297 @c 
3298 scaled mp_m_log (MP mp,scaled x) {
3299   integer y,z; /* auxiliary registers */
3300   integer k; /* iteration counter */
3301   if ( x<=0 ) {
3302      @<Handle non-positive logarithm@>;
3303   } else  { 
3304     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3305     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3306     while ( x<fraction_four ) {
3307        double(x); y-=93032639; z-=48782;
3308     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3309     y=y+(z / unity); k=2;
3310     while ( x>fraction_four+4 ) {
3311       @<Increase |k| until |x| can be multiplied by a
3312         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3313     }
3314     return (y / 8);
3315   }
3316 }
3317
3318 @ @<Increase |k| until |x| can...@>=
3319
3320   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3321   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3322   y+=spec_log[k]; x-=z;
3323 }
3324
3325 @ @<Handle non-positive logarithm@>=
3326
3327   print_err("Logarithm of ");
3328 @.Logarithm...replaced by 0@>
3329   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3330   help2("Since I don't take logs of non-positive numbers,")
3331        ("I'm zeroing this one. Proceed, with fingers crossed.");
3332   mp_error(mp); 
3333   return 0;
3334 }
3335
3336 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3337 when |x| is |scaled|. The result is an integer approximation to
3338 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3339
3340 @c 
3341 scaled mp_m_exp (MP mp,scaled x) {
3342   small_number k; /* loop control index */
3343   integer y,z; /* auxiliary registers */
3344   if ( x>174436200 ) {
3345     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3346     mp->arith_error=true; 
3347     return el_gordo;
3348   } else if ( x<-197694359 ) {
3349         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3350     return 0;
3351   } else { 
3352     if ( x<=0 ) { 
3353        z=-8*x; y=04000000; /* $y=2^{20}$ */
3354     } else { 
3355       if ( x<=127919879 ) { 
3356         z=1023359037-8*x;
3357         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3358       } else {
3359        z=8*(174436200-x); /* |z| is always nonnegative */
3360       }
3361       y=el_gordo;
3362     };
3363     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3364     if ( x<=127919879 ) 
3365        return ((y+8) / 16);
3366      else 
3367        return y;
3368   }
3369 }
3370
3371 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3372 to multiplying |y| by $1-2^{-k}$.
3373
3374 A subtle point (which had to be checked) was that if $x=127919879$, the
3375 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3376 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3377 and by~16 when |k=27|.
3378
3379 @<Multiply |y| by...@>=
3380 k=1;
3381 while ( z>0 ) { 
3382   while ( z>=spec_log[k] ) { 
3383     z-=spec_log[k];
3384     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3385   }
3386   incr(k);
3387 }
3388
3389 @ The trigonometric subroutines use an auxiliary table such that
3390 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3391 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3392
3393 @<Constants ...@>=
3394 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3395 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3396 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3397
3398 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3399 returns the |angle| whose tangent points in the direction $(x,y)$.
3400 This subroutine first determines the correct octant, then solves the
3401 problem for |0<=y<=x|, then converts the result appropriately to
3402 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3403 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3404 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3405
3406 The octants are represented in a ``Gray code,'' since that turns out
3407 to be computationally simplest.
3408
3409 @d negate_x 1
3410 @d negate_y 2
3411 @d switch_x_and_y 4
3412 @d first_octant 1
3413 @d second_octant (first_octant+switch_x_and_y)
3414 @d third_octant (first_octant+switch_x_and_y+negate_x)
3415 @d fourth_octant (first_octant+negate_x)
3416 @d fifth_octant (first_octant+negate_x+negate_y)
3417 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3418 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3419 @d eighth_octant (first_octant+negate_y)
3420
3421 @c 
3422 angle mp_n_arg (MP mp,integer x, integer y) {
3423   angle z; /* auxiliary register */
3424   integer t; /* temporary storage */
3425   small_number k; /* loop counter */
3426   int octant; /* octant code */
3427   if ( x>=0 ) {
3428     octant=first_octant;
3429   } else { 
3430     negate(x); octant=first_octant+negate_x;
3431   }
3432   if ( y<0 ) { 
3433     negate(y); octant=octant+negate_y;
3434   }
3435   if ( x<y ) { 
3436     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3437   }
3438   if ( x==0 ) { 
3439     @<Handle undefined arg@>; 
3440   } else { 
3441     @<Set variable |z| to the arg of $(x,y)$@>;
3442     @<Return an appropriate answer based on |z| and |octant|@>;
3443   }
3444 }
3445
3446 @ @<Handle undefined arg@>=
3447
3448   print_err("angle(0,0) is taken as zero");
3449 @.angle(0,0)...zero@>
3450   help2("The `angle' between two identical points is undefined.")
3451        ("I'm zeroing this one. Proceed, with fingers crossed.");
3452   mp_error(mp); 
3453   return 0;
3454 }
3455
3456 @ @<Return an appropriate answer...@>=
3457 switch (octant) {
3458 case first_octant: return z;
3459 case second_octant: return (ninety_deg-z);
3460 case third_octant: return (ninety_deg+z);
3461 case fourth_octant: return (one_eighty_deg-z);
3462 case fifth_octant: return (z-one_eighty_deg);
3463 case sixth_octant: return (-z-ninety_deg);
3464 case seventh_octant: return (z-ninety_deg);
3465 case eighth_octant: return (-z);
3466 }; /* there are no other cases */
3467 return 0
3468
3469 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3470 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3471 will be made.
3472
3473 @<Set variable |z| to the arg...@>=
3474 while ( x>=fraction_two ) { 
3475   x=halfp(x); y=halfp(y);
3476 }
3477 z=0;
3478 if ( y>0 ) { 
3479  while ( x<fraction_one ) { 
3480     x+=x; y+=y; 
3481  };
3482  @<Increase |z| to the arg of $(x,y)$@>;
3483 }
3484
3485 @ During the calculations of this section, variables |x| and~|y|
3486 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3487 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3488 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3489 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3490 coordinates whose angle has decreased by~$\phi$; in the special case
3491 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3492 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3493 @^Meggitt, John E.@>
3494 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3495
3496 The initial value of |x| will be multiplied by at most
3497 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3498 there is no chance of integer overflow.
3499
3500 @<Increase |z|...@>=
3501 k=0;
3502 do {  
3503   y+=y; incr(k);
3504   if ( y>x ){ 
3505     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3506   };
3507 } while (k!=15);
3508 do {  
3509   y+=y; incr(k);
3510   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3511 } while (k!=26)
3512
3513 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3514 and cosine of that angle. The results of this routine are
3515 stored in global integer variables |n_sin| and |n_cos|.
3516
3517 @<Glob...@>=
3518 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3519
3520 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3521 the purpose of |n_sin_cos(z)| is to set
3522 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3523 for some rather large number~|r|. The maximum of |x| and |y|
3524 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3525 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3526
3527 @c 
3528 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3529                                        and cosine */ 
3530   small_number k; /* loop control variable */
3531   int q; /* specifies the quadrant */
3532   fraction r; /* magnitude of |(x,y)| */
3533   integer x,y,t; /* temporary registers */
3534   while ( z<0 ) z=z+three_sixty_deg;
3535   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3536   q=z / forty_five_deg; z=z % forty_five_deg;
3537   x=fraction_one; y=x;
3538   if ( ! odd(q) ) z=forty_five_deg-z;
3539   @<Subtract angle |z| from |(x,y)|@>;
3540   @<Convert |(x,y)| to the octant determined by~|q|@>;
3541   r=mp_pyth_add(mp, x,y); 
3542   mp->n_cos=mp_make_fraction(mp, x,r); 
3543   mp->n_sin=mp_make_fraction(mp, y,r);
3544 }
3545
3546 @ In this case the octants are numbered sequentially.
3547
3548 @<Convert |(x,...@>=
3549 switch (q) {
3550 case 0: break;
3551 case 1: t=x; x=y; y=t; break;
3552 case 2: t=x; x=-y; y=t; break;
3553 case 3: negate(x); break;
3554 case 4: negate(x); negate(y); break;
3555 case 5: t=x; x=-y; y=-t; break;
3556 case 6: t=x; x=y; y=-t; break;
3557 case 7: negate(y); break;
3558 } /* there are no other cases */
3559
3560 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3561 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3562 that this loop is guaranteed to terminate before the (nonexistent) value
3563 |spec_atan[27]| would be required.
3564
3565 @<Subtract angle |z|...@>=
3566 k=1;
3567 while ( z>0 ){ 
3568   if ( z>=spec_atan[k] ) { 
3569     z=z-spec_atan[k]; t=x;
3570     x=t+y / two_to_the(k);
3571     y=y-t / two_to_the(k);
3572   }
3573   incr(k);
3574 }
3575 if ( y<0 ) y=0 /* this precaution may never be needed */
3576
3577 @ And now let's complete our collection of numeric utility routines
3578 by considering random number generation.
3579 \MP\ generates pseudo-random numbers with the additive scheme recommended
3580 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3581 results are random fractions between 0 and |fraction_one-1|, inclusive.
3582
3583 There's an auxiliary array |randoms| that contains 55 pseudo-random
3584 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3585 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3586 The global variable |j_random| tells which element has most recently
3587 been consumed.
3588 The global variable |random_seed| was introduced in version 0.9,
3589 for the sole reason of stressing the fact that the initial value of the
3590 random seed is system-dependant. The initialization code below will initialize
3591 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3592 is not good enough on modern fast machines that are capable of running
3593 multiple MetaPost processes within the same second.
3594 @^system dependencies@>
3595
3596 @<Glob...@>=
3597 fraction randoms[55]; /* the last 55 random values generated */
3598 int j_random; /* the number of unused |randoms| */
3599
3600 @ @<Option variables@>=
3601 int random_seed; /* the default random seed */
3602
3603 @ @<Allocate or initialize ...@>=
3604 mp->random_seed = (scaled)opt->random_seed;
3605
3606 @ To consume a random fraction, the program below will say `|next_random|'
3607 and then it will fetch |randoms[j_random]|.
3608
3609 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3610   else decr(mp->j_random); }
3611
3612 @c 
3613 void mp_new_randoms (MP mp) {
3614   int k; /* index into |randoms| */
3615   fraction x; /* accumulator */
3616   for (k=0;k<=23;k++) { 
3617    x=mp->randoms[k]-mp->randoms[k+31];
3618     if ( x<0 ) x=x+fraction_one;
3619     mp->randoms[k]=x;
3620   }
3621   for (k=24;k<= 54;k++){ 
3622     x=mp->randoms[k]-mp->randoms[k-24];
3623     if ( x<0 ) x=x+fraction_one;
3624     mp->randoms[k]=x;
3625   }
3626   mp->j_random=54;
3627 }
3628
3629 @ @<Declarations@>=
3630 void mp_init_randoms (MP mp,scaled seed);
3631
3632 @ To initialize the |randoms| table, we call the following routine.
3633
3634 @c 
3635 void mp_init_randoms (MP mp,scaled seed) {
3636   fraction j,jj,k; /* more or less random integers */
3637   int i; /* index into |randoms| */
3638   j=abs(seed);
3639   while ( j>=fraction_one ) j=halfp(j);
3640   k=1;
3641   for (i=0;i<=54;i++ ){ 
3642     jj=k; k=j-k; j=jj;
3643     if ( k<0 ) k=k+fraction_one;
3644     mp->randoms[(i*21)% 55]=j;
3645   }
3646   mp_new_randoms(mp); 
3647   mp_new_randoms(mp); 
3648   mp_new_randoms(mp); /* ``warm up'' the array */
3649 }
3650
3651 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3652 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3653
3654 Note that the call of |take_fraction| will produce the values 0 and~|x|
3655 with about half the probability that it will produce any other particular
3656 values between 0 and~|x|, because it rounds its answers.
3657
3658 @c 
3659 scaled mp_unif_rand (MP mp,scaled x) {
3660   scaled y; /* trial value */
3661   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3662   if ( y==abs(x) ) return 0;
3663   else if ( x>0 ) return y;
3664   else return (-y);
3665 }
3666
3667 @ Finally, a normal deviate with mean zero and unit standard deviation
3668 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3669 {\sl The Art of Computer Programming\/}).
3670
3671 @c 
3672 scaled mp_norm_rand (MP mp) {
3673   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3674   do { 
3675     do {  
3676       next_random;
3677       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3678       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3679       next_random; u=mp->randoms[mp->j_random];
3680     } while (abs(x)>=u);
3681     x=mp_make_fraction(mp, x,u);
3682     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3683   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3684   return x;
3685 }
3686
3687 @* \[9] Packed data.
3688 In order to make efficient use of storage space, \MP\ bases its major data
3689 structures on a |memory_word|, which contains either a (signed) integer,
3690 possibly scaled, or a small number of fields that are one half or one
3691 quarter of the size used for storing integers.
3692
3693 If |x| is a variable of type |memory_word|, it contains up to four
3694 fields that can be referred to as follows:
3695 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3696 |x|&.|int|&(an |integer|)\cr
3697 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3698 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3699 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3700   field)\cr
3701 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3702   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3703 This is somewhat cumbersome to write, and not very readable either, but
3704 macros will be used to make the notation shorter and more transparent.
3705 The code below gives a formal definition of |memory_word| and
3706 its subsidiary types, using packed variant records. \MP\ makes no
3707 assumptions about the relative positions of the fields within a word.
3708
3709 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3710 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3711
3712 @ Here are the inequalities that the quarterword and halfword values
3713 must satisfy (or rather, the inequalities that they mustn't satisfy):
3714
3715 @<Check the ``constant''...@>=
3716 if (mp->ini_version) {
3717   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3718 } else {
3719   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3720 }
3721 if ( max_quarterword<255 ) mp->bad=9;
3722 if ( max_halfword<65535 ) mp->bad=10;
3723 if ( max_quarterword>max_halfword ) mp->bad=11;
3724 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3725 if ( mp->max_strings>max_halfword ) mp->bad=13;
3726
3727 @ The macros |qi| and |qo| are used for input to and output 
3728 from quarterwords. These are legacy macros.
3729 @^system dependencies@>
3730
3731 @d qo(A) (A) /* to read eight bits from a quarterword */
3732 @d qi(A) (A) /* to store eight bits in a quarterword */
3733
3734 @ The reader should study the following definitions closely:
3735 @^system dependencies@>
3736
3737 @d sc cint /* |scaled| data is equivalent to |integer| */
3738
3739 @<Types...@>=
3740 typedef short quarterword; /* 1/4 of a word */
3741 typedef int halfword; /* 1/2 of a word */
3742 typedef union {
3743   struct {
3744     halfword RH, LH;
3745   } v;
3746   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3747     halfword junk;
3748     quarterword B0, B1;
3749   } u;
3750 } two_halves;
3751 typedef struct {
3752   struct {
3753     quarterword B2, B3, B0, B1;
3754   } u;
3755 } four_quarters;
3756 typedef union {
3757   two_halves hh;
3758   integer cint;
3759   four_quarters qqqq;
3760 } memory_word;
3761 #define b0 u.B0
3762 #define b1 u.B1
3763 #define b2 u.B2
3764 #define b3 u.B3
3765 #define rh v.RH
3766 #define lh v.LH
3767
3768 @ When debugging, we may want to print a |memory_word| without knowing
3769 what type it is; so we print it in all modes.
3770 @^debugging@>
3771
3772 @c 
3773 void mp_print_word (MP mp,memory_word w) {
3774   /* prints |w| in all ways */
3775   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3776   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3777   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3778   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3779   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3780   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3781   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3782   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3783   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3784   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3785   mp_print_int(mp, w.qqqq.b3);
3786 }
3787
3788
3789 @* \[10] Dynamic memory allocation.
3790
3791 The \MP\ system does nearly all of its own memory allocation, so that it
3792 can readily be transported into environments that do not have automatic
3793 facilities for strings, garbage collection, etc., and so that it can be in
3794 control of what error messages the user receives. The dynamic storage
3795 requirements of \MP\ are handled by providing a large array |mem| in
3796 which consecutive blocks of words are used as nodes by the \MP\ routines.
3797
3798 Pointer variables are indices into this array, or into another array
3799 called |eqtb| that will be explained later. A pointer variable might
3800 also be a special flag that lies outside the bounds of |mem|, so we
3801 allow pointers to assume any |halfword| value. The minimum memory
3802 index represents a null pointer.
3803
3804 @d null 0 /* the null pointer */
3805 @d mp_void (null+1) /* a null pointer different from |null| */
3806
3807
3808 @<Types...@>=
3809 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3810
3811 @ The |mem| array is divided into two regions that are allocated separately,
3812 but the dividing line between these two regions is not fixed; they grow
3813 together until finding their ``natural'' size in a particular job.
3814 Locations less than or equal to |lo_mem_max| are used for storing
3815 variable-length records consisting of two or more words each. This region
3816 is maintained using an algorithm similar to the one described in exercise
3817 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3818 appears in the allocated nodes; the program is responsible for knowing the
3819 relevant size when a node is freed. Locations greater than or equal to
3820 |hi_mem_min| are used for storing one-word records; a conventional
3821 \.{AVAIL} stack is used for allocation in this region.
3822
3823 Locations of |mem| between |0| and |mem_top| may be dumped as part
3824 of preloaded format files, by the \.{INIMP} preprocessor.
3825 @.INIMP@>
3826 Production versions of \MP\ may extend the memory at the top end in order to
3827 provide more space; these locations, between |mem_top| and |mem_max|,
3828 are always used for single-word nodes.
3829
3830 The key pointers that govern |mem| allocation have a prescribed order:
3831 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3832
3833 @<Glob...@>=
3834 memory_word *mem; /* the big dynamic storage area */
3835 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3836 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3837
3838
3839
3840 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3841 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3842 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3843 @d xstrdup(A)  mp_xstrdup(mp,A)
3844 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3845
3846 @<Declare helpers@>=
3847 void mp_xfree (void *x);
3848 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3849 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3850 char *mp_xstrdup(MP mp, const char *s);
3851
3852 @ The |max_size_test| guards against overflow, on the assumption that
3853 |size_t| is at least 31bits wide.
3854
3855 @d max_size_test 0x7FFFFFFF
3856
3857 @c
3858 void mp_xfree (void *x) {
3859   if (x!=NULL) free(x);
3860 }
3861 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3862   void *w ; 
3863   if ((max_size_test/size)<nmem) {
3864     do_fprintf(mp->err_out,"Memory size overflow!\n");
3865     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3866   }
3867   w = realloc (p,(nmem*size));
3868   if (w==NULL) {
3869     do_fprintf(mp->err_out,"Out of memory!\n");
3870     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3871   }
3872   return w;
3873 }
3874 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3875   void *w;
3876   if ((max_size_test/size)<nmem) {
3877     do_fprintf(mp->err_out,"Memory size overflow!\n");
3878     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3879   }
3880   w = malloc (nmem*size);
3881   if (w==NULL) {
3882     do_fprintf(mp->err_out,"Out of memory!\n");
3883     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3884   }
3885   return w;
3886 }
3887 char *mp_xstrdup(MP mp, const char *s) {
3888   char *w; 
3889   if (s==NULL)
3890     return NULL;
3891   w = strdup(s);
3892   if (w==NULL) {
3893     do_fprintf(mp->err_out,"Out of memory!\n");
3894     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3895   }
3896   return w;
3897 }
3898
3899
3900
3901 @<Allocate or initialize ...@>=
3902 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3903 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3904
3905 @ @<Dealloc variables@>=
3906 xfree(mp->mem);
3907
3908 @ Users who wish to study the memory requirements of particular applications can
3909 can use optional special features that keep track of current and
3910 maximum memory usage. When code between the delimiters |stat| $\ldots$
3911 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3912 report these statistics when |mp_tracing_stats| is positive.
3913
3914 @<Glob...@>=
3915 integer var_used; integer dyn_used; /* how much memory is in use */
3916
3917 @ Let's consider the one-word memory region first, since it's the
3918 simplest. The pointer variable |mem_end| holds the highest-numbered location
3919 of |mem| that has ever been used. The free locations of |mem| that
3920 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3921 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3922 and |rh| fields of |mem[p]| when it is of this type. The single-word
3923 free locations form a linked list
3924 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3925 terminated by |null|.
3926
3927 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3928 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3929
3930 @<Glob...@>=
3931 pointer avail; /* head of the list of available one-word nodes */
3932 pointer mem_end; /* the last one-word node used in |mem| */
3933
3934 @ If one-word memory is exhausted, it might mean that the user has forgotten
3935 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3936 later that try to help pinpoint the trouble.
3937
3938 @c 
3939 @<Declare the procedure called |show_token_list|@>;
3940 @<Declare the procedure called |runaway|@>
3941
3942 @ The function |get_avail| returns a pointer to a new one-word node whose
3943 |link| field is null. However, \MP\ will halt if there is no more room left.
3944 @^inner loop@>
3945
3946 @c 
3947 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3948   pointer p; /* the new node being got */
3949   p=mp->avail; /* get top location in the |avail| stack */
3950   if ( p!=null ) {
3951     mp->avail=link(mp->avail); /* and pop it off */
3952   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3953     incr(mp->mem_end); p=mp->mem_end;
3954   } else { 
3955     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3956     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3957       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3958       mp_overflow(mp, "main memory size",mp->mem_max);
3959       /* quit; all one-word nodes are busy */
3960 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3961     }
3962   }
3963   link(p)=null; /* provide an oft-desired initialization of the new node */
3964   incr(mp->dyn_used);/* maintain statistics */
3965   return p;
3966 };
3967
3968 @ Conversely, a one-word node is recycled by calling |free_avail|.
3969
3970 @d free_avail(A)  /* single-word node liberation */
3971   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3972
3973 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3974 overhead at the expense of extra programming. This macro is used in
3975 the places that would otherwise account for the most calls of |get_avail|.
3976 @^inner loop@>
3977
3978 @d fast_get_avail(A) { 
3979   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
3980   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
3981   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
3982   }
3983
3984 @ The available-space list that keeps track of the variable-size portion
3985 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3986 pointed to by the roving pointer |rover|.
3987
3988 Each empty node has size 2 or more; the first word contains the special
3989 value |max_halfword| in its |link| field and the size in its |info| field;
3990 the second word contains the two pointers for double linking.
3991
3992 Each nonempty node also has size 2 or more. Its first word is of type
3993 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3994 Otherwise there is complete flexibility with respect to the contents
3995 of its other fields and its other words.
3996
3997 (We require |mem_max<max_halfword| because terrible things can happen
3998 when |max_halfword| appears in the |link| field of a nonempty node.)
3999
4000 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4001 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4002 @d node_size   info /* the size field in empty variable-size nodes */
4003 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4004 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4005
4006 @<Glob...@>=
4007 pointer rover; /* points to some node in the list of empties */
4008
4009 @ A call to |get_node| with argument |s| returns a pointer to a new node
4010 of size~|s|, which must be 2~or more. The |link| field of the first word
4011 of this new node is set to null. An overflow stop occurs if no suitable
4012 space exists.
4013
4014 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4015 areas and returns the value |max_halfword|.
4016
4017 @<Internal library declarations@>=
4018 pointer mp_get_node (MP mp,integer s) ;
4019
4020 @ @c 
4021 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4022   pointer p; /* the node currently under inspection */
4023   pointer q;  /* the node physically after node |p| */
4024   integer r; /* the newly allocated node, or a candidate for this honor */
4025   integer t,tt; /* temporary registers */
4026 @^inner loop@>
4027  RESTART: 
4028   p=mp->rover; /* start at some free node in the ring */
4029   do {  
4030     @<Try to allocate within node |p| and its physical successors,
4031      and |goto found| if allocation was possible@>;
4032     if (rlink(p)==null || rlink(p)==p) {
4033       print_err("Free list garbled");
4034       help3("I found an entry in the list of free nodes that links")
4035        ("badly. I will try to ignore the broken link, but something")
4036        ("is seriously amiss. It is wise to warn the maintainers.")
4037           mp_error(mp);
4038       rlink(p)=mp->rover;
4039     }
4040         p=rlink(p); /* move to the next node in the ring */
4041   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4042   if ( s==010000000000 ) { 
4043     return max_halfword;
4044   };
4045   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4046     if ( mp->lo_mem_max+2<=max_halfword ) {
4047       @<Grow more variable-size memory and |goto restart|@>;
4048     }
4049   }
4050   mp_overflow(mp, "main memory size",mp->mem_max);
4051   /* sorry, nothing satisfactory is left */
4052 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4053 FOUND: 
4054   link(r)=null; /* this node is now nonempty */
4055   mp->var_used+=s; /* maintain usage statistics */
4056   return r;
4057 }
4058
4059 @ The lower part of |mem| grows by 1000 words at a time, unless
4060 we are very close to going under. When it grows, we simply link
4061 a new node into the available-space list. This method of controlled
4062 growth helps to keep the |mem| usage consecutive when \MP\ is
4063 implemented on ``virtual memory'' systems.
4064 @^virtual memory@>
4065
4066 @<Grow more variable-size memory and |goto restart|@>=
4067
4068   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4069     t=mp->lo_mem_max+1000;
4070   } else {
4071     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4072     /* |lo_mem_max+2<=t<hi_mem_min| */
4073   }
4074   if ( t>max_halfword ) t=max_halfword;
4075   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4076   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4077   node_size(q)=t-mp->lo_mem_max;
4078   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4079   mp->rover=q; 
4080   goto RESTART;
4081 }
4082
4083 @ @<Try to allocate...@>=
4084 q=p+node_size(p); /* find the physical successor */
4085 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4086   t=rlink(q); tt=llink(q);
4087 @^inner loop@>
4088   if ( q==mp->rover ) mp->rover=t;
4089   llink(t)=tt; rlink(tt)=t;
4090   q=q+node_size(q);
4091 }
4092 r=q-s;
4093 if ( r>p+1 ) {
4094   @<Allocate from the top of node |p| and |goto found|@>;
4095 }
4096 if ( r==p ) { 
4097   if ( rlink(p)!=p ) {
4098     @<Allocate entire node |p| and |goto found|@>;
4099   }
4100 }
4101 node_size(p)=q-p /* reset the size in case it grew */
4102
4103 @ @<Allocate from the top...@>=
4104
4105   node_size(p)=r-p; /* store the remaining size */
4106   mp->rover=p; /* start searching here next time */
4107   goto FOUND;
4108 }
4109
4110 @ Here we delete node |p| from the ring, and let |rover| rove around.
4111
4112 @<Allocate entire...@>=
4113
4114   mp->rover=rlink(p); t=llink(p);
4115   llink(mp->rover)=t; rlink(t)=mp->rover;
4116   goto FOUND;
4117 }
4118
4119 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4120 the operation |free_node(p,s)| will make its words available, by inserting
4121 |p| as a new empty node just before where |rover| now points.
4122
4123 @<Internal library declarations@>=
4124 void mp_free_node (MP mp, pointer p, halfword s) ;
4125
4126 @ @c 
4127 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4128   liberation */
4129   pointer q; /* |llink(rover)| */
4130   node_size(p)=s; link(p)=empty_flag;
4131 @^inner loop@>
4132   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4133   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4134   mp->var_used-=s; /* maintain statistics */
4135 }
4136
4137 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4138 available space list. The list is probably very short at such times, so a
4139 simple insertion sort is used. The smallest available location will be
4140 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4141
4142 @c 
4143 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4144   by location */
4145   pointer p,q,r; /* indices into |mem| */
4146   pointer old_rover; /* initial |rover| setting */
4147   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4148   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4149   while ( p!=old_rover ) {
4150     @<Sort |p| into the list starting at |rover|
4151      and advance |p| to |rlink(p)|@>;
4152   }
4153   p=mp->rover;
4154   while ( rlink(p)!=max_halfword ) { 
4155     llink(rlink(p))=p; p=rlink(p);
4156   };
4157   rlink(p)=mp->rover; llink(mp->rover)=p;
4158 }
4159
4160 @ The following |while| loop is guaranteed to
4161 terminate, since the list that starts at
4162 |rover| ends with |max_halfword| during the sorting procedure.
4163
4164 @<Sort |p|...@>=
4165 if ( p<mp->rover ) { 
4166   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4167 } else  { 
4168   q=mp->rover;
4169   while ( rlink(q)<p ) q=rlink(q);
4170   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4171 }
4172
4173 @* \[11] Memory layout.
4174 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4175 more efficient than dynamic allocation when we can get away with it. For
4176 example, locations |0| to |1| are always used to store a
4177 two-word dummy token whose second word is zero.
4178 The following macro definitions accomplish the static allocation by giving
4179 symbolic names to the fixed positions. Static variable-size nodes appear
4180 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4181 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4182
4183 @d null_dash (2) /* the first two words are reserved for a null value */
4184 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4185 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4186 @d temp_val (zero_val+2) /* two words for a temporary value node */
4187 @d end_attr temp_val /* we use |end_attr+2| only */
4188 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4189 @d test_pen (inf_val+2)
4190   /* nine words for a pen used when testing the turning number */
4191 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4192 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4193   allocated word in the variable-size |mem| */
4194 @#
4195 @d sentinel mp->mem_top /* end of sorted lists */
4196 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4197 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4198 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4199 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4200   the one-word |mem| */
4201
4202 @ The following code gets the dynamic part of |mem| off to a good start,
4203 when \MP\ is initializing itself the slow way.
4204
4205 @<Initialize table entries (done by \.{INIMP} only)@>=
4206 @^data structure assumptions@>
4207 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4208 link(mp->rover)=empty_flag;
4209 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4210 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4211 mp->lo_mem_max=mp->rover+1000; 
4212 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4213 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4214   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4215 }
4216 mp->avail=null; mp->mem_end=mp->mem_top;
4217 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4218 mp->var_used=lo_mem_stat_max+1; 
4219 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4220 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4221
4222 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4223 nodes that starts at a given position, until coming to |sentinel| or a
4224 pointer that is not in the one-word region. Another procedure,
4225 |flush_node_list|, frees an entire linked list of one-word and two-word
4226 nodes, until coming to a |null| pointer.
4227 @^inner loop@>
4228
4229 @c 
4230 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4231   pointer q,r; /* list traversers */
4232   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4233     r=p;
4234     do {  
4235       q=r; r=link(r); 
4236       decr(mp->dyn_used);
4237       if ( r<mp->hi_mem_min ) break;
4238     } while (r!=sentinel);
4239   /* now |q| is the last node on the list */
4240     link(q)=mp->avail; mp->avail=p;
4241   }
4242 }
4243 @#
4244 void mp_flush_node_list (MP mp,pointer p) {
4245   pointer q; /* the node being recycled */
4246   while ( p!=null ){ 
4247     q=p; p=link(p);
4248     if ( q<mp->hi_mem_min ) 
4249       mp_free_node(mp, q,2);
4250     else 
4251       free_avail(q);
4252   }
4253 }
4254
4255 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4256 For example, some pointers might be wrong, or some ``dead'' nodes might not
4257 have been freed when the last reference to them disappeared. Procedures
4258 |check_mem| and |search_mem| are available to help diagnose such
4259 problems. These procedures make use of two arrays called |free| and
4260 |was_free| that are present only if \MP's debugging routines have
4261 been included. (You may want to decrease the size of |mem| while you
4262 @^debugging@>
4263 are debugging.)
4264
4265 Because |boolean|s are typedef-d as ints, it is better to use
4266 unsigned chars here.
4267
4268 @<Glob...@>=
4269 unsigned char *free; /* free cells */
4270 unsigned char *was_free; /* previously free cells */
4271 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4272   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4273 boolean panicking; /* do we want to check memory constantly? */
4274
4275 @ @<Allocate or initialize ...@>=
4276 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4277 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4278
4279 @ @<Dealloc variables@>=
4280 xfree(mp->free);
4281 xfree(mp->was_free);
4282
4283 @ @<Allocate or ...@>=
4284 mp->was_mem_end=0; /* indicate that everything was previously free */
4285 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4286 mp->panicking=false;
4287
4288 @ @<Declare |mp_reallocate| functions@>=
4289 void mp_reallocate_memory(MP mp, int l) ;
4290
4291 @ @c
4292 void mp_reallocate_memory(MP mp, int l) {
4293    XREALLOC(mp->free,     l, unsigned char);
4294    XREALLOC(mp->was_free, l, unsigned char);
4295    if (mp->mem) {
4296          int newarea = l-mp->mem_max;
4297      XREALLOC(mp->mem,      l, memory_word);
4298      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4299    } else {
4300      XREALLOC(mp->mem,      l, memory_word);
4301      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4302    }
4303    mp->mem_max = l;
4304    if (mp->ini_version) 
4305      mp->mem_top = l;
4306 }
4307
4308
4309
4310 @ Procedure |check_mem| makes sure that the available space lists of
4311 |mem| are well formed, and it optionally prints out all locations
4312 that are reserved now but were free the last time this procedure was called.
4313
4314 @c 
4315 void mp_check_mem (MP mp,boolean print_locs ) {
4316   pointer p,q,r; /* current locations of interest in |mem| */
4317   boolean clobbered; /* is something amiss? */
4318   for (p=0;p<=mp->lo_mem_max;p++) {
4319     mp->free[p]=false; /* you can probably do this faster */
4320   }
4321   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4322     mp->free[p]=false; /* ditto */
4323   }
4324   @<Check single-word |avail| list@>;
4325   @<Check variable-size |avail| list@>;
4326   @<Check flags of unavailable nodes@>;
4327   @<Check the list of linear dependencies@>;
4328   if ( print_locs ) {
4329     @<Print newly busy locations@>;
4330   }
4331   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4332   mp->was_mem_end=mp->mem_end; 
4333   mp->was_lo_max=mp->lo_mem_max; 
4334   mp->was_hi_min=mp->hi_mem_min;
4335 }
4336
4337 @ @<Check single-word...@>=
4338 p=mp->avail; q=null; clobbered=false;
4339 while ( p!=null ) { 
4340   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4341   else if ( mp->free[p] ) clobbered=true;
4342   if ( clobbered ) { 
4343     mp_print_nl(mp, "AVAIL list clobbered at ");
4344 @.AVAIL list clobbered...@>
4345     mp_print_int(mp, q); break;
4346   }
4347   mp->free[p]=true; q=p; p=link(q);
4348 }
4349
4350 @ @<Check variable-size...@>=
4351 p=mp->rover; q=null; clobbered=false;
4352 do {  
4353   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4354   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4355   else if (  !(is_empty(p))||(node_size(p)<2)||
4356    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4357   if ( clobbered ) { 
4358     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4359 @.Double-AVAIL list clobbered...@>
4360     mp_print_int(mp, q); break;
4361   }
4362   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4363     if ( mp->free[q] ) { 
4364       mp_print_nl(mp, "Doubly free location at ");
4365 @.Doubly free location...@>
4366       mp_print_int(mp, q); break;
4367     }
4368     mp->free[q]=true;
4369   }
4370   q=p; p=rlink(p);
4371 } while (p!=mp->rover)
4372
4373
4374 @ @<Check flags...@>=
4375 p=0;
4376 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4377   if ( is_empty(p) ) {
4378     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4379 @.Bad flag...@>
4380   }
4381   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4382   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4383 }
4384
4385 @ @<Print newly busy...@>=
4386
4387   @<Do intialization required before printing new busy locations@>;
4388   mp_print_nl(mp, "New busy locs:");
4389 @.New busy locs@>
4390   for (p=0;p<= mp->lo_mem_max;p++ ) {
4391     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4392       @<Indicate that |p| is a new busy location@>;
4393     }
4394   }
4395   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4396     if ( ! mp->free[p] &&
4397         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4398       @<Indicate that |p| is a new busy location@>;
4399     }
4400   }
4401   @<Finish printing new busy locations@>;
4402 }
4403
4404 @ There might be many new busy locations so we are careful to print contiguous
4405 blocks compactly.  During this operation |q| is the last new busy location and
4406 |r| is the start of the block containing |q|.
4407
4408 @<Indicate that |p| is a new busy location@>=
4409
4410   if ( p>q+1 ) { 
4411     if ( q>r ) { 
4412       mp_print(mp, ".."); mp_print_int(mp, q);
4413     }
4414     mp_print_char(mp, ' '); mp_print_int(mp, p);
4415     r=p;
4416   }
4417   q=p;
4418 }
4419
4420 @ @<Do intialization required before printing new busy locations@>=
4421 q=mp->mem_max; r=mp->mem_max
4422
4423 @ @<Finish printing new busy locations@>=
4424 if ( q>r ) { 
4425   mp_print(mp, ".."); mp_print_int(mp, q);
4426 }
4427
4428 @ The |search_mem| procedure attempts to answer the question ``Who points
4429 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4430 that might not be of type |two_halves|. Strictly speaking, this is
4431 undefined, and it can lead to ``false drops'' (words that seem to
4432 point to |p| purely by coincidence). But for debugging purposes, we want
4433 to rule out the places that do {\sl not\/} point to |p|, so a few false
4434 drops are tolerable.
4435
4436 @c
4437 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4438   integer q; /* current position being searched */
4439   for (q=0;q<=mp->lo_mem_max;q++) { 
4440     if ( link(q)==p ){ 
4441       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4442     }
4443     if ( info(q)==p ) { 
4444       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4445     }
4446   }
4447   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4448     if ( link(q)==p ) {
4449       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4450     }
4451     if ( info(q)==p ) {
4452       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4453     }
4454   }
4455   @<Search |eqtb| for equivalents equal to |p|@>;
4456 }
4457
4458 @* \[12] The command codes.
4459 Before we can go much further, we need to define symbolic names for the internal
4460 code numbers that represent the various commands obeyed by \MP. These codes
4461 are somewhat arbitrary, but not completely so. For example,
4462 some codes have been made adjacent so that |case| statements in the
4463 program need not consider cases that are widely spaced, or so that |case|
4464 statements can be replaced by |if| statements. A command can begin an
4465 expression if and only if its code lies between |min_primary_command| and
4466 |max_primary_command|, inclusive. The first token of a statement that doesn't
4467 begin with an expression has a command code between |min_command| and
4468 |max_statement_command|, inclusive. Anything less than |min_command| is
4469 eliminated during macro expansions, and anything no more than |max_pre_command|
4470 is eliminated when expanding \TeX\ material.  Ranges such as
4471 |min_secondary_command..max_secondary_command| are used when parsing
4472 expressions, but the relative ordering within such a range is generally not
4473 critical.
4474
4475 The ordering of the highest-numbered commands
4476 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4477 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4478 for the smallest two commands.  The ordering is also important in the ranges
4479 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4480
4481 At any rate, here is the list, for future reference.
4482
4483 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4484 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4485 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4486 @d max_pre_command mpx_break
4487 @d if_test 4 /* conditional text (\&{if}) */
4488 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi} */
4489 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4490 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4491 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4492 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4493 @d relax 10 /* do nothing (\.{\char`\\}) */
4494 @d scan_tokens 11 /* put a string into the input buffer */
4495 @d expand_after 12 /* look ahead one token */
4496 @d defined_macro 13 /* a macro defined by the user */
4497 @d min_command (defined_macro+1)
4498 @d save_command 14 /* save a list of tokens (\&{save}) */
4499 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4500 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4501 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4502 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4503 @d ship_out_command 19 /* output a character (\&{shipout}) */
4504 @d add_to_command 20 /* add to edges (\&{addto}) */
4505 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4506 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4507 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4508 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4509 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4510 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4511 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4512 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4513 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4514 @d special_command 30 /* output special info (\&{special})
4515                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4516 @d write_command 31 /* write text to a file (\&{write}) */
4517 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc. */
4518 @d max_statement_command type_name
4519 @d min_primary_command type_name
4520 @d left_delimiter 33 /* the left delimiter of a matching pair */
4521 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4522 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4523 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4524 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4525 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4526 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4527 @d capsule_token 40 /* a value that has been put into a token list */
4528 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4529 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4530 @d min_suffix_token internal_quantity
4531 @d tag_token 43 /* a symbolic token without a primitive meaning */
4532 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4533 @d max_suffix_token numeric_token
4534 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4535 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4536 @d min_tertiary_command plus_or_minus
4537 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4538 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4539 @d max_tertiary_command tertiary_binary
4540 @d left_brace 48 /* the operator `\.{\char`\{}' */
4541 @d min_expression_command left_brace
4542 @d path_join 49 /* the operator `\.{..}' */
4543 @d ampersand 50 /* the operator `\.\&' */
4544 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4545 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4546 @d equals 53 /* the operator `\.=' */
4547 @d max_expression_command equals
4548 @d and_command 54 /* the operator `\&{and}' */
4549 @d min_secondary_command and_command
4550 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4551 @d slash 56 /* the operator `\./' */
4552 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4553 @d max_secondary_command secondary_binary
4554 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4555 @d controls 59 /* specify control points explicitly (\&{controls}) */
4556 @d tension 60 /* specify tension between knots (\&{tension}) */
4557 @d at_least 61 /* bounded tension value (\&{atleast}) */
4558 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4559 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4560 @d right_delimiter 64 /* the right delimiter of a matching pair */
4561 @d left_bracket 65 /* the operator `\.[' */
4562 @d right_bracket 66 /* the operator `\.]' */
4563 @d right_brace 67 /* the operator `\.{\char`\}}' */
4564 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4565 @d thing_to_add 69
4566   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4567 @d of_token 70 /* the operator `\&{of}' */
4568 @d to_token 71 /* the operator `\&{to}' */
4569 @d step_token 72 /* the operator `\&{step}' */
4570 @d until_token 73 /* the operator `\&{until}' */
4571 @d within_token 74 /* the operator `\&{within}' */
4572 @d lig_kern_token 75
4573   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}, etc. */
4574 @d assignment 76 /* the operator `\.{:=}' */
4575 @d skip_to 77 /* the operation `\&{skipto}' */
4576 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4577 @d double_colon 79 /* the operator `\.{::}' */
4578 @d colon 80 /* the operator `\.:' */
4579 @#
4580 @d comma 81 /* the operator `\.,', must be |colon+1| */
4581 @d end_of_statement (mp->cur_cmd>comma)
4582 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4583 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4584 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4585 @d max_command_code stop
4586 @d outer_tag (max_command_code+1) /* protection code added to command code */
4587
4588 @<Types...@>=
4589 typedef int command_code;
4590
4591 @ Variables and capsules in \MP\ have a variety of ``types,''
4592 distinguished by the code numbers defined here. These numbers are also
4593 not completely arbitrary.  Things that get expanded must have types
4594 |>mp_independent|; a type remaining after expansion is numeric if and only if
4595 its code number is at least |numeric_type|; objects containing numeric
4596 parts must have types between |transform_type| and |pair_type|;
4597 all other types must be smaller than |transform_type|; and among the types
4598 that are not unknown or vacuous, the smallest two must be |boolean_type|
4599 and |string_type| in that order.
4600  
4601 @d undefined 0 /* no type has been declared */
4602 @d unknown_tag 1 /* this constant is added to certain type codes below */
4603 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4604   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4605
4606 @<Types...@>=
4607 enum mp_variable_type {
4608 mp_vacuous=1, /* no expression was present */
4609 mp_boolean_type, /* \&{boolean} with a known value */
4610 mp_unknown_boolean,
4611 mp_string_type, /* \&{string} with a known value */
4612 mp_unknown_string,
4613 mp_pen_type, /* \&{pen} with a known value */
4614 mp_unknown_pen,
4615 mp_path_type, /* \&{path} with a known value */
4616 mp_unknown_path,
4617 mp_picture_type, /* \&{picture} with a known value */
4618 mp_unknown_picture,
4619 mp_transform_type, /* \&{transform} variable or capsule */
4620 mp_color_type, /* \&{color} variable or capsule */
4621 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4622 mp_pair_type, /* \&{pair} variable or capsule */
4623 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4624 mp_known, /* \&{numeric} with a known value */
4625 mp_dependent, /* a linear combination with |fraction| coefficients */
4626 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4627 mp_independent, /* \&{numeric} with unknown value */
4628 mp_token_list, /* variable name or suffix argument or text argument */
4629 mp_structured, /* variable with subscripts and attributes */
4630 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4631 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4632 } ;
4633
4634 @ @<Declarations@>=
4635 void mp_print_type (MP mp,small_number t) ;
4636
4637 @ @<Basic printing procedures@>=
4638 void mp_print_type (MP mp,small_number t) { 
4639   switch (t) {
4640   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4641   case mp_boolean_type:mp_print(mp, "boolean"); break;
4642   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4643   case mp_string_type:mp_print(mp, "string"); break;
4644   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4645   case mp_pen_type:mp_print(mp, "pen"); break;
4646   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4647   case mp_path_type:mp_print(mp, "path"); break;
4648   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4649   case mp_picture_type:mp_print(mp, "picture"); break;
4650   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4651   case mp_transform_type:mp_print(mp, "transform"); break;
4652   case mp_color_type:mp_print(mp, "color"); break;
4653   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4654   case mp_pair_type:mp_print(mp, "pair"); break;
4655   case mp_known:mp_print(mp, "known numeric"); break;
4656   case mp_dependent:mp_print(mp, "dependent"); break;
4657   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4658   case mp_numeric_type:mp_print(mp, "numeric"); break;
4659   case mp_independent:mp_print(mp, "independent"); break;
4660   case mp_token_list:mp_print(mp, "token list"); break;
4661   case mp_structured:mp_print(mp, "mp_structured"); break;
4662   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4663   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4664   default: mp_print(mp, "undefined"); break;
4665   }
4666 }
4667
4668 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4669 as well as a |type|. The possibilities for |name_type| are defined
4670 here; they will be explained in more detail later.
4671
4672 @<Types...@>=
4673 enum mp_name_type {
4674  mp_root=0, /* |name_type| at the top level of a variable */
4675  mp_saved_root, /* same, when the variable has been saved */
4676  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4677  mp_subscr, /* |name_type| in a subscript node */
4678  mp_attr, /* |name_type| in an attribute node */
4679  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4680  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4681  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4682  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4683  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4684  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4685  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4686  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4687  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4688  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4689  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4690  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4691  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4692  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4693  mp_capsule, /* |name_type| in stashed-away subexpressions */
4694  mp_token  /* |name_type| in a numeric token or string token */
4695 };
4696
4697 @ Primitive operations that produce values have a secondary identification
4698 code in addition to their command code; it's something like genera and species.
4699 For example, `\.*' has the command code |primary_binary|, and its
4700 secondary identification is |times|. The secondary codes start at 30 so that
4701 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4702 are used as operators as well as type identifications.  The relative values
4703 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4704 and |filled_op..bounded_op|.  The restrictions are that
4705 |and_op-false_code=or_op-true_code|, that the ordering of
4706 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4707 and the ordering of |filled_op..bounded_op| must match that of the code
4708 values they test for.
4709
4710 @d true_code 30 /* operation code for \.{true} */
4711 @d false_code 31 /* operation code for \.{false} */
4712 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4713 @d null_pen_code 33 /* operation code for \.{nullpen} */
4714 @d job_name_op 34 /* operation code for \.{jobname} */
4715 @d read_string_op 35 /* operation code for \.{readstring} */
4716 @d pen_circle 36 /* operation code for \.{pencircle} */
4717 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4718 @d read_from_op 38 /* operation code for \.{readfrom} */
4719 @d close_from_op 39 /* operation code for \.{closefrom} */
4720 @d odd_op 40 /* operation code for \.{odd} */
4721 @d known_op 41 /* operation code for \.{known} */
4722 @d unknown_op 42 /* operation code for \.{unknown} */
4723 @d not_op 43 /* operation code for \.{not} */
4724 @d decimal 44 /* operation code for \.{decimal} */
4725 @d reverse 45 /* operation code for \.{reverse} */
4726 @d make_path_op 46 /* operation code for \.{makepath} */
4727 @d make_pen_op 47 /* operation code for \.{makepen} */
4728 @d oct_op 48 /* operation code for \.{oct} */
4729 @d hex_op 49 /* operation code for \.{hex} */
4730 @d ASCII_op 50 /* operation code for \.{ASCII} */
4731 @d char_op 51 /* operation code for \.{char} */
4732 @d length_op 52 /* operation code for \.{length} */
4733 @d turning_op 53 /* operation code for \.{turningnumber} */
4734 @d color_model_part 54 /* operation code for \.{colormodel} */
4735 @d x_part 55 /* operation code for \.{xpart} */
4736 @d y_part 56 /* operation code for \.{ypart} */
4737 @d xx_part 57 /* operation code for \.{xxpart} */
4738 @d xy_part 58 /* operation code for \.{xypart} */
4739 @d yx_part 59 /* operation code for \.{yxpart} */
4740 @d yy_part 60 /* operation code for \.{yypart} */
4741 @d red_part 61 /* operation code for \.{redpart} */
4742 @d green_part 62 /* operation code for \.{greenpart} */
4743 @d blue_part 63 /* operation code for \.{bluepart} */
4744 @d cyan_part 64 /* operation code for \.{cyanpart} */
4745 @d magenta_part 65 /* operation code for \.{magentapart} */
4746 @d yellow_part 66 /* operation code for \.{yellowpart} */
4747 @d black_part 67 /* operation code for \.{blackpart} */
4748 @d grey_part 68 /* operation code for \.{greypart} */
4749 @d font_part 69 /* operation code for \.{fontpart} */
4750 @d text_part 70 /* operation code for \.{textpart} */
4751 @d path_part 71 /* operation code for \.{pathpart} */
4752 @d pen_part 72 /* operation code for \.{penpart} */
4753 @d dash_part 73 /* operation code for \.{dashpart} */
4754 @d sqrt_op 74 /* operation code for \.{sqrt} */
4755 @d m_exp_op 75 /* operation code for \.{mexp} */
4756 @d m_log_op 76 /* operation code for \.{mlog} */
4757 @d sin_d_op 77 /* operation code for \.{sind} */
4758 @d cos_d_op 78 /* operation code for \.{cosd} */
4759 @d floor_op 79 /* operation code for \.{floor} */
4760 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4761 @d char_exists_op 81 /* operation code for \.{charexists} */
4762 @d font_size 82 /* operation code for \.{fontsize} */
4763 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4764 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4765 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4766 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4767 @d arc_length 87 /* operation code for \.{arclength} */
4768 @d angle_op 88 /* operation code for \.{angle} */
4769 @d cycle_op 89 /* operation code for \.{cycle} */
4770 @d filled_op 90 /* operation code for \.{filled} */
4771 @d stroked_op 91 /* operation code for \.{stroked} */
4772 @d textual_op 92 /* operation code for \.{textual} */
4773 @d clipped_op 93 /* operation code for \.{clipped} */
4774 @d bounded_op 94 /* operation code for \.{bounded} */
4775 @d plus 95 /* operation code for \.+ */
4776 @d minus 96 /* operation code for \.- */
4777 @d times 97 /* operation code for \.* */
4778 @d over 98 /* operation code for \./ */
4779 @d pythag_add 99 /* operation code for \.{++} */
4780 @d pythag_sub 100 /* operation code for \.{+-+} */
4781 @d or_op 101 /* operation code for \.{or} */
4782 @d and_op 102 /* operation code for \.{and} */
4783 @d less_than 103 /* operation code for \.< */
4784 @d less_or_equal 104 /* operation code for \.{<=} */
4785 @d greater_than 105 /* operation code for \.> */
4786 @d greater_or_equal 106 /* operation code for \.{>=} */
4787 @d equal_to 107 /* operation code for \.= */
4788 @d unequal_to 108 /* operation code for \.{<>} */
4789 @d concatenate 109 /* operation code for \.\& */
4790 @d rotated_by 110 /* operation code for \.{rotated} */
4791 @d slanted_by 111 /* operation code for \.{slanted} */
4792 @d scaled_by 112 /* operation code for \.{scaled} */
4793 @d shifted_by 113 /* operation code for \.{shifted} */
4794 @d transformed_by 114 /* operation code for \.{transformed} */
4795 @d x_scaled 115 /* operation code for \.{xscaled} */
4796 @d y_scaled 116 /* operation code for \.{yscaled} */
4797 @d z_scaled 117 /* operation code for \.{zscaled} */
4798 @d in_font 118 /* operation code for \.{infont} */
4799 @d intersect 119 /* operation code for \.{intersectiontimes} */
4800 @d double_dot 120 /* operation code for improper \.{..} */
4801 @d substring_of 121 /* operation code for \.{substring} */
4802 @d min_of substring_of
4803 @d subpath_of 122 /* operation code for \.{subpath} */
4804 @d direction_time_of 123 /* operation code for \.{directiontime} */
4805 @d point_of 124 /* operation code for \.{point} */
4806 @d precontrol_of 125 /* operation code for \.{precontrol} */
4807 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4808 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4809 @d arc_time_of 128 /* operation code for \.{arctime} */
4810 @d mp_version 129 /* operation code for \.{mpversion} */
4811 @d envelope_of 130 /* operation code for \.{envelope} */
4812
4813 @c void mp_print_op (MP mp,quarterword c) { 
4814   if (c<=mp_numeric_type ) {
4815     mp_print_type(mp, c);
4816   } else {
4817     switch (c) {
4818     case true_code:mp_print(mp, "true"); break;
4819     case false_code:mp_print(mp, "false"); break;
4820     case null_picture_code:mp_print(mp, "nullpicture"); break;
4821     case null_pen_code:mp_print(mp, "nullpen"); break;
4822     case job_name_op:mp_print(mp, "jobname"); break;
4823     case read_string_op:mp_print(mp, "readstring"); break;
4824     case pen_circle:mp_print(mp, "pencircle"); break;
4825     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4826     case read_from_op:mp_print(mp, "readfrom"); break;
4827     case close_from_op:mp_print(mp, "closefrom"); break;
4828     case odd_op:mp_print(mp, "odd"); break;
4829     case known_op:mp_print(mp, "known"); break;
4830     case unknown_op:mp_print(mp, "unknown"); break;
4831     case not_op:mp_print(mp, "not"); break;
4832     case decimal:mp_print(mp, "decimal"); break;
4833     case reverse:mp_print(mp, "reverse"); break;
4834     case make_path_op:mp_print(mp, "makepath"); break;
4835     case make_pen_op:mp_print(mp, "makepen"); break;
4836     case oct_op:mp_print(mp, "oct"); break;
4837     case hex_op:mp_print(mp, "hex"); break;
4838     case ASCII_op:mp_print(mp, "ASCII"); break;
4839     case char_op:mp_print(mp, "char"); break;
4840     case length_op:mp_print(mp, "length"); break;
4841     case turning_op:mp_print(mp, "turningnumber"); break;
4842     case x_part:mp_print(mp, "xpart"); break;
4843     case y_part:mp_print(mp, "ypart"); break;
4844     case xx_part:mp_print(mp, "xxpart"); break;
4845     case xy_part:mp_print(mp, "xypart"); break;
4846     case yx_part:mp_print(mp, "yxpart"); break;
4847     case yy_part:mp_print(mp, "yypart"); break;
4848     case red_part:mp_print(mp, "redpart"); break;
4849     case green_part:mp_print(mp, "greenpart"); break;
4850     case blue_part:mp_print(mp, "bluepart"); break;
4851     case cyan_part:mp_print(mp, "cyanpart"); break;
4852     case magenta_part:mp_print(mp, "magentapart"); break;
4853     case yellow_part:mp_print(mp, "yellowpart"); break;
4854     case black_part:mp_print(mp, "blackpart"); break;
4855     case grey_part:mp_print(mp, "greypart"); break;
4856     case color_model_part:mp_print(mp, "colormodel"); break;
4857     case font_part:mp_print(mp, "fontpart"); break;
4858     case text_part:mp_print(mp, "textpart"); break;
4859     case path_part:mp_print(mp, "pathpart"); break;
4860     case pen_part:mp_print(mp, "penpart"); break;
4861     case dash_part:mp_print(mp, "dashpart"); break;
4862     case sqrt_op:mp_print(mp, "sqrt"); break;
4863     case m_exp_op:mp_print(mp, "mexp"); break;
4864     case m_log_op:mp_print(mp, "mlog"); break;
4865     case sin_d_op:mp_print(mp, "sind"); break;
4866     case cos_d_op:mp_print(mp, "cosd"); break;
4867     case floor_op:mp_print(mp, "floor"); break;
4868     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4869     case char_exists_op:mp_print(mp, "charexists"); break;
4870     case font_size:mp_print(mp, "fontsize"); break;
4871     case ll_corner_op:mp_print(mp, "llcorner"); break;
4872     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4873     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4874     case ur_corner_op:mp_print(mp, "urcorner"); break;
4875     case arc_length:mp_print(mp, "arclength"); break;
4876     case angle_op:mp_print(mp, "angle"); break;
4877     case cycle_op:mp_print(mp, "cycle"); break;
4878     case filled_op:mp_print(mp, "filled"); break;
4879     case stroked_op:mp_print(mp, "stroked"); break;
4880     case textual_op:mp_print(mp, "textual"); break;
4881     case clipped_op:mp_print(mp, "clipped"); break;
4882     case bounded_op:mp_print(mp, "bounded"); break;
4883     case plus:mp_print_char(mp, '+'); break;
4884     case minus:mp_print_char(mp, '-'); break;
4885     case times:mp_print_char(mp, '*'); break;
4886     case over:mp_print_char(mp, '/'); break;
4887     case pythag_add:mp_print(mp, "++"); break;
4888     case pythag_sub:mp_print(mp, "+-+"); break;
4889     case or_op:mp_print(mp, "or"); break;
4890     case and_op:mp_print(mp, "and"); break;
4891     case less_than:mp_print_char(mp, '<'); break;
4892     case less_or_equal:mp_print(mp, "<="); break;
4893     case greater_than:mp_print_char(mp, '>'); break;
4894     case greater_or_equal:mp_print(mp, ">="); break;
4895     case equal_to:mp_print_char(mp, '='); break;
4896     case unequal_to:mp_print(mp, "<>"); break;
4897     case concatenate:mp_print(mp, "&"); break;
4898     case rotated_by:mp_print(mp, "rotated"); break;
4899     case slanted_by:mp_print(mp, "slanted"); break;
4900     case scaled_by:mp_print(mp, "scaled"); break;
4901     case shifted_by:mp_print(mp, "shifted"); break;
4902     case transformed_by:mp_print(mp, "transformed"); break;
4903     case x_scaled:mp_print(mp, "xscaled"); break;
4904     case y_scaled:mp_print(mp, "yscaled"); break;
4905     case z_scaled:mp_print(mp, "zscaled"); break;
4906     case in_font:mp_print(mp, "infont"); break;
4907     case intersect:mp_print(mp, "intersectiontimes"); break;
4908     case substring_of:mp_print(mp, "substring"); break;
4909     case subpath_of:mp_print(mp, "subpath"); break;
4910     case direction_time_of:mp_print(mp, "directiontime"); break;
4911     case point_of:mp_print(mp, "point"); break;
4912     case precontrol_of:mp_print(mp, "precontrol"); break;
4913     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4914     case pen_offset_of:mp_print(mp, "penoffset"); break;
4915     case arc_time_of:mp_print(mp, "arctime"); break;
4916     case mp_version:mp_print(mp, "mpversion"); break;
4917     case envelope_of:mp_print(mp, "envelope"); break;
4918     default: mp_print(mp, ".."); break;
4919     }
4920   }
4921 }
4922
4923 @ \MP\ also has a bunch of internal parameters that a user might want to
4924 fuss with. Every such parameter has an identifying code number, defined here.
4925
4926 @<Types...@>=
4927 enum mp_given_internal {
4928   mp_tracing_titles=1, /* show titles online when they appear */
4929   mp_tracing_equations, /* show each variable when it becomes known */
4930   mp_tracing_capsules, /* show capsules too */
4931   mp_tracing_choices, /* show the control points chosen for paths */
4932   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4933   mp_tracing_commands, /* show commands and operations before they are performed */
4934   mp_tracing_restores, /* show when a variable or internal is restored */
4935   mp_tracing_macros, /* show macros before they are expanded */
4936   mp_tracing_output, /* show digitized edges as they are output */
4937   mp_tracing_stats, /* show memory usage at end of job */
4938   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4939   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4940   mp_year, /* the current year (e.g., 1984) */
4941   mp_month, /* the current month (e.g, 3 $\equiv$ March) */
4942   mp_day, /* the current day of the month */
4943   mp_time, /* the number of minutes past midnight when this job started */
4944   mp_char_code, /* the number of the next character to be output */
4945   mp_char_ext, /* the extension code of the next character to be output */
4946   mp_char_wd, /* the width of the next character to be output */
4947   mp_char_ht, /* the height of the next character to be output */
4948   mp_char_dp, /* the depth of the next character to be output */
4949   mp_char_ic, /* the italic correction of the next character to be output */
4950   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4951   mp_pausing, /* positive to display lines on the terminal before they are read */
4952   mp_showstopping, /* positive to stop after each \&{show} command */
4953   mp_fontmaking, /* positive if font metric output is to be produced */
4954   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4955   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4956   mp_miterlimit, /* controls miter length as in \ps */
4957   mp_warning_check, /* controls error message when variable value is large */
4958   mp_boundary_char, /* the right boundary character for ligatures */
4959   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4960   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4961   mp_default_color_model, /* the default color model for unspecified items */
4962   mp_restore_clip_color,
4963   mp_procset, /* wether or not create PostScript command shortcuts */
4964   mp_gtroffmode,  /* whether the user specified |-troff| on the command line */
4965 };
4966
4967 @
4968
4969 @d max_given_internal mp_gtroffmode
4970
4971 @<Glob...@>=
4972 scaled *internal;  /* the values of internal quantities */
4973 char **int_name;  /* their names */
4974 int int_ptr;  /* the maximum internal quantity defined so far */
4975 int max_internal; /* current maximum number of internal quantities */
4976
4977 @ @<Option variables@>=
4978 int troff_mode; 
4979
4980 @ @<Allocate or initialize ...@>=
4981 mp->max_internal=2*max_given_internal;
4982 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
4983 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
4984 mp->troff_mode=(opt->troff_mode>0 ? true : false);
4985
4986 @ @<Exported function ...@>=
4987 int mp_troff_mode(MP mp);
4988
4989 @ @c
4990 int mp_troff_mode(MP mp) { return mp->troff_mode; }
4991
4992 @ @<Set initial ...@>=
4993 for (k=0;k<= mp->max_internal; k++ ) { 
4994    mp->internal[k]=0; 
4995    mp->int_name[k]=NULL; 
4996 }
4997 mp->int_ptr=max_given_internal;
4998
4999 @ The symbolic names for internal quantities are put into \MP's hash table
5000 by using a routine called |primitive|, which will be defined later. Let us
5001 enter them now, so that we don't have to list all those names again
5002 anywhere else.
5003
5004 @<Put each of \MP's primitives into the hash table@>=
5005 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5006 @:tracingtitles_}{\&{tracingtitles} primitive@>
5007 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5008 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5009 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5010 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5011 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5012 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5013 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5014 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5015 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5016 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5017 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5018 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5019 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5020 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5021 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5022 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5023 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5024 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5025 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5026 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5027 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5028 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5029 mp_primitive(mp, "year",internal_quantity,mp_year);
5030 @:mp_year_}{\&{year} primitive@>
5031 mp_primitive(mp, "month",internal_quantity,mp_month);
5032 @:mp_month_}{\&{month} primitive@>
5033 mp_primitive(mp, "day",internal_quantity,mp_day);
5034 @:mp_day_}{\&{day} primitive@>
5035 mp_primitive(mp, "time",internal_quantity,mp_time);
5036 @:time_}{\&{time} primitive@>
5037 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5038 @:mp_char_code_}{\&{charcode} primitive@>
5039 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5040 @:mp_char_ext_}{\&{charext} primitive@>
5041 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5042 @:mp_char_wd_}{\&{charwd} primitive@>
5043 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5044 @:mp_char_ht_}{\&{charht} primitive@>
5045 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5046 @:mp_char_dp_}{\&{chardp} primitive@>
5047 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5048 @:mp_char_ic_}{\&{charic} primitive@>
5049 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5050 @:mp_design_size_}{\&{designsize} primitive@>
5051 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5052 @:mp_pausing_}{\&{pausing} primitive@>
5053 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5054 @:mp_showstopping_}{\&{showstopping} primitive@>
5055 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5056 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5057 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5058 @:mp_linejoin_}{\&{linejoin} primitive@>
5059 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5060 @:mp_linecap_}{\&{linecap} primitive@>
5061 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5062 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5063 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5064 @:mp_warning_check_}{\&{warningcheck} primitive@>
5065 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5066 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5067 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5068 @:mp_prologues_}{\&{prologues} primitive@>
5069 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5070 @:mp_true_corners_}{\&{truecorners} primitive@>
5071 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5072 @:mp_procset_}{\&{mpprocset} primitive@>
5073 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5074 @:troffmode_}{\&{troffmode} primitive@>
5075 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5076 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5077 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5078 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5079
5080 @ Colors can be specified in four color models. In the special
5081 case of |no_model|, MetaPost does not output any color operator to
5082 the postscript output.
5083
5084 Note: these values are passed directly on to |with_option|. This only
5085 works because the other possible values passed to |with_option| are
5086 8 and 10 respectively (from |with_pen| and |with_picture|).
5087
5088 There is a first state, that is only used for |gs_colormodel|. It flags
5089 the fact that there has not been any kind of color specification by
5090 the user so far in the game.
5091
5092 @<Types...@>=
5093 enum mp_color_model {
5094   mp_no_model=1,
5095   mp_grey_model=3,
5096   mp_rgb_model=5,
5097   mp_cmyk_model=7,
5098   mp_uninitialized_model=9,
5099 };
5100
5101
5102 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5103 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5104 mp->internal[mp_restore_clip_color]=unity;
5105
5106 @ Well, we do have to list the names one more time, for use in symbolic
5107 printouts.
5108
5109 @<Initialize table...@>=
5110 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5111 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5112 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5113 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5114 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5115 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5116 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5117 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5118 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5119 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5120 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5121 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5122 mp->int_name[mp_year]=xstrdup("year");
5123 mp->int_name[mp_month]=xstrdup("month");
5124 mp->int_name[mp_day]=xstrdup("day");
5125 mp->int_name[mp_time]=xstrdup("time");
5126 mp->int_name[mp_char_code]=xstrdup("charcode");
5127 mp->int_name[mp_char_ext]=xstrdup("charext");
5128 mp->int_name[mp_char_wd]=xstrdup("charwd");
5129 mp->int_name[mp_char_ht]=xstrdup("charht");
5130 mp->int_name[mp_char_dp]=xstrdup("chardp");
5131 mp->int_name[mp_char_ic]=xstrdup("charic");
5132 mp->int_name[mp_design_size]=xstrdup("designsize");
5133 mp->int_name[mp_pausing]=xstrdup("pausing");
5134 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5135 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5136 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5137 mp->int_name[mp_linecap]=xstrdup("linecap");
5138 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5139 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5140 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5141 mp->int_name[mp_prologues]=xstrdup("prologues");
5142 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5143 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5144 mp->int_name[mp_procset]=xstrdup("mpprocset");
5145 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5146 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5147
5148 @ The following procedure, which is called just before \MP\ initializes its
5149 input and output, establishes the initial values of the date and time.
5150 @^system dependencies@>
5151
5152 Note that the values are |scaled| integers. Hence \MP\ can no longer
5153 be used after the year 32767.
5154
5155 @c 
5156 void mp_fix_date_and_time (MP mp) { 
5157   time_t clock = time ((time_t *) 0);
5158   struct tm *tmptr = localtime (&clock);
5159   mp->internal[mp_time]=
5160       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5161   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5162   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5163   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5164 }
5165
5166 @ @<Declarations@>=
5167 void mp_fix_date_and_time (MP mp) ;
5168
5169 @ \MP\ is occasionally supposed to print diagnostic information that
5170 goes only into the transcript file, unless |mp_tracing_online| is positive.
5171 Now that we have defined |mp_tracing_online| we can define
5172 two routines that adjust the destination of print commands:
5173
5174 @<Declarations@>=
5175 void mp_begin_diagnostic (MP mp) ;
5176 void mp_end_diagnostic (MP mp,boolean blank_line);
5177 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) ;
5178
5179 @ @<Basic printing...@>=
5180 @<Declare a function called |true_line|@>;
5181 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5182   mp->old_setting=mp->selector;
5183   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5184     decr(mp->selector);
5185     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5186   }
5187 }
5188 @#
5189 void mp_end_diagnostic (MP mp,boolean blank_line) {
5190   /* restore proper conditions after tracing */
5191   mp_print_nl(mp, "");
5192   if ( blank_line ) mp_print_ln(mp);
5193   mp->selector=mp->old_setting;
5194 }
5195
5196
5197
5198 @<Glob...@>=
5199 unsigned int old_setting;
5200
5201 @ We will occasionally use |begin_diagnostic| in connection with line-number
5202 printing, as follows. (The parameter |s| is typically |"Path"| or
5203 |"Cycle spec"|, etc.)
5204
5205 @<Basic printing...@>=
5206 void mp_print_diagnostic (MP mp, char *s, char *t, boolean nuline) { 
5207   mp_begin_diagnostic(mp);
5208   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5209   mp_print(mp, " at line "); 
5210   mp_print_int(mp, mp_true_line(mp));
5211   mp_print(mp, t); mp_print_char(mp, ':');
5212 }
5213
5214 @ The 256 |ASCII_code| characters are grouped into classes by means of
5215 the |char_class| table. Individual class numbers have no semantic
5216 or syntactic significance, except in a few instances defined here.
5217 There's also |max_class|, which can be used as a basis for additional
5218 class numbers in nonstandard extensions of \MP.
5219
5220 @d digit_class 0 /* the class number of \.{0123456789} */
5221 @d period_class 1 /* the class number of `\..' */
5222 @d space_class 2 /* the class number of spaces and nonstandard characters */
5223 @d percent_class 3 /* the class number of `\.\%' */
5224 @d string_class 4 /* the class number of `\."' */
5225 @d right_paren_class 8 /* the class number of `\.)' */
5226 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5227 @d letter_class 9 /* letters and the underline character */
5228 @d left_bracket_class 17 /* `\.[' */
5229 @d right_bracket_class 18 /* `\.]' */
5230 @d invalid_class 20 /* bad character in the input */
5231 @d max_class 20 /* the largest class number */
5232
5233 @<Glob...@>=
5234 int char_class[256]; /* the class numbers */
5235
5236 @ If changes are made to accommodate non-ASCII character sets, they should
5237 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5238 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5239 @^system dependencies@>
5240
5241 @<Set initial ...@>=
5242 for (k='0';k<='9';k++) 
5243   mp->char_class[k]=digit_class;
5244 mp->char_class['.']=period_class;
5245 mp->char_class[' ']=space_class;
5246 mp->char_class['%']=percent_class;
5247 mp->char_class['"']=string_class;
5248 mp->char_class[',']=5;
5249 mp->char_class[';']=6;
5250 mp->char_class['(']=7;
5251 mp->char_class[')']=right_paren_class;
5252 for (k='A';k<= 'Z';k++ )
5253   mp->char_class[k]=letter_class;
5254 for (k='a';k<='z';k++) 
5255   mp->char_class[k]=letter_class;
5256 mp->char_class['_']=letter_class;
5257 mp->char_class['<']=10;
5258 mp->char_class['=']=10;
5259 mp->char_class['>']=10;
5260 mp->char_class[':']=10;
5261 mp->char_class['|']=10;
5262 mp->char_class['`']=11;
5263 mp->char_class['\'']=11;
5264 mp->char_class['+']=12;
5265 mp->char_class['-']=12;
5266 mp->char_class['/']=13;
5267 mp->char_class['*']=13;
5268 mp->char_class['\\']=13;
5269 mp->char_class['!']=14;
5270 mp->char_class['?']=14;
5271 mp->char_class['#']=15;
5272 mp->char_class['&']=15;
5273 mp->char_class['@@']=15;
5274 mp->char_class['$']=15;
5275 mp->char_class['^']=16;
5276 mp->char_class['~']=16;
5277 mp->char_class['[']=left_bracket_class;
5278 mp->char_class[']']=right_bracket_class;
5279 mp->char_class['{']=19;
5280 mp->char_class['}']=19;
5281 for (k=0;k<' ';k++)
5282   mp->char_class[k]=invalid_class;
5283 mp->char_class['\t']=space_class;
5284 mp->char_class['\f']=space_class;
5285 for (k=127;k<=255;k++)
5286   mp->char_class[k]=invalid_class;
5287
5288 @* \[13] The hash table.
5289 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5290 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5291 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5292 table, it is never removed.
5293
5294 The actual sequence of characters forming a symbolic token is
5295 stored in the |str_pool| array together with all the other strings. An
5296 auxiliary array |hash| consists of items with two halfword fields per
5297 word. The first of these, called |next(p)|, points to the next identifier
5298 belonging to the same coalesced list as the identifier corresponding to~|p|;
5299 and the other, called |text(p)|, points to the |str_start| entry for
5300 |p|'s identifier. If position~|p| of the hash table is empty, we have
5301 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5302 hash list, we have |next(p)=0|.
5303
5304 An auxiliary pointer variable called |hash_used| is maintained in such a
5305 way that all locations |p>=hash_used| are nonempty. The global variable
5306 |st_count| tells how many symbolic tokens have been defined, if statistics
5307 are being kept.
5308
5309 The first 256 locations of |hash| are reserved for symbols of length one.
5310
5311 There's a parallel array called |eqtb| that contains the current equivalent
5312 values of each symbolic token. The entries of this array consist of
5313 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5314 piece of information that qualifies the |eq_type|).
5315
5316 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5317 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5318 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5319 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5320 @d hash_base 257 /* hashing actually starts here */
5321 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5322
5323 @<Glob...@>=
5324 pointer hash_used; /* allocation pointer for |hash| */
5325 integer st_count; /* total number of known identifiers */
5326
5327 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5328 since they are used in error recovery.
5329
5330 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5331 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5332 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5333 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5334 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5335 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5336 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5337 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5338 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5339 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5340 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5341 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5342 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5343 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5344 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5345 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5346 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5347
5348 @<Glob...@>=
5349 two_halves *hash; /* the hash table */
5350 two_halves *eqtb; /* the equivalents */
5351
5352 @ @<Allocate or initialize ...@>=
5353 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5354 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5355
5356 @ @<Dealloc variables@>=
5357 xfree(mp->hash);
5358 xfree(mp->eqtb);
5359
5360 @ @<Set init...@>=
5361 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5362 for (k=2;k<=hash_end;k++)  { 
5363   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5364 }
5365
5366 @ @<Initialize table entries...@>=
5367 mp->hash_used=frozen_inaccessible; /* nothing is used */
5368 mp->st_count=0;
5369 text(frozen_bad_vardef)=intern("a bad variable");
5370 text(frozen_etex)=intern("etex");
5371 text(frozen_mpx_break)=intern("mpxbreak");
5372 text(frozen_fi)=intern("fi");
5373 text(frozen_end_group)=intern("endgroup");
5374 text(frozen_end_def)=intern("enddef");
5375 text(frozen_end_for)=intern("endfor");
5376 text(frozen_semicolon)=intern(";");
5377 text(frozen_colon)=intern(":");
5378 text(frozen_slash)=intern("/");
5379 text(frozen_left_bracket)=intern("[");
5380 text(frozen_right_delimiter)=intern(")");
5381 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5382 eq_type(frozen_right_delimiter)=right_delimiter;
5383
5384 @ @<Check the ``constant'' values...@>=
5385 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5386
5387 @ Here is the subroutine that searches the hash table for an identifier
5388 that matches a given string of length~|l| appearing in |buffer[j..
5389 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5390 will always be found, and the corresponding hash table address
5391 will be returned.
5392
5393 @c 
5394 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5395   integer h; /* hash code */
5396   pointer p; /* index in |hash| array */
5397   pointer k; /* index in |buffer| array */
5398   if (l==1) {
5399     @<Treat special case of length 1 and |break|@>;
5400   }
5401   @<Compute the hash code |h|@>;
5402   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5403   while (true)  { 
5404         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5405       break;
5406     if ( next(p)==0 ) {
5407       @<Insert a new symbolic token after |p|, then
5408         make |p| point to it and |break|@>;
5409     }
5410     p=next(p);
5411   }
5412   return p;
5413 };
5414
5415 @ @<Treat special case of length 1...@>=
5416  p=mp->buffer[j]+1; text(p)=p-1; return p;
5417
5418
5419 @ @<Insert a new symbolic...@>=
5420 {
5421 if ( text(p)>0 ) { 
5422   do {  
5423     if ( hash_is_full )
5424       mp_overflow(mp, "hash size",mp->hash_size);
5425 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5426     decr(mp->hash_used);
5427   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5428   next(p)=mp->hash_used; 
5429   p=mp->hash_used;
5430 }
5431 str_room(l);
5432 for (k=j;k<=j+l-1;k++) {
5433   append_char(mp->buffer[k]);
5434 }
5435 text(p)=mp_make_string(mp); 
5436 mp->str_ref[text(p)]=max_str_ref;
5437 incr(mp->st_count);
5438 break;
5439 }
5440
5441
5442 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5443 should be a prime number.  The theory of hashing tells us to expect fewer
5444 than two table probes, on the average, when the search is successful.
5445 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5446 @^Vitter, Jeffrey Scott@>
5447
5448 @<Compute the hash code |h|@>=
5449 h=mp->buffer[j];
5450 for (k=j+1;k<=j+l-1;k++){ 
5451   h=h+h+mp->buffer[k];
5452   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5453 }
5454
5455 @ @<Search |eqtb| for equivalents equal to |p|@>=
5456 for (q=1;q<=hash_end;q++) { 
5457   if ( equiv(q)==p ) { 
5458     mp_print_nl(mp, "EQUIV("); 
5459     mp_print_int(mp, q); 
5460     mp_print_char(mp, ')');
5461   }
5462 }
5463
5464 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5465 table, together with their command code (which will be the |eq_type|)
5466 and an operand (which will be the |equiv|). The |primitive| procedure
5467 does this, in a way that no \MP\ user can. The global value |cur_sym|
5468 contains the new |eqtb| pointer after |primitive| has acted.
5469
5470 @c 
5471 void mp_primitive (MP mp, char *ss, halfword c, halfword o) {
5472   pool_pointer k; /* index into |str_pool| */
5473   small_number j; /* index into |buffer| */
5474   small_number l; /* length of the string */
5475   str_number s;
5476   s = intern(ss);
5477   k=mp->str_start[s]; l=str_stop(s)-k;
5478   /* we will move |s| into the (empty) |buffer| */
5479   for (j=0;j<=l-1;j++) {
5480     mp->buffer[j]=mp->str_pool[k+j];
5481   }
5482   mp->cur_sym=mp_id_lookup(mp, 0,l);
5483   if ( s>=256 ) { /* we don't want to have the string twice */
5484     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5485   };
5486   eq_type(mp->cur_sym)=c; 
5487   equiv(mp->cur_sym)=o;
5488 }
5489
5490
5491 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5492 by their |eq_type| alone. These primitives are loaded into the hash table
5493 as follows:
5494
5495 @<Put each of \MP's primitives into the hash table@>=
5496 mp_primitive(mp, "..",path_join,0);
5497 @:.._}{\.{..} primitive@>
5498 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5499 @:[ }{\.{[} primitive@>
5500 mp_primitive(mp, "]",right_bracket,0);
5501 @:] }{\.{]} primitive@>
5502 mp_primitive(mp, "}",right_brace,0);
5503 @:]]}{\.{\char`\}} primitive@>
5504 mp_primitive(mp, "{",left_brace,0);
5505 @:][}{\.{\char`\{} primitive@>
5506 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5507 @:: }{\.{:} primitive@>
5508 mp_primitive(mp, "::",double_colon,0);
5509 @::: }{\.{::} primitive@>
5510 mp_primitive(mp, "||:",bchar_label,0);
5511 @:::: }{\.{\char'174\char'174:} primitive@>
5512 mp_primitive(mp, ":=",assignment,0);
5513 @::=_}{\.{:=} primitive@>
5514 mp_primitive(mp, ",",comma,0);
5515 @:, }{\., primitive@>
5516 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5517 @:; }{\.; primitive@>
5518 mp_primitive(mp, "\\",relax,0);
5519 @:]]\\}{\.{\char`\\} primitive@>
5520 @#
5521 mp_primitive(mp, "addto",add_to_command,0);
5522 @:add_to_}{\&{addto} primitive@>
5523 mp_primitive(mp, "atleast",at_least,0);
5524 @:at_least_}{\&{atleast} primitive@>
5525 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5526 @:begin_group_}{\&{begingroup} primitive@>
5527 mp_primitive(mp, "controls",controls,0);
5528 @:controls_}{\&{controls} primitive@>
5529 mp_primitive(mp, "curl",curl_command,0);
5530 @:curl_}{\&{curl} primitive@>
5531 mp_primitive(mp, "delimiters",delimiters,0);
5532 @:delimiters_}{\&{delimiters} primitive@>
5533 mp_primitive(mp, "endgroup",end_group,0);
5534  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5535 @:endgroup_}{\&{endgroup} primitive@>
5536 mp_primitive(mp, "everyjob",every_job_command,0);
5537 @:every_job_}{\&{everyjob} primitive@>
5538 mp_primitive(mp, "exitif",exit_test,0);
5539 @:exit_if_}{\&{exitif} primitive@>
5540 mp_primitive(mp, "expandafter",expand_after,0);
5541 @:expand_after_}{\&{expandafter} primitive@>
5542 mp_primitive(mp, "interim",interim_command,0);
5543 @:interim_}{\&{interim} primitive@>
5544 mp_primitive(mp, "let",let_command,0);
5545 @:let_}{\&{let} primitive@>
5546 mp_primitive(mp, "newinternal",new_internal,0);
5547 @:new_internal_}{\&{newinternal} primitive@>
5548 mp_primitive(mp, "of",of_token,0);
5549 @:of_}{\&{of} primitive@>
5550 mp_primitive(mp, "randomseed",mp_random_seed,0);
5551 @:mp_random_seed_}{\&{randomseed} primitive@>
5552 mp_primitive(mp, "save",save_command,0);
5553 @:save_}{\&{save} primitive@>
5554 mp_primitive(mp, "scantokens",scan_tokens,0);
5555 @:scan_tokens_}{\&{scantokens} primitive@>
5556 mp_primitive(mp, "shipout",ship_out_command,0);
5557 @:ship_out_}{\&{shipout} primitive@>
5558 mp_primitive(mp, "skipto",skip_to,0);
5559 @:skip_to_}{\&{skipto} primitive@>
5560 mp_primitive(mp, "special",special_command,0);
5561 @:special}{\&{special} primitive@>
5562 mp_primitive(mp, "fontmapfile",special_command,1);
5563 @:fontmapfile}{\&{fontmapfile} primitive@>
5564 mp_primitive(mp, "fontmapline",special_command,2);
5565 @:fontmapline}{\&{fontmapline} primitive@>
5566 mp_primitive(mp, "step",step_token,0);
5567 @:step_}{\&{step} primitive@>
5568 mp_primitive(mp, "str",str_op,0);
5569 @:str_}{\&{str} primitive@>
5570 mp_primitive(mp, "tension",tension,0);
5571 @:tension_}{\&{tension} primitive@>
5572 mp_primitive(mp, "to",to_token,0);
5573 @:to_}{\&{to} primitive@>
5574 mp_primitive(mp, "until",until_token,0);
5575 @:until_}{\&{until} primitive@>
5576 mp_primitive(mp, "within",within_token,0);
5577 @:within_}{\&{within} primitive@>
5578 mp_primitive(mp, "write",write_command,0);
5579 @:write_}{\&{write} primitive@>
5580
5581 @ Each primitive has a corresponding inverse, so that it is possible to
5582 display the cryptic numeric contents of |eqtb| in symbolic form.
5583 Every call of |primitive| in this program is therefore accompanied by some
5584 straightforward code that forms part of the |print_cmd_mod| routine
5585 explained below.
5586
5587 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5588 case add_to_command:mp_print(mp, "addto"); break;
5589 case assignment:mp_print(mp, ":="); break;
5590 case at_least:mp_print(mp, "atleast"); break;
5591 case bchar_label:mp_print(mp, "||:"); break;
5592 case begin_group:mp_print(mp, "begingroup"); break;
5593 case colon:mp_print(mp, ":"); break;
5594 case comma:mp_print(mp, ","); break;
5595 case controls:mp_print(mp, "controls"); break;
5596 case curl_command:mp_print(mp, "curl"); break;
5597 case delimiters:mp_print(mp, "delimiters"); break;
5598 case double_colon:mp_print(mp, "::"); break;
5599 case end_group:mp_print(mp, "endgroup"); break;
5600 case every_job_command:mp_print(mp, "everyjob"); break;
5601 case exit_test:mp_print(mp, "exitif"); break;
5602 case expand_after:mp_print(mp, "expandafter"); break;
5603 case interim_command:mp_print(mp, "interim"); break;
5604 case left_brace:mp_print(mp, "{"); break;
5605 case left_bracket:mp_print(mp, "["); break;
5606 case let_command:mp_print(mp, "let"); break;
5607 case new_internal:mp_print(mp, "newinternal"); break;
5608 case of_token:mp_print(mp, "of"); break;
5609 case path_join:mp_print(mp, ".."); break;
5610 case mp_random_seed:mp_print(mp, "randomseed"); break;
5611 case relax:mp_print_char(mp, '\\'); break;
5612 case right_brace:mp_print(mp, "}"); break;
5613 case right_bracket:mp_print(mp, "]"); break;
5614 case save_command:mp_print(mp, "save"); break;
5615 case scan_tokens:mp_print(mp, "scantokens"); break;
5616 case semicolon:mp_print(mp, ";"); break;
5617 case ship_out_command:mp_print(mp, "shipout"); break;
5618 case skip_to:mp_print(mp, "skipto"); break;
5619 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5620                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5621                  mp_print(mp, "special"); break;
5622 case step_token:mp_print(mp, "step"); break;
5623 case str_op:mp_print(mp, "str"); break;
5624 case tension:mp_print(mp, "tension"); break;
5625 case to_token:mp_print(mp, "to"); break;
5626 case until_token:mp_print(mp, "until"); break;
5627 case within_token:mp_print(mp, "within"); break;
5628 case write_command:mp_print(mp, "write"); break;
5629
5630 @ We will deal with the other primitives later, at some point in the program
5631 where their |eq_type| and |equiv| values are more meaningful.  For example,
5632 the primitives for macro definitions will be loaded when we consider the
5633 routines that define macros.
5634 It is easy to find where each particular
5635 primitive was treated by looking in the index at the end; for example, the
5636 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5637
5638 @* \[14] Token lists.
5639 A \MP\ token is either symbolic or numeric or a string, or it denotes
5640 a macro parameter or capsule; so there are five corresponding ways to encode it
5641 @^token@>
5642 internally: (1)~A symbolic token whose hash code is~|p|
5643 is represented by the number |p|, in the |info| field of a single-word
5644 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5645 represented in a two-word node of~|mem|; the |type| field is |known|,
5646 the |name_type| field is |token|, and the |value| field holds~|v|.
5647 The fact that this token appears in a two-word node rather than a
5648 one-word node is, of course, clear from the node address.
5649 (3)~A string token is also represented in a two-word node; the |type|
5650 field is |mp_string_type|, the |name_type| field is |token|, and the
5651 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5652 |name_type=capsule|, and their |type| and |value| fields represent
5653 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5654 are like symbolic tokens in that they appear in |info| fields of
5655 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5656 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5657 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5658 Actual values of these parameters are kept in a separate stack, as we will
5659 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5660 of course, chosen so that there will be no confusion between symbolic
5661 tokens and parameters of various types.
5662
5663 Note that
5664 the `\\{type}' field of a node has nothing to do with ``type'' in a
5665 printer's sense. It's curious that the same word is used in such different ways.
5666
5667 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5668 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5669 @d token_node_size 2 /* the number of words in a large token node */
5670 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5671 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5672 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5673 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5674 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5675
5676 @<Check the ``constant''...@>=
5677 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5678
5679 @ We have set aside a two word node beginning at |null| so that we can have
5680 |value(null)=0|.  We will make use of this coincidence later.
5681
5682 @<Initialize table entries...@>=
5683 link(null)=null; value(null)=0;
5684
5685 @ A numeric token is created by the following trivial routine.
5686
5687 @c 
5688 pointer mp_new_num_tok (MP mp,scaled v) {
5689   pointer p; /* the new node */
5690   p=mp_get_node(mp, token_node_size); value(p)=v;
5691   type(p)=mp_known; name_type(p)=mp_token; 
5692   return p;
5693 }
5694
5695 @ A token list is a singly linked list of nodes in |mem|, where
5696 each node contains a token and a link.  Here's a subroutine that gets rid
5697 of a token list when it is no longer needed.
5698
5699 @c void mp_flush_token_list (MP mp,pointer p) {
5700   pointer q; /* the node being recycled */
5701   while ( p!=null ) { 
5702     q=p; p=link(p);
5703     if ( q>=mp->hi_mem_min ) {
5704      free_avail(q);
5705     } else { 
5706       switch (type(q)) {
5707       case mp_vacuous: case mp_boolean_type: case mp_known:
5708         break;
5709       case mp_string_type:
5710         delete_str_ref(value(q));
5711         break;
5712       case unknown_types: case mp_pen_type: case mp_path_type: 
5713       case mp_picture_type: case mp_pair_type: case mp_color_type:
5714       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5715       case mp_proto_dependent: case mp_independent:
5716         mp_recycle_value(mp,q);
5717         break;
5718       default: mp_confusion(mp, "token");
5719 @:this can't happen token}{\quad token@>
5720       }
5721       mp_free_node(mp, q,token_node_size);
5722     }
5723   }
5724 }
5725
5726 @ The procedure |show_token_list|, which prints a symbolic form of
5727 the token list that starts at a given node |p|, illustrates these
5728 conventions. The token list being displayed should not begin with a reference
5729 count. However, the procedure is intended to be fairly robust, so that if the
5730 memory links are awry or if |p| is not really a pointer to a token list,
5731 almost nothing catastrophic can happen.
5732
5733 An additional parameter |q| is also given; this parameter is either null
5734 or it points to a node in the token list where a certain magic computation
5735 takes place that will be explained later. (Basically, |q| is non-null when
5736 we are printing the two-line context information at the time of an error
5737 message; |q| marks the place corresponding to where the second line
5738 should begin.)
5739
5740 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5741 of printing exceeds a given limit~|l|; the length of printing upon entry is
5742 assumed to be a given amount called |null_tally|. (Note that
5743 |show_token_list| sometimes uses itself recursively to print
5744 variable names within a capsule.)
5745 @^recursion@>
5746
5747 Unusual entries are printed in the form of all-caps tokens
5748 preceded by a space, e.g., `\.{\char`\ BAD}'.
5749
5750 @<Declare the procedure called |show_token_list|@>=
5751 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5752                          integer null_tally) ;
5753
5754 @ @c
5755 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5756                          integer null_tally) {
5757   small_number class,c; /* the |char_class| of previous and new tokens */
5758   integer r,v; /* temporary registers */
5759   class=percent_class;
5760   mp->tally=null_tally;
5761   while ( (p!=null) && (mp->tally<l) ) { 
5762     if ( p==q ) 
5763       @<Do magic computation@>;
5764     @<Display token |p| and set |c| to its class;
5765       but |return| if there are problems@>;
5766     class=c; p=link(p);
5767   }
5768   if ( p!=null ) 
5769      mp_print(mp, " ETC.");
5770 @.ETC@>
5771   return;
5772 };
5773
5774 @ @<Display token |p| and set |c| to its class...@>=
5775 c=letter_class; /* the default */
5776 if ( (p<0)||(p>mp->mem_end) ) { 
5777   mp_print(mp, " CLOBBERED"); return;
5778 @.CLOBBERED@>
5779 }
5780 if ( p<mp->hi_mem_min ) { 
5781   @<Display two-word token@>;
5782 } else { 
5783   r=info(p);
5784   if ( r>=expr_base ) {
5785      @<Display a parameter token@>;
5786   } else {
5787     if ( r<1 ) {
5788       if ( r==0 ) { 
5789         @<Display a collective subscript@>
5790       } else {
5791         mp_print(mp, " IMPOSSIBLE");
5792 @.IMPOSSIBLE@>
5793       }
5794     } else { 
5795       r=text(r);
5796       if ( (r<0)||(r>mp->max_str_ptr) ) {
5797         mp_print(mp, " NONEXISTENT");
5798 @.NONEXISTENT@>
5799       } else {
5800        @<Print string |r| as a symbolic token
5801         and set |c| to its class@>;
5802       }
5803     }
5804   }
5805 }
5806
5807 @ @<Display two-word token@>=
5808 if ( name_type(p)==mp_token ) {
5809   if ( type(p)==mp_known ) {
5810     @<Display a numeric token@>;
5811   } else if ( type(p)!=mp_string_type ) {
5812     mp_print(mp, " BAD");
5813 @.BAD@>
5814   } else { 
5815     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5816     c=string_class;
5817   }
5818 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5819   mp_print(mp, " BAD");
5820 } else { 
5821   mp_print_capsule(mp,p); c=right_paren_class;
5822 }
5823
5824 @ @<Display a numeric token@>=
5825 if ( class==digit_class ) 
5826   mp_print_char(mp, ' ');
5827 v=value(p);
5828 if ( v<0 ){ 
5829   if ( class==left_bracket_class ) 
5830     mp_print_char(mp, ' ');
5831   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5832   c=right_bracket_class;
5833 } else { 
5834   mp_print_scaled(mp, v); c=digit_class;
5835 }
5836
5837
5838 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5839 But we will see later (in the |print_variable_name| routine) that
5840 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5841
5842 @<Display a collective subscript@>=
5843 {
5844 if ( class==left_bracket_class ) 
5845   mp_print_char(mp, ' ');
5846 mp_print(mp, "[]"); c=right_bracket_class;
5847 }
5848
5849 @ @<Display a parameter token@>=
5850 {
5851 if ( r<suffix_base ) { 
5852   mp_print(mp, "(EXPR"); r=r-(expr_base);
5853 @.EXPR@>
5854 } else if ( r<text_base ) { 
5855   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5856 @.SUFFIX@>
5857 } else { 
5858   mp_print(mp, "(TEXT"); r=r-(text_base);
5859 @.TEXT@>
5860 }
5861 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5862 }
5863
5864
5865 @ @<Print string |r| as a symbolic token...@>=
5866
5867 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5868 if ( c==class ) {
5869   switch (c) {
5870   case letter_class:mp_print_char(mp, '.'); break;
5871   case isolated_classes: break;
5872   default: mp_print_char(mp, ' '); break;
5873   }
5874 }
5875 mp_print_str(mp, r);
5876 }
5877
5878 @ @<Declarations@>=
5879 void mp_print_capsule (MP mp, pointer p);
5880
5881 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5882 void mp_print_capsule (MP mp, pointer p) { 
5883   mp_print_char(mp, '('); mp_print_exp(mp,p,0); mp_print_char(mp, ')');
5884 }
5885
5886 @ Macro definitions are kept in \MP's memory in the form of token lists
5887 that have a few extra one-word nodes at the beginning.
5888
5889 The first node contains a reference count that is used to tell when the
5890 list is no longer needed. To emphasize the fact that a reference count is
5891 present, we shall refer to the |info| field of this special node as the
5892 |ref_count| field.
5893 @^reference counts@>
5894
5895 The next node or nodes after the reference count serve to describe the
5896 formal parameters. They either contain a code word that specifies all
5897 of the parameters, or they contain zero or more parameter tokens followed
5898 by the code `|general_macro|'.
5899
5900 @d ref_count info
5901   /* reference count preceding a macro definition or picture header */
5902 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5903 @d general_macro 0 /* preface to a macro defined with a parameter list */
5904 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5905 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5906 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5907 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5908 @d of_macro 5 /* preface to a macro with
5909   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5910 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5911 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5912
5913 @c 
5914 void mp_delete_mac_ref (MP mp,pointer p) {
5915   /* |p| points to the reference count of a macro list that is
5916     losing one reference */
5917   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5918   else decr(ref_count(p));
5919 }
5920
5921 @ The following subroutine displays a macro, given a pointer to its
5922 reference count.
5923
5924 @c 
5925 @<Declare the procedure called |print_cmd_mod|@>;
5926 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5927   pointer r; /* temporary storage */
5928   p=link(p); /* bypass the reference count */
5929   while ( info(p)>text_macro ){ 
5930     r=link(p); link(p)=null;
5931     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5932     if ( l>0 ) l=l-mp->tally; else return;
5933   } /* control printing of `\.{ETC.}' */
5934 @.ETC@>
5935   mp->tally=0;
5936   switch(info(p)) {
5937   case general_macro:mp_print(mp, "->"); break;
5938 @.->@>
5939   case primary_macro: case secondary_macro: case tertiary_macro:
5940     mp_print_char(mp, '<');
5941     mp_print_cmd_mod(mp, param_type,info(p)); 
5942     mp_print(mp, ">->");
5943     break;
5944   case expr_macro:mp_print(mp, "<expr>->"); break;
5945   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5946   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5947   case text_macro:mp_print(mp, "<text>->"); break;
5948   } /* there are no other cases */
5949   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5950 }
5951
5952 @* \[15] Data structures for variables.
5953 The variables of \MP\ programs can be simple, like `\.x', or they can
5954 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5955 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5956 example, `\.{boolean} \.{x20a.b}'. It's time for us to study how such
5957 things are represented inside of the computer.
5958
5959 Each variable value occupies two consecutive words, either in a two-word
5960 node called a value node, or as a two-word subfield of a larger node.  One
5961 of those two words is called the |value| field; it is an integer,
5962 containing either a |scaled| numeric value or the representation of some
5963 other type of quantity. (It might also be subdivided into halfwords, in
5964 which case it is referred to by other names instead of |value|.) The other
5965 word is broken into subfields called |type|, |name_type|, and |link|.  The
5966 |type| field is a quarterword that specifies the variable's type, and
5967 |name_type| is a quarterword from which \MP\ can reconstruct the
5968 variable's name (sometimes by using the |link| field as well).  Thus, only
5969 1.25 words are actually devoted to the value itself; the other
5970 three-quarters of a word are overhead, but they aren't wasted because they
5971 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5972
5973 In this section we shall be concerned only with the structural aspects of
5974 variables, not their values. Later parts of the program will change the
5975 |type| and |value| fields, but we shall treat those fields as black boxes
5976 whose contents should not be touched.
5977
5978 However, if the |type| field is |mp_structured|, there is no |value| field,
5979 and the second word is broken into two pointer fields called |attr_head|
5980 and |subscr_head|. Those fields point to additional nodes that
5981 contain structural information, as we shall see.
5982
5983 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
5984 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
5985 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
5986 @d value_node_size 2 /* the number of words in a value node */
5987
5988 @ An attribute node is three words long. Two of these words contain |type|
5989 and |value| fields as described above, and the third word contains
5990 additional information:  There is an |attr_loc| field, which contains the
5991 hash address of the token that names this attribute; and there's also a
5992 |parent| field, which points to the value node of |mp_structured| type at the
5993 next higher level (i.e., at the level to which this attribute is
5994 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
5995 |link| field points to the next attribute with the same parent; these are
5996 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
5997 final attribute node links to the constant |end_attr|, whose |attr_loc|
5998 field is greater than any legal hash address. The |attr_head| in the
5999 parent points to a node whose |name_type| is |mp_structured_root|; this
6000 node represents the null attribute, i.e., the variable that is relevant
6001 when no attributes are attached to the parent. The |attr_head| node is either
6002 a value node, a subscript node, or an attribute node, depending on what
6003 the parent would be if it were not structured; but the subscript and
6004 attribute fields are ignored, so it effectively contains only the data of
6005 a value node. The |link| field in this special node points to an attribute
6006 node whose |attr_loc| field is zero; the latter node represents a collective
6007 subscript `\.{[]}' attached to the parent, and its |link| field points to
6008 the first non-special attribute node (or to |end_attr| if there are none).
6009
6010 A subscript node likewise occupies three words, with |type| and |value| fields
6011 plus extra information; its |name_type| is |subscr|. In this case the
6012 third word is called the |subscript| field, which is a |scaled| integer.
6013 The |link| field points to the subscript node with the next larger
6014 subscript, if any; otherwise the |link| points to the attribute node
6015 for collective subscripts at this level. We have seen that the latter node
6016 contains an upward pointer, so that the parent can be deduced.
6017
6018 The |name_type| in a parent-less value node is |root|, and the |link|
6019 is the hash address of the token that names this value.
6020
6021 In other words, variables have a hierarchical structure that includes
6022 enough threads running around so that the program is able to move easily
6023 between siblings, parents, and children. An example should be helpful:
6024 (The reader is advised to draw a picture while reading the following
6025 description, since that will help to firm up the ideas.)
6026 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6027 and `\.{x20b}' have been mentioned in a user's program, where
6028 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6029 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6030 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6031 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6032 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6033 node and |r| to a subscript node. (Are you still following this? Use
6034 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6035 |type(q)| and |value(q)|; furthermore
6036 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6037 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6038 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6039 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6040 |qq| is a value node with |type(qq)=mp_numeric_type| (assuming that \.{x5} is
6041 numeric, because |qq| represents `\.{x[]}' with no further attributes),
6042 |name_type(qq)=mp_structured_root|, and
6043 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6044 an attribute node representing `\.{x[][]}', which has never yet
6045 occurred; its |type| field is |undefined|, and its |value| field is
6046 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6047 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6048 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6049 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6050 (Maybe colored lines will help untangle your picture.)
6051  Node |r| is a subscript node with |type| and |value|
6052 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6053 and |link(r)=r1| is another subscript node. To complete the picture,
6054 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6055 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6056 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6057 and we finish things off with three more nodes
6058 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6059 with a larger sheet of paper.) The value of variable \.{x20b}
6060 appears in node~|qqq2|, as you can well imagine.
6061
6062 If the example in the previous paragraph doesn't make things crystal
6063 clear, a glance at some of the simpler subroutines below will reveal how
6064 things work out in practice.
6065
6066 The only really unusual thing about these conventions is the use of
6067 collective subscript attributes. The idea is to avoid repeating a lot of
6068 type information when many elements of an array are identical macros
6069 (for which distinct values need not be stored) or when they don't have
6070 all of the possible attributes. Branches of the structure below collective
6071 subscript attributes do not carry actual values except for macro identifiers;
6072 branches of the structure below subscript nodes do not carry significant
6073 information in their collective subscript attributes.
6074
6075 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6076 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6077 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6078 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6079 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6080 @d attr_node_size 3 /* the number of words in an attribute node */
6081 @d subscr_node_size 3 /* the number of words in a subscript node */
6082 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6083
6084 @<Initialize table...@>=
6085 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6086
6087 @ Variables of type \&{pair} will have values that point to four-word
6088 nodes containing two numeric values. The first of these values has
6089 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6090 the |link| in the first points back to the node whose |value| points
6091 to this four-word node.
6092
6093 Variables of type \&{transform} are similar, but in this case their
6094 |value| points to a 12-word node containing six values, identified by
6095 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6096 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6097 Finally, variables of type \&{color} have 3~values in 6~words
6098 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6099
6100 When an entire structured variable is saved, the |root| indication
6101 is temporarily replaced by |saved_root|.
6102
6103 Some variables have no name; they just are used for temporary storage
6104 while expressions are being evaluated. We call them {\sl capsules}.
6105
6106 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6107 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6108 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6109 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6110 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6111 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6112 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6113 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6114 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6115 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6116 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6117 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6118 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6119 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6120 @#
6121 @d pair_node_size 4 /* the number of words in a pair node */
6122 @d transform_node_size 12 /* the number of words in a transform node */
6123 @d color_node_size 6 /* the number of words in a color node */
6124 @d cmykcolor_node_size 8 /* the number of words in a color node */
6125
6126 @<Glob...@>=
6127 small_number big_node_size[mp_pair_type+1];
6128 small_number sector0[mp_pair_type+1];
6129 small_number sector_offset[mp_black_part_sector+1];
6130
6131 @ The |sector0| array gives for each big node type, |name_type| values
6132 for its first subfield; the |sector_offset| array gives for each
6133 |name_type| value, the offset from the first subfield in words;
6134 and the |big_node_size| array gives the size in words for each type of
6135 big node.
6136
6137 @<Set init...@>=
6138 mp->big_node_size[mp_transform_type]=transform_node_size;
6139 mp->big_node_size[mp_pair_type]=pair_node_size;
6140 mp->big_node_size[mp_color_type]=color_node_size;
6141 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6142 mp->sector0[mp_transform_type]=mp_x_part_sector;
6143 mp->sector0[mp_pair_type]=mp_x_part_sector;
6144 mp->sector0[mp_color_type]=mp_red_part_sector;
6145 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6146 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6147   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6148 }
6149 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6150   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6151 }
6152 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6153   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6154 }
6155
6156 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6157 procedure call |init_big_node(p)| will allocate a pair or transform node
6158 for~|p|.  The individual parts of such nodes are initially of type
6159 |mp_independent|.
6160
6161 @c 
6162 void mp_init_big_node (MP mp,pointer p) {
6163   pointer q; /* the new node */
6164   small_number s; /* its size */
6165   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6166   do {  
6167     s=s-2; 
6168     @<Make variable |q+s| newly independent@>;
6169     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6170     link(q+s)=null;
6171   } while (s!=0);
6172   link(q)=p; value(p)=q;
6173 }
6174
6175 @ The |id_transform| function creates a capsule for the
6176 identity transformation.
6177
6178 @c 
6179 pointer mp_id_transform (MP mp) {
6180   pointer p,q,r; /* list manipulation registers */
6181   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6182   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6183   r=q+transform_node_size;
6184   do {  
6185     r=r-2;
6186     type(r)=mp_known; value(r)=0;
6187   } while (r!=q);
6188   value(xx_part_loc(q))=unity; 
6189   value(yy_part_loc(q))=unity;
6190   return p;
6191 }
6192
6193 @ Tokens are of type |tag_token| when they first appear, but they point
6194 to |null| until they are first used as the root of a variable.
6195 The following subroutine establishes the root node on such grand occasions.
6196
6197 @c 
6198 void mp_new_root (MP mp,pointer x) {
6199   pointer p; /* the new node */
6200   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6201   link(p)=x; equiv(x)=p;
6202 }
6203
6204 @ These conventions for variable representation are illustrated by the
6205 |print_variable_name| routine, which displays the full name of a
6206 variable given only a pointer to its two-word value packet.
6207
6208 @<Declarations@>=
6209 void mp_print_variable_name (MP mp, pointer p);
6210
6211 @ @c 
6212 void mp_print_variable_name (MP mp, pointer p) {
6213   pointer q; /* a token list that will name the variable's suffix */
6214   pointer r; /* temporary for token list creation */
6215   while ( name_type(p)>=mp_x_part_sector ) {
6216     @<Preface the output with a part specifier; |return| in the
6217       case of a capsule@>;
6218   }
6219   q=null;
6220   while ( name_type(p)>mp_saved_root ) {
6221     @<Ascend one level, pushing a token onto list |q|
6222      and replacing |p| by its parent@>;
6223   }
6224   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6225   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6226 @.SAVED@>
6227   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6228   mp_flush_token_list(mp, r);
6229 }
6230
6231 @ @<Ascend one level, pushing a token onto list |q|...@>=
6232
6233   if ( name_type(p)==mp_subscr ) { 
6234     r=mp_new_num_tok(mp, subscript(p));
6235     do {  
6236       p=link(p);
6237     } while (name_type(p)!=mp_attr);
6238   } else if ( name_type(p)==mp_structured_root ) {
6239     p=link(p); goto FOUND;
6240   } else { 
6241     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6242 @:this can't happen var}{\quad var@>
6243     r=mp_get_avail(mp); info(r)=attr_loc(p);
6244   }
6245   link(r)=q; q=r;
6246 FOUND:  
6247   p=parent(p);
6248 }
6249
6250 @ @<Preface the output with a part specifier...@>=
6251 { switch (name_type(p)) {
6252   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6253   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6254   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6255   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6256   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6257   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6258   case mp_red_part_sector: mp_print(mp, "red"); break;
6259   case mp_green_part_sector: mp_print(mp, "green"); break;
6260   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6261   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6262   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6263   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6264   case mp_black_part_sector: mp_print(mp, "black"); break;
6265   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6266   case mp_capsule: 
6267     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6268     break;
6269 @.CAPSULE@>
6270   } /* there are no other cases */
6271   mp_print(mp, "part "); 
6272   p=link(p-mp->sector_offset[name_type(p)]);
6273 }
6274
6275 @ The |interesting| function returns |true| if a given variable is not
6276 in a capsule, or if the user wants to trace capsules.
6277
6278 @c 
6279 boolean mp_interesting (MP mp,pointer p) {
6280   small_number t; /* a |name_type| */
6281   if ( mp->internal[mp_tracing_capsules]>0 ) {
6282     return true;
6283   } else { 
6284     t=name_type(p);
6285     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6286       t=name_type(link(p-mp->sector_offset[t]));
6287     return (t!=mp_capsule);
6288   }
6289 }
6290
6291 @ Now here is a subroutine that converts an unstructured type into an
6292 equivalent structured type, by inserting a |mp_structured| node that is
6293 capable of growing. This operation is done only when |name_type(p)=root|,
6294 |subscr|, or |attr|.
6295
6296 The procedure returns a pointer to the new node that has taken node~|p|'s
6297 place in the structure. Node~|p| itself does not move, nor are its
6298 |value| or |type| fields changed in any way.
6299
6300 @c 
6301 pointer mp_new_structure (MP mp,pointer p) {
6302   pointer q,r=0; /* list manipulation registers */
6303   switch (name_type(p)) {
6304   case mp_root: 
6305     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6306     break;
6307   case mp_subscr: 
6308     @<Link a new subscript node |r| in place of node |p|@>;
6309     break;
6310   case mp_attr: 
6311     @<Link a new attribute node |r| in place of node |p|@>;
6312     break;
6313   default: 
6314     mp_confusion(mp, "struct");
6315 @:this can't happen struct}{\quad struct@>
6316     break;
6317   }
6318   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6319   attr_head(r)=p; name_type(p)=mp_structured_root;
6320   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6321   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6322   attr_loc(q)=collective_subscript; 
6323   return r;
6324 };
6325
6326 @ @<Link a new subscript node |r| in place of node |p|@>=
6327
6328   q=p;
6329   do {  
6330     q=link(q);
6331   } while (name_type(q)!=mp_attr);
6332   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6333   do {  
6334     q=r; r=link(r);
6335   } while (r!=p);
6336   r=mp_get_node(mp, subscr_node_size);
6337   link(q)=r; subscript(r)=subscript(p);
6338 }
6339
6340 @ If the attribute is |collective_subscript|, there are two pointers to
6341 node~|p|, so we must change both of them.
6342
6343 @<Link a new attribute node |r| in place of node |p|@>=
6344
6345   q=parent(p); r=attr_head(q);
6346   do {  
6347     q=r; r=link(r);
6348   } while (r!=p);
6349   r=mp_get_node(mp, attr_node_size); link(q)=r;
6350   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6351   if ( attr_loc(p)==collective_subscript ) { 
6352     q=subscr_head_loc(parent(p));
6353     while ( link(q)!=p ) q=link(q);
6354     link(q)=r;
6355   }
6356 }
6357
6358 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6359 list of suffixes; it returns a pointer to the corresponding two-word
6360 value. For example, if |t| points to token \.x followed by a numeric
6361 token containing the value~7, |find_variable| finds where the value of
6362 \.{x7} is stored in memory. This may seem a simple task, and it
6363 usually is, except when \.{x7} has never been referenced before.
6364 Indeed, \.x may never have even been subscripted before; complexities
6365 arise with respect to updating the collective subscript information.
6366
6367 If a macro type is detected anywhere along path~|t|, or if the first
6368 item on |t| isn't a |tag_token|, the value |null| is returned.
6369 Otherwise |p| will be a non-null pointer to a node such that
6370 |undefined<type(p)<mp_structured|.
6371
6372 @d abort_find { return null; }
6373
6374 @c 
6375 pointer mp_find_variable (MP mp,pointer t) {
6376   pointer p,q,r,s; /* nodes in the ``value'' line */
6377   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6378   integer n; /* subscript or attribute */
6379   memory_word save_word; /* temporary storage for a word of |mem| */
6380 @^inner loop@>
6381   p=info(t); t=link(t);
6382   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6383   if ( equiv(p)==null ) mp_new_root(mp, p);
6384   p=equiv(p); pp=p;
6385   while ( t!=null ) { 
6386     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6387     if ( t<mp->hi_mem_min ) {
6388       @<Descend one level for the subscript |value(t)|@>
6389     } else {
6390       @<Descend one level for the attribute |info(t)|@>;
6391     }
6392     t=link(t);
6393   }
6394   if ( type(pp)>=mp_structured ) {
6395     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6396   }
6397   if ( type(p)==mp_structured ) p=attr_head(p);
6398   if ( type(p)==undefined ) { 
6399     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6400     type(p)=type(pp); value(p)=null;
6401   };
6402   return p;
6403 }
6404
6405 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6406 |pp|~stays in the collective line while |p|~goes through actual subscript
6407 values.
6408
6409 @<Make sure that both nodes |p| and |pp|...@>=
6410 if ( type(pp)!=mp_structured ) { 
6411   if ( type(pp)>mp_structured ) abort_find;
6412   ss=mp_new_structure(mp, pp);
6413   if ( p==pp ) p=ss;
6414   pp=ss;
6415 }; /* now |type(pp)=mp_structured| */
6416 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6417   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6418
6419 @ We want this part of the program to be reasonably fast, in case there are
6420 @^inner loop@>
6421 lots of subscripts at the same level of the data structure. Therefore
6422 we store an ``infinite'' value in the word that appears at the end of the
6423 subscript list, even though that word isn't part of a subscript node.
6424
6425 @<Descend one level for the subscript |value(t)|@>=
6426
6427   n=value(t);
6428   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6429   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6430   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6431   do {  
6432     r=s; s=link(s);
6433   } while (n>subscript(s));
6434   if ( n==subscript(s) ) {
6435     p=s;
6436   } else { 
6437     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6438     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6439   }
6440   mp->mem[subscript_loc(q)]=save_word;
6441 }
6442
6443 @ @<Descend one level for the attribute |info(t)|@>=
6444
6445   n=info(t);
6446   ss=attr_head(pp);
6447   do {  
6448     rr=ss; ss=link(ss);
6449   } while (n>attr_loc(ss));
6450   if ( n<attr_loc(ss) ) { 
6451     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6452     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6453     parent(qq)=pp; ss=qq;
6454   }
6455   if ( p==pp ) { 
6456     p=ss; pp=ss;
6457   } else { 
6458     pp=ss; s=attr_head(p);
6459     do {  
6460       r=s; s=link(s);
6461     } while (n>attr_loc(s));
6462     if ( n==attr_loc(s) ) {
6463       p=s;
6464     } else { 
6465       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6466       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6467       parent(q)=p; p=q;
6468     }
6469   }
6470 }
6471
6472 @ Variables lose their former values when they appear in a type declaration,
6473 or when they are defined to be macros or \&{let} equal to something else.
6474 A subroutine will be defined later that recycles the storage associated
6475 with any particular |type| or |value|; our goal now is to study a higher
6476 level process called |flush_variable|, which selectively frees parts of a
6477 variable structure.
6478
6479 This routine has some complexity because of examples such as
6480 `\hbox{\tt numeric x[]a[]b}'
6481 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6482 `\hbox{\tt vardef x[]a[]=...}'
6483 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6484 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6485 to handle such examples is to use recursion; so that's what we~do.
6486 @^recursion@>
6487
6488 Parameter |p| points to the root information of the variable;
6489 parameter |t| points to a list of one-word nodes that represent
6490 suffixes, with |info=collective_subscript| for subscripts.
6491
6492 @<Declarations@>=
6493 @<Declare subroutines for printing expressions@>
6494 @<Declare basic dependency-list subroutines@>
6495 @<Declare the recycling subroutines@>
6496 void mp_flush_cur_exp (MP mp,scaled v) ;
6497 @<Declare the procedure called |flush_below_variable|@>
6498
6499 @ @c 
6500 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6501   pointer q,r; /* list manipulation */
6502   halfword n; /* attribute to match */
6503   while ( t!=null ) { 
6504     if ( type(p)!=mp_structured ) return;
6505     n=info(t); t=link(t);
6506     if ( n==collective_subscript ) { 
6507       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6508       while ( name_type(q)==mp_subscr ){ 
6509         mp_flush_variable(mp, q,t,discard_suffixes);
6510         if ( t==null ) {
6511           if ( type(q)==mp_structured ) r=q;
6512           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6513         } else {
6514           r=q;
6515         }
6516         q=link(r);
6517       }
6518     }
6519     p=attr_head(p);
6520     do {  
6521       r=p; p=link(p);
6522     } while (attr_loc(p)<n);
6523     if ( attr_loc(p)!=n ) return;
6524   }
6525   if ( discard_suffixes ) {
6526     mp_flush_below_variable(mp, p);
6527   } else { 
6528     if ( type(p)==mp_structured ) p=attr_head(p);
6529     mp_recycle_value(mp, p);
6530   }
6531 }
6532
6533 @ The next procedure is simpler; it wipes out everything but |p| itself,
6534 which becomes undefined.
6535
6536 @<Declare the procedure called |flush_below_variable|@>=
6537 void mp_flush_below_variable (MP mp, pointer p);
6538
6539 @ @c
6540 void mp_flush_below_variable (MP mp,pointer p) {
6541    pointer q,r; /* list manipulation registers */
6542   if ( type(p)!=mp_structured ) {
6543     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6544   } else { 
6545     q=subscr_head(p);
6546     while ( name_type(q)==mp_subscr ) { 
6547       mp_flush_below_variable(mp, q); r=q; q=link(q);
6548       mp_free_node(mp, r,subscr_node_size);
6549     }
6550     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6551     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6552     else mp_free_node(mp, r,subscr_node_size);
6553     /* we assume that |subscr_node_size=attr_node_size| */
6554     do {  
6555       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6556     } while (q!=end_attr);
6557     type(p)=undefined;
6558   }
6559 }
6560
6561 @ Just before assigning a new value to a variable, we will recycle the
6562 old value and make the old value undefined. The |und_type| routine
6563 determines what type of undefined value should be given, based on
6564 the current type before recycling.
6565
6566 @c 
6567 small_number mp_und_type (MP mp,pointer p) { 
6568   switch (type(p)) {
6569   case undefined: case mp_vacuous:
6570     return undefined;
6571   case mp_boolean_type: case mp_unknown_boolean:
6572     return mp_unknown_boolean;
6573   case mp_string_type: case mp_unknown_string:
6574     return mp_unknown_string;
6575   case mp_pen_type: case mp_unknown_pen:
6576     return mp_unknown_pen;
6577   case mp_path_type: case mp_unknown_path:
6578     return mp_unknown_path;
6579   case mp_picture_type: case mp_unknown_picture:
6580     return mp_unknown_picture;
6581   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6582   case mp_pair_type: case mp_numeric_type: 
6583     return type(p);
6584   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6585     return mp_numeric_type;
6586   } /* there are no other cases */
6587   return 0;
6588 }
6589
6590 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6591 of a symbolic token. It must remove any variable structure or macro
6592 definition that is currently attached to that symbol. If the |saving|
6593 parameter is true, a subsidiary structure is saved instead of destroyed.
6594
6595 @c 
6596 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6597   pointer q; /* |equiv(p)| */
6598   q=equiv(p);
6599   switch (eq_type(p) % outer_tag)  {
6600   case defined_macro:
6601   case secondary_primary_macro:
6602   case tertiary_secondary_macro:
6603   case expression_tertiary_macro: 
6604     if ( ! saving ) mp_delete_mac_ref(mp, q);
6605     break;
6606   case tag_token:
6607     if ( q!=null ) {
6608       if ( saving ) {
6609         name_type(q)=mp_saved_root;
6610       } else { 
6611         mp_flush_below_variable(mp, q); mp_free_node(mp,q,value_node_size); 
6612       }
6613     }
6614     break;
6615   default:
6616     break;
6617   }
6618   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6619 };
6620
6621 @* \[16] Saving and restoring equivalents.
6622 The nested structure given by \&{begingroup} and \&{endgroup}
6623 allows |eqtb| entries to be saved and restored, so that temporary changes
6624 can be made without difficulty.  When the user requests a current value to
6625 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6626 \&{endgroup} ultimately causes the old values to be removed from the save
6627 stack and put back in their former places.
6628
6629 The save stack is a linked list containing three kinds of entries,
6630 distinguished by their |info| fields. If |p| points to a saved item,
6631 then
6632
6633 \smallskip\hang
6634 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6635 such an item to the save stack and each \&{endgroup} cuts back the stack
6636 until the most recent such entry has been removed.
6637
6638 \smallskip\hang
6639 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6640 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6641 commands or suitable \&{interim} commands.
6642
6643 \smallskip\hang
6644 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6645 integer to be restored to internal parameter number~|q|. Such entries
6646 are generated by \&{interim} commands.
6647
6648 \smallskip\noindent
6649 The global variable |save_ptr| points to the top item on the save stack.
6650
6651 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6652 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6653 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6654   link((A))=mp->save_ptr; mp->save_ptr=(A);
6655   }
6656
6657 @<Glob...@>=
6658 pointer save_ptr; /* the most recently saved item */
6659
6660 @ @<Set init...@>=mp->save_ptr=null;
6661
6662 @ The |save_variable| routine is given a hash address |q|; it salts this
6663 address in the save stack, together with its current equivalent,
6664 then makes token~|q| behave as though it were brand new.
6665
6666 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6667 things from the stack when the program is not inside a group, so there's
6668 no point in wasting the space.
6669
6670 @c void mp_save_variable (MP mp,pointer q) {
6671   pointer p; /* temporary register */
6672   if ( mp->save_ptr!=null ){ 
6673     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6674     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6675   }
6676   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6677 }
6678
6679 @ Similarly, |save_internal| is given the location |q| of an internal
6680 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6681 third kind.
6682
6683 @c void mp_save_internal (MP mp,halfword q) {
6684   pointer p; /* new item for the save stack */
6685   if ( mp->save_ptr!=null ){ 
6686      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6687     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6688   }
6689 }
6690
6691 @ At the end of a group, the |unsave| routine restores all of the saved
6692 equivalents in reverse order. This routine will be called only when there
6693 is at least one boundary item on the save stack.
6694
6695 @c 
6696 void mp_unsave (MP mp) {
6697   pointer q; /* index to saved item */
6698   pointer p; /* temporary register */
6699   while ( info(mp->save_ptr)!=0 ) {
6700     q=info(mp->save_ptr);
6701     if ( q>hash_end ) {
6702       if ( mp->internal[mp_tracing_restores]>0 ) {
6703         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6704         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6705         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6706         mp_end_diagnostic(mp, false);
6707       }
6708       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6709     } else { 
6710       if ( mp->internal[mp_tracing_restores]>0 ) {
6711         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6712         mp_print_text(q); mp_print_char(mp, '}');
6713         mp_end_diagnostic(mp, false);
6714       }
6715       mp_clear_symbol(mp, q,false);
6716       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6717       if ( eq_type(q) % outer_tag==tag_token ) {
6718         p=equiv(q);
6719         if ( p!=null ) name_type(p)=mp_root;
6720       }
6721     }
6722     p=link(mp->save_ptr); 
6723     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6724   }
6725   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6726 }
6727
6728 @* \[17] Data structures for paths.
6729 When a \MP\ user specifies a path, \MP\ will create a list of knots
6730 and control points for the associated cubic spline curves. If the
6731 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6732 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6733 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6734 @:Bezier}{B\'ezier, Pierre Etienne@>
6735 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6736 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6737 for |0<=t<=1|.
6738
6739 There is a 8-word node for each knot $z_k$, containing one word of
6740 control information and six words for the |x| and |y| coordinates of
6741 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6742 |left_type| and |right_type| fields, which each occupy a quarter of
6743 the first word in the node; they specify properties of the curve as it
6744 enters and leaves the knot. There's also a halfword |link| field,
6745 which points to the following knot, and a final supplementary word (of
6746 which only a quarter is used).
6747
6748 If the path is a closed contour, knots 0 and |n| are identical;
6749 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6750 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6751 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6752 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6753
6754 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6755 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6756 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6757 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6758 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6759 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6760 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6761 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6762 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6763 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6764 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6765 @d left_coord(A)   mp->mem[(A)+2].sc
6766   /* coordinate of previous control point given |x_loc| or |y_loc| */
6767 @d right_coord(A)   mp->mem[(A)+4].sc
6768   /* coordinate of next control point given |x_loc| or |y_loc| */
6769 @d knot_node_size 8 /* number of words in a knot node */
6770
6771 @<Types...@>=
6772 enum mp_knot_type {
6773  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6774  mp_explicit, /* |left_type| or |right_type| when control points are known */
6775  mp_given, /* |left_type| or |right_type| when a direction is given */
6776  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6777  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6778  mp_end_cycle
6779 } ;
6780
6781 @ Before the B\'ezier control points have been calculated, the memory
6782 space they will ultimately occupy is taken up by information that can be
6783 used to compute them. There are four cases:
6784
6785 \yskip
6786 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6787 the knot in the same direction it entered; \MP\ will figure out a
6788 suitable direction.
6789
6790 \yskip
6791 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6792 knot in a direction depending on the angle at which it enters the next
6793 knot and on the curl parameter stored in |right_curl|.
6794
6795 \yskip
6796 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6797 knot in a nonzero direction stored as an |angle| in |right_given|.
6798
6799 \yskip
6800 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6801 point for leaving this knot has already been computed; it is in the
6802 |right_x| and |right_y| fields.
6803
6804 \yskip\noindent
6805 The rules for |left_type| are similar, but they refer to the curve entering
6806 the knot, and to \\{left} fields instead of \\{right} fields.
6807
6808 Non-|explicit| control points will be chosen based on ``tension'' parameters
6809 in the |left_tension| and |right_tension| fields. The
6810 `\&{atleast}' option is represented by negative tension values.
6811 @:at_least_}{\&{atleast} primitive@>
6812
6813 For example, the \MP\ path specification
6814 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6815   3 and 4..p},$$
6816 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6817 by the six knots
6818 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6819 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6820 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6821 \noalign{\yskip}
6822 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6823 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6824 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6825 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6826 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6827 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6828 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6829 Of course, this example is more complicated than anything a normal user
6830 would ever write.
6831
6832 These types must satisfy certain restrictions because of the form of \MP's
6833 path syntax:
6834 (i)~|open| type never appears in the same node together with |endpoint|,
6835 |given|, or |curl|.
6836 (ii)~The |right_type| of a node is |explicit| if and only if the
6837 |left_type| of the following node is |explicit|.
6838 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6839
6840 @d left_curl left_x /* curl information when entering this knot */
6841 @d left_given left_x /* given direction when entering this knot */
6842 @d left_tension left_y /* tension information when entering this knot */
6843 @d right_curl right_x /* curl information when leaving this knot */
6844 @d right_given right_x /* given direction when leaving this knot */
6845 @d right_tension right_y /* tension information when leaving this knot */
6846
6847 @ Knots can be user-supplied, or they can be created by program code,
6848 like the |split_cubic| function, or |copy_path|. The distinction is
6849 needed for the cleanup routine that runs after |split_cubic|, because
6850 it should only delete knots it has previously inserted, and never
6851 anything that was user-supplied. In order to be able to differentiate
6852 one knot from another, we will set |originator(p):=mp_metapost_user| when
6853 it appeared in the actual metapost program, and
6854 |originator(p):=mp_program_code| in all other cases.
6855
6856 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6857
6858 @<Types...@>=
6859 enum {
6860   mp_program_code=0, /* not created by a user */
6861   mp_metapost_user, /* created by a user */
6862 };
6863
6864 @ Here is a routine that prints a given knot list
6865 in symbolic form. It illustrates the conventions discussed above,
6866 and checks for anomalies that might arise while \MP\ is being debugged.
6867
6868 @<Declare subroutines for printing expressions@>=
6869 void mp_pr_path (MP mp,pointer h);
6870
6871 @ @c
6872 void mp_pr_path (MP mp,pointer h) {
6873   pointer p,q; /* for list traversal */
6874   p=h;
6875   do {  
6876     q=link(p);
6877     if ( (p==null)||(q==null) ) { 
6878       mp_print_nl(mp, "???"); return; /* this won't happen */
6879 @.???@>
6880     }
6881     @<Print information for adjacent knots |p| and |q|@>;
6882   DONE1:
6883     p=q;
6884     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6885       @<Print two dots, followed by |given| or |curl| if present@>;
6886     }
6887   } while (p!=h);
6888   if ( left_type(h)!=mp_endpoint ) 
6889     mp_print(mp, "cycle");
6890 }
6891
6892 @ @<Print information for adjacent knots...@>=
6893 mp_print_two(mp, x_coord(p),y_coord(p));
6894 switch (right_type(p)) {
6895 case mp_endpoint: 
6896   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6897 @.open?@>
6898   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6899   goto DONE1;
6900   break;
6901 case mp_explicit: 
6902   @<Print control points between |p| and |q|, then |goto done1|@>;
6903   break;
6904 case mp_open: 
6905   @<Print information for a curve that begins |open|@>;
6906   break;
6907 case mp_curl:
6908 case mp_given: 
6909   @<Print information for a curve that begins |curl| or |given|@>;
6910   break;
6911 default:
6912   mp_print(mp, "???"); /* can't happen */
6913 @.???@>
6914   break;
6915 }
6916 if ( left_type(q)<=mp_explicit ) {
6917   mp_print(mp, "..control?"); /* can't happen */
6918 @.control?@>
6919 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6920   @<Print tension between |p| and |q|@>;
6921 }
6922
6923 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6924 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6925
6926 @<Print two dots...@>=
6927
6928   mp_print_nl(mp, " ..");
6929   if ( left_type(p)==mp_given ) { 
6930     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6931     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6932     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6933   } else if ( left_type(p)==mp_curl ){ 
6934     mp_print(mp, "{curl "); 
6935     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6936   }
6937 }
6938
6939 @ @<Print tension between |p| and |q|@>=
6940
6941   mp_print(mp, "..tension ");
6942   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6943   mp_print_scaled(mp, abs(right_tension(p)));
6944   if ( right_tension(p)!=left_tension(q) ){ 
6945     mp_print(mp, " and ");
6946     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6947     mp_print_scaled(mp, abs(left_tension(q)));
6948   }
6949 }
6950
6951 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6952
6953   mp_print(mp, "..controls "); 
6954   mp_print_two(mp, right_x(p),right_y(p)); 
6955   mp_print(mp, " and ");
6956   if ( left_type(q)!=mp_explicit ) { 
6957     mp_print(mp, "??"); /* can't happen */
6958 @.??@>
6959   } else {
6960     mp_print_two(mp, left_x(q),left_y(q));
6961   }
6962   goto DONE1;
6963 }
6964
6965 @ @<Print information for a curve that begins |open|@>=
6966 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
6967   mp_print(mp, "{open?}"); /* can't happen */
6968 @.open?@>
6969 }
6970
6971 @ A curl of 1 is shown explicitly, so that the user sees clearly that
6972 \MP's default curl is present.
6973
6974 The code here uses the fact that |left_curl==left_given| and
6975 |right_curl==right_given|.
6976
6977 @<Print information for a curve that begins |curl|...@>=
6978
6979   if ( left_type(p)==mp_open )  
6980     mp_print(mp, "??"); /* can't happen */
6981 @.??@>
6982   if ( right_type(p)==mp_curl ) { 
6983     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
6984   } else { 
6985     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
6986     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
6987     mp_print_scaled(mp, mp->n_sin);
6988   }
6989   mp_print_char(mp, '}');
6990 }
6991
6992 @ It is convenient to have another version of |pr_path| that prints the path
6993 as a diagnostic message.
6994
6995 @<Declare subroutines for printing expressions@>=
6996 void mp_print_path (MP mp,pointer h, char *s, boolean nuline) { 
6997   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
6998 @.Path at line...@>
6999   mp_pr_path(mp, h);
7000   mp_end_diagnostic(mp, true);
7001 }
7002
7003 @ If we want to duplicate a knot node, we can say |copy_knot|:
7004
7005 @c 
7006 pointer mp_copy_knot (MP mp,pointer p) {
7007   pointer q; /* the copy */
7008   int k; /* runs through the words of a knot node */
7009   q=mp_get_node(mp, knot_node_size);
7010   for (k=0;k<knot_node_size;k++) {
7011     mp->mem[q+k]=mp->mem[p+k];
7012   }
7013   originator(q)=originator(p);
7014   return q;
7015 }
7016
7017 @ The |copy_path| routine makes a clone of a given path.
7018
7019 @c 
7020 pointer mp_copy_path (MP mp, pointer p) {
7021   pointer q,pp,qq; /* for list manipulation */
7022   q=mp_copy_knot(mp, p);
7023   qq=q; pp=link(p);
7024   while ( pp!=p ) { 
7025     link(qq)=mp_copy_knot(mp, pp);
7026     qq=link(qq);
7027     pp=link(pp);
7028   }
7029   link(qq)=q;
7030   return q;
7031 }
7032
7033
7034 @ Just before |ship_out|, knot lists are exported for printing.
7035
7036 The |gr_XXXX| macros are defined in |mppsout.h|.
7037
7038 @c 
7039 struct mp_knot *mp_export_knot (MP mp,pointer p) {
7040   struct mp_knot *q; /* the copy */
7041   if (p==null)
7042      return NULL;
7043   q = mp_xmalloc(mp, 1, sizeof (struct mp_knot));
7044   memset(q,0,sizeof (struct mp_knot));
7045   gr_left_type(q)  = left_type(p);
7046   gr_right_type(q) = right_type(p);
7047   gr_x_coord(q)    = x_coord(p);
7048   gr_y_coord(q)    = y_coord(p);
7049   gr_left_x(q)     = left_x(p);
7050   gr_left_y(q)     = left_y(p);
7051   gr_right_x(q)    = right_x(p);
7052   gr_right_y(q)    = right_y(p);
7053   gr_originator(q) = originator(p);
7054   return q;
7055 }
7056
7057 @ The |export_knot_list| routine therefore also makes a clone 
7058 of a given path.
7059
7060 @c 
7061 struct mp_knot *mp_export_knot_list (MP mp, pointer p) {
7062   struct mp_knot *q, *qq; /* for list manipulation */
7063   pointer pp; /* for list manipulation */
7064   if (p==null)
7065      return NULL;
7066   q=mp_export_knot(mp, p);
7067   qq=q; pp=link(p);
7068   while ( pp!=p ) { 
7069     gr_next_knot(qq)=mp_export_knot(mp, pp);
7070     qq=gr_next_knot(qq);
7071     pp=link(pp);
7072   }
7073   gr_next_knot(qq)=q;
7074   return q;
7075 }
7076
7077
7078 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7079 returns a pointer to the first node of the copy, if the path is a cycle,
7080 but to the final node of a non-cyclic copy. The global
7081 variable |path_tail| will point to the final node of the original path;
7082 this trick makes it easier to implement `\&{doublepath}'.
7083
7084 All node types are assumed to be |endpoint| or |explicit| only.
7085
7086 @c 
7087 pointer mp_htap_ypoc (MP mp,pointer p) {
7088   pointer q,pp,qq,rr; /* for list manipulation */
7089   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7090   qq=q; pp=p;
7091   while (1) { 
7092     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7093     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7094     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7095     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7096     originator(qq)=originator(pp);
7097     if ( link(pp)==p ) { 
7098       link(q)=qq; mp->path_tail=pp; return q;
7099     }
7100     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7101   }
7102 }
7103
7104 @ @<Glob...@>=
7105 pointer path_tail; /* the node that links to the beginning of a path */
7106
7107 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7108 calling the following subroutine.
7109
7110 @<Declare the recycling subroutines@>=
7111 void mp_toss_knot_list (MP mp,pointer p) ;
7112
7113 @ @c
7114 void mp_toss_knot_list (MP mp,pointer p) {
7115   pointer q; /* the node being freed */
7116   pointer r; /* the next node */
7117   q=p;
7118   do {  
7119     r=link(q); 
7120     mp_free_node(mp, q,knot_node_size); q=r;
7121   } while (q!=p);
7122 }
7123
7124 @* \[18] Choosing control points.
7125 Now we must actually delve into one of \MP's more difficult routines,
7126 the |make_choices| procedure that chooses angles and control points for
7127 the splines of a curve when the user has not specified them explicitly.
7128 The parameter to |make_choices| points to a list of knots and
7129 path information, as described above.
7130
7131 A path decomposes into independent segments at ``breakpoint'' knots,
7132 which are knots whose left and right angles are both prespecified in
7133 some way (i.e., their |left_type| and |right_type| aren't both open).
7134
7135 @c 
7136 @<Declare the procedure called |solve_choices|@>;
7137 void mp_make_choices (MP mp,pointer knots) {
7138   pointer h; /* the first breakpoint */
7139   pointer p,q; /* consecutive breakpoints being processed */
7140   @<Other local variables for |make_choices|@>;
7141   check_arith; /* make sure that |arith_error=false| */
7142   if ( mp->internal[mp_tracing_choices]>0 )
7143     mp_print_path(mp, knots,", before choices",true);
7144   @<If consecutive knots are equal, join them explicitly@>;
7145   @<Find the first breakpoint, |h|, on the path;
7146     insert an artificial breakpoint if the path is an unbroken cycle@>;
7147   p=h;
7148   do {  
7149     @<Fill in the control points between |p| and the next breakpoint,
7150       then advance |p| to that breakpoint@>;
7151   } while (p!=h);
7152   if ( mp->internal[mp_tracing_choices]>0 )
7153     mp_print_path(mp, knots,", after choices",true);
7154   if ( mp->arith_error ) {
7155     @<Report an unexpected problem during the choice-making@>;
7156   }
7157 }
7158
7159 @ @<Report an unexpected problem during the choice...@>=
7160
7161   print_err("Some number got too big");
7162 @.Some number got too big@>
7163   help2("The path that I just computed is out of range.")
7164        ("So it will probably look funny. Proceed, for a laugh.");
7165   mp_put_get_error(mp); mp->arith_error=false;
7166 }
7167
7168 @ Two knots in a row with the same coordinates will always be joined
7169 by an explicit ``curve'' whose control points are identical with the
7170 knots.
7171
7172 @<If consecutive knots are equal, join them explicitly@>=
7173 p=knots;
7174 do {  
7175   q=link(p);
7176   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7177     right_type(p)=mp_explicit;
7178     if ( left_type(p)==mp_open ) { 
7179       left_type(p)=mp_curl; left_curl(p)=unity;
7180     }
7181     left_type(q)=mp_explicit;
7182     if ( right_type(q)==mp_open ) { 
7183       right_type(q)=mp_curl; right_curl(q)=unity;
7184     }
7185     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7186     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7187   }
7188   p=q;
7189 } while (p!=knots)
7190
7191 @ If there are no breakpoints, it is necessary to compute the direction
7192 angles around an entire cycle. In this case the |left_type| of the first
7193 node is temporarily changed to |end_cycle|.
7194
7195 @<Find the first breakpoint, |h|, on the path...@>=
7196 h=knots;
7197 while (1) { 
7198   if ( left_type(h)!=mp_open ) break;
7199   if ( right_type(h)!=mp_open ) break;
7200   h=link(h);
7201   if ( h==knots ) { 
7202     left_type(h)=mp_end_cycle; break;
7203   }
7204 }
7205
7206 @ If |right_type(p)<given| and |q=link(p)|, we must have
7207 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7208
7209 @<Fill in the control points between |p| and the next breakpoint...@>=
7210 q=link(p);
7211 if ( right_type(p)>=mp_given ) { 
7212   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7213   @<Fill in the control information between
7214     consecutive breakpoints |p| and |q|@>;
7215 } else if ( right_type(p)==mp_endpoint ) {
7216   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7217 }
7218 p=q
7219
7220 @ This step makes it possible to transform an explicitly computed path without
7221 checking the |left_type| and |right_type| fields.
7222
7223 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7224
7225   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7226   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7227 }
7228
7229 @ Before we can go further into the way choices are made, we need to
7230 consider the underlying theory. The basic ideas implemented in |make_choices|
7231 are due to John Hobby, who introduced the notion of ``mock curvature''
7232 @^Hobby, John Douglas@>
7233 at a knot. Angles are chosen so that they preserve mock curvature when
7234 a knot is passed, and this has been found to produce excellent results.
7235
7236 It is convenient to introduce some notations that simplify the necessary
7237 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7238 between knots |k| and |k+1|; and let
7239 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7240 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7241 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7242 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7243 $$\eqalign{z_k^+&=z_k+
7244   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7245  z\k^-&=z\k-
7246   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7247 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7248 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7249 corresponding ``offset angles.'' These angles satisfy the condition
7250 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7251 whenever the curve leaves an intermediate knot~|k| in the direction that
7252 it enters.
7253
7254 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7255 the curve at its beginning and ending points. This means that
7256 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7257 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7258 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7259 z\k^-,z\k^{\phantom+};t)$
7260 has curvature
7261 @^curvature@>
7262 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7263 \qquad{\rm and}\qquad
7264 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7265 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7266 @^mock curvature@>
7267 approximation to this true curvature that arises in the limit for
7268 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7269 The standard velocity function satisfies
7270 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7271 hence the mock curvatures are respectively
7272 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7273 \qquad{\rm and}\qquad
7274 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7275
7276 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7277 determines $\phi_k$ when $\theta_k$ is known, so the task of
7278 angle selection is essentially to choose appropriate values for each
7279 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7280 from $(**)$, we obtain a system of linear equations of the form
7281 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7282 where
7283 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7284 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7285 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7286 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7287 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7288 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7289 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7290 hence they have a unique solution. Moreover, in most cases the tensions
7291 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7292 solution numerically stable, and there is an exponential damping
7293 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7294 a factor of~$O(2^{-j})$.
7295
7296 @ However, we still must consider the angles at the starting and ending
7297 knots of a non-cyclic path. These angles might be given explicitly, or
7298 they might be specified implicitly in terms of an amount of ``curl.''
7299
7300 Let's assume that angles need to be determined for a non-cyclic path
7301 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7302 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7303 have been given for $0<k<n$, and it will be convenient to introduce
7304 equations of the same form for $k=0$ and $k=n$, where
7305 $$A_0=B_0=C_n=D_n=0.$$
7306 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7307 define $C_0=0$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7308 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7309 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7310 mock curvature at $z_1$; i.e.,
7311 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7312 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7313 This equation simplifies to
7314 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7315  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7316  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7317 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7318 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7319 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7320 hence the linear equations remain nonsingular.
7321
7322 Similar considerations apply at the right end, when the final angle $\phi_n$
7323 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7324 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7325 or we have
7326 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7327 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7328   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7329
7330 When |make_choices| chooses angles, it must compute the coefficients of
7331 these linear equations, then solve the equations. To compute the coefficients,
7332 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7333 When the equations are solved, the chosen directions $\theta_k$ are put
7334 back into the form of control points by essentially computing sines and
7335 cosines.
7336
7337 @ OK, we are ready to make the hard choices of |make_choices|.
7338 Most of the work is relegated to an auxiliary procedure
7339 called |solve_choices|, which has been introduced to keep
7340 |make_choices| from being extremely long.
7341
7342 @<Fill in the control information between...@>=
7343 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7344   set $n$ to the length of the path@>;
7345 @<Remove |open| types at the breakpoints@>;
7346 mp_solve_choices(mp, p,q,n)
7347
7348 @ It's convenient to precompute quantities that will be needed several
7349 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7350 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7351 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7352 and $z\k-z_k$ will be stored in |psi[k]|.
7353
7354 @<Glob...@>=
7355 int path_size; /* maximum number of knots between breakpoints of a path */
7356 scaled *delta_x;
7357 scaled *delta_y;
7358 scaled *delta; /* knot differences */
7359 angle  *psi; /* turning angles */
7360
7361 @ @<Allocate or initialize ...@>=
7362 mp->delta_x = NULL;
7363 mp->delta_y = NULL;
7364 mp->delta = NULL;
7365 mp->psi = NULL;
7366
7367 @ @<Dealloc variables@>=
7368 xfree(mp->delta_x);
7369 xfree(mp->delta_y);
7370 xfree(mp->delta);
7371 xfree(mp->psi);
7372
7373 @ @<Other local variables for |make_choices|@>=
7374   int k,n; /* current and final knot numbers */
7375   pointer s,t; /* registers for list traversal */
7376   scaled delx,dely; /* directions where |open| meets |explicit| */
7377   fraction sine,cosine; /* trig functions of various angles */
7378
7379 @ @<Calculate the turning angles...@>=
7380 {
7381 RESTART:
7382   k=0; s=p; n=mp->path_size;
7383   do {  
7384     t=link(s);
7385     mp->delta_x[k]=x_coord(t)-x_coord(s);
7386     mp->delta_y[k]=y_coord(t)-y_coord(s);
7387     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7388     if ( k>0 ) { 
7389       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7390       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7391       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7392         mp_take_fraction(mp, mp->delta_y[k],sine),
7393         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7394           mp_take_fraction(mp, mp->delta_x[k],sine));
7395     }
7396     incr(k); s=t;
7397     if ( k==mp->path_size ) {
7398       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7399       goto RESTART; /* retry, loop size has changed */
7400     }
7401     if ( s==q ) n=k;
7402   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7403   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7404 }
7405
7406 @ When we get to this point of the code, |right_type(p)| is either
7407 |given| or |curl| or |open|. If it is |open|, we must have
7408 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7409 case, the |open| type is converted to |given|; however, if the
7410 velocity coming into this knot is zero, the |open| type is
7411 converted to a |curl|, since we don't know the incoming direction.
7412
7413 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7414 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7415
7416 @<Remove |open| types at the breakpoints@>=
7417 if ( left_type(q)==mp_open ) { 
7418   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7419   if ( (delx==0)&&(dely==0) ) { 
7420     left_type(q)=mp_curl; left_curl(q)=unity;
7421   } else { 
7422     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7423   }
7424 }
7425 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7426   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7427   if ( (delx==0)&&(dely==0) ) { 
7428     right_type(p)=mp_curl; right_curl(p)=unity;
7429   } else { 
7430     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7431   }
7432 }
7433
7434 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7435 and exactly one of the breakpoints involves a curl. The simplest case occurs
7436 when |n=1| and there is a curl at both breakpoints; then we simply draw
7437 a straight line.
7438
7439 But before coding up the simple cases, we might as well face the general case,
7440 since we must deal with it sooner or later, and since the general case
7441 is likely to give some insight into the way simple cases can be handled best.
7442
7443 When there is no cycle, the linear equations to be solved form a tridiagonal
7444 system, and we can apply the standard technique of Gaussian elimination
7445 to convert that system to a sequence of equations of the form
7446 $$\theta_0+u_0\theta_1=v_0,\quad
7447 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7448 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7449 \theta_n=v_n.$$
7450 It is possible to do this diagonalization while generating the equations.
7451 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7452 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7453
7454 The procedure is slightly more complex when there is a cycle, but the
7455 basic idea will be nearly the same. In the cyclic case the right-hand
7456 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7457 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7458 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7459 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7460 eliminate the $w$'s from the system, after which the solution can be
7461 obtained as before.
7462
7463 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7464 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7465 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7466 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7467
7468 @<Glob...@>=
7469 angle *theta; /* values of $\theta_k$ */
7470 fraction *uu; /* values of $u_k$ */
7471 angle *vv; /* values of $v_k$ */
7472 fraction *ww; /* values of $w_k$ */
7473
7474 @ @<Allocate or initialize ...@>=
7475 mp->theta = NULL;
7476 mp->uu = NULL;
7477 mp->vv = NULL;
7478 mp->ww = NULL;
7479
7480 @ @<Dealloc variables@>=
7481 xfree(mp->theta);
7482 xfree(mp->uu);
7483 xfree(mp->vv);
7484 xfree(mp->ww);
7485
7486 @ @<Declare |mp_reallocate| functions@>=
7487 void mp_reallocate_paths (MP mp, int l);
7488
7489 @ @c
7490 void mp_reallocate_paths (MP mp, int l) {
7491   XREALLOC (mp->delta_x, l, scaled);
7492   XREALLOC (mp->delta_y, l, scaled);
7493   XREALLOC (mp->delta,   l, scaled);
7494   XREALLOC (mp->psi,     l, angle);
7495   XREALLOC (mp->theta,   l, angle);
7496   XREALLOC (mp->uu,      l, fraction);
7497   XREALLOC (mp->vv,      l, angle);
7498   XREALLOC (mp->ww,      l, fraction);
7499   mp->path_size = l;
7500 }
7501
7502 @ Our immediate problem is to get the ball rolling by setting up the
7503 first equation or by realizing that no equations are needed, and to fit
7504 this initialization into a framework suitable for the overall computation.
7505
7506 @<Declare the procedure called |solve_choices|@>=
7507 @<Declare subroutines needed by |solve_choices|@>;
7508 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7509   int k; /* current knot number */
7510   pointer r,s,t; /* registers for list traversal */
7511   @<Other local variables for |solve_choices|@>;
7512   k=0; s=p; r=0;
7513   while (1) { 
7514     t=link(s);
7515     if ( k==0 ) {
7516       @<Get the linear equations started; or |return|
7517         with the control points in place, if linear equations
7518         needn't be solved@>
7519     } else  { 
7520       switch (left_type(s)) {
7521       case mp_end_cycle: case mp_open:
7522         @<Set up equation to match mock curvatures
7523           at $z_k$; then |goto found| with $\theta_n$
7524           adjusted to equal $\theta_0$, if a cycle has ended@>;
7525         break;
7526       case mp_curl:
7527         @<Set up equation for a curl at $\theta_n$
7528           and |goto found|@>;
7529         break;
7530       case mp_given:
7531         @<Calculate the given value of $\theta_n$
7532           and |goto found|@>;
7533         break;
7534       } /* there are no other cases */
7535     }
7536     r=s; s=t; incr(k);
7537   }
7538 FOUND:
7539   @<Finish choosing angles and assigning control points@>;
7540 }
7541
7542 @ On the first time through the loop, we have |k=0| and |r| is not yet
7543 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7544
7545 @<Get the linear equations started...@>=
7546 switch (right_type(s)) {
7547 case mp_given: 
7548   if ( left_type(t)==mp_given ) {
7549     @<Reduce to simple case of two givens  and |return|@>
7550   } else {
7551     @<Set up the equation for a given value of $\theta_0$@>;
7552   }
7553   break;
7554 case mp_curl: 
7555   if ( left_type(t)==mp_curl ) {
7556     @<Reduce to simple case of straight line and |return|@>
7557   } else {
7558     @<Set up the equation for a curl at $\theta_0$@>;
7559   }
7560   break;
7561 case mp_open: 
7562   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7563   /* this begins a cycle */
7564   break;
7565 } /* there are no other cases */
7566
7567 @ The general equation that specifies equality of mock curvature at $z_k$ is
7568 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7569 as derived above. We want to combine this with the already-derived equation
7570 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7571 a new equation
7572 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7573 equation
7574 $$(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}
7575     -A_kw_{k-1}\theta_0$$
7576 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7577 fixed-point arithmetic, avoiding the chance of overflow while retaining
7578 suitable precision.
7579
7580 The calculations will be performed in several registers that
7581 provide temporary storage for intermediate quantities.
7582
7583 @<Other local variables for |solve_choices|@>=
7584 fraction aa,bb,cc,ff,acc; /* temporary registers */
7585 scaled dd,ee; /* likewise, but |scaled| */
7586 scaled lt,rt; /* tension values */
7587
7588 @ @<Set up equation to match mock curvatures...@>=
7589 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7590     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7591     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7592   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7593   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7594   @<Calculate the values of $v_k$ and $w_k$@>;
7595   if ( left_type(s)==mp_end_cycle ) {
7596     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7597   }
7598 }
7599
7600 @ Since tension values are never less than 3/4, the values |aa| and
7601 |bb| computed here are never more than 4/5.
7602
7603 @<Calculate the values $\\{aa}=...@>=
7604 if ( abs(right_tension(r))==unity) { 
7605   aa=fraction_half; dd=2*mp->delta[k];
7606 } else { 
7607   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7608   dd=mp_take_fraction(mp, mp->delta[k],
7609     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7610 }
7611 if ( abs(left_tension(t))==unity ){ 
7612   bb=fraction_half; ee=2*mp->delta[k-1];
7613 } else { 
7614   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7615   ee=mp_take_fraction(mp, mp->delta[k-1],
7616     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7617 }
7618 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7619
7620 @ The ratio to be calculated in this step can be written in the form
7621 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7622   \\{cc}\cdot\\{dd},$$
7623 because of the quantities just calculated. The values of |dd| and |ee|
7624 will not be needed after this step has been performed.
7625
7626 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7627 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7628 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7629   if ( lt<rt ) { 
7630     ff=mp_make_fraction(mp, lt,rt);
7631     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7632     dd=mp_take_fraction(mp, dd,ff);
7633   } else { 
7634     ff=mp_make_fraction(mp, rt,lt);
7635     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7636     ee=mp_take_fraction(mp, ee,ff);
7637   }
7638 }
7639 ff=mp_make_fraction(mp, ee,ee+dd)
7640
7641 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7642 equation was specified by a curl. In that case we must use a special
7643 method of computation to prevent overflow.
7644
7645 Fortunately, the calculations turn out to be even simpler in this ``hard''
7646 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7647 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7648
7649 @<Calculate the values of $v_k$ and $w_k$@>=
7650 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7651 if ( right_type(r)==mp_curl ) { 
7652   mp->ww[k]=0;
7653   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7654 } else { 
7655   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7656     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7657   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7658   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7659   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7660   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7661   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7662 }
7663
7664 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7665 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7666 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7667 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7668 were no cycle.
7669
7670 The idea in the following code is to observe that
7671 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7672 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7673   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7674 so we can solve for $\theta_n=\theta_0$.
7675
7676 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7677
7678 aa=0; bb=fraction_one; /* we have |k=n| */
7679 do {  decr(k);
7680 if ( k==0 ) k=n;
7681   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7682   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7683 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7684 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7685 mp->theta[n]=aa; mp->vv[0]=aa;
7686 for (k=1;k<=n-1;k++) {
7687   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7688 }
7689 goto FOUND;
7690 }
7691
7692 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7693   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7694
7695 @<Calculate the given value of $\theta_n$...@>=
7696
7697   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7698   reduce_angle(mp->theta[n]);
7699   goto FOUND;
7700 }
7701
7702 @ @<Set up the equation for a given value of $\theta_0$@>=
7703
7704   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7705   reduce_angle(mp->vv[0]);
7706   mp->uu[0]=0; mp->ww[0]=0;
7707 }
7708
7709 @ @<Set up the equation for a curl at $\theta_0$@>=
7710 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7711   if ( (rt==unity)&&(lt==unity) )
7712     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7713   else 
7714     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7715   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7716 }
7717
7718 @ @<Set up equation for a curl at $\theta_n$...@>=
7719 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7720   if ( (rt==unity)&&(lt==unity) )
7721     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7722   else 
7723     ff=mp_curl_ratio(mp, cc,lt,rt);
7724   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7725     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7726   goto FOUND;
7727 }
7728
7729 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7730 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7731 a somewhat tedious program to calculate
7732 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7733   \alpha^3\gamma+(3-\beta)\beta^2},$$
7734 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7735 is necessary only if the curl and tension are both large.)
7736 The values of $\alpha$ and $\beta$ will be at most~4/3.
7737
7738 @<Declare subroutines needed by |solve_choices|@>=
7739 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7740                         scaled b_tension) {
7741   fraction alpha,beta,num,denom,ff; /* registers */
7742   alpha=mp_make_fraction(mp, unity,a_tension);
7743   beta=mp_make_fraction(mp, unity,b_tension);
7744   if ( alpha<=beta ) {
7745     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7746     gamma=mp_take_fraction(mp, gamma,ff);
7747     beta=beta / 010000; /* convert |fraction| to |scaled| */
7748     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7749     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7750   } else { 
7751     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7752     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7753     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7754       /* $1365\approx 2^{12}/3$ */
7755     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7756   }
7757   if ( num>=denom+denom+denom+denom ) return fraction_four;
7758   else return mp_make_fraction(mp, num,denom);
7759 }
7760
7761 @ We're in the home stretch now.
7762
7763 @<Finish choosing angles and assigning control points@>=
7764 for (k=n-1;k>=0;k--) {
7765   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7766 }
7767 s=p; k=0;
7768 do {  
7769   t=link(s);
7770   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7771   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7772   mp_set_controls(mp, s,t,k);
7773   incr(k); s=t;
7774 } while (k!=n)
7775
7776 @ The |set_controls| routine actually puts the control points into
7777 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7778 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7779 $\cos\phi$ needed in this calculation.
7780
7781 @<Glob...@>=
7782 fraction st;
7783 fraction ct;
7784 fraction sf;
7785 fraction cf; /* sines and cosines */
7786
7787 @ @<Declare subroutines needed by |solve_choices|@>=
7788 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7789   fraction rr,ss; /* velocities, divided by thrice the tension */
7790   scaled lt,rt; /* tensions */
7791   fraction sine; /* $\sin(\theta+\phi)$ */
7792   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7793   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7794   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7795   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7796     @<Decrease the velocities,
7797       if necessary, to stay inside the bounding triangle@>;
7798   }
7799   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7800                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7801                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7802   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7803                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7804                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7805   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7806                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7807                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7808   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7809                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7810                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7811   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7812 }
7813
7814 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7815 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7816 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7817 there is no ``bounding triangle.''
7818 @:at_least_}{\&{atleast} primitive@>
7819
7820 @<Decrease the velocities, if necessary...@>=
7821 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7822   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7823                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7824   if ( sine>0 ) {
7825     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7826     if ( right_tension(p)<0 )
7827      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7828       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7829     if ( left_tension(q)<0 )
7830      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7831       ss=mp_make_fraction(mp, abs(mp->st),sine);
7832   }
7833 }
7834
7835 @ Only the simple cases remain to be handled.
7836
7837 @<Reduce to simple case of two givens and |return|@>=
7838
7839   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7840   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7841   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7842   mp_set_controls(mp, p,q,0); return;
7843 }
7844
7845 @ @<Reduce to simple case of straight line and |return|@>=
7846
7847   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7848   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7849   if ( rt==unity ) {
7850     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7851     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7852     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7853     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7854   } else { 
7855     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7856     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7857     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7858   }
7859   if ( lt==unity ) {
7860     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7861     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7862     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7863     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7864   } else  { 
7865     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7866     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7867     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7868   }
7869   return;
7870 }
7871
7872 @* \[19] Measuring paths.
7873 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7874 allow the user to measure the bounding box of anything that can go into a
7875 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7876 by just finding the bounding box of the knots and the control points. We
7877 need a more accurate version of the bounding box, but we can still use the
7878 easy estimate to save time by focusing on the interesting parts of the path.
7879
7880 @ Computing an accurate bounding box involves a theme that will come up again
7881 and again. Given a Bernshte{\u\i}n polynomial
7882 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7883 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7884 we can conveniently bisect its range as follows:
7885
7886 \smallskip
7887 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7888
7889 \smallskip
7890 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7891 |0<=k<n-j|, for |0<=j<n|.
7892
7893 \smallskip\noindent
7894 Then
7895 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7896  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7897 This formula gives us the coefficients of polynomials to use over the ranges
7898 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7899
7900 @ Now here's a subroutine that's handy for all sorts of path computations:
7901 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7902 returns the unique |fraction| value |t| between 0 and~1 at which
7903 $B(a,b,c;t)$ changes from positive to negative, or returns
7904 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7905 is already negative at |t=0|), |crossing_point| returns the value zero.
7906
7907 @d no_crossing {  return (fraction_one+1); }
7908 @d one_crossing { return fraction_one; }
7909 @d zero_crossing { return 0; }
7910 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7911
7912 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7913   integer d; /* recursive counter */
7914   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7915   if ( a<0 ) zero_crossing;
7916   if ( c>=0 ) { 
7917     if ( b>=0 ) {
7918       if ( c>0 ) { no_crossing; }
7919       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7920       else { one_crossing; } 
7921     }
7922     if ( a==0 ) zero_crossing;
7923   } else if ( a==0 ) {
7924     if ( b<=0 ) zero_crossing;
7925   }
7926   @<Use bisection to find the crossing point, if one exists@>;
7927 }
7928
7929 @ The general bisection method is quite simple when $n=2$, hence
7930 |crossing_point| does not take much time. At each stage in the
7931 recursion we have a subinterval defined by |l| and~|j| such that
7932 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7933 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7934
7935 It is convenient for purposes of calculation to combine the values
7936 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7937 of bisection then corresponds simply to doubling $d$ and possibly
7938 adding~1. Furthermore it proves to be convenient to modify
7939 our previous conventions for bisection slightly, maintaining the
7940 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7941 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7942 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7943
7944 The following code maintains the invariant relations
7945 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7946 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7947 it has been constructed in such a way that no arithmetic overflow
7948 will occur if the inputs satisfy
7949 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7950
7951 @<Use bisection to find the crossing point...@>=
7952 d=1; x0=a; x1=a-b; x2=b-c;
7953 do {  
7954   x=half(x1+x2);
7955   if ( x1-x0>x0 ) { 
7956     x2=x; x0+=x0; d+=d;  
7957   } else { 
7958     xx=x1+x-x0;
7959     if ( xx>x0 ) { 
7960       x2=x; x0+=x0; d+=d;
7961     }  else { 
7962       x0=x0-xx;
7963       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7964       x1=x; d=d+d+1;
7965     }
7966   }
7967 } while (d<fraction_one);
7968 return (d-fraction_one)
7969
7970 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7971 a cubic corresponding to the |fraction| value~|t|.
7972
7973 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7974 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7975
7976 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
7977
7978 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
7979   scaled x1,x2,x3; /* intermediate values */
7980   x1=t_of_the_way(knot_coord(p),right_coord(p));
7981   x2=t_of_the_way(right_coord(p),left_coord(q));
7982   x3=t_of_the_way(left_coord(q),knot_coord(q));
7983   x1=t_of_the_way(x1,x2);
7984   x2=t_of_the_way(x2,x3);
7985   return t_of_the_way(x1,x2);
7986 }
7987
7988 @ The actual bounding box information is stored in global variables.
7989 Since it is convenient to address the $x$ and $y$ information
7990 separately, we define arrays indexed by |x_code..y_code| and use
7991 macros to give them more convenient names.
7992
7993 @<Types...@>=
7994 enum mp_bb_code  {
7995   mp_x_code=0, /* index for |minx| and |maxx| */
7996   mp_y_code /* index for |miny| and |maxy| */
7997 } ;
7998
7999
8000 @d minx mp->bbmin[mp_x_code]
8001 @d maxx mp->bbmax[mp_x_code]
8002 @d miny mp->bbmin[mp_y_code]
8003 @d maxy mp->bbmax[mp_y_code]
8004
8005 @<Glob...@>=
8006 scaled bbmin[mp_y_code+1];
8007 scaled bbmax[mp_y_code+1]; 
8008 /* the result of procedures that compute bounding box information */
8009
8010 @ Now we're ready for the key part of the bounding box computation.
8011 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8012 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8013     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8014 $$
8015 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8016 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8017 The |c| parameter is |x_code| or |y_code|.
8018
8019 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8020   boolean wavy; /* whether we need to look for extremes */
8021   scaled del1,del2,del3,del,dmax; /* proportional to the control
8022      points of a quadratic derived from a cubic */
8023   fraction t,tt; /* where a quadratic crosses zero */
8024   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8025   x=knot_coord(q);
8026   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8027   @<Check the control points against the bounding box and set |wavy:=true|
8028     if any of them lie outside@>;
8029   if ( wavy ) {
8030     del1=right_coord(p)-knot_coord(p);
8031     del2=left_coord(q)-right_coord(p);
8032     del3=knot_coord(q)-left_coord(q);
8033     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8034       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8035     if ( del<0 ) {
8036       negate(del1); negate(del2); negate(del3);
8037     };
8038     t=mp_crossing_point(mp, del1,del2,del3);
8039     if ( t<fraction_one ) {
8040       @<Test the extremes of the cubic against the bounding box@>;
8041     }
8042   }
8043 }
8044
8045 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8046 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8047 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8048
8049 @ @<Check the control points against the bounding box and set...@>=
8050 wavy=true;
8051 if ( mp->bbmin[c]<=right_coord(p) )
8052   if ( right_coord(p)<=mp->bbmax[c] )
8053     if ( mp->bbmin[c]<=left_coord(q) )
8054       if ( left_coord(q)<=mp->bbmax[c] )
8055         wavy=false
8056
8057 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8058 section. We just set |del=0| in that case.
8059
8060 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8061 if ( del1!=0 ) del=del1;
8062 else if ( del2!=0 ) del=del2;
8063 else del=del3;
8064 if ( del!=0 ) {
8065   dmax=abs(del1);
8066   if ( abs(del2)>dmax ) dmax=abs(del2);
8067   if ( abs(del3)>dmax ) dmax=abs(del3);
8068   while ( dmax<fraction_half ) {
8069     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8070   }
8071 }
8072
8073 @ Since |crossing_point| has tried to choose |t| so that
8074 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8075 slope, the value of |del2| computed below should not be positive.
8076 But rounding error could make it slightly positive in which case we
8077 must cut it to zero to avoid confusion.
8078
8079 @<Test the extremes of the cubic against the bounding box@>=
8080
8081   x=mp_eval_cubic(mp, p,q,t);
8082   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8083   del2=t_of_the_way(del2,del3);
8084     /* now |0,del2,del3| represent the derivative on the remaining interval */
8085   if ( del2>0 ) del2=0;
8086   tt=mp_crossing_point(mp, 0,-del2,-del3);
8087   if ( tt<fraction_one ) {
8088     @<Test the second extreme against the bounding box@>;
8089   }
8090 }
8091
8092 @ @<Test the second extreme against the bounding box@>=
8093 {
8094    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8095   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8096 }
8097
8098 @ Finding the bounding box of a path is basically a matter of applying
8099 |bound_cubic| twice for each pair of adjacent knots.
8100
8101 @c void mp_path_bbox (MP mp,pointer h) {
8102   pointer p,q; /* a pair of adjacent knots */
8103    minx=x_coord(h); miny=y_coord(h);
8104   maxx=minx; maxy=miny;
8105   p=h;
8106   do {  
8107     if ( right_type(p)==mp_endpoint ) return;
8108     q=link(p);
8109     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8110     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8111     p=q;
8112   } while (p!=h);
8113 }
8114
8115 @ Another important way to measure a path is to find its arc length.  This
8116 is best done by using the general bisection algorithm to subdivide the path
8117 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8118 by simple means.
8119
8120 Since the arc length is the integral with respect to time of the magnitude of
8121 the velocity, it is natural to use Simpson's rule for the approximation.
8122 @^Simpson's rule@>
8123 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8124 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8125 for the arc length of a path of length~1.  For a cubic spline
8126 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8127 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8128 approximation is
8129 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8130 where
8131 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8132 is the result of the bisection algorithm.
8133
8134 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8135 This could be done via the theoretical error bound for Simpson's rule,
8136 @^Simpson's rule@>
8137 but this is impractical because it requires an estimate of the fourth
8138 derivative of the quantity being integrated.  It is much easier to just perform
8139 a bisection step and see how much the arc length estimate changes.  Since the
8140 error for Simpson's rule is proportional to the fourth power of the sample
8141 spacing, the remaining error is typically about $1\over16$ of the amount of
8142 the change.  We say ``typically'' because the error has a pseudo-random behavior
8143 that could cause the two estimates to agree when each contain large errors.
8144
8145 To protect against disasters such as undetected cusps, the bisection process
8146 should always continue until all the $dz_i$ vectors belong to a single
8147 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8148 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8149 If such a spline happens to produce an erroneous arc length estimate that
8150 is little changed by bisection, the amount of the error is likely to be fairly
8151 small.  We will try to arrange things so that freak accidents of this type do
8152 not destroy the inverse relationship between the \&{arclength} and
8153 \&{arctime} operations.
8154 @:arclength_}{\&{arclength} primitive@>
8155 @:arctime_}{\&{arctime} primitive@>
8156
8157 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8158 @^recursion@>
8159 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8160 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8161 returns the time when the arc length reaches |a_goal| if there is such a time.
8162 Thus the return value is either an arc length less than |a_goal| or, if the
8163 arc length would be at least |a_goal|, it returns a time value decreased by
8164 |two|.  This allows the caller to use the sign of the result to distinguish
8165 between arc lengths and time values.  On certain types of overflow, it is
8166 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8167 Otherwise, the result is always less than |a_goal|.
8168
8169 Rather than halving the control point coordinates on each recursive call to
8170 |arc_test|, it is better to keep them proportional to velocity on the original
8171 curve and halve the results instead.  This means that recursive calls can
8172 potentially use larger error tolerances in their arc length estimates.  How
8173 much larger depends on to what extent the errors behave as though they are
8174 independent of each other.  To save computing time, we use optimistic assumptions
8175 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8176 call.
8177
8178 In addition to the tolerance parameter, |arc_test| should also have parameters
8179 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8180 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8181 and they are needed in different instances of |arc_test|.
8182
8183 @c @t\4@>@<Declare subroutines needed by |arc_test|@>;
8184 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8185                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8186                     scaled v2, scaled a_goal, scaled tol) {
8187   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8188   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8189   scaled v002, v022;
8190     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8191   scaled arc; /* best arc length estimate before recursion */
8192   @<Other local variables in |arc_test|@>;
8193   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8194     |dx2|, |dy2|@>;
8195   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8196     set |arc_test| and |return|@>;
8197   @<Test if the control points are confined to one quadrant or rotating them
8198     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8199   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8200     if ( arc < a_goal ) {
8201       return arc;
8202     } else {
8203        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8204          that time minus |two|@>;
8205     }
8206   } else {
8207     @<Use one or two recursive calls to compute the |arc_test| function@>;
8208   }
8209 }
8210
8211 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8212 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8213 |make_fraction| in this inner loop.
8214 @^inner loop@>
8215
8216 @<Use one or two recursive calls to compute the |arc_test| function@>=
8217
8218   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8219     large as possible@>;
8220   tol = tol + halfp(tol);
8221   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8222                   halfp(v02), a_new, tol);
8223   if ( a<0 )  {
8224      return (-halfp(two-a));
8225   } else { 
8226     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8227     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8228                     halfp(v02), v022, v2, a_new, tol);
8229     if ( b<0 )  
8230       return (-halfp(-b) - half_unit);
8231     else  
8232       return (a + half(b-a));
8233   }
8234 }
8235
8236 @ @<Other local variables in |arc_test|@>=
8237 scaled a,b; /* results of recursive calls */
8238 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8239
8240 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8241 a_aux = el_gordo - a_goal;
8242 if ( a_goal > a_aux ) {
8243   a_aux = a_goal - a_aux;
8244   a_new = el_gordo;
8245 } else { 
8246   a_new = a_goal + a_goal;
8247   a_aux = 0;
8248 }
8249
8250 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8251 to force the additions and subtractions to be done in an order that avoids
8252 overflow.
8253
8254 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8255 if ( a > a_aux ) {
8256   a_aux = a_aux - a;
8257   a_new = a_new + a_aux;
8258 }
8259
8260 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8261 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8262 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8263 this bound.  Note that recursive calls will maintain this invariant.
8264
8265 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8266 dx01 = half(dx0 + dx1);
8267 dx12 = half(dx1 + dx2);
8268 dx02 = half(dx01 + dx12);
8269 dy01 = half(dy0 + dy1);
8270 dy12 = half(dy1 + dy2);
8271 dy02 = half(dy01 + dy12)
8272
8273 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8274 |a_goal=el_gordo| is guaranteed to yield the arc length.
8275
8276 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8277 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8278 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8279 tmp = halfp(v02+2);
8280 arc1 = v002 + half(halfp(v0+tmp) - v002);
8281 arc = v022 + half(halfp(v2+tmp) - v022);
8282 if ( (arc < el_gordo-arc1) )  {
8283   arc = arc+arc1;
8284 } else { 
8285   mp->arith_error = true;
8286   if ( a_goal==el_gordo )  return (el_gordo);
8287   else return (-two);
8288 }
8289
8290 @ @<Other local variables in |arc_test|@>=
8291 scaled tmp, tmp2; /* all purpose temporary registers */
8292 scaled arc1; /* arc length estimate for the first half */
8293
8294 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8295 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8296          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8297 if ( simple )
8298   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8299            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8300 if ( ! simple ) {
8301   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8302            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8303   if ( simple ) 
8304     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8305              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8306 }
8307
8308 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8309 @^Simpson's rule@>
8310 it is appropriate to use the same approximation to decide when the integral
8311 reaches the intermediate value |a_goal|.  At this point
8312 $$\eqalign{
8313     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8314     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8315     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8316     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8317     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8318 }
8319 $$
8320 and
8321 $$ {\vb\dot B(t)\vb\over 3} \approx
8322   \cases{B\left(\hbox{|v0|},
8323       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8324       {1\over 2}\hbox{|v02|}; 2t \right)&
8325     if $t\le{1\over 2}$\cr
8326   B\left({1\over 2}\hbox{|v02|},
8327       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8328       \hbox{|v2|}; 2t-1 \right)&
8329     if $t\ge{1\over 2}$.\cr}
8330  \eqno (*)
8331 $$
8332 We can integrate $\vb\dot B(t)\vb$ by using
8333 $$\int 3B(a,b,c;\tau)\,dt =
8334   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8335 $$
8336
8337 This construction allows us to find the time when the arc length reaches
8338 |a_goal| by solving a cubic equation of the form
8339 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8340 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8341 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8342 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8343 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8344 $\tau$ given $a$, $b$, $c$, and $x$.
8345
8346 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8347
8348   tmp = (v02 + 2) / 4;
8349   if ( a_goal<=arc1 ) {
8350     tmp2 = halfp(v0);
8351     return 
8352       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8353   } else { 
8354     tmp2 = halfp(v2);
8355     return ((half_unit - two) +
8356       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8357   }
8358 }
8359
8360 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8361 $$ B(0, a, a+b, a+b+c; t) = x. $$
8362 This routine is based on |crossing_point| but is simplified by the
8363 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8364 If rounding error causes this condition to be violated slightly, we just ignore
8365 it and proceed with binary search.  This finds a time when the function value
8366 reaches |x| and the slope is positive.
8367
8368 @<Declare subroutines needed by |arc_test|@>=
8369 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8370   scaled ab, bc, ac; /* bisection results */
8371   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8372   integer xx; /* temporary for updating |x| */
8373   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8374 @:this can't happen rising?}{\quad rising?@>
8375   if ( x<=0 ) {
8376         return 0;
8377   } else if ( x >= a+b+c ) {
8378     return unity;
8379   } else { 
8380     t = 1;
8381     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8382       |el_gordo div 3|@>;
8383     do {  
8384       t+=t;
8385       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8386       xx = x - a - ab - ac;
8387       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8388       else { x = x + xx;  a=ac; b=mp->bc; t = t+1; };
8389     } while (t < unity);
8390     return (t - unity);
8391   }
8392 }
8393
8394 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8395 ab = half(a+b);
8396 bc = half(b+c);
8397 ac = half(ab+bc)
8398
8399 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8400
8401 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8402 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8403   a = halfp(a);
8404   b = half(b);
8405   c = halfp(c);
8406   x = halfp(x);
8407 }
8408
8409 @ It is convenient to have a simpler interface to |arc_test| that requires no
8410 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8411 length less than |fraction_four|.
8412
8413 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8414
8415 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8416                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8417   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8418   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8419   v0 = mp_pyth_add(mp, dx0,dy0);
8420   v1 = mp_pyth_add(mp, dx1,dy1);
8421   v2 = mp_pyth_add(mp, dx2,dy2);
8422   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8423     mp->arith_error = true;
8424     if ( a_goal==el_gordo )  return el_gordo;
8425     else return (-two);
8426   } else { 
8427     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8428     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8429                                  v0, v02, v2, a_goal, arc_tol));
8430   }
8431 }
8432
8433 @ Now it is easy to find the arc length of an entire path.
8434
8435 @c scaled mp_get_arc_length (MP mp,pointer h) {
8436   pointer p,q; /* for traversing the path */
8437   scaled a,a_tot; /* current and total arc lengths */
8438   a_tot = 0;
8439   p = h;
8440   while ( right_type(p)!=mp_endpoint ){ 
8441     q = link(p);
8442     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8443       left_x(q)-right_x(p), left_y(q)-right_y(p),
8444       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8445     a_tot = mp_slow_add(mp, a, a_tot);
8446     if ( q==h ) break;  else p=q;
8447   }
8448   check_arith;
8449   return a_tot;
8450 }
8451
8452 @ The inverse operation of finding the time on a path~|h| when the arc length
8453 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8454 is required to handle very large times or negative times on cyclic paths.  For
8455 non-cyclic paths, |arc0| values that are negative or too large cause
8456 |get_arc_time| to return 0 or the length of path~|h|.
8457
8458 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8459 time value greater than the length of the path.  Since it could be much greater,
8460 we must be prepared to compute the arc length of path~|h| and divide this into
8461 |arc0| to find how many multiples of the length of path~|h| to add.
8462
8463 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8464   pointer p,q; /* for traversing the path */
8465   scaled t_tot; /* accumulator for the result */
8466   scaled t; /* the result of |do_arc_test| */
8467   scaled arc; /* portion of |arc0| not used up so far */
8468   integer n; /* number of extra times to go around the cycle */
8469   if ( arc0<0 ) {
8470     @<Deal with a negative |arc0| value and |return|@>;
8471   }
8472   if ( arc0==el_gordo ) decr(arc0);
8473   t_tot = 0;
8474   arc = arc0;
8475   p = h;
8476   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8477     q = link(p);
8478     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8479       left_x(q)-right_x(p), left_y(q)-right_y(p),
8480       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8481     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8482     if ( q==h ) {
8483       @<Update |t_tot| and |arc| to avoid going around the cyclic
8484         path too many times but set |arith_error:=true| and |goto done| on
8485         overflow@>;
8486     }
8487     p = q;
8488   }
8489   check_arith;
8490   return t_tot;
8491 }
8492
8493 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8494 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8495 else { t_tot = t_tot + unity;  arc = arc - t;  }
8496
8497 @ @<Deal with a negative |arc0| value and |return|@>=
8498
8499   if ( left_type(h)==mp_endpoint ) {
8500     t_tot=0;
8501   } else { 
8502     p = mp_htap_ypoc(mp, h);
8503     t_tot = -mp_get_arc_time(mp, p, -arc0);
8504     mp_toss_knot_list(mp, p);
8505   }
8506   check_arith;
8507   return t_tot;
8508 }
8509
8510 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8511 if ( arc>0 ) { 
8512   n = arc / (arc0 - arc);
8513   arc = arc - n*(arc0 - arc);
8514   if ( t_tot > el_gordo / (n+1) ) { 
8515     mp->arith_error = true;
8516     t_tot = el_gordo;
8517     break;
8518   }
8519   t_tot = (n + 1)*t_tot;
8520 }
8521
8522 @* \[20] Data structures for pens.
8523 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8524 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8525 @:stroke}{\&{stroke} command@>
8526 converted into an area fill as described in the next part of this program.
8527 The mathematics behind this process is based on simple aspects of the theory
8528 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8529 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8530 Foundations of Computer Science {\bf 24} (1983), 100--111].
8531
8532 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8533 @:makepen_}{\&{makepen} primitive@>
8534 This path representation is almost sufficient for our purposes except that
8535 a pen path should always be a convex polygon with the vertices in
8536 counter-clockwise order.
8537 Since we will need to scan pen polygons both forward and backward, a pen
8538 should be represented as a doubly linked ring of knot nodes.  There is
8539 room for the extra back pointer because we do not need the
8540 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8541 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8542 so that certain procedures can operate on both pens and paths.  In particular,
8543 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8544
8545 @d knil info
8546   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8547
8548 @ The |make_pen| procedure turns a path into a pen by initializing
8549 the |knil| pointers and making sure the knots form a convex polygon.
8550 Thus each cubic in the given path becomes a straight line and the control
8551 points are ignored.  If the path is not cyclic, the ends are connected by a
8552 straight line.
8553
8554 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8555
8556 @c @<Declare a function called |convex_hull|@>;
8557 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8558   pointer p,q; /* two consecutive knots */
8559   q=h;
8560   do {  
8561     p=q; q=link(q);
8562     knil(q)=p;
8563   } while (q!=h);
8564   if ( need_hull ){ 
8565     h=mp_convex_hull(mp, h);
8566     @<Make sure |h| isn't confused with an elliptical pen@>;
8567   }
8568   return h;
8569 }
8570
8571 @ The only information required about an elliptical pen is the overall
8572 transformation that has been applied to the original \&{pencircle}.
8573 @:pencircle_}{\&{pencircle} primitive@>
8574 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8575 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8576 knot node and transformed as if it were a path.
8577
8578 @d pen_is_elliptical(A) ((A)==link((A)))
8579
8580 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8581   pointer h; /* the knot node to return */
8582   h=mp_get_node(mp, knot_node_size);
8583   link(h)=h; knil(h)=h;
8584   originator(h)=mp_program_code;
8585   x_coord(h)=0; y_coord(h)=0;
8586   left_x(h)=diam; left_y(h)=0;
8587   right_x(h)=0; right_y(h)=diam;
8588   return h;
8589 }
8590
8591 @ If the polygon being returned by |make_pen| has only one vertex, it will
8592 be interpreted as an elliptical pen.  This is no problem since a degenerate
8593 polygon can equally well be thought of as a degenerate ellipse.  We need only
8594 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8595
8596 @<Make sure |h| isn't confused with an elliptical pen@>=
8597 if ( pen_is_elliptical( h) ){ 
8598   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8599   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8600 }
8601
8602 @ We have to cheat a little here but most operations on pens only use
8603 the first three words in each knot node.
8604 @^data structure assumptions@>
8605
8606 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8607 x_coord(test_pen)=-half_unit;
8608 y_coord(test_pen)=0;
8609 x_coord(test_pen+3)=half_unit;
8610 y_coord(test_pen+3)=0;
8611 x_coord(test_pen+6)=0;
8612 y_coord(test_pen+6)=unity;
8613 link(test_pen)=test_pen+3;
8614 link(test_pen+3)=test_pen+6;
8615 link(test_pen+6)=test_pen;
8616 knil(test_pen)=test_pen+6;
8617 knil(test_pen+3)=test_pen;
8618 knil(test_pen+6)=test_pen+3
8619
8620 @ Printing a polygonal pen is very much like printing a path
8621
8622 @<Declare subroutines for printing expressions@>=
8623 void mp_pr_pen (MP mp,pointer h) {
8624   pointer p,q; /* for list traversal */
8625   if ( pen_is_elliptical(h) ) {
8626     @<Print the elliptical pen |h|@>;
8627   } else { 
8628     p=h;
8629     do {  
8630       mp_print_two(mp, x_coord(p),y_coord(p));
8631       mp_print_nl(mp, " .. ");
8632       @<Advance |p| making sure the links are OK and |return| if there is
8633         a problem@>;
8634      } while (p!=h);
8635      mp_print(mp, "cycle");
8636   }
8637 }
8638
8639 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8640 q=link(p);
8641 if ( (q==null) || (knil(q)!=p) ) { 
8642   mp_print_nl(mp, "???"); return; /* this won't happen */
8643 @.???@>
8644 }
8645 p=q
8646
8647 @ @<Print the elliptical pen |h|@>=
8648
8649 mp_print(mp, "pencircle transformed (");
8650 mp_print_scaled(mp, x_coord(h));
8651 mp_print_char(mp, ',');
8652 mp_print_scaled(mp, y_coord(h));
8653 mp_print_char(mp, ',');
8654 mp_print_scaled(mp, left_x(h)-x_coord(h));
8655 mp_print_char(mp, ',');
8656 mp_print_scaled(mp, right_x(h)-x_coord(h));
8657 mp_print_char(mp, ',');
8658 mp_print_scaled(mp, left_y(h)-y_coord(h));
8659 mp_print_char(mp, ',');
8660 mp_print_scaled(mp, right_y(h)-y_coord(h));
8661 mp_print_char(mp, ')');
8662 }
8663
8664 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8665 message.
8666
8667 @<Declare subroutines for printing expressions@>=
8668 void mp_print_pen (MP mp,pointer h, char *s, boolean nuline) { 
8669   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8670 @.Pen at line...@>
8671   mp_pr_pen(mp, h);
8672   mp_end_diagnostic(mp, true);
8673 }
8674
8675 @ Making a polygonal pen into a path involves restoring the |left_type| and
8676 |right_type| fields and setting the control points so as to make a polygonal
8677 path.
8678
8679 @c 
8680 void mp_make_path (MP mp,pointer h) {
8681   pointer p; /* for traversing the knot list */
8682   small_number k; /* a loop counter */
8683   @<Other local variables in |make_path|@>;
8684   if ( pen_is_elliptical(h) ) {
8685     @<Make the elliptical pen |h| into a path@>;
8686   } else { 
8687     p=h;
8688     do {  
8689       left_type(p)=mp_explicit;
8690       right_type(p)=mp_explicit;
8691       @<copy the coordinates of knot |p| into its control points@>;
8692        p=link(p);
8693     } while (p!=h);
8694   }
8695 }
8696
8697 @ @<copy the coordinates of knot |p| into its control points@>=
8698 left_x(p)=x_coord(p);
8699 left_y(p)=y_coord(p);
8700 right_x(p)=x_coord(p);
8701 right_y(p)=y_coord(p)
8702
8703 @ We need an eight knot path to get a good approximation to an ellipse.
8704
8705 @<Make the elliptical pen |h| into a path@>=
8706
8707   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8708   p=h;
8709   for (k=0;k<=7;k++ ) { 
8710     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8711       transforming it appropriately@>;
8712     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8713     p=link(p);
8714   }
8715 }
8716
8717 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8718 center_x=x_coord(h);
8719 center_y=y_coord(h);
8720 width_x=left_x(h)-center_x;
8721 width_y=left_y(h)-center_y;
8722 height_x=right_x(h)-center_x;
8723 height_y=right_y(h)-center_y
8724
8725 @ @<Other local variables in |make_path|@>=
8726 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8727 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8728 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8729 scaled dx,dy; /* the vector from knot |p| to its right control point */
8730 integer kk;
8731   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8732
8733 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8734 find the point $k/8$ of the way around the circle and the direction vector
8735 to use there.
8736
8737 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8738 kk=(k+6)% 8;
8739 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8740            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8741 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8742            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8743 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8744    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8745 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8746    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8747 right_x(p)=x_coord(p)+dx;
8748 right_y(p)=y_coord(p)+dy;
8749 left_x(p)=x_coord(p)-dx;
8750 left_y(p)=y_coord(p)-dy;
8751 left_type(p)=mp_explicit;
8752 right_type(p)=mp_explicit;
8753 originator(p)=mp_program_code
8754
8755 @ @<Glob...@>=
8756 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8757 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8758
8759 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8760 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8761 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8762 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8763   \approx 0.132608244919772.
8764 $$
8765
8766 @<Set init...@>=
8767 mp->half_cos[0]=fraction_half;
8768 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8769 mp->half_cos[2]=0;
8770 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8771 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8772 mp->d_cos[2]=0;
8773 for (k=3;k<= 4;k++ ) { 
8774   mp->half_cos[k]=-mp->half_cos[4-k];
8775   mp->d_cos[k]=-mp->d_cos[4-k];
8776 }
8777 for (k=5;k<= 7;k++ ) { 
8778   mp->half_cos[k]=mp->half_cos[8-k];
8779   mp->d_cos[k]=mp->d_cos[8-k];
8780 }
8781
8782 @ The |convex_hull| function forces a pen polygon to be convex when it is
8783 returned by |make_pen| and after any subsequent transformation where rounding
8784 error might allow the convexity to be lost.
8785 The convex hull algorithm used here is described by F.~P. Preparata and
8786 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8787
8788 @<Declare a function called |convex_hull|@>=
8789 @<Declare a procedure called |move_knot|@>;
8790 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8791   pointer l,r; /* the leftmost and rightmost knots */
8792   pointer p,q; /* knots being scanned */
8793   pointer s; /* the starting point for an upcoming scan */
8794   scaled dx,dy; /* a temporary pointer */
8795   if ( pen_is_elliptical(h) ) {
8796      return h;
8797   } else { 
8798     @<Set |l| to the leftmost knot in polygon~|h|@>;
8799     @<Set |r| to the rightmost knot in polygon~|h|@>;
8800     if ( l!=r ) { 
8801       s=link(r);
8802       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8803         move them past~|r|@>;
8804       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8805         move them past~|l|@>;
8806       @<Sort the path from |l| to |r| by increasing $x$@>;
8807       @<Sort the path from |r| to |l| by decreasing $x$@>;
8808     }
8809     if ( l!=link(l) ) {
8810       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8811     }
8812     return l;
8813   }
8814 }
8815
8816 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8817
8818 @<Set |l| to the leftmost knot in polygon~|h|@>=
8819 l=h;
8820 p=link(h);
8821 while ( p!=h ) { 
8822   if ( x_coord(p)<=x_coord(l) )
8823     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8824       l=p;
8825   p=link(p);
8826 }
8827
8828 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8829 r=h;
8830 p=link(h);
8831 while ( p!=h ) { 
8832   if ( x_coord(p)>=x_coord(r) )
8833     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8834       r=p;
8835   p=link(p);
8836 }
8837
8838 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8839 dx=x_coord(r)-x_coord(l);
8840 dy=y_coord(r)-y_coord(l);
8841 p=link(l);
8842 while ( p!=r ) { 
8843   q=link(p);
8844   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))>0 )
8845     mp_move_knot(mp, p, r);
8846   p=q;
8847 }
8848
8849 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8850 it after |q|.
8851
8852 @ @<Declare a procedure called |move_knot|@>=
8853 void mp_move_knot (MP mp,pointer p, pointer q) { 
8854   link(knil(p))=link(p);
8855   knil(link(p))=knil(p);
8856   knil(p)=q;
8857   link(p)=link(q);
8858   link(q)=p;
8859   knil(link(p))=p;
8860 }
8861
8862 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8863 p=s;
8864 while ( p!=l ) { 
8865   q=link(p);
8866   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8867     mp_move_knot(mp, p,l);
8868   p=q;
8869 }
8870
8871 @ The list is likely to be in order already so we just do linear insertions.
8872 Secondary comparisons on $y$ ensure that the sort is consistent with the
8873 choice of |l| and |r|.
8874
8875 @<Sort the path from |l| to |r| by increasing $x$@>=
8876 p=link(l);
8877 while ( p!=r ) { 
8878   q=knil(p);
8879   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8880   while ( x_coord(q)==x_coord(p) ) {
8881     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8882   }
8883   if ( q==knil(p) ) p=link(p);
8884   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8885 }
8886
8887 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8888 p=link(r);
8889 while ( p!=l ){ 
8890   q=knil(p);
8891   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8892   while ( x_coord(q)==x_coord(p) ) {
8893     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8894   }
8895   if ( q==knil(p) ) p=link(p);
8896   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8897 }
8898
8899 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8900 at knot |q|.  There usually will be a left turn so we streamline the case
8901 where the |then| clause is not executed.
8902
8903 @<Do a Gramm scan and remove vertices where there...@>=
8904
8905 p=l; q=link(l);
8906 while (1) { 
8907   dx=x_coord(q)-x_coord(p);
8908   dy=y_coord(q)-y_coord(p);
8909   p=q; q=link(q);
8910   if ( p==l ) break;
8911   if ( p!=r )
8912     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8913       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8914     }
8915   }
8916 }
8917
8918 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8919
8920 s=knil(p);
8921 mp_free_node(mp, p,knot_node_size);
8922 link(s)=q; knil(q)=s;
8923 if ( s==l ) p=s;
8924 else { p=knil(s); q=s; };
8925 }
8926
8927 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8928 offset associated with the given direction |(x,y)|.  If two different offsets
8929 apply, it chooses one of them.
8930
8931 @c 
8932 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8933   pointer p,q; /* consecutive knots */
8934   scaled wx,wy,hx,hy;
8935   /* the transformation matrix for an elliptical pen */
8936   fraction xx,yy; /* untransformed offset for an elliptical pen */
8937   fraction d; /* a temporary register */
8938   if ( pen_is_elliptical(h) ) {
8939     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8940   } else { 
8941     q=h;
8942     do {  
8943       p=q; q=link(q);
8944     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8945     do {  
8946       p=q; q=link(q);
8947     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8948     mp->cur_x=x_coord(p);
8949     mp->cur_y=y_coord(p);
8950   }
8951 }
8952
8953 @ @<Glob...@>=
8954 scaled cur_x;
8955 scaled cur_y; /* all-purpose return value registers */
8956
8957 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8958 if ( (x==0) && (y==0) ) {
8959   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8960 } else { 
8961   @<Find the non-constant part of the transformation for |h|@>;
8962   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8963     x+=x; y+=y;  
8964   };
8965   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8966     untransformed version of |(x,y)|@>;
8967   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8968   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8969 }
8970
8971 @ @<Find the non-constant part of the transformation for |h|@>=
8972 wx=left_x(h)-x_coord(h);
8973 wy=left_y(h)-y_coord(h);
8974 hx=right_x(h)-x_coord(h);
8975 hy=right_y(h)-y_coord(h)
8976
8977 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
8978 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
8979 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
8980 d=mp_pyth_add(mp, xx,yy);
8981 if ( d>0 ) { 
8982   xx=half(mp_make_fraction(mp, xx,d));
8983   yy=half(mp_make_fraction(mp, yy,d));
8984 }
8985
8986 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
8987 But we can handle that case by just calling |find_offset| twice.  The answer
8988 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
8989
8990 @c 
8991 void mp_pen_bbox (MP mp,pointer h) {
8992   pointer p; /* for scanning the knot list */
8993   if ( pen_is_elliptical(h) ) {
8994     @<Find the bounding box of an elliptical pen@>;
8995   } else { 
8996     minx=x_coord(h); maxx=minx;
8997     miny=y_coord(h); maxy=miny;
8998     p=link(h);
8999     while ( p!=h ) {
9000       if ( x_coord(p)<minx ) minx=x_coord(p);
9001       if ( y_coord(p)<miny ) miny=y_coord(p);
9002       if ( x_coord(p)>maxx ) maxx=x_coord(p);
9003       if ( y_coord(p)>maxy ) maxy=y_coord(p);
9004       p=link(p);
9005     }
9006   }
9007 }
9008
9009 @ @<Find the bounding box of an elliptical pen@>=
9010
9011 mp_find_offset(mp, 0,fraction_one,h);
9012 maxx=mp->cur_x;
9013 minx=2*x_coord(h)-mp->cur_x;
9014 mp_find_offset(mp, -fraction_one,0,h);
9015 maxy=mp->cur_y;
9016 miny=2*y_coord(h)-mp->cur_y;
9017 }
9018
9019 @* \[21] Edge structures.
9020 Now we come to \MP's internal scheme for representing pictures.
9021 The representation is very different from \MF's edge structures
9022 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9023 images.  However, the basic idea is somewhat similar in that shapes
9024 are represented via their boundaries.
9025
9026 The main purpose of edge structures is to keep track of graphical objects
9027 until it is time to translate them into \ps.  Since \MP\ does not need to
9028 know anything about an edge structure other than how to translate it into
9029 \ps\ and how to find its bounding box, edge structures can be just linked
9030 lists of graphical objects.  \MP\ has no easy way to determine whether
9031 two such objects overlap, but it suffices to draw the first one first and
9032 let the second one overwrite it if necessary.
9033
9034 @<Types...@>=
9035 enum mp_graphical_object_code {
9036   @<Graphical object codes@>
9037 };
9038
9039 @ Let's consider the types of graphical objects one at a time.
9040 First of all, a filled contour is represented by a eight-word node.  The first
9041 word contains |type| and |link| fields, and the next six words contain a
9042 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9043 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9044 give the relevant information.
9045
9046 @d path_p(A) link((A)+1)
9047   /* a pointer to the path that needs filling */
9048 @d pen_p(A) info((A)+1)
9049   /* a pointer to the pen to fill or stroke with */
9050 @d color_model(A) type((A)+2) /*  the color model  */
9051 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9052 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9053 @d obj_grey_loc obj_red_loc  /* the location for the color */
9054 @d red_val(A) mp->mem[(A)+3].sc
9055   /* the red component of the color in the range $0\ldots1$ */
9056 @d cyan_val red_val
9057 @d grey_val red_val
9058 @d green_val(A) mp->mem[(A)+4].sc
9059   /* the green component of the color in the range $0\ldots1$ */
9060 @d magenta_val green_val
9061 @d blue_val(A) mp->mem[(A)+5].sc
9062   /* the blue component of the color in the range $0\ldots1$ */
9063 @d yellow_val blue_val
9064 @d black_val(A) mp->mem[(A)+6].sc
9065   /* the blue component of the color in the range $0\ldots1$ */
9066 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9067 @:mp_linejoin_}{\&{linejoin} primitive@>
9068 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9069 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9070 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9071   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9072 @d pre_script(A) mp->mem[(A)+8].hh.lh
9073 @d post_script(A) mp->mem[(A)+8].hh.rh
9074 @d fill_node_size 9
9075
9076 @ @<Graphical object codes@>=
9077 mp_fill_code=1,
9078
9079 @ @c 
9080 pointer mp_new_fill_node (MP mp,pointer p) {
9081   /* make a fill node for cyclic path |p| and color black */
9082   pointer t; /* the new node */
9083   t=mp_get_node(mp, fill_node_size);
9084   type(t)=mp_fill_code;
9085   path_p(t)=p;
9086   pen_p(t)=null; /* |null| means don't use a pen */
9087   red_val(t)=0;
9088   green_val(t)=0;
9089   blue_val(t)=0;
9090   black_val(t)=0;
9091   color_model(t)=mp_uninitialized_model;
9092   pre_script(t)=null;
9093   post_script(t)=null;
9094   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9095   return t;
9096 }
9097
9098 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9099 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9100 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9101 else ljoin_val(t)=0;
9102 if ( mp->internal[mp_miterlimit]<unity )
9103   miterlim_val(t)=unity;
9104 else
9105   miterlim_val(t)=mp->internal[mp_miterlimit]
9106
9107 @ A stroked path is represented by an eight-word node that is like a filled
9108 contour node except that it contains the current \&{linecap} value, a scale
9109 factor for the dash pattern, and a pointer that is non-null if the stroke
9110 is to be dashed.  The purpose of the scale factor is to allow a picture to
9111 be transformed without touching the picture that |dash_p| points to.
9112
9113 @d dash_p(A) link((A)+9)
9114   /* a pointer to the edge structure that gives the dash pattern */
9115 @d lcap_val(A) type((A)+9)
9116   /* the value of \&{linecap} */
9117 @:mp_linecap_}{\&{linecap} primitive@>
9118 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9119 @d stroked_node_size 11
9120
9121 @ @<Graphical object codes@>=
9122 mp_stroked_code=2,
9123
9124 @ @c 
9125 pointer mp_new_stroked_node (MP mp,pointer p) {
9126   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9127   pointer t; /* the new node */
9128   t=mp_get_node(mp, stroked_node_size);
9129   type(t)=mp_stroked_code;
9130   path_p(t)=p; pen_p(t)=null;
9131   dash_p(t)=null;
9132   dash_scale(t)=unity;
9133   red_val(t)=0;
9134   green_val(t)=0;
9135   blue_val(t)=0;
9136   black_val(t)=0;
9137   color_model(t)=mp_uninitialized_model;
9138   pre_script(t)=null;
9139   post_script(t)=null;
9140   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9141   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9142   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9143   else lcap_val(t)=0;
9144   return t;
9145 }
9146
9147 @ When a dashed line is computed in a transformed coordinate system, the dash
9148 lengths get scaled like the pen shape and we need to compensate for this.  Since
9149 there is no unique scale factor for an arbitrary transformation, we use the
9150 the square root of the determinant.  The properties of the determinant make it
9151 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9152 except for the initialization of the scale factor |s|.  The factor of 64 is
9153 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9154 to counteract the effect of |take_fraction|.
9155
9156 @<Declare subroutines needed by |print_edges|@>=
9157 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9158   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9159   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9160   @<Initialize |maxabs|@>;
9161   s=64;
9162   while ( (maxabs<fraction_one) && (s>1) ){ 
9163     a+=a; b+=b; c+=c; d+=d;
9164     maxabs+=maxabs; s=halfp(s);
9165   }
9166   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9167 }
9168 @#
9169 scaled mp_get_pen_scale (MP mp,pointer p) { 
9170   return mp_sqrt_det(mp, 
9171     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9172     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9173 }
9174
9175 @ @<Internal library ...@>=
9176 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9177
9178
9179 @ @<Initialize |maxabs|@>=
9180 maxabs=abs(a);
9181 if ( abs(b)>maxabs ) maxabs=abs(b);
9182 if ( abs(c)>maxabs ) maxabs=abs(c);
9183 if ( abs(d)>maxabs ) maxabs=abs(d)
9184
9185 @ When a picture contains text, this is represented by a fourteen-word node
9186 where the color information and |type| and |link| fields are augmented by
9187 additional fields that describe the text and  how it is transformed.
9188 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9189 the font and a string number that gives the text to be displayed.
9190 The |width|, |height|, and |depth| fields
9191 give the dimensions of the text at its design size, and the remaining six
9192 words give a transformation to be applied to the text.  The |new_text_node|
9193 function initializes everything to default values so that the text comes out
9194 black with its reference point at the origin.
9195
9196 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9197 @d font_n(A) info((A)+1)  /* the font number */
9198 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9199 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9200 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9201 @d text_tx_loc(A) ((A)+11)
9202   /* the first of six locations for transformation parameters */
9203 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9204 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9205 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9206 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9207 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9208 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9209 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9210     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9211 @d text_node_size 17
9212
9213 @ @<Graphical object codes@>=
9214 mp_text_code=3,
9215
9216 @ @c @<Declare text measuring subroutines@>;
9217 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9218   /* make a text node for font |f| and text string |s| */
9219   pointer t; /* the new node */
9220   t=mp_get_node(mp, text_node_size);
9221   type(t)=mp_text_code;
9222   text_p(t)=s;
9223   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9224   red_val(t)=0;
9225   green_val(t)=0;
9226   blue_val(t)=0;
9227   black_val(t)=0;
9228   color_model(t)=mp_uninitialized_model;
9229   pre_script(t)=null;
9230   post_script(t)=null;
9231   tx_val(t)=0; ty_val(t)=0;
9232   txx_val(t)=unity; txy_val(t)=0;
9233   tyx_val(t)=0; tyy_val(t)=unity;
9234   mp_set_text_box(mp, t); /* this finds the bounding box */
9235   return t;
9236 }
9237
9238 @ The last two types of graphical objects that can occur in an edge structure
9239 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9240 @:set_bounds_}{\&{setbounds} primitive@>
9241 to implement because we must keep track of exactly what is being clipped or
9242 bounded when pictures get merged together.  For this reason, each clipping or
9243 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9244 two-word node whose |path_p| gives the relevant path, then there is the list
9245 of objects to clip or bound followed by a two-word node whose second word is
9246 unused.
9247
9248 Using at least two words for each graphical object node allows them all to be
9249 allocated and deallocated similarly with a global array |gr_object_size| to
9250 give the size in words for each object type.
9251
9252 @d start_clip_size 2
9253 @d start_bounds_size 2
9254 @d stop_clip_size 2 /* the second word is not used here */
9255 @d stop_bounds_size 2 /* the second word is not used here */
9256 @#
9257 @d stop_type(A) ((A)+2)
9258   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9259 @d has_color(A) (type((A))<mp_start_clip_code)
9260   /* does a graphical object have color fields? */
9261 @d has_pen(A) (type((A))<mp_text_code)
9262   /* does a graphical object have a |pen_p| field? */
9263 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9264 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9265
9266 @ @<Graphical object codes@>=
9267 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9268 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9269 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9270 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9271
9272 @ @c 
9273 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9274   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9275   pointer t; /* the new node */
9276   t=mp_get_node(mp, mp->gr_object_size[c]);
9277   type(t)=c;
9278   path_p(t)=p;
9279   return t;
9280 };
9281
9282 @ We need an array to keep track of the sizes of graphical objects.
9283
9284 @<Glob...@>=
9285 small_number gr_object_size[mp_stop_bounds_code+1];
9286
9287 @ @<Set init...@>=
9288 mp->gr_object_size[mp_fill_code]=fill_node_size;
9289 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9290 mp->gr_object_size[mp_text_code]=text_node_size;
9291 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9292 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9293 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9294 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9295
9296 @ All the essential information in an edge structure is encoded as a linked list
9297 of graphical objects as we have just seen, but it is helpful to add some
9298 redundant information.  A single edge structure might be used as a dash pattern
9299 many times, and it would be nice to avoid scanning the same structure
9300 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9301 has a header that gives a list of dashes in a sorted order designed for rapid
9302 translation into \ps.
9303
9304 Each dash is represented by a three-word node containing the initial and final
9305 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9306 the dash node with the next higher $x$-coordinates and the final link points
9307 to a special location called |null_dash|.  (There should be no overlap between
9308 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9309 the period of repetition, this needs to be stored in the edge header along
9310 with a pointer to the list of dash nodes.
9311
9312 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9313 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9314 @d dash_node_size 3
9315 @d dash_list link
9316   /* in an edge header this points to the first dash node */
9317 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9318
9319 @ It is also convenient for an edge header to contain the bounding
9320 box information needed by the \&{llcorner} and \&{urcorner} operators
9321 so that this does not have to be recomputed unnecessarily.  This is done by
9322 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9323 how far the bounding box computation has gotten.  Thus if the user asks for
9324 the bounding box and then adds some more text to the picture before asking
9325 for more bounding box information, the second computation need only look at
9326 the additional text.
9327
9328 When the bounding box has not been computed, the |bblast| pointer points
9329 to a dummy link at the head of the graphical object list while the |minx_val|
9330 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9331 fields contain |-el_gordo|.
9332
9333 Since the bounding box of pictures containing objects of type
9334 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9335 @:mp_true_corners_}{\&{truecorners} primitive@>
9336 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9337 field is needed to keep track of this.
9338
9339 @d minx_val(A) mp->mem[(A)+2].sc
9340 @d miny_val(A) mp->mem[(A)+3].sc
9341 @d maxx_val(A) mp->mem[(A)+4].sc
9342 @d maxy_val(A) mp->mem[(A)+5].sc
9343 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9344 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9345 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9346 @d no_bounds 0
9347   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9348 @d bounds_set 1
9349   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9350 @d bounds_unset 2
9351   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9352
9353 @c 
9354 void mp_init_bbox (MP mp,pointer h) {
9355   /* Initialize the bounding box information in edge structure |h| */
9356   bblast(h)=dummy_loc(h);
9357   bbtype(h)=no_bounds;
9358   minx_val(h)=el_gordo;
9359   miny_val(h)=el_gordo;
9360   maxx_val(h)=-el_gordo;
9361   maxy_val(h)=-el_gordo;
9362 }
9363
9364 @ The only other entries in an edge header are a reference count in the first
9365 word and a pointer to the tail of the object list in the last word.
9366
9367 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9368 @d edge_header_size 8
9369
9370 @c 
9371 void mp_init_edges (MP mp,pointer h) {
9372   /* initialize an edge header to null values */
9373   dash_list(h)=null_dash;
9374   obj_tail(h)=dummy_loc(h);
9375   link(dummy_loc(h))=null;
9376   ref_count(h)=null;
9377   mp_init_bbox(mp, h);
9378 }
9379
9380 @ Here is how edge structures are deleted.  The process can be recursive because
9381 of the need to dereference edge structures that are used as dash patterns.
9382 @^recursion@>
9383
9384 @d add_edge_ref(A) incr(ref_count(A))
9385 @d delete_edge_ref(A) { 
9386    if ( ref_count((A))==null ) 
9387      mp_toss_edges(mp, A);
9388    else 
9389      decr(ref_count(A)); 
9390    }
9391
9392 @<Declare the recycling subroutines@>=
9393 void mp_flush_dash_list (MP mp,pointer h);
9394 pointer mp_toss_gr_object (MP mp,pointer p) ;
9395 void mp_toss_edges (MP mp,pointer h) ;
9396
9397 @ @c void mp_toss_edges (MP mp,pointer h) {
9398   pointer p,q;  /* pointers that scan the list being recycled */
9399   pointer r; /* an edge structure that object |p| refers to */
9400   mp_flush_dash_list(mp, h);
9401   q=link(dummy_loc(h));
9402   while ( (q!=null) ) { 
9403     p=q; q=link(q);
9404     r=mp_toss_gr_object(mp, p);
9405     if ( r!=null ) delete_edge_ref(r);
9406   }
9407   mp_free_node(mp, h,edge_header_size);
9408 }
9409 void mp_flush_dash_list (MP mp,pointer h) {
9410   pointer p,q;  /* pointers that scan the list being recycled */
9411   q=dash_list(h);
9412   while ( q!=null_dash ) { 
9413     p=q; q=link(q);
9414     mp_free_node(mp, p,dash_node_size);
9415   }
9416   dash_list(h)=null_dash;
9417 }
9418 pointer mp_toss_gr_object (MP mp,pointer p) {
9419   /* returns an edge structure that needs to be dereferenced */
9420   pointer e; /* the edge structure to return */
9421   e=null;
9422   @<Prepare to recycle graphical object |p|@>;
9423   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9424   return e;
9425 }
9426
9427 @ @<Prepare to recycle graphical object |p|@>=
9428 switch (type(p)) {
9429 case mp_fill_code: 
9430   mp_toss_knot_list(mp, path_p(p));
9431   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9432   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9433   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9434   break;
9435 case mp_stroked_code: 
9436   mp_toss_knot_list(mp, path_p(p));
9437   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9438   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9439   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9440   e=dash_p(p);
9441   break;
9442 case mp_text_code: 
9443   delete_str_ref(text_p(p));
9444   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9445   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9446   break;
9447 case mp_start_clip_code:
9448 case mp_start_bounds_code: 
9449   mp_toss_knot_list(mp, path_p(p));
9450   break;
9451 case mp_stop_clip_code:
9452 case mp_stop_bounds_code: 
9453   break;
9454 } /* there are no other cases */
9455
9456 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9457 to be done before making a significant change to an edge structure.  Much of
9458 the work is done in a separate routine |copy_objects| that copies a list of
9459 graphical objects into a new edge header.
9460
9461 @c @<Declare a function called |copy_objects|@>;
9462 pointer mp_private_edges (MP mp,pointer h) {
9463   /* make a private copy of the edge structure headed by |h| */
9464   pointer hh;  /* the edge header for the new copy */
9465   pointer p,pp;  /* pointers for copying the dash list */
9466   if ( ref_count(h)==null ) {
9467     return h;
9468   } else { 
9469     decr(ref_count(h));
9470     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9471     @<Copy the dash list from |h| to |hh|@>;
9472     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9473       point into the new object list@>;
9474     return hh;
9475   }
9476 }
9477
9478 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9479 @^data structure assumptions@>
9480
9481 @<Copy the dash list from |h| to |hh|@>=
9482 pp=hh; p=dash_list(h);
9483 while ( (p!=null_dash) ) { 
9484   link(pp)=mp_get_node(mp, dash_node_size);
9485   pp=link(pp);
9486   start_x(pp)=start_x(p);
9487   stop_x(pp)=stop_x(p);
9488   p=link(p);
9489 }
9490 link(pp)=null_dash;
9491 dash_y(hh)=dash_y(h)
9492
9493
9494 @ |h| is an edge structure
9495
9496 @d gr_start_x(A)    (A)->start_x_field
9497 @d gr_stop_x(A)     (A)->stop_x_field
9498 @d gr_dash_link(A)  (A)->next_field
9499
9500 @d gr_dash_list(A)  (A)->list_field
9501 @d gr_dash_y(A)     (A)->y_field
9502
9503 @c
9504 struct mp_dash_list *mp_export_dashes (MP mp, pointer h) {
9505   struct mp_dash_list *dl;
9506   struct mp_dash_item *dh, *di;
9507   pointer p;
9508   if (h==null ||  dash_list(h)==null_dash) 
9509         return NULL;
9510   p = dash_list(h);
9511   dl = mp_xmalloc(mp,1,sizeof(struct mp_dash_list));
9512   gr_dash_list(dl) = NULL;
9513   gr_dash_y(dl) = dash_y(h);
9514   dh = NULL;
9515   while (p != null_dash) { 
9516     di=mp_xmalloc(mp,1,sizeof(struct mp_dash_item));
9517     gr_dash_link(di) = NULL;
9518     gr_start_x(di) = start_x(p);
9519     gr_stop_x(di) = stop_x(p);
9520     if (dh==NULL) {
9521       gr_dash_list(dl) = di;
9522     } else {
9523       gr_dash_link(dh) = di;
9524     }
9525     dh = di;
9526     p=link(p);
9527   }
9528   return dl;
9529 }
9530
9531
9532 @ @<Copy the bounding box information from |h| to |hh|...@>=
9533 minx_val(hh)=minx_val(h);
9534 miny_val(hh)=miny_val(h);
9535 maxx_val(hh)=maxx_val(h);
9536 maxy_val(hh)=maxy_val(h);
9537 bbtype(hh)=bbtype(h);
9538 p=dummy_loc(h); pp=dummy_loc(hh);
9539 while ((p!=bblast(h)) ) { 
9540   if ( p==null ) mp_confusion(mp, "bblast");
9541 @:this can't happen bblast}{\quad bblast@>
9542   p=link(p); pp=link(pp);
9543 }
9544 bblast(hh)=pp
9545
9546 @ Here is the promised routine for copying graphical objects into a new edge
9547 structure.  It starts copying at object~|p| and stops just before object~|q|.
9548 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9549 structure requires further initialization by |init_bbox|.
9550
9551 @<Declare a function called |copy_objects|@>=
9552 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9553   pointer hh;  /* the new edge header */
9554   pointer pp;  /* the last newly copied object */
9555   small_number k;  /* temporary register */
9556   hh=mp_get_node(mp, edge_header_size);
9557   dash_list(hh)=null_dash;
9558   ref_count(hh)=null;
9559   pp=dummy_loc(hh);
9560   while ( (p!=q) ) {
9561     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9562   }
9563   obj_tail(hh)=pp;
9564   link(pp)=null;
9565   return hh;
9566 }
9567
9568 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9569 { k=mp->gr_object_size[type(p)];
9570   link(pp)=mp_get_node(mp, k);
9571   pp=link(pp);
9572   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9573   @<Fix anything in graphical object |pp| that should differ from the
9574     corresponding field in |p|@>;
9575   p=link(p);
9576 }
9577
9578 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9579 switch (type(p)) {
9580 case mp_start_clip_code:
9581 case mp_start_bounds_code: 
9582   path_p(pp)=mp_copy_path(mp, path_p(p));
9583   break;
9584 case mp_fill_code: 
9585   path_p(pp)=mp_copy_path(mp, path_p(p));
9586   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9587   break;
9588 case mp_stroked_code: 
9589   path_p(pp)=mp_copy_path(mp, path_p(p));
9590   pen_p(pp)=copy_pen(pen_p(p));
9591   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9592   break;
9593 case mp_text_code: 
9594   add_str_ref(text_p(pp));
9595   break;
9596 case mp_stop_clip_code:
9597 case mp_stop_bounds_code: 
9598   break;
9599 }  /* there are no other cases */
9600
9601 @ Here is one way to find an acceptable value for the second argument to
9602 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9603 skips past one picture component, where a ``picture component'' is a single
9604 graphical object, or a start bounds or start clip object and everything up
9605 through the matching stop bounds or stop clip object.  The macro version avoids
9606 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9607 unless |p| points to a stop bounds or stop clip node, in which case it executes
9608 |e| instead.
9609
9610 @d skip_component(A)
9611     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9612     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9613     else 
9614
9615 @c 
9616 pointer mp_skip_1component (MP mp,pointer p) {
9617   integer lev; /* current nesting level */
9618   lev=0;
9619   do {  
9620    if ( is_start_or_stop(p) ) {
9621      if ( is_stop(p) ) decr(lev);  else incr(lev);
9622    }
9623    p=link(p);
9624   } while (lev!=0);
9625   return p;
9626 }
9627
9628 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9629
9630 @<Declare subroutines for printing expressions@>=
9631 @<Declare subroutines needed by |print_edges|@>;
9632 void mp_print_edges (MP mp,pointer h, char *s, boolean nuline) {
9633   pointer p;  /* a graphical object to be printed */
9634   pointer hh,pp;  /* temporary pointers */
9635   scaled scf;  /* a scale factor for the dash pattern */
9636   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9637   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9638   p=dummy_loc(h);
9639   while ( link(p)!=null ) { 
9640     p=link(p);
9641     mp_print_ln(mp);
9642     switch (type(p)) {
9643       @<Cases for printing graphical object node |p|@>;
9644     default: 
9645           mp_print(mp, "[unknown object type!]");
9646           break;
9647     }
9648   }
9649   mp_print_nl(mp, "End edges");
9650   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9651 @.End edges?@>
9652   mp_end_diagnostic(mp, true);
9653 }
9654
9655 @ @<Cases for printing graphical object node |p|@>=
9656 case mp_fill_code: 
9657   mp_print(mp, "Filled contour ");
9658   mp_print_obj_color(mp, p);
9659   mp_print_char(mp, ':'); mp_print_ln(mp);
9660   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9661   if ( (pen_p(p)!=null) ) {
9662     @<Print join type for graphical object |p|@>;
9663     mp_print(mp, " with pen"); mp_print_ln(mp);
9664     mp_pr_pen(mp, pen_p(p));
9665   }
9666   break;
9667
9668 @ @<Print join type for graphical object |p|@>=
9669 switch (ljoin_val(p)) {
9670 case 0:
9671   mp_print(mp, "mitered joins limited ");
9672   mp_print_scaled(mp, miterlim_val(p));
9673   break;
9674 case 1:
9675   mp_print(mp, "round joins");
9676   break;
9677 case 2:
9678   mp_print(mp, "beveled joins");
9679   break;
9680 default: 
9681   mp_print(mp, "?? joins");
9682 @.??@>
9683   break;
9684 }
9685
9686 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9687
9688 @<Print join and cap types for stroked node |p|@>=
9689 switch (lcap_val(p)) {
9690 case 0:mp_print(mp, "butt"); break;
9691 case 1:mp_print(mp, "round"); break;
9692 case 2:mp_print(mp, "square"); break;
9693 default: mp_print(mp, "??"); break;
9694 @.??@>
9695 }
9696 mp_print(mp, " ends, ");
9697 @<Print join type for graphical object |p|@>
9698
9699 @ Here is a routine that prints the color of a graphical object if it isn't
9700 black (the default color).
9701
9702 @<Declare subroutines needed by |print_edges|@>=
9703 @<Declare a procedure called |print_compact_node|@>;
9704 void mp_print_obj_color (MP mp,pointer p) { 
9705   if ( color_model(p)==mp_grey_model ) {
9706     if ( grey_val(p)>0 ) { 
9707       mp_print(mp, "greyed ");
9708       mp_print_compact_node(mp, obj_grey_loc(p),1);
9709     };
9710   } else if ( color_model(p)==mp_cmyk_model ) {
9711     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9712          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9713       mp_print(mp, "processcolored ");
9714       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9715     };
9716   } else if ( color_model(p)==mp_rgb_model ) {
9717     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9718       mp_print(mp, "colored "); 
9719       mp_print_compact_node(mp, obj_red_loc(p),3);
9720     };
9721   }
9722 }
9723
9724 @ We also need a procedure for printing consecutive scaled values as if they
9725 were a known big node.
9726
9727 @<Declare a procedure called |print_compact_node|@>=
9728 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9729   pointer q;  /* last location to print */
9730   q=p+k-1;
9731   mp_print_char(mp, '(');
9732   while ( p<=q ){ 
9733     mp_print_scaled(mp, mp->mem[p].sc);
9734     if ( p<q ) mp_print_char(mp, ',');
9735     incr(p);
9736   }
9737   mp_print_char(mp, ')');
9738 }
9739
9740 @ @<Cases for printing graphical object node |p|@>=
9741 case mp_stroked_code: 
9742   mp_print(mp, "Filled pen stroke ");
9743   mp_print_obj_color(mp, p);
9744   mp_print_char(mp, ':'); mp_print_ln(mp);
9745   mp_pr_path(mp, path_p(p));
9746   if ( dash_p(p)!=null ) { 
9747     mp_print_nl(mp, "dashed (");
9748     @<Finish printing the dash pattern that |p| refers to@>;
9749   }
9750   mp_print_ln(mp);
9751   @<Print join and cap types for stroked node |p|@>;
9752   mp_print(mp, " with pen"); mp_print_ln(mp);
9753   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9754 @.???@>
9755   else mp_pr_pen(mp, pen_p(p));
9756   break;
9757
9758 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9759 when it is not known to define a suitable dash pattern.  This is disallowed
9760 here because the |dash_p| field should never point to such an edge header.
9761 Note that memory is allocated for |start_x(null_dash)| and we are free to
9762 give it any convenient value.
9763
9764 @<Finish printing the dash pattern that |p| refers to@>=
9765 ok_to_dash=pen_is_elliptical(pen_p(p));
9766 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9767 hh=dash_p(p);
9768 pp=dash_list(hh);
9769 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9770   mp_print(mp, " ??");
9771 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9772   while ( pp!=null_dash ) { 
9773     mp_print(mp, "on ");
9774     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9775     mp_print(mp, " off ");
9776     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9777     pp = link(pp);
9778     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9779   }
9780   mp_print(mp, ") shifted ");
9781   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9782   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9783 }
9784
9785 @ @<Declare subroutines needed by |print_edges|@>=
9786 scaled mp_dash_offset (MP mp,pointer h) {
9787   scaled x;  /* the answer */
9788   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9789 @:this can't happen dash0}{\quad dash0@>
9790   if ( dash_y(h)==0 ) {
9791     x=0; 
9792   } else { 
9793     x=-(start_x(dash_list(h)) % dash_y(h));
9794     if ( x<0 ) x=x+dash_y(h);
9795   }
9796   return x;
9797 }
9798
9799 @ @<Cases for printing graphical object node |p|@>=
9800 case mp_text_code: 
9801   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9802   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9803   mp_print_char(mp, '"'); mp_print_ln(mp);
9804   mp_print_obj_color(mp, p);
9805   mp_print(mp, "transformed ");
9806   mp_print_compact_node(mp, text_tx_loc(p),6);
9807   break;
9808
9809 @ @<Cases for printing graphical object node |p|@>=
9810 case mp_start_clip_code: 
9811   mp_print(mp, "clipping path:");
9812   mp_print_ln(mp);
9813   mp_pr_path(mp, path_p(p));
9814   break;
9815 case mp_stop_clip_code: 
9816   mp_print(mp, "stop clipping");
9817   break;
9818
9819 @ @<Cases for printing graphical object node |p|@>=
9820 case mp_start_bounds_code: 
9821   mp_print(mp, "setbounds path:");
9822   mp_print_ln(mp);
9823   mp_pr_path(mp, path_p(p));
9824   break;
9825 case mp_stop_bounds_code: 
9826   mp_print(mp, "end of setbounds");
9827   break;
9828
9829 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9830 subroutine that scans an edge structure and tries to interpret it as a dash
9831 pattern.  This can only be done when there are no filled regions or clipping
9832 paths and all the pen strokes have the same color.  The first step is to let
9833 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9834 project all the pen stroke paths onto the line $y=y_0$ and require that there
9835 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9836 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9837 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9838
9839 @c @<Declare a procedure called |x_retrace_error|@>;
9840 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9841   pointer p;  /* this scans the stroked nodes in the object list */
9842   pointer p0;  /* if not |null| this points to the first stroked node */
9843   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9844   pointer d,dd;  /* pointers used to create the dash list */
9845   @<Other local variables in |make_dashes|@>;
9846   scaled y0=0;  /* the initial $y$ coordinate */
9847   if ( dash_list(h)!=null_dash ) 
9848         return h;
9849   p0=null;
9850   p=link(dummy_loc(h));
9851   while ( p!=null ) { 
9852     if ( type(p)!=mp_stroked_code ) {
9853       @<Compain that the edge structure contains a node of the wrong type
9854         and |goto not_found|@>;
9855     }
9856     pp=path_p(p);
9857     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9858     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9859       or |goto not_found| if there is an error@>;
9860     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9861     p=link(p);
9862   }
9863   if ( dash_list(h)==null_dash ) 
9864     goto NOT_FOUND; /* No error message */
9865   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9866   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9867   return h;
9868 NOT_FOUND: 
9869   @<Flush the dash list, recycle |h| and return |null|@>;
9870 };
9871
9872 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9873
9874 print_err("Picture is too complicated to use as a dash pattern");
9875 help3("When you say `dashed p', picture p should not contain any")
9876   ("text, filled regions, or clipping paths.  This time it did")
9877   ("so I'll just make it a solid line instead.");
9878 mp_put_get_error(mp);
9879 goto NOT_FOUND;
9880 }
9881
9882 @ A similar error occurs when monotonicity fails.
9883
9884 @<Declare a procedure called |x_retrace_error|@>=
9885 void mp_x_retrace_error (MP mp) { 
9886 print_err("Picture is too complicated to use as a dash pattern");
9887 help3("When you say `dashed p', every path in p should be monotone")
9888   ("in x and there must be no overlapping.  This failed")
9889   ("so I'll just make it a solid line instead.");
9890 mp_put_get_error(mp);
9891 }
9892
9893 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9894 handle the case where the pen stroke |p| is itself dashed.
9895
9896 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9897 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9898   an error@>;
9899 rr=pp;
9900 if ( link(pp)!=pp ) {
9901   do {  
9902     qq=rr; rr=link(rr);
9903     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9904       if there is a problem@>;
9905   } while (right_type(rr)!=mp_endpoint);
9906 }
9907 d=mp_get_node(mp, dash_node_size);
9908 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9909 if ( x_coord(pp)<x_coord(rr) ) { 
9910   start_x(d)=x_coord(pp);
9911   stop_x(d)=x_coord(rr);
9912 } else { 
9913   start_x(d)=x_coord(rr);
9914   stop_x(d)=x_coord(pp);
9915 }
9916
9917 @ We also need to check for the case where the segment from |qq| to |rr| is
9918 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9919
9920 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9921 x0=x_coord(qq);
9922 x1=right_x(qq);
9923 x2=left_x(rr);
9924 x3=x_coord(rr);
9925 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9926   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9927     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9928       mp_x_retrace_error(mp); goto NOT_FOUND;
9929     }
9930   }
9931 }
9932 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9933   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9934     mp_x_retrace_error(mp); goto NOT_FOUND;
9935   }
9936 }
9937
9938 @ @<Other local variables in |make_dashes|@>=
9939   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9940
9941 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9942 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9943   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9944   print_err("Picture is too complicated to use as a dash pattern");
9945   help3("When you say `dashed p', everything in picture p should")
9946     ("be the same color.  I can\'t handle your color changes")
9947     ("so I'll just make it a solid line instead.");
9948   mp_put_get_error(mp);
9949   goto NOT_FOUND;
9950 }
9951
9952 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9953 start_x(null_dash)=stop_x(d);
9954 dd=h; /* this makes |link(dd)=dash_list(h)| */
9955 while ( start_x(link(dd))<stop_x(d) )
9956   dd=link(dd);
9957 if ( dd!=h ) {
9958   if ( (stop_x(dd)>start_x(d)) )
9959     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9960 }
9961 link(d)=link(dd);
9962 link(dd)=d
9963
9964 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9965 d=dash_list(h);
9966 while ( (link(d)!=null_dash) )
9967   d=link(d);
9968 dd=dash_list(h);
9969 dash_y(h)=stop_x(d)-start_x(dd);
9970 if ( abs(y0)>dash_y(h) ) {
9971   dash_y(h)=abs(y0);
9972 } else if ( d!=dd ) { 
9973   dash_list(h)=link(dd);
9974   stop_x(d)=stop_x(dd)+dash_y(h);
9975   mp_free_node(mp, dd,dash_node_size);
9976 }
9977
9978 @ We get here when the argument is a null picture or when there is an error.
9979 Recovering from an error involves making |dash_list(h)| empty to indicate
9980 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9981 since it is not being used for the return value.
9982
9983 @<Flush the dash list, recycle |h| and return |null|@>=
9984 mp_flush_dash_list(mp, h);
9985 delete_edge_ref(h);
9986 return null
9987
9988 @ Having carefully saved the dashed stroked nodes in the
9989 corresponding dash nodes, we must be prepared to break up these dashes into
9990 smaller dashes.
9991
9992 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
9993 d=h;  /* now |link(d)=dash_list(h)| */
9994 while ( link(d)!=null_dash ) {
9995   ds=info(link(d));
9996   if ( ds==null ) { 
9997     d=link(d);
9998   } else {
9999     hh=dash_p(ds);
10000     hsf=dash_scale(ds);
10001     if ( (hh==null) ) mp_confusion(mp, "dash1");
10002 @:this can't happen dash0}{\quad dash1@>
10003     if ( dash_y(hh)==0 ) {
10004       d=link(d);
10005     } else { 
10006       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10007 @:this can't happen dash0}{\quad dash1@>
10008       @<Replace |link(d)| by a dashed version as determined by edge header
10009           |hh| and scale factor |ds|@>;
10010     }
10011   }
10012 }
10013
10014 @ @<Other local variables in |make_dashes|@>=
10015 pointer dln;  /* |link(d)| */
10016 pointer hh;  /* an edge header that tells how to break up |dln| */
10017 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10018 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10019 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10020
10021 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10022 dln=link(d);
10023 dd=dash_list(hh);
10024 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10025         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10026 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10027                    +mp_take_scaled(mp, hsf,dash_y(hh));
10028 stop_x(null_dash)=start_x(null_dash);
10029 @<Advance |dd| until finding the first dash that overlaps |dln| when
10030   offset by |xoff|@>;
10031 while ( start_x(dln)<=stop_x(dln) ) {
10032   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10033   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10034     of |dd|@>;
10035   dd=link(dd);
10036   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10037 }
10038 link(d)=link(dln);
10039 mp_free_node(mp, dln,dash_node_size)
10040
10041 @ The name of this module is a bit of a lie because we just find the
10042 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10043 overlap possible.  It could be that the unoffset version of dash |dln| falls
10044 in the gap between |dd| and its predecessor.
10045
10046 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10047 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10048   dd=link(dd);
10049 }
10050
10051 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10052 if ( dd==null_dash ) { 
10053   dd=dash_list(hh);
10054   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10055 }
10056
10057 @ At this point we already know that
10058 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10059
10060 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10061 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10062   link(d)=mp_get_node(mp, dash_node_size);
10063   d=link(d);
10064   link(d)=dln;
10065   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10066     start_x(d)=start_x(dln);
10067   else 
10068     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10069   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10070     stop_x(d)=stop_x(dln);
10071   else 
10072     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10073 }
10074
10075 @ The next major task is to update the bounding box information in an edge
10076 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10077 header's bounding box to accommodate the box computed by |path_bbox| or
10078 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10079 |maxy|.)
10080
10081 @c void mp_adjust_bbox (MP mp,pointer h) { 
10082   if ( minx<minx_val(h) ) minx_val(h)=minx;
10083   if ( miny<miny_val(h) ) miny_val(h)=miny;
10084   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10085   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10086 }
10087
10088 @ Here is a special routine for updating the bounding box information in
10089 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10090 that is to be stroked with the pen~|pp|.
10091
10092 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10093   pointer q;  /* a knot node adjacent to knot |p| */
10094   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10095   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10096   scaled z;  /* a coordinate being tested against the bounding box */
10097   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10098   integer i; /* a loop counter */
10099   if ( right_type(p)!=mp_endpoint ) { 
10100     q=link(p);
10101     while (1) { 
10102       @<Make |(dx,dy)| the final direction for the path segment from
10103         |q| to~|p|; set~|d|@>;
10104       d=mp_pyth_add(mp, dx,dy);
10105       if ( d>0 ) { 
10106          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10107          for (i=1;i<= 2;i++) { 
10108            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10109              update the bounding box to accommodate it@>;
10110            dx=-dx; dy=-dy; 
10111         }
10112       }
10113       if ( right_type(p)==mp_endpoint ) {
10114          return;
10115       } else {
10116         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10117       } 
10118     }
10119   }
10120 }
10121
10122 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10123 if ( q==link(p) ) { 
10124   dx=x_coord(p)-right_x(p);
10125   dy=y_coord(p)-right_y(p);
10126   if ( (dx==0)&&(dy==0) ) {
10127     dx=x_coord(p)-left_x(q);
10128     dy=y_coord(p)-left_y(q);
10129   }
10130 } else { 
10131   dx=x_coord(p)-left_x(p);
10132   dy=y_coord(p)-left_y(p);
10133   if ( (dx==0)&&(dy==0) ) {
10134     dx=x_coord(p)-right_x(q);
10135     dy=y_coord(p)-right_y(q);
10136   }
10137 }
10138 dx=x_coord(p)-x_coord(q);
10139 dy=y_coord(p)-y_coord(q)
10140
10141 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10142 dx=mp_make_fraction(mp, dx,d);
10143 dy=mp_make_fraction(mp, dy,d);
10144 mp_find_offset(mp, -dy,dx,pp);
10145 xx=mp->cur_x; yy=mp->cur_y
10146
10147 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10148 mp_find_offset(mp, dx,dy,pp);
10149 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10150 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10151   mp_confusion(mp, "box_ends");
10152 @:this can't happen box ends}{\quad\\{box\_ends}@>
10153 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10154 if ( z<minx_val(h) ) minx_val(h)=z;
10155 if ( z>maxx_val(h) ) maxx_val(h)=z;
10156 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10157 if ( z<miny_val(h) ) miny_val(h)=z;
10158 if ( z>maxy_val(h) ) maxy_val(h)=z
10159
10160 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10161 do {  
10162   q=p;
10163   p=link(p);
10164 } while (right_type(p)!=mp_endpoint)
10165
10166 @ The major difficulty in finding the bounding box of an edge structure is the
10167 effect of clipping paths.  We treat them conservatively by only clipping to the
10168 clipping path's bounding box, but this still
10169 requires recursive calls to |set_bbox| in order to find the bounding box of
10170 @^recursion@>
10171 the objects to be clipped.  Such calls are distinguished by the fact that the
10172 boolean parameter |top_level| is false.
10173
10174 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10175   pointer p;  /* a graphical object being considered */
10176   scaled sminx,sminy,smaxx,smaxy;
10177   /* for saving the bounding box during recursive calls */
10178   scaled x0,x1,y0,y1;  /* temporary registers */
10179   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10180   @<Wipe out any existing bounding box information if |bbtype(h)| is
10181   incompatible with |internal[mp_true_corners]|@>;
10182   while ( link(bblast(h))!=null ) { 
10183     p=link(bblast(h));
10184     bblast(h)=p;
10185     switch (type(p)) {
10186     case mp_stop_clip_code: 
10187       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10188 @:this can't happen bbox}{\quad bbox@>
10189       break;
10190     @<Other cases for updating the bounding box based on the type of object |p|@>;
10191     } /* all cases are enumerated above */
10192   }
10193   if ( ! top_level ) mp_confusion(mp, "bbox");
10194 }
10195
10196 @ @<Internal library declarations@>=
10197 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10198
10199 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10200 switch (bbtype(h)) {
10201 case no_bounds: 
10202   break;
10203 case bounds_set: 
10204   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10205   break;
10206 case bounds_unset: 
10207   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10208   break;
10209 } /* there are no other cases */
10210
10211 @ @<Other cases for updating the bounding box...@>=
10212 case mp_fill_code: 
10213   mp_path_bbox(mp, path_p(p));
10214   if ( pen_p(p)!=null ) { 
10215     x0=minx; y0=miny;
10216     x1=maxx; y1=maxy;
10217     mp_pen_bbox(mp, pen_p(p));
10218     minx=minx+x0;
10219     miny=miny+y0;
10220     maxx=maxx+x1;
10221     maxy=maxy+y1;
10222   }
10223   mp_adjust_bbox(mp, h);
10224   break;
10225
10226 @ @<Other cases for updating the bounding box...@>=
10227 case mp_start_bounds_code: 
10228   if ( mp->internal[mp_true_corners]>0 ) {
10229     bbtype(h)=bounds_unset;
10230   } else { 
10231     bbtype(h)=bounds_set;
10232     mp_path_bbox(mp, path_p(p));
10233     mp_adjust_bbox(mp, h);
10234     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10235       |bblast(h)|@>;
10236   }
10237   break;
10238 case mp_stop_bounds_code: 
10239   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10240 @:this can't happen bbox2}{\quad bbox2@>
10241   break;
10242
10243 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10244 lev=1;
10245 while ( lev!=0 ) { 
10246   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10247 @:this can't happen bbox2}{\quad bbox2@>
10248   p=link(p);
10249   if ( type(p)==mp_start_bounds_code ) incr(lev);
10250   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10251 }
10252 bblast(h)=p
10253
10254 @ It saves a lot of grief here to be slightly conservative and not account for
10255 omitted parts of dashed lines.  We also don't worry about the material omitted
10256 when using butt end caps.  The basic computation is for round end caps and
10257 |box_ends| augments it for square end caps.
10258
10259 @<Other cases for updating the bounding box...@>=
10260 case mp_stroked_code: 
10261   mp_path_bbox(mp, path_p(p));
10262   x0=minx; y0=miny;
10263   x1=maxx; y1=maxy;
10264   mp_pen_bbox(mp, pen_p(p));
10265   minx=minx+x0;
10266   miny=miny+y0;
10267   maxx=maxx+x1;
10268   maxy=maxy+y1;
10269   mp_adjust_bbox(mp, h);
10270   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10271     mp_box_ends(mp, path_p(p), pen_p(p), h);
10272   break;
10273
10274 @ The height width and depth information stored in a text node determines a
10275 rectangle that needs to be transformed according to the transformation
10276 parameters stored in the text node.
10277
10278 @<Other cases for updating the bounding box...@>=
10279 case mp_text_code: 
10280   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10281   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10282   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10283   minx=tx_val(p);
10284   maxx=minx;
10285   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10286   else         { minx=minx+y1; maxx=maxx+y0;  }
10287   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10288   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10289   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10290   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10291   miny=ty_val(p);
10292   maxy=miny;
10293   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10294   else         { miny=miny+y1; maxy=maxy+y0;  }
10295   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10296   mp_adjust_bbox(mp, h);
10297   break;
10298
10299 @ This case involves a recursive call that advances |bblast(h)| to the node of
10300 type |mp_stop_clip_code| that matches |p|.
10301
10302 @<Other cases for updating the bounding box...@>=
10303 case mp_start_clip_code: 
10304   mp_path_bbox(mp, path_p(p));
10305   x0=minx; y0=miny;
10306   x1=maxx; y1=maxy;
10307   sminx=minx_val(h); sminy=miny_val(h);
10308   smaxx=maxx_val(h); smaxy=maxy_val(h);
10309   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10310     starting at |link(p)|@>;
10311   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10312     |y0|, |y1|@>;
10313   minx=sminx; miny=sminy;
10314   maxx=smaxx; maxy=smaxy;
10315   mp_adjust_bbox(mp, h);
10316   break;
10317
10318 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10319 minx_val(h)=el_gordo;
10320 miny_val(h)=el_gordo;
10321 maxx_val(h)=-el_gordo;
10322 maxy_val(h)=-el_gordo;
10323 mp_set_bbox(mp, h,false)
10324
10325 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10326 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10327 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10328 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10329 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10330
10331 @* \[22] Finding an envelope.
10332 When \MP\ has a path and a polygonal pen, it needs to express the desired
10333 shape in terms of things \ps\ can understand.  The present task is to compute
10334 a new path that describes the region to be filled.  It is convenient to
10335 define this as a two step process where the first step is determining what
10336 offset to use for each segment of the path.
10337
10338 @ Given a pointer |c| to a cyclic path,
10339 and a pointer~|h| to the first knot of a pen polygon,
10340 the |offset_prep| routine changes the path into cubics that are
10341 associated with particular pen offsets. Thus if the cubic between |p|
10342 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10343 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10344 to because |l-k| could be negative.)
10345
10346 After overwriting the type information with offset differences, we no longer
10347 have a true path so we refer to the knot list returned by |offset_prep| as an
10348 ``envelope spec.''
10349 @^envelope spec@>
10350 Since an envelope spec only determines relative changes in pen offsets,
10351 |offset_prep| sets a global variable |spec_offset| to the relative change from
10352 |h| to the first offset.
10353
10354 @d zero_off 16384 /* added to offset changes to make them positive */
10355
10356 @<Glob...@>=
10357 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10358
10359 @ @c @<Declare subroutines needed by |offset_prep|@>;
10360 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10361   halfword n; /* the number of vertices in the pen polygon */
10362   pointer p,q,q0,r,w, ww; /* for list manipulation */
10363   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10364   pointer w0; /* a pointer to pen offset to use just before |p| */
10365   scaled dxin,dyin; /* the direction into knot |p| */
10366   integer turn_amt; /* change in pen offsets for the current cubic */
10367   @<Other local variables for |offset_prep|@>;
10368   dx0=0; dy0=0;
10369   @<Initialize the pen size~|n|@>;
10370   @<Initialize the incoming direction and pen offset at |c|@>;
10371   p=c; k_needed=0;
10372   do {  
10373     q=link(p);
10374     @<Split the cubic between |p| and |q|, if necessary, into cubics
10375       associated with single offsets, after which |q| should
10376       point to the end of the final such cubic@>;
10377   NOT_FOUND:
10378     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10379       might have been introduced by the splitting process@>;
10380   } while (q!=c);
10381   @<Fix the offset change in |info(c)| and set |c| to the return value of
10382     |offset_prep|@>;
10383   return c;
10384 }
10385
10386 @ We shall want to keep track of where certain knots on the cyclic path
10387 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10388 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10389 |offset_prep| updates the following pointers
10390
10391 @<Glob...@>=
10392 pointer spec_p1;
10393 pointer spec_p2; /* pointers to distinguished knots */
10394
10395 @ @<Set init...@>=
10396 mp->spec_p1=null; mp->spec_p2=null;
10397
10398 @ @<Initialize the pen size~|n|@>=
10399 n=0; p=h;
10400 do {  
10401   incr(n);
10402   p=link(p);
10403 } while (p!=h)
10404
10405 @ Since the true incoming direction isn't known yet, we just pick a direction
10406 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10407 later.
10408
10409 @<Initialize the incoming direction and pen offset at |c|@>=
10410 dxin=x_coord(link(h))-x_coord(knil(h));
10411 dyin=y_coord(link(h))-y_coord(knil(h));
10412 if ( (dxin==0)&&(dyin==0) ) {
10413   dxin=y_coord(knil(h))-y_coord(h);
10414   dyin=x_coord(h)-x_coord(knil(h));
10415 }
10416 w0=h
10417
10418 @ We must be careful not to remove the only cubic in a cycle.
10419
10420 But we must also be careful for another reason. If the user-supplied
10421 path starts with a set of degenerate cubics, the target node |q| can
10422 be collapsed to the initial node |p| which might be the same as the
10423 initial node |c| of the curve. This would cause the |offset_prep| routine
10424 to bail out too early, causing distress later on. (See for example
10425 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10426 on Sarovar.)
10427
10428 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10429 q0=q;
10430 do { 
10431   r=link(p);
10432   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10433        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10434        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10435        r!=p ) {
10436       @<Remove the cubic following |p| and update the data structures
10437         to merge |r| into |p|@>;
10438   }
10439   p=r;
10440 } while (p!=q);
10441 /* Check if we removed too much */
10442 if(q!=q0)
10443   q = link(q)
10444
10445 @ @<Remove the cubic following |p| and update the data structures...@>=
10446 { k_needed=info(p)-zero_off;
10447   if ( r==q ) { 
10448     q=p;
10449   } else { 
10450     info(p)=k_needed+info(r);
10451     k_needed=0;
10452   };
10453   if ( r==c ) { info(p)=info(c); c=p; };
10454   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10455   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10456   r=p; mp_remove_cubic(mp, p);
10457 }
10458
10459 @ Not setting the |info| field of the newly created knot allows the splitting
10460 routine to work for paths.
10461
10462 @<Declare subroutines needed by |offset_prep|@>=
10463 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10464   scaled v; /* an intermediate value */
10465   pointer q,r; /* for list manipulation */
10466   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10467   originator(r)=mp_program_code;
10468   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10469   v=t_of_the_way(right_x(p),left_x(q));
10470   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10471   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10472   left_x(r)=t_of_the_way(right_x(p),v);
10473   right_x(r)=t_of_the_way(v,left_x(q));
10474   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10475   v=t_of_the_way(right_y(p),left_y(q));
10476   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10477   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10478   left_y(r)=t_of_the_way(right_y(p),v);
10479   right_y(r)=t_of_the_way(v,left_y(q));
10480   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10481 }
10482
10483 @ This does not set |info(p)| or |right_type(p)|.
10484
10485 @<Declare subroutines needed by |offset_prep|@>=
10486 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10487   pointer q; /* the node that disappears */
10488   q=link(p); link(p)=link(q);
10489   right_x(p)=right_x(q); right_y(p)=right_y(q);
10490   mp_free_node(mp, q,knot_node_size);
10491 }
10492
10493 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10494 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10495 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10496 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10497 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10498 When listed by increasing $k$, these directions occur in counter-clockwise
10499 order so that $d_k\preceq d\k$ for all~$k$.
10500 The goal of |offset_prep| is to find an offset index~|k| to associate with
10501 each cubic, such that the direction $d(t)$ of the cubic satisfies
10502 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10503 We may have to split a cubic into many pieces before each
10504 piece corresponds to a unique offset.
10505
10506 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10507 info(p)=zero_off+k_needed;
10508 k_needed=0;
10509 @<Prepare for derivative computations;
10510   |goto not_found| if the current cubic is dead@>;
10511 @<Find the initial direction |(dx,dy)|@>;
10512 @<Update |info(p)| and find the offset $w_k$ such that
10513   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10514   the direction change at |p|@>;
10515 @<Find the final direction |(dxin,dyin)|@>;
10516 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10517 @<Complete the offset splitting process@>;
10518 w0=mp_pen_walk(mp, w0,turn_amt)
10519
10520 @ @<Declare subroutines needed by |offset_prep|@>=
10521 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10522   /* walk |k| steps around a pen from |w| */
10523   while ( k>0 ) { w=link(w); decr(k);  };
10524   while ( k<0 ) { w=knil(w); incr(k);  };
10525   return w;
10526 }
10527
10528 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10529 calculated from the quadratic polynomials
10530 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10531 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10532 Since we may be calculating directions from several cubics
10533 split from the current one, it is desirable to do these calculations
10534 without losing too much precision. ``Scaled up'' values of the
10535 derivatives, which will be less tainted by accumulated errors than
10536 derivatives found from the cubics themselves, are maintained in
10537 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10538 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10539 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)$.
10540
10541 @<Other local variables for |offset_prep|@>=
10542 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10543 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10544 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10545 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10546 integer max_coef; /* used while scaling */
10547 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10548 fraction t; /* where the derivative passes through zero */
10549 fraction s; /* a temporary value */
10550
10551 @ @<Prepare for derivative computations...@>=
10552 x0=right_x(p)-x_coord(p);
10553 x2=x_coord(q)-left_x(q);
10554 x1=left_x(q)-right_x(p);
10555 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10556 y1=left_y(q)-right_y(p);
10557 max_coef=abs(x0);
10558 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10559 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10560 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10561 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10562 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10563 if ( max_coef==0 ) goto NOT_FOUND;
10564 while ( max_coef<fraction_half ) {
10565   double(max_coef);
10566   double(x0); double(x1); double(x2);
10567   double(y0); double(y1); double(y2);
10568 }
10569
10570 @ Let us first solve a special case of the problem: Suppose we
10571 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10572 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10573 $d(0)\succ d_{k-1}$.
10574 Then, in a sense, we're halfway done, since one of the two relations
10575 in $(*)$ is satisfied, and the other couldn't be satisfied for
10576 any other value of~|k|.
10577
10578 Actually, the conditions can be relaxed somewhat since a relation such as
10579 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10580 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10581 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10582 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10583 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10584 counterclockwise direction.
10585
10586 The |fin_offset_prep| subroutine solves the stated subproblem.
10587 It has a parameter called |rise| that is |1| in
10588 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10589 the derivative of the cubic following |p|.
10590 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10591 be set properly.  The |turn_amt| parameter gives the absolute value of the
10592 overall net change in pen offsets.
10593
10594 @<Declare subroutines needed by |offset_prep|@>=
10595 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10596   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10597   integer rise, integer turn_amt)  {
10598   pointer ww; /* for list manipulation */
10599   scaled du,dv; /* for slope calculation */
10600   integer t0,t1,t2; /* test coefficients */
10601   fraction t; /* place where the derivative passes a critical slope */
10602   fraction s; /* slope or reciprocal slope */
10603   integer v; /* intermediate value for updating |x0..y2| */
10604   pointer q; /* original |link(p)| */
10605   q=link(p);
10606   while (1)  { 
10607     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10608     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10609     @<Compute test coefficients |(t0,t1,t2)|
10610       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10611     t=mp_crossing_point(mp, t0,t1,t2);
10612     if ( t>=fraction_one ) {
10613       if ( turn_amt>0 ) t=fraction_one;  else return;
10614     }
10615     @<Split the cubic at $t$,
10616       and split off another cubic if the derivative crosses back@>;
10617     w=ww;
10618   }
10619 }
10620
10621 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10622 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10623 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10624 begins to fail.
10625
10626 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10627 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10628 if ( abs(du)>=abs(dv) ) {
10629   s=mp_make_fraction(mp, dv,du);
10630   t0=mp_take_fraction(mp, x0,s)-y0;
10631   t1=mp_take_fraction(mp, x1,s)-y1;
10632   t2=mp_take_fraction(mp, x2,s)-y2;
10633   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10634 } else { 
10635   s=mp_make_fraction(mp, du,dv);
10636   t0=x0-mp_take_fraction(mp, y0,s);
10637   t1=x1-mp_take_fraction(mp, y1,s);
10638   t2=x2-mp_take_fraction(mp, y2,s);
10639   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10640 }
10641 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10642
10643 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10644 $(*)$, and it might cross again, yielding another solution of $(*)$.
10645
10646 @<Split the cubic at $t$, and split off another...@>=
10647
10648 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10649 decr(turn_amt);
10650 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10651 x0=t_of_the_way(v,x1);
10652 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10653 y0=t_of_the_way(v,y1);
10654 if ( turn_amt<0 ) {
10655   t1=t_of_the_way(t1,t2);
10656   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10657   t=mp_crossing_point(mp, 0,-t1,-t2);
10658   if ( t>fraction_one ) t=fraction_one;
10659   incr(turn_amt);
10660   if ( (t==fraction_one)&&(link(p)!=q) ) {
10661     info(link(p))=info(link(p))-rise;
10662   } else { 
10663     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10664     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10665     x2=t_of_the_way(x1,v);
10666     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10667     y2=t_of_the_way(y1,v);
10668   }
10669 }
10670 }
10671
10672 @ Now we must consider the general problem of |offset_prep|, when
10673 nothing is known about a given cubic. We start by finding its
10674 direction in the vicinity of |t=0|.
10675
10676 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10677 has not yet introduced any more numerical errors.  Thus we can compute
10678 the true initial direction for the given cubic, even if it is almost
10679 degenerate.
10680
10681 @<Find the initial direction |(dx,dy)|@>=
10682 dx=x0; dy=y0;
10683 if ( dx==0 && dy==0 ) { 
10684   dx=x1; dy=y1;
10685   if ( dx==0 && dy==0 ) { 
10686     dx=x2; dy=y2;
10687   }
10688 }
10689 if ( p==c ) { dx0=dx; dy0=dy;  }
10690
10691 @ @<Find the final direction |(dxin,dyin)|@>=
10692 dxin=x2; dyin=y2;
10693 if ( dxin==0 && dyin==0 ) {
10694   dxin=x1; dyin=y1;
10695   if ( dxin==0 && dyin==0 ) {
10696     dxin=x0; dyin=y0;
10697   }
10698 }
10699
10700 @ The next step is to bracket the initial direction between consecutive
10701 edges of the pen polygon.  We must be careful to turn clockwise only if
10702 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10703 counter-clockwise in order to make \&{doublepath} envelopes come out
10704 @:double_path_}{\&{doublepath} primitive@>
10705 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10706
10707 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10708 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10709 w=mp_pen_walk(mp, w0, turn_amt);
10710 w0=w;
10711 info(p)=info(p)+turn_amt
10712
10713 @ Decide how many pen offsets to go away from |w| in order to find the offset
10714 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10715 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10716 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10717
10718 If the pen polygon has only two edges, they could both be parallel
10719 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10720 such edge in order to avoid an infinite loop.
10721
10722 @<Declare subroutines needed by |offset_prep|@>=
10723 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10724                          scaled dy, boolean  ccw) {
10725   pointer ww; /* a neighbor of knot~|w| */
10726   integer s; /* turn amount so far */
10727   integer t; /* |ab_vs_cd| result */
10728   s=0;
10729   if ( ccw ) { 
10730     ww=link(w);
10731     do {  
10732       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10733                         dx,(y_coord(ww)-y_coord(w)));
10734       if ( t<0 ) break;
10735       incr(s);
10736       w=ww; ww=link(ww);
10737     } while (t>0);
10738   } else { 
10739     ww=knil(w);
10740     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10741                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10742       decr(s);
10743       w=ww; ww=knil(ww);
10744     }
10745   }
10746   return s;
10747 }
10748
10749 @ When we're all done, the final offset is |w0| and the final curve direction
10750 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10751 can correct |info(c)| which was erroneously based on an incoming offset
10752 of~|h|.
10753
10754 @d fix_by(A) info(c)=info(c)+(A)
10755
10756 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10757 mp->spec_offset=info(c)-zero_off;
10758 if ( link(c)==c ) {
10759   info(c)=zero_off+n;
10760 } else { 
10761   fix_by(k_needed);
10762   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10763   while ( info(c)<=zero_off-n ) fix_by(n);
10764   while ( info(c)>zero_off ) fix_by(-n);
10765   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10766 }
10767 return c
10768
10769 @ Finally we want to reduce the general problem to situations that
10770 |fin_offset_prep| can handle. We split the cubic into at most three parts
10771 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10772
10773 @<Complete the offset splitting process@>=
10774 ww=knil(w);
10775 @<Compute test coeff...@>;
10776 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10777   |t:=fraction_one+1|@>;
10778 if ( t>fraction_one ) {
10779   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10780 } else {
10781   mp_split_cubic(mp, p,t); r=link(p);
10782   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10783   x2a=t_of_the_way(x1a,x1);
10784   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10785   y2a=t_of_the_way(y1a,y1);
10786   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10787   info(r)=zero_off-1;
10788   if ( turn_amt>=0 ) {
10789     t1=t_of_the_way(t1,t2);
10790     if ( t1>0 ) t1=0;
10791     t=mp_crossing_point(mp, 0,-t1,-t2);
10792     if ( t>fraction_one ) t=fraction_one;
10793     @<Split off another rising cubic for |fin_offset_prep|@>;
10794     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10795   } else {
10796     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10797   }
10798 }
10799
10800 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10801 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10802 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10803 x0a=t_of_the_way(x1,x1a);
10804 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10805 y0a=t_of_the_way(y1,y1a);
10806 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10807 x2=x0a; y2=y0a
10808
10809 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10810 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10811 need to decide whether the directions are parallel or antiparallel.  We
10812 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10813 should be avoided when the value of |turn_amt| already determines the
10814 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10815 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10816 crossing and the first crossing cannot be antiparallel.
10817
10818 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10819 t=mp_crossing_point(mp, t0,t1,t2);
10820 if ( turn_amt>=0 ) {
10821   if ( t2<0 ) {
10822     t=fraction_one+1;
10823   } else { 
10824     u0=t_of_the_way(x0,x1);
10825     u1=t_of_the_way(x1,x2);
10826     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10827     v0=t_of_the_way(y0,y1);
10828     v1=t_of_the_way(y1,y2);
10829     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10830     if ( ss<0 ) t=fraction_one+1;
10831   }
10832 } else if ( t>fraction_one ) {
10833   t=fraction_one;
10834 }
10835
10836 @ @<Other local variables for |offset_prep|@>=
10837 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10838 integer ss = 0; /* the part of the dot product computed so far */
10839 int d_sign; /* sign of overall change in direction for this cubic */
10840
10841 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10842 problem to decide which way it loops around but that's OK as long we're
10843 consistent.  To make \&{doublepath} envelopes work properly, reversing
10844 the path should always change the sign of |turn_amt|.
10845
10846 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10847 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10848 if ( d_sign==0 ) {
10849   @<Check rotation direction based on node position@>
10850 }
10851 if ( d_sign==0 ) {
10852   if ( dx==0 ) {
10853     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10854   } else {
10855     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10856   }
10857 }
10858 @<Make |ss| negative if and only if the total change in direction is
10859   more than $180^\circ$@>;
10860 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10861 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10862
10863 @ We check rotation direction by looking at the vector connecting the current
10864 node with the next. If its angle with incoming and outgoing tangents has the
10865 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10866 Otherwise we proceed to the cusp code.
10867
10868 @<Check rotation direction based on node position@>=
10869 u0=x_coord(q)-x_coord(p);
10870 u1=y_coord(q)-y_coord(p);
10871 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10872   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10873
10874 @ In order to be invariant under path reversal, the result of this computation
10875 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10876 then swapped with |(x2,y2)|.  We make use of the identities
10877 |take_fraction(-a,-b)=take_fraction(a,b)| and
10878 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10879
10880 @<Make |ss| negative if and only if the total change in direction is...@>=
10881 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10882 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10883 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10884 if ( t0>0 ) {
10885   t=mp_crossing_point(mp, t0,t1,-t0);
10886   u0=t_of_the_way(x0,x1);
10887   u1=t_of_the_way(x1,x2);
10888   v0=t_of_the_way(y0,y1);
10889   v1=t_of_the_way(y1,y2);
10890 } else { 
10891   t=mp_crossing_point(mp, -t0,t1,t0);
10892   u0=t_of_the_way(x2,x1);
10893   u1=t_of_the_way(x1,x0);
10894   v0=t_of_the_way(y2,y1);
10895   v1=t_of_the_way(y1,y0);
10896 }
10897 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10898    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10899
10900 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10901 that the |cur_pen| has not been walked around to the first offset.
10902
10903 @c 
10904 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, char *s) {
10905   pointer p,q; /* list traversal */
10906   pointer w; /* the current pen offset */
10907   mp_print_diagnostic(mp, "Envelope spec",s,true);
10908   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10909   mp_print_ln(mp);
10910   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10911   mp_print(mp, " % beginning with offset ");
10912   mp_print_two(mp, x_coord(w),y_coord(w));
10913   do { 
10914     while (1) {  
10915       q=link(p);
10916       @<Print the cubic between |p| and |q|@>;
10917       p=q;
10918           if ((p==cur_spec) || (info(p)!=zero_off)) 
10919         break;
10920     }
10921     if ( info(p)!=zero_off ) {
10922       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10923     }
10924   } while (p!=cur_spec);
10925   mp_print_nl(mp, " & cycle");
10926   mp_end_diagnostic(mp, true);
10927 }
10928
10929 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10930
10931   w=mp_pen_walk(mp, w, (info(p)-zero_off));
10932   mp_print(mp, " % ");
10933   if ( info(p)>zero_off ) mp_print(mp, "counter");
10934   mp_print(mp, "clockwise to offset ");
10935   mp_print_two(mp, x_coord(w),y_coord(w));
10936 }
10937
10938 @ @<Print the cubic between |p| and |q|@>=
10939
10940   mp_print_nl(mp, "   ..controls ");
10941   mp_print_two(mp, right_x(p),right_y(p));
10942   mp_print(mp, " and ");
10943   mp_print_two(mp, left_x(q),left_y(q));
10944   mp_print_nl(mp, " ..");
10945   mp_print_two(mp, x_coord(q),y_coord(q));
10946 }
10947
10948 @ Once we have an envelope spec, the remaining task to construct the actual
10949 envelope by offsetting each cubic as determined by the |info| fields in
10950 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10951 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10952 the envelope.
10953
10954 The |ljoin| and |miterlim| parameters control the treatment of points where the
10955 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10956 The endpoints are easily located because |c| is given in undoubled form
10957 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10958 track of the endpoints and treat them like very sharp corners.
10959 Butt end caps are treated like beveled joins; round end caps are treated like
10960 round joins; and square end caps are achieved by setting |join_type:=3|.
10961
10962 None of these parameters apply to inside joins where the convolution tracing
10963 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10964 approach that is achieved by setting |join_type:=2|.
10965
10966 @c @<Declare a function called |insert_knot|@>;
10967 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10968   small_number lcap, scaled miterlim) {
10969   pointer p,q,r,q0; /* for manipulating the path */
10970   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10971   pointer w,w0; /* the pen knot for the current offset */
10972   scaled qx,qy; /* unshifted coordinates of |q| */
10973   halfword k,k0; /* controls pen edge insertion */
10974   @<Other local variables for |make_envelope|@>;
10975   dxin=0; dyin=0; dxout=0; dyout=0;
10976   mp->spec_p1=null; mp->spec_p2=null;
10977   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10978   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10979     the initial offset@>;
10980   w=h;
10981   p=c;
10982   do {  
10983     q=link(p); q0=q;
10984     qx=x_coord(q); qy=y_coord(q);
10985     k=info(q);
10986     k0=k; w0=w;
10987     if ( k!=zero_off ) {
10988       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
10989     }
10990     @<Add offset |w| to the cubic from |p| to |q|@>;
10991     while ( k!=zero_off ) { 
10992       @<Step |w| and move |k| one step closer to |zero_off|@>;
10993       if ( (join_type==1)||(k==zero_off) )
10994          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
10995     };
10996     if ( q!=link(p) ) {
10997       @<Set |p=link(p)| and add knots between |p| and |q| as
10998         required by |join_type|@>;
10999     }
11000     p=q;
11001   } while (q0!=c);
11002   return c;
11003 }
11004
11005 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11006 c=mp_offset_prep(mp, c,h);
11007 if ( mp->internal[mp_tracing_specs]>0 ) 
11008   mp_print_spec(mp, c,h,"");
11009 h=mp_pen_walk(mp, h,mp->spec_offset)
11010
11011 @ Mitered and squared-off joins depend on path directions that are difficult to
11012 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11013 have degenerate cubics only if the entire cycle collapses to a single
11014 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11015 envelope degenerate as well.
11016
11017 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11018 if ( k<zero_off ) {
11019   join_type=2;
11020 } else {
11021   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11022   else if ( lcap==2 ) join_type=3;
11023   else join_type=2-lcap;
11024   if ( (join_type==0)||(join_type==3) ) {
11025     @<Set the incoming and outgoing directions at |q|; in case of
11026       degeneracy set |join_type:=2|@>;
11027     if ( join_type==0 ) {
11028       @<If |miterlim| is less than the secant of half the angle at |q|
11029         then set |join_type:=2|@>;
11030     }
11031   }
11032 }
11033
11034 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11035
11036   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11037       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11038   if ( tmp<unity )
11039     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11040 }
11041
11042 @ @<Other local variables for |make_envelope|@>=
11043 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11044 scaled tmp; /* a temporary value */
11045
11046 @ The coordinates of |p| have already been shifted unless |p| is the first
11047 knot in which case they get shifted at the very end.
11048
11049 @<Add offset |w| to the cubic from |p| to |q|@>=
11050 right_x(p)=right_x(p)+x_coord(w);
11051 right_y(p)=right_y(p)+y_coord(w);
11052 left_x(q)=left_x(q)+x_coord(w);
11053 left_y(q)=left_y(q)+y_coord(w);
11054 x_coord(q)=x_coord(q)+x_coord(w);
11055 y_coord(q)=y_coord(q)+y_coord(w);
11056 left_type(q)=mp_explicit;
11057 right_type(q)=mp_explicit
11058
11059 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11060 if ( k>zero_off ){ w=link(w); decr(k);  }
11061 else { w=knil(w); incr(k);  }
11062
11063 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11064 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11065 case the cubic containing these control points is ``yet to be examined.''
11066
11067 @<Declare a function called |insert_knot|@>=
11068 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11069   /* returns the inserted knot */
11070   pointer r; /* the new knot */
11071   r=mp_get_node(mp, knot_node_size);
11072   link(r)=link(q); link(q)=r;
11073   right_x(r)=right_x(q);
11074   right_y(r)=right_y(q);
11075   x_coord(r)=x;
11076   y_coord(r)=y;
11077   right_x(q)=x_coord(q);
11078   right_y(q)=y_coord(q);
11079   left_x(r)=x_coord(r);
11080   left_y(r)=y_coord(r);
11081   left_type(r)=mp_explicit;
11082   right_type(r)=mp_explicit;
11083   originator(r)=mp_program_code;
11084   return r;
11085 }
11086
11087 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11088
11089 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11090
11091   p=link(p);
11092   if ( (join_type==0)||(join_type==3) ) {
11093     if ( join_type==0 ) {
11094       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11095     } else {
11096       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11097         squared join@>;
11098     }
11099     if ( r!=null ) { 
11100       right_x(r)=x_coord(r);
11101       right_y(r)=y_coord(r);
11102     }
11103   }
11104 }
11105
11106 @ For very small angles, adding a knot is unnecessary and would cause numerical
11107 problems, so we just set |r:=null| in that case.
11108
11109 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11110
11111   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11112   if ( abs(det)<26844 ) { 
11113      r=null; /* sine $<10^{-4}$ */
11114   } else { 
11115     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11116         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11117     tmp=mp_make_fraction(mp, tmp,det);
11118     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11119       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11120   }
11121 }
11122
11123 @ @<Other local variables for |make_envelope|@>=
11124 fraction det; /* a determinant used for mitered join calculations */
11125
11126 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11127
11128   ht_x=y_coord(w)-y_coord(w0);
11129   ht_y=x_coord(w0)-x_coord(w);
11130   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11131     ht_x+=ht_x; ht_y+=ht_y;
11132   }
11133   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11134     product with |(ht_x,ht_y)|@>;
11135   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11136                                   mp_take_fraction(mp, dyin,ht_y));
11137   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11138                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11139   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11140                                   mp_take_fraction(mp, dyout,ht_y));
11141   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11142                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11143 }
11144
11145 @ @<Other local variables for |make_envelope|@>=
11146 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11147 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11148 halfword kk; /* keeps track of the pen vertices being scanned */
11149 pointer ww; /* the pen vertex being tested */
11150
11151 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11152 from zero to |max_ht|.
11153
11154 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11155 max_ht=0;
11156 kk=zero_off;
11157 ww=w;
11158 while (1)  { 
11159   @<Step |ww| and move |kk| one step closer to |k0|@>;
11160   if ( kk==k0 ) break;
11161   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11162       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11163   if ( tmp>max_ht ) max_ht=tmp;
11164 }
11165
11166
11167 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11168 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11169 else { ww=knil(ww); incr(kk);  }
11170
11171 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11172 if ( left_type(c)==mp_endpoint ) { 
11173   mp->spec_p1=mp_htap_ypoc(mp, c);
11174   mp->spec_p2=mp->path_tail;
11175   originator(mp->spec_p1)=mp_program_code;
11176   link(mp->spec_p2)=link(mp->spec_p1);
11177   link(mp->spec_p1)=c;
11178   mp_remove_cubic(mp, mp->spec_p1);
11179   c=mp->spec_p1;
11180   if ( c!=link(c) ) {
11181     originator(mp->spec_p2)=mp_program_code;
11182     mp_remove_cubic(mp, mp->spec_p2);
11183   } else {
11184     @<Make |c| look like a cycle of length one@>;
11185   }
11186 }
11187
11188 @ @<Make |c| look like a cycle of length one@>=
11189
11190   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11191   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11192   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11193 }
11194
11195 @ In degenerate situations we might have to look at the knot preceding~|q|.
11196 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11197
11198 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11199 dxin=x_coord(q)-left_x(q);
11200 dyin=y_coord(q)-left_y(q);
11201 if ( (dxin==0)&&(dyin==0) ) {
11202   dxin=x_coord(q)-right_x(p);
11203   dyin=y_coord(q)-right_y(p);
11204   if ( (dxin==0)&&(dyin==0) ) {
11205     dxin=x_coord(q)-x_coord(p);
11206     dyin=y_coord(q)-y_coord(p);
11207     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11208       dxin=dxin+x_coord(w);
11209       dyin=dyin+y_coord(w);
11210     }
11211   }
11212 }
11213 tmp=mp_pyth_add(mp, dxin,dyin);
11214 if ( tmp==0 ) {
11215   join_type=2;
11216 } else { 
11217   dxin=mp_make_fraction(mp, dxin,tmp);
11218   dyin=mp_make_fraction(mp, dyin,tmp);
11219   @<Set the outgoing direction at |q|@>;
11220 }
11221
11222 @ If |q=c| then the coordinates of |r| and the control points between |q|
11223 and~|r| have already been offset by |h|.
11224
11225 @<Set the outgoing direction at |q|@>=
11226 dxout=right_x(q)-x_coord(q);
11227 dyout=right_y(q)-y_coord(q);
11228 if ( (dxout==0)&&(dyout==0) ) {
11229   r=link(q);
11230   dxout=left_x(r)-x_coord(q);
11231   dyout=left_y(r)-y_coord(q);
11232   if ( (dxout==0)&&(dyout==0) ) {
11233     dxout=x_coord(r)-x_coord(q);
11234     dyout=y_coord(r)-y_coord(q);
11235   }
11236 }
11237 if ( q==c ) {
11238   dxout=dxout-x_coord(h);
11239   dyout=dyout-y_coord(h);
11240 }
11241 tmp=mp_pyth_add(mp, dxout,dyout);
11242 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11243 @:this can't happen degerate spec}{\quad degenerate spec@>
11244 dxout=mp_make_fraction(mp, dxout,tmp);
11245 dyout=mp_make_fraction(mp, dyout,tmp)
11246
11247 @* \[23] Direction and intersection times.
11248 A path of length $n$ is defined parametrically by functions $x(t)$ and
11249 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11250 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11251 we shall consider operations that determine special times associated with
11252 given paths: the first time that a path travels in a given direction, and
11253 a pair of times at which two paths cross each other.
11254
11255 @ Let's start with the easier task. The function |find_direction_time| is
11256 given a direction |(x,y)| and a path starting at~|h|. If the path never
11257 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11258 it will be nonnegative.
11259
11260 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11261 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11262 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11263 assumed to match any given direction at time~|t|.
11264
11265 The routine solves this problem in nondegenerate cases by rotating the path
11266 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11267 to find when a given path first travels ``due east.''
11268
11269 @c 
11270 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11271   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11272   pointer p,q; /* for list traversal */
11273   scaled n; /* the direction time at knot |p| */
11274   scaled tt; /* the direction time within a cubic */
11275   @<Other local variables for |find_direction_time|@>;
11276   @<Normalize the given direction for better accuracy;
11277     but |return| with zero result if it's zero@>;
11278   n=0; p=h; phi=0;
11279   while (1) { 
11280     if ( right_type(p)==mp_endpoint ) break;
11281     q=link(p);
11282     @<Rotate the cubic between |p| and |q|; then
11283       |goto found| if the rotated cubic travels due east at some time |tt|;
11284       but |break| if an entire cyclic path has been traversed@>;
11285     p=q; n=n+unity;
11286   }
11287   return (-unity);
11288 FOUND: 
11289   return (n+tt);
11290 }
11291
11292 @ @<Normalize the given direction for better accuracy...@>=
11293 if ( abs(x)<abs(y) ) { 
11294   x=mp_make_fraction(mp, x,abs(y));
11295   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11296 } else if ( x==0 ) { 
11297   return 0;
11298 } else  { 
11299   y=mp_make_fraction(mp, y,abs(x));
11300   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11301 }
11302
11303 @ Since we're interested in the tangent directions, we work with the
11304 derivative $${\textstyle1\over3}B'(x_0,x_1,x_2,x_3;t)=
11305 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11306 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11307 in order to achieve better accuracy.
11308
11309 The given path may turn abruptly at a knot, and it might pass the critical
11310 tangent direction at such a time. Therefore we remember the direction |phi|
11311 in which the previous rotated cubic was traveling. (The value of |phi| will be
11312 undefined on the first cubic, i.e., when |n=0|.)
11313
11314 @<Rotate the cubic between |p| and |q|; then...@>=
11315 tt=0;
11316 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11317   points of the rotated derivatives@>;
11318 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11319 if ( n>0 ) { 
11320   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11321   if ( p==h ) break;
11322   };
11323 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11324 @<Exit to |found| if the curve whose derivatives are specified by
11325   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11326
11327 @ @<Other local variables for |find_direction_time|@>=
11328 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11329 angle theta,phi; /* angles of exit and entry at a knot */
11330 fraction t; /* temp storage */
11331
11332 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11333 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11334 x3=x_coord(q)-left_x(q);
11335 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11336 y3=y_coord(q)-left_y(q);
11337 max=abs(x1);
11338 if ( abs(x2)>max ) max=abs(x2);
11339 if ( abs(x3)>max ) max=abs(x3);
11340 if ( abs(y1)>max ) max=abs(y1);
11341 if ( abs(y2)>max ) max=abs(y2);
11342 if ( abs(y3)>max ) max=abs(y3);
11343 if ( max==0 ) goto FOUND;
11344 while ( max<fraction_half ){ 
11345   max+=max; x1+=x1; x2+=x2; x3+=x3;
11346   y1+=y1; y2+=y2; y3+=y3;
11347 }
11348 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11349 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11350 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11351 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11352 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11353 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11354
11355 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11356 theta=mp_n_arg(mp, x1,y1);
11357 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11358 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11359
11360 @ In this step we want to use the |crossing_point| routine to find the
11361 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11362 Several complications arise: If the quadratic equation has a double root,
11363 the curve never crosses zero, and |crossing_point| will find nothing;
11364 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11365 equation has simple roots, or only one root, we may have to negate it
11366 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11367 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11368 identically zero.
11369
11370 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11371 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11372 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11373   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11374     either |goto found| or |goto done|@>;
11375 }
11376 if ( y1<=0 ) {
11377   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11378   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11379 }
11380 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11381   $B(x_1,x_2,x_3;t)\ge0$@>;
11382 DONE:
11383
11384 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11385 two roots, because we know that it isn't identically zero.
11386
11387 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11388 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11389 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11390 subject to rounding errors. Yet this code optimistically tries to
11391 do the right thing.
11392
11393 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11394
11395 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11396 t=mp_crossing_point(mp, y1,y2,y3);
11397 if ( t>fraction_one ) goto DONE;
11398 y2=t_of_the_way(y2,y3);
11399 x1=t_of_the_way(x1,x2);
11400 x2=t_of_the_way(x2,x3);
11401 x1=t_of_the_way(x1,x2);
11402 if ( x1>=0 ) we_found_it;
11403 if ( y2>0 ) y2=0;
11404 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11405 if ( t>fraction_one ) goto DONE;
11406 x1=t_of_the_way(x1,x2);
11407 x2=t_of_the_way(x2,x3);
11408 if ( t_of_the_way(x1,x2)>=0 ) { 
11409   t=t_of_the_way(tt,fraction_one); we_found_it;
11410 }
11411
11412 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11413     either |goto found| or |goto done|@>=
11414
11415   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11416     t=mp_make_fraction(mp, y1,y1-y2);
11417     x1=t_of_the_way(x1,x2);
11418     x2=t_of_the_way(x2,x3);
11419     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11420   } else if ( y3==0 ) {
11421     if ( y1==0 ) {
11422       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11423     } else if ( x3>=0 ) {
11424       tt=unity; goto FOUND;
11425     }
11426   }
11427   goto DONE;
11428 }
11429
11430 @ At this point we know that the derivative of |y(t)| is identically zero,
11431 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11432 traveling east.
11433
11434 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11435
11436   t=mp_crossing_point(mp, -x1,-x2,-x3);
11437   if ( t<=fraction_one ) we_found_it;
11438   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11439     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11440   }
11441 }
11442
11443 @ The intersection of two cubics can be found by an interesting variant
11444 of the general bisection scheme described in the introduction to
11445 |crossing_point|.\
11446 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)$,
11447 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11448 if an intersection exists. First we find the smallest rectangle that
11449 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11450 the smallest rectangle that encloses
11451 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11452 But if the rectangles do overlap, we bisect the intervals, getting
11453 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11454 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11455 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11456 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11457 levels of bisection we will have determined the intersection times $t_1$
11458 and~$t_2$ to $l$~bits of accuracy.
11459
11460 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11461 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11462 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11463 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11464 to determine when the enclosing rectangles overlap. Here's why:
11465 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11466 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11467 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11468 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11469 overlap if and only if $u\submin\L x\submax$ and
11470 $x\submin\L u\submax$. Letting
11471 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11472   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11473 we have $u\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11474 reduces to
11475 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11476 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11477 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11478 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11479 because of the overlap condition; i.e., we know that $X\submin$,
11480 $X\submax$, and their relatives are bounded, hence $X\submax-
11481 U\submin$ and $X\submin-U\submax$ are bounded.
11482
11483 @ Incidentally, if the given cubics intersect more than once, the process
11484 just sketched will not necessarily find the lexicographically smallest pair
11485 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11486 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11487 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11488 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11489 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11490 Shuffled order agrees with lexicographic order if all pairs of solutions
11491 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11492 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11493 and the bisection algorithm would be substantially less efficient if it were
11494 constrained by lexicographic order.
11495
11496 For example, suppose that an overlap has been found for $l=3$ and
11497 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11498 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11499 Then there is probably an intersection in one of the subintervals
11500 $(.1011,.011x)$; but lexicographic order would require us to explore
11501 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11502 want to store all of the subdivision data for the second path, so the
11503 subdivisions would have to be regenerated many times. Such inefficiencies
11504 would be associated with every `1' in the binary representation of~$t_1$.
11505
11506 @ The subdivision process introduces rounding errors, hence we need to
11507 make a more liberal test for overlap. It is not hard to show that the
11508 computed values of $U_i$ differ from the truth by at most~$l$, on
11509 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11510 If $\beta$ is an upper bound on the absolute error in the computed
11511 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11512 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11513 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11514
11515 More accuracy is obtained if we try the algorithm first with |tol=0|;
11516 the more liberal tolerance is used only if an exact approach fails.
11517 It is convenient to do this double-take by letting `3' in the preceding
11518 paragraph be a parameter, which is first 0, then 3.
11519
11520 @<Glob...@>=
11521 unsigned int tol_step; /* either 0 or 3, usually */
11522
11523 @ We shall use an explicit stack to implement the recursive bisection
11524 method described above. The |bisect_stack| array will contain numerous 5-word
11525 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11526 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11527
11528 The following macros define the allocation of stack positions to
11529 the quantities needed for bisection-intersection.
11530
11531 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11532 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11533 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11534 @d stack_min(A) mp->bisect_stack[(A)+3]
11535   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11536 @d stack_max(A) mp->bisect_stack[(A)+4]
11537   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11538 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11539 @#
11540 @d u_packet(A) ((A)-5)
11541 @d v_packet(A) ((A)-10)
11542 @d x_packet(A) ((A)-15)
11543 @d y_packet(A) ((A)-20)
11544 @d l_packets (mp->bisect_ptr-int_packets)
11545 @d r_packets mp->bisect_ptr
11546 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11547 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11548 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11549 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11550 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11551 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11552 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11553 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11554 @#
11555 @d u1l stack_1(ul_packet) /* $U'_1$ */
11556 @d u2l stack_2(ul_packet) /* $U'_2$ */
11557 @d u3l stack_3(ul_packet) /* $U'_3$ */
11558 @d v1l stack_1(vl_packet) /* $V'_1$ */
11559 @d v2l stack_2(vl_packet) /* $V'_2$ */
11560 @d v3l stack_3(vl_packet) /* $V'_3$ */
11561 @d x1l stack_1(xl_packet) /* $X'_1$ */
11562 @d x2l stack_2(xl_packet) /* $X'_2$ */
11563 @d x3l stack_3(xl_packet) /* $X'_3$ */
11564 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11565 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11566 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11567 @d u1r stack_1(ur_packet) /* $U''_1$ */
11568 @d u2r stack_2(ur_packet) /* $U''_2$ */
11569 @d u3r stack_3(ur_packet) /* $U''_3$ */
11570 @d v1r stack_1(vr_packet) /* $V''_1$ */
11571 @d v2r stack_2(vr_packet) /* $V''_2$ */
11572 @d v3r stack_3(vr_packet) /* $V''_3$ */
11573 @d x1r stack_1(xr_packet) /* $X''_1$ */
11574 @d x2r stack_2(xr_packet) /* $X''_2$ */
11575 @d x3r stack_3(xr_packet) /* $X''_3$ */
11576 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11577 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11578 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11579 @#
11580 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11581 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11582 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11583 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11584 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11585 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11586
11587 @<Glob...@>=
11588 integer *bisect_stack;
11589 unsigned int bisect_ptr;
11590
11591 @ @<Allocate or initialize ...@>=
11592 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11593
11594 @ @<Dealloc variables@>=
11595 xfree(mp->bisect_stack);
11596
11597 @ @<Check the ``constant''...@>=
11598 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11599
11600 @ Computation of the min and max is a tedious but fairly fast sequence of
11601 instructions; exactly four comparisons are made in each branch.
11602
11603 @d set_min_max(A) 
11604   if ( stack_1((A))<0 ) {
11605     if ( stack_3((A))>=0 ) {
11606       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11607       else stack_min((A))=stack_1((A));
11608       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11609       if ( stack_max((A))<0 ) stack_max((A))=0;
11610     } else { 
11611       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11612       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11613       stack_max((A))=stack_1((A))+stack_2((A));
11614       if ( stack_max((A))<0 ) stack_max((A))=0;
11615     }
11616   } else if ( stack_3((A))<=0 ) {
11617     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11618     else stack_max((A))=stack_1((A));
11619     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11620     if ( stack_min((A))>0 ) stack_min((A))=0;
11621   } else  { 
11622     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11623     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11624     stack_min((A))=stack_1((A))+stack_2((A));
11625     if ( stack_min((A))>0 ) stack_min((A))=0;
11626   }
11627
11628 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11629 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11630 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11631 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11632 plus the |scaled| values of $t_1$ and~$t_2$.
11633
11634 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11635 finds no intersection. The routine gives up and gives an approximate answer
11636 if it has backtracked
11637 more than 5000 times (otherwise there are cases where several minutes
11638 of fruitless computation would be possible).
11639
11640 @d max_patience 5000
11641
11642 @<Glob...@>=
11643 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11644 integer time_to_go; /* this many backtracks before giving up */
11645 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11646
11647 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11648 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11649 and |(pp,link(pp))|, respectively.
11650
11651 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11652   pointer q,qq; /* |link(p)|, |link(pp)| */
11653   mp->time_to_go=max_patience; mp->max_t=2;
11654   @<Initialize for intersections at level zero@>;
11655 CONTINUE:
11656   while (1) { 
11657     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11658     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11659     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11660     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11661     { 
11662       if ( mp->cur_t>=mp->max_t ){ 
11663         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11664            mp->cur_t=halfp(mp->cur_t+1); mp->cur_tt=halfp(mp->cur_tt+1); return;
11665         }
11666         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11667       }
11668       @<Subdivide for a new level of intersection@>;
11669       goto CONTINUE;
11670     }
11671     if ( mp->time_to_go>0 ) {
11672       decr(mp->time_to_go);
11673     } else { 
11674       while ( mp->appr_t<unity ) { 
11675         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11676       }
11677       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11678     }
11679     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11680   }
11681 }
11682
11683 @ The following variables are global, although they are used only by
11684 |cubic_intersection|, because it is necessary on some machines to
11685 split |cubic_intersection| up into two procedures.
11686
11687 @<Glob...@>=
11688 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11689 integer tol; /* bound on the uncertainly in the overlap test */
11690 unsigned int uv;
11691 unsigned int xy; /* pointers to the current packets of interest */
11692 integer three_l; /* |tol_step| times the bisection level */
11693 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11694
11695 @ We shall assume that the coordinates are sufficiently non-extreme that
11696 integer overflow will not occur.
11697
11698 @<Initialize for intersections at level zero@>=
11699 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11700 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11701 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11702 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11703 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11704 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11705 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11706 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11707 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11708 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11709 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11710 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11711
11712 @ @<Subdivide for a new level of intersection@>=
11713 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11714 stack_uv=mp->uv; stack_xy=mp->xy;
11715 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11716 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11717 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11718 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11719 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11720 u3l=half(u2l+u2r); u1r=u3l;
11721 set_min_max(ul_packet); set_min_max(ur_packet);
11722 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11723 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11724 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11725 v3l=half(v2l+v2r); v1r=v3l;
11726 set_min_max(vl_packet); set_min_max(vr_packet);
11727 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11728 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11729 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11730 x3l=half(x2l+x2r); x1r=x3l;
11731 set_min_max(xl_packet); set_min_max(xr_packet);
11732 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11733 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11734 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11735 y3l=half(y2l+y2r); y1r=y3l;
11736 set_min_max(yl_packet); set_min_max(yr_packet);
11737 mp->uv=l_packets; mp->xy=l_packets;
11738 mp->delx+=mp->delx; mp->dely+=mp->dely;
11739 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11740 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11741
11742 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11743 NOT_FOUND: 
11744 if ( odd(mp->cur_tt) ) {
11745   if ( odd(mp->cur_t) ) {
11746      @<Descend to the previous level and |goto not_found|@>;
11747   } else { 
11748     incr(mp->cur_t);
11749     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11750       +stack_3(u_packet(mp->uv));
11751     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11752       +stack_3(v_packet(mp->uv));
11753     mp->uv=mp->uv+int_packets; /* switch from |l_packet| to |r_packet| */
11754     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11755          /* switch from |r_packet| to |l_packet| */
11756     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11757       +stack_3(x_packet(mp->xy));
11758     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11759       +stack_3(y_packet(mp->xy));
11760   }
11761 } else { 
11762   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11763   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11764     -stack_3(x_packet(mp->xy));
11765   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11766     -stack_3(y_packet(mp->xy));
11767   mp->xy=mp->xy+int_packets; /* switch from |l_packet| to |r_packet| */
11768 }
11769
11770 @ @<Descend to the previous level...@>=
11771
11772   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11773   if ( mp->cur_t==0 ) return;
11774   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11775   mp->three_l=mp->three_l-mp->tol_step;
11776   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11777   mp->uv=stack_uv; mp->xy=stack_xy;
11778   goto NOT_FOUND;
11779 }
11780
11781 @ The |path_intersection| procedure is much simpler.
11782 It invokes |cubic_intersection| in lexicographic order until finding a
11783 pair of cubics that intersect. The final intersection times are placed in
11784 |cur_t| and~|cur_tt|.
11785
11786 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11787   pointer p,pp; /* link registers that traverse the given paths */
11788   integer n,nn; /* integer parts of intersection times, minus |unity| */
11789   @<Change one-point paths into dead cycles@>;
11790   mp->tol_step=0;
11791   do {  
11792     n=-unity; p=h;
11793     do {  
11794       if ( right_type(p)!=mp_endpoint ) { 
11795         nn=-unity; pp=hh;
11796         do {  
11797           if ( right_type(pp)!=mp_endpoint )  { 
11798             mp_cubic_intersection(mp, p,pp);
11799             if ( mp->cur_t>0 ) { 
11800               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11801               return;
11802             }
11803           }
11804           nn=nn+unity; pp=link(pp);
11805         } while (pp!=hh);
11806       }
11807       n=n+unity; p=link(p);
11808     } while (p!=h);
11809     mp->tol_step=mp->tol_step+3;
11810   } while (mp->tol_step<=3);
11811   mp->cur_t=-unity; mp->cur_tt=-unity;
11812 }
11813
11814 @ @<Change one-point paths...@>=
11815 if ( right_type(h)==mp_endpoint ) {
11816   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11817   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11818 }
11819 if ( right_type(hh)==mp_endpoint ) {
11820   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11821   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11822 }
11823
11824 @* \[24] Dynamic linear equations.
11825 \MP\ users define variables implicitly by stating equations that should be
11826 satisfied; the computer is supposed to be smart enough to solve those equations.
11827 And indeed, the computer tries valiantly to do so, by distinguishing five
11828 different types of numeric values:
11829
11830 \smallskip\hang
11831 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11832 of the variable whose address is~|p|.
11833
11834 \smallskip\hang
11835 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11836 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11837 as a |scaled| number plus a sum of independent variables with |fraction|
11838 coefficients.
11839
11840 \smallskip\hang
11841 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11842 number'' reflecting the time this variable was first used in an equation;
11843 also |0<=m<64|, and each dependent variable
11844 that refers to this one is actually referring to the future value of
11845 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11846 scaling are sometimes needed to keep the coefficients in dependency lists
11847 from getting too large. The value of~|m| will always be even.)
11848
11849 \smallskip\hang
11850 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11851 equation before, but it has been explicitly declared to be numeric.
11852
11853 \smallskip\hang
11854 |type(p)=undefined| means that variable |p| hasn't appeared before.
11855
11856 \smallskip\noindent
11857 We have actually discussed these five types in the reverse order of their
11858 history during a computation: Once |known|, a variable never again
11859 becomes |dependent|; once |dependent|, it almost never again becomes
11860 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11861 and once |mp_numeric_type|, it never again becomes |undefined| (except
11862 of course when the user specifically decides to scrap the old value
11863 and start again). A backward step may, however, take place: Sometimes
11864 a |dependent| variable becomes |mp_independent| again, when one of the
11865 independent variables it depends on is reverting to |undefined|.
11866
11867
11868 The next patch detects overflow of independent-variable serial
11869 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11870
11871 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11872 @d max_indep_vars 0177777777 /* $2^{25}-1$ */
11873 @d max_serial_no 017777777700 /* |max_indep_vars*s_scale| */
11874 @d new_indep(A)  /* create a new independent variable */
11875   { if ( mp->serial_no==max_serial_no )
11876     mp_fatal_error(mp, "variable instance identifiers exhausted");
11877   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11878   value((A))=mp->serial_no;
11879   }
11880
11881 @<Glob...@>=
11882 integer serial_no; /* the most recent serial number, times |s_scale| */
11883
11884 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11885
11886 @ But how are dependency lists represented? It's simple: The linear combination
11887 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11888 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11889 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11890 of $\alpha_1$; and |link(p)| points to the dependency list
11891 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11892 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11893 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11894 they appear in decreasing order of their |value| fields (i.e., of
11895 their serial numbers). \ (It is convenient to use decreasing order,
11896 since |value(null)=0|. If the independent variables were not sorted by
11897 serial number but by some other criterion, such as their location in |mem|,
11898 the equation-solving mechanism would be too system-dependent, because
11899 the ordering can affect the computed results.)
11900
11901 The |link| field in the node that contains the constant term $\beta$ is
11902 called the {\sl final link\/} of the dependency list. \MP\ maintains
11903 a doubly-linked master list of all dependency lists, in terms of a permanently
11904 allocated node
11905 in |mem| called |dep_head|. If there are no dependencies, we have
11906 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11907 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11908 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11909 points to its dependency list. If the final link of that dependency list
11910 occurs in location~|q|, then |link(q)| points to the next dependent
11911 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11912
11913 @d dep_list(A) link(value_loc((A)))
11914   /* half of the |value| field in a |dependent| variable */
11915 @d prev_dep(A) info(value_loc((A)))
11916   /* the other half; makes a doubly linked list */
11917 @d dep_node_size 2 /* the number of words per dependency node */
11918
11919 @<Initialize table entries...@>= mp->serial_no=0;
11920 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11921 info(dep_head)=null; dep_list(dep_head)=null;
11922
11923 @ Actually the description above contains a little white lie. There's
11924 another kind of variable called |mp_proto_dependent|, which is
11925 just like a |dependent| one except that the $\alpha$ coefficients
11926 in its dependency list are |scaled| instead of being fractions.
11927 Proto-dependency lists are mixed with dependency lists in the
11928 nodes reachable from |dep_head|.
11929
11930 @ Here is a procedure that prints a dependency list in symbolic form.
11931 The second parameter should be either |dependent| or |mp_proto_dependent|,
11932 to indicate the scaling of the coefficients.
11933
11934 @<Declare subroutines for printing expressions@>=
11935 void mp_print_dependency (MP mp,pointer p, small_number t) {
11936   integer v; /* a coefficient */
11937   pointer pp,q; /* for list manipulation */
11938   pp=p;
11939   while (1) { 
11940     v=abs(value(p)); q=info(p);
11941     if ( q==null ) { /* the constant term */
11942       if ( (v!=0)||(p==pp) ) {
11943          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11944          mp_print_scaled(mp, value(p));
11945       }
11946       return;
11947     }
11948     @<Print the coefficient, unless it's $\pm1.0$@>;
11949     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11950 @:this can't happen dep}{\quad dep@>
11951     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11952     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11953     p=link(p);
11954   }
11955 }
11956
11957 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11958 if ( value(p)<0 ) mp_print_char(mp, '-');
11959 else if ( p!=pp ) mp_print_char(mp, '+');
11960 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11961 if ( v!=unity ) mp_print_scaled(mp, v)
11962
11963 @ The maximum absolute value of a coefficient in a given dependency list
11964 is returned by the following simple function.
11965
11966 @c fraction mp_max_coef (MP mp,pointer p) {
11967   fraction x; /* the maximum so far */
11968   x=0;
11969   while ( info(p)!=null ) {
11970     if ( abs(value(p))>x ) x=abs(value(p));
11971     p=link(p);
11972   }
11973   return x;
11974 }
11975
11976 @ One of the main operations needed on dependency lists is to add a multiple
11977 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11978 to dependency lists and |f| is a fraction.
11979
11980 If the coefficient of any independent variable becomes |coef_bound| or
11981 more, in absolute value, this procedure changes the type of that variable
11982 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11983 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
11984 $\mu^2+\mu<8$; this means that the numbers we deal with won't
11985 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
11986 2.3723$, the safer value 7/3 is taken as the threshold.)
11987
11988 The changes mentioned in the preceding paragraph are actually done only if
11989 the global variable |watch_coefs| is |true|. But it usually is; in fact,
11990 it is |false| only when \MP\ is making a dependency list that will soon
11991 be equated to zero.
11992
11993 Several procedures that act on dependency lists, including |p_plus_fq|,
11994 set the global variable |dep_final| to the final (constant term) node of
11995 the dependency list that they produce.
11996
11997 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
11998 @d independent_needing_fix 0
11999
12000 @<Glob...@>=
12001 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12002 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12003 pointer dep_final; /* location of the constant term and final link */
12004
12005 @ @<Set init...@>=
12006 mp->fix_needed=false; mp->watch_coefs=true;
12007
12008 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12009 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12010 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12011 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12012
12013 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12014
12015 The final link of the dependency list or proto-dependency list returned
12016 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12017 constant term of the result will be located in the same |mem| location
12018 as the original constant term of~|p|.
12019
12020 Coefficients of the result are assumed to be zero if they are less than
12021 a certain threshold. This compensates for inevitable rounding errors,
12022 and tends to make more variables `|known|'. The threshold is approximately
12023 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12024 proto-dependencies.
12025
12026 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12027 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12028 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12029 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12030
12031 @<Declare basic dependency-list subroutines@>=
12032 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12033                       pointer q, small_number t, small_number tt) ;
12034
12035 @ @c
12036 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12037                       pointer q, small_number t, small_number tt) {
12038   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12039   pointer r,s; /* for list manipulation */
12040   integer mp_threshold; /* defines a neighborhood of zero */
12041   integer v; /* temporary register */
12042   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12043   else mp_threshold=scaled_threshold;
12044   r=temp_head; pp=info(p); qq=info(q);
12045   while (1) {
12046     if ( pp==qq ) {
12047       if ( pp==null ) {
12048        break;
12049       } else {
12050         @<Contribute a term from |p|, plus |f| times the
12051           corresponding term from |q|@>
12052       }
12053     } else if ( value(pp)<value(qq) ) {
12054       @<Contribute a term from |q|, multiplied by~|f|@>
12055     } else { 
12056      link(r)=p; r=p; p=link(p); pp=info(p);
12057     }
12058   }
12059   if ( t==mp_dependent )
12060     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12061   else  
12062     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12063   link(r)=p; mp->dep_final=p; 
12064   return link(temp_head);
12065 }
12066
12067 @ @<Contribute a term from |p|, plus |f|...@>=
12068
12069   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12070   else v=value(p)+mp_take_scaled(mp, f,value(q));
12071   value(p)=v; s=p; p=link(p);
12072   if ( abs(v)<mp_threshold ) {
12073     mp_free_node(mp, s,dep_node_size);
12074   } else {
12075     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12076       type(qq)=independent_needing_fix; mp->fix_needed=true;
12077     }
12078     link(r)=s; r=s;
12079   };
12080   pp=info(p); q=link(q); qq=info(q);
12081 }
12082
12083 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12084
12085   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12086   else v=mp_take_scaled(mp, f,value(q));
12087   if ( abs(v)>halfp(mp_threshold) ) { 
12088     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12089     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12090       type(qq)=independent_needing_fix; mp->fix_needed=true;
12091     }
12092     link(r)=s; r=s;
12093   }
12094   q=link(q); qq=info(q);
12095 }
12096
12097 @ It is convenient to have another subroutine for the special case
12098 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12099 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12100
12101 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12102   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12103   pointer r,s; /* for list manipulation */
12104   integer mp_threshold; /* defines a neighborhood of zero */
12105   integer v; /* temporary register */
12106   if ( t==mp_dependent ) mp_threshold=fraction_threshold;
12107   else mp_threshold=scaled_threshold;
12108   r=temp_head; pp=info(p); qq=info(q);
12109   while (1) {
12110     if ( pp==qq ) {
12111       if ( pp==null ) {
12112         break;
12113       } else {
12114         @<Contribute a term from |p|, plus the
12115           corresponding term from |q|@>
12116       }
12117     } else if ( value(pp)<value(qq) ) {
12118       s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12119       q=link(q); qq=info(q); link(r)=s; r=s;
12120     } else { 
12121       link(r)=p; r=p; p=link(p); pp=info(p);
12122     }
12123   }
12124   value(p)=mp_slow_add(mp, value(p),value(q));
12125   link(r)=p; mp->dep_final=p; 
12126   return link(temp_head);
12127 }
12128
12129 @ @<Contribute a term from |p|, plus the...@>=
12130
12131   v=value(p)+value(q);
12132   value(p)=v; s=p; p=link(p); pp=info(p);
12133   if ( abs(v)<mp_threshold ) {
12134     mp_free_node(mp, s,dep_node_size);
12135   } else { 
12136     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12137       type(qq)=independent_needing_fix; mp->fix_needed=true;
12138     }
12139     link(r)=s; r=s;
12140   }
12141   q=link(q); qq=info(q);
12142 }
12143
12144 @ A somewhat simpler routine will multiply a dependency list
12145 by a given constant~|v|. The constant is either a |fraction| less than
12146 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12147 convert a dependency list to a proto-dependency list.
12148 Parameters |t0| and |t1| are the list types before and after;
12149 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12150 and |v_is_scaled=true|.
12151
12152 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12153                          small_number t1, boolean v_is_scaled) {
12154   pointer r,s; /* for list manipulation */
12155   integer w; /* tentative coefficient */
12156   integer mp_threshold;
12157   boolean scaling_down;
12158   if ( t0!=t1 ) scaling_down=true; else scaling_down=! v_is_scaled;
12159   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12160   else mp_threshold=half_scaled_threshold;
12161   r=temp_head;
12162   while ( info(p)!=null ) {    
12163     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12164     else w=mp_take_scaled(mp, v,value(p));
12165     if ( abs(w)<=mp_threshold ) { 
12166       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12167     } else {
12168       if ( abs(w)>=coef_bound ) { 
12169         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12170       }
12171       link(r)=p; r=p; value(p)=w; p=link(p);
12172     }
12173   }
12174   link(r)=p;
12175   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12176   else value(p)=mp_take_fraction(mp, value(p),v);
12177   return link(temp_head);
12178 };
12179
12180 @ Similarly, we sometimes need to divide a dependency list
12181 by a given |scaled| constant.
12182
12183 @<Declare basic dependency-list subroutines@>=
12184 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12185   t0, small_number t1) ;
12186
12187 @ @c
12188 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12189   t0, small_number t1) {
12190   pointer r,s; /* for list manipulation */
12191   integer w; /* tentative coefficient */
12192   integer mp_threshold;
12193   boolean scaling_down;
12194   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12195   if ( t1==mp_dependent ) mp_threshold=half_fraction_threshold;
12196   else mp_threshold=half_scaled_threshold;
12197   r=temp_head;
12198   while ( info( p)!=null ) {
12199     if ( scaling_down ) {
12200       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12201       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12202     } else {
12203       w=mp_make_scaled(mp, value(p),v);
12204     }
12205     if ( abs(w)<=mp_threshold ) {
12206       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12207     } else { 
12208       if ( abs(w)>=coef_bound ) {
12209          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12210       }
12211       link(r)=p; r=p; value(p)=w; p=link(p);
12212     }
12213   }
12214   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12215   return link(temp_head);
12216 };
12217
12218 @ Here's another utility routine for dependency lists. When an independent
12219 variable becomes dependent, we want to remove it from all existing
12220 dependencies. The |p_with_x_becoming_q| function computes the
12221 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12222
12223 This procedure has basically the same calling conventions as |p_plus_fq|:
12224 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12225 final link are inherited from~|p|; and the fourth parameter tells whether
12226 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12227 is not altered if |x| does not occur in list~|p|.
12228
12229 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12230            pointer x, pointer q, small_number t) {
12231   pointer r,s; /* for list manipulation */
12232   integer v; /* coefficient of |x| */
12233   integer sx; /* serial number of |x| */
12234   s=p; r=temp_head; sx=value(x);
12235   while ( value(info(s))>sx ) { r=s; s=link(s); };
12236   if ( info(s)!=x ) { 
12237     return p;
12238   } else { 
12239     link(temp_head)=p; link(r)=link(s); v=value(s);
12240     mp_free_node(mp, s,dep_node_size);
12241     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12242   }
12243 }
12244
12245 @ Here's a simple procedure that reports an error when a variable
12246 has just received a known value that's out of the required range.
12247
12248 @<Declare basic dependency-list subroutines@>=
12249 void mp_val_too_big (MP mp,scaled x) ;
12250
12251 @ @c void mp_val_too_big (MP mp,scaled x) { 
12252   if ( mp->internal[mp_warning_check]>0 ) { 
12253     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12254 @.Value is too large@>
12255     help4("The equation I just processed has given some variable")
12256       ("a value of 4096 or more. Continue and I'll try to cope")
12257       ("with that big value; but it might be dangerous.")
12258       ("(Set warningcheck:=0 to suppress this message.)");
12259     mp_error(mp);
12260   }
12261 }
12262
12263 @ When a dependent variable becomes known, the following routine
12264 removes its dependency list. Here |p| points to the variable, and
12265 |q| points to the dependency list (which is one node long).
12266
12267 @<Declare basic dependency-list subroutines@>=
12268 void mp_make_known (MP mp,pointer p, pointer q) ;
12269
12270 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12271   int t; /* the previous type */
12272   prev_dep(link(q))=prev_dep(p);
12273   link(prev_dep(p))=link(q); t=type(p);
12274   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12275   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12276   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12277     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12278 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12279     mp_print_variable_name(mp, p); 
12280     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12281     mp_end_diagnostic(mp, false);
12282   }
12283   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12284     mp->cur_type=mp_known; mp->cur_exp=value(p);
12285     mp_free_node(mp, p,value_node_size);
12286   }
12287 }
12288
12289 @ The |fix_dependencies| routine is called into action when |fix_needed|
12290 has been triggered. The program keeps a list~|s| of independent variables
12291 whose coefficients must be divided by~4.
12292
12293 In unusual cases, this fixup process might reduce one or more coefficients
12294 to zero, so that a variable will become known more or less by default.
12295
12296 @<Declare basic dependency-list subroutines@>=
12297 void mp_fix_dependencies (MP mp);
12298
12299 @ @c void mp_fix_dependencies (MP mp) {
12300   pointer p,q,r,s,t; /* list manipulation registers */
12301   pointer x; /* an independent variable */
12302   r=link(dep_head); s=null;
12303   while ( r!=dep_head ){ 
12304     t=r;
12305     @<Run through the dependency list for variable |t|, fixing
12306       all nodes, and ending with final link~|q|@>;
12307     r=link(q);
12308     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12309   }
12310   while ( s!=null ) { 
12311     p=link(s); x=info(s); free_avail(s); s=p;
12312     type(x)=mp_independent; value(x)=value(x)+2;
12313   }
12314   mp->fix_needed=false;
12315 }
12316
12317 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12318
12319 @<Run through the dependency list for variable |t|...@>=
12320 r=value_loc(t); /* |link(r)=dep_list(t)| */
12321 while (1) { 
12322   q=link(r); x=info(q);
12323   if ( x==null ) break;
12324   if ( type(x)<=independent_being_fixed ) {
12325     if ( type(x)<independent_being_fixed ) {
12326       p=mp_get_avail(mp); link(p)=s; s=p;
12327       info(s)=x; type(x)=independent_being_fixed;
12328     }
12329     value(q)=value(q) / 4;
12330     if ( value(q)==0 ) {
12331       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12332     }
12333   }
12334   r=q;
12335 }
12336
12337
12338 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12339 linking it into the list of all known dependencies. We assume that
12340 |dep_final| points to the final node of list~|p|.
12341
12342 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12343   pointer r; /* what used to be the first dependency */
12344   dep_list(q)=p; prev_dep(q)=dep_head;
12345   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12346   link(dep_head)=q;
12347 }
12348
12349 @ Here is one of the ways a dependency list gets started.
12350 The |const_dependency| routine produces a list that has nothing but
12351 a constant term.
12352
12353 @c pointer mp_const_dependency (MP mp, scaled v) {
12354   mp->dep_final=mp_get_node(mp, dep_node_size);
12355   value(mp->dep_final)=v; info(mp->dep_final)=null;
12356   return mp->dep_final;
12357 }
12358
12359 @ And here's a more interesting way to start a dependency list from scratch:
12360 The parameter to |single_dependency| is the location of an
12361 independent variable~|x|, and the result is the simple dependency list
12362 `|x+0|'.
12363
12364 In the unlikely event that the given independent variable has been doubled so
12365 often that we can't refer to it with a nonzero coefficient,
12366 |single_dependency| returns the simple list `0'.  This case can be
12367 recognized by testing that the returned list pointer is equal to
12368 |dep_final|.
12369
12370 @c pointer mp_single_dependency (MP mp,pointer p) {
12371   pointer q; /* the new dependency list */
12372   integer m; /* the number of doublings */
12373   m=value(p) % s_scale;
12374   if ( m>28 ) {
12375     return mp_const_dependency(mp, 0);
12376   } else { 
12377     q=mp_get_node(mp, dep_node_size);
12378     value(q)=two_to_the(28-m); info(q)=p;
12379     link(q)=mp_const_dependency(mp, 0);
12380     return q;
12381   }
12382 }
12383
12384 @ We sometimes need to make an exact copy of a dependency list.
12385
12386 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12387   pointer q; /* the new dependency list */
12388   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12389   while (1) { 
12390     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12391     if ( info(mp->dep_final)==null ) break;
12392     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12393     mp->dep_final=link(mp->dep_final); p=link(p);
12394   }
12395   return q;
12396 }
12397
12398 @ But how do variables normally become known? Ah, now we get to the heart of the
12399 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12400 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12401 appears. It equates this list to zero, by choosing an independent variable
12402 with the largest coefficient and making it dependent on the others. The
12403 newly dependent variable is eliminated from all current dependencies,
12404 thereby possibly making other dependent variables known.
12405
12406 The given list |p| is, of course, totally destroyed by all this processing.
12407
12408 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12409   pointer q,r,s; /* for link manipulation */
12410   pointer x; /* the variable that loses its independence */
12411   integer n; /* the number of times |x| had been halved */
12412   integer v; /* the coefficient of |x| in list |p| */
12413   pointer prev_r; /* lags one step behind |r| */
12414   pointer final_node; /* the constant term of the new dependency list */
12415   integer w; /* a tentative coefficient */
12416    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12417   x=info(q); n=value(x) % s_scale;
12418   @<Divide list |p| by |-v|, removing node |q|@>;
12419   if ( mp->internal[mp_tracing_equations]>0 ) {
12420     @<Display the new dependency@>;
12421   }
12422   @<Simplify all existing dependencies by substituting for |x|@>;
12423   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12424   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12425 }
12426
12427 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12428 q=p; r=link(p); v=value(q);
12429 while ( info(r)!=null ) { 
12430   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12431   r=link(r);
12432 }
12433
12434 @ Here we want to change the coefficients from |scaled| to |fraction|,
12435 except in the constant term. In the common case of a trivial equation
12436 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12437
12438 @<Divide list |p| by |-v|, removing node |q|@>=
12439 s=temp_head; link(s)=p; r=p;
12440 do { 
12441   if ( r==q ) {
12442     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12443   } else  { 
12444     w=mp_make_fraction(mp, value(r),v);
12445     if ( abs(w)<=half_fraction_threshold ) {
12446       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12447     } else { 
12448       value(r)=-w; s=r;
12449     }
12450   }
12451   r=link(s);
12452 } while (info(r)!=null);
12453 if ( t==mp_proto_dependent ) {
12454   value(r)=-mp_make_scaled(mp, value(r),v);
12455 } else if ( v!=-fraction_one ) {
12456   value(r)=-mp_make_fraction(mp, value(r),v);
12457 }
12458 final_node=r; p=link(temp_head)
12459
12460 @ @<Display the new dependency@>=
12461 if ( mp_interesting(mp, x) ) {
12462   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12463   mp_print_variable_name(mp, x);
12464 @:]]]\#\#_}{\.{\#\#}@>
12465   w=n;
12466   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12467   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12468   mp_end_diagnostic(mp, false);
12469 }
12470
12471 @ @<Simplify all existing dependencies by substituting for |x|@>=
12472 prev_r=dep_head; r=link(dep_head);
12473 while ( r!=dep_head ) {
12474   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12475   if ( info(q)==null ) {
12476     mp_make_known(mp, r,q);
12477   } else { 
12478     dep_list(r)=q;
12479     do {  q=link(q); } while (info(q)!=null);
12480     prev_r=q;
12481   }
12482   r=link(prev_r);
12483 }
12484
12485 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12486 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12487 if ( info(p)==null ) {
12488   type(x)=mp_known;
12489   value(x)=value(p);
12490   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12491   mp_free_node(mp, p,dep_node_size);
12492   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12493     mp->cur_exp=value(x); mp->cur_type=mp_known;
12494     mp_free_node(mp, x,value_node_size);
12495   }
12496 } else { 
12497   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12498   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12499 }
12500
12501 @ @<Divide list |p| by $2^n$@>=
12502
12503   s=temp_head; link(temp_head)=p; r=p;
12504   do {  
12505     if ( n>30 ) w=0;
12506     else w=value(r) / two_to_the(n);
12507     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12508       link(s)=link(r);
12509       mp_free_node(mp, r,dep_node_size);
12510     } else { 
12511       value(r)=w; s=r;
12512     }
12513     r=link(s);
12514   } while (info(s)!=null);
12515   p=link(temp_head);
12516 }
12517
12518 @ The |check_mem| procedure, which is used only when \MP\ is being
12519 debugged, makes sure that the current dependency lists are well formed.
12520
12521 @<Check the list of linear dependencies@>=
12522 q=dep_head; p=link(q);
12523 while ( p!=dep_head ) {
12524   if ( prev_dep(p)!=q ) {
12525     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12526 @.Bad PREVDEP...@>
12527   }
12528   p=dep_list(p);
12529   while (1) {
12530     r=info(p); q=p; p=link(q);
12531     if ( r==null ) break;
12532     if ( value(info(p))>=value(r) ) {
12533       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12534 @.Out of order...@>
12535     }
12536   }
12537 }
12538
12539 @* \[25] Dynamic nonlinear equations.
12540 Variables of numeric type are maintained by the general scheme of
12541 independent, dependent, and known values that we have just studied;
12542 and the components of pair and transform variables are handled in the
12543 same way. But \MP\ also has five other types of values: \&{boolean},
12544 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12545
12546 Equations are allowed between nonlinear quantities, but only in a
12547 simple form. Two variables that haven't yet been assigned values are
12548 either equal to each other, or they're not.
12549
12550 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12551 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12552 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12553 |null| (which means that no other variables are equivalent to this one), or
12554 it points to another variable of the same undefined type. The pointers in the
12555 latter case form a cycle of nodes, which we shall call a ``ring.''
12556 Rings of undefined variables may include capsules, which arise as
12557 intermediate results within expressions or as \&{expr} parameters to macros.
12558
12559 When one member of a ring receives a value, the same value is given to
12560 all the other members. In the case of paths and pictures, this implies
12561 making separate copies of a potentially large data structure; users should
12562 restrain their enthusiasm for such generality, unless they have lots and
12563 lots of memory space.
12564
12565 @ The following procedure is called when a capsule node is being
12566 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12567
12568 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12569   pointer q; /* the new capsule node */
12570   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12571   type(q)=type(p);
12572   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12573   value(p)=q;
12574   return q;
12575 }
12576
12577 @ Conversely, we might delete a capsule or a variable before it becomes known.
12578 The following procedure simply detaches a quantity from its ring,
12579 without recycling the storage.
12580
12581 @<Declare the recycling subroutines@>=
12582 void mp_ring_delete (MP mp,pointer p) {
12583   pointer q; 
12584   q=value(p);
12585   if ( q!=null ) if ( q!=p ){ 
12586     while ( value(q)!=p ) q=value(q);
12587     value(q)=value(p);
12588   }
12589 }
12590
12591 @ Eventually there might be an equation that assigns values to all of the
12592 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12593 propagation of values.
12594
12595 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12596 value, it will soon be recycled.
12597
12598 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12599   small_number t; /* the type of ring |p| */
12600   pointer q,r; /* link manipulation registers */
12601   t=type(p)-unknown_tag; q=value(p);
12602   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12603   do {  
12604     r=value(q); type(q)=t;
12605     switch (t) {
12606     case mp_boolean_type: value(q)=v; break;
12607     case mp_string_type: value(q)=v; add_str_ref(v); break;
12608     case mp_pen_type: value(q)=copy_pen(v); break;
12609     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12610     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12611     } /* there ain't no more cases */
12612     q=r;
12613   } while (q!=p);
12614 }
12615
12616 @ If two members of rings are equated, and if they have the same type,
12617 the |ring_merge| procedure is called on to make them equivalent.
12618
12619 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12620   pointer r; /* traverses one list */
12621   r=value(p);
12622   while ( r!=p ) {
12623     if ( r==q ) {
12624       @<Exclaim about a redundant equation@>;
12625       return;
12626     };
12627     r=value(r);
12628   }
12629   r=value(p); value(p)=value(q); value(q)=r;
12630 }
12631
12632 @ @<Exclaim about a redundant equation@>=
12633
12634   print_err("Redundant equation");
12635 @.Redundant equation@>
12636   help2("I already knew that this equation was true.")
12637    ("But perhaps no harm has been done; let's continue.");
12638   mp_put_get_error(mp);
12639 }
12640
12641 @* \[26] Introduction to the syntactic routines.
12642 Let's pause a moment now and try to look at the Big Picture.
12643 The \MP\ program consists of three main parts: syntactic routines,
12644 semantic routines, and output routines. The chief purpose of the
12645 syntactic routines is to deliver the user's input to the semantic routines,
12646 while parsing expressions and locating operators and operands. The
12647 semantic routines act as an interpreter responding to these operators,
12648 which may be regarded as commands. And the output routines are
12649 periodically called on to produce compact font descriptions that can be
12650 used for typesetting or for making interim proof drawings. We have
12651 discussed the basic data structures and many of the details of semantic
12652 operations, so we are good and ready to plunge into the part of \MP\ that
12653 actually controls the activities.
12654
12655 Our current goal is to come to grips with the |get_next| procedure,
12656 which is the keystone of \MP's input mechanism. Each call of |get_next|
12657 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12658 representing the next input token.
12659 $$\vbox{\halign{#\hfil\cr
12660   \hbox{|cur_cmd| denotes a command code from the long list of codes
12661    given earlier;}\cr
12662   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12663   \hbox{|cur_sym| is the hash address of the symbolic token that was
12664    just scanned,}\cr
12665   \hbox{\qquad or zero in the case of a numeric or string
12666    or capsule token.}\cr}}$$
12667 Underlying this external behavior of |get_next| is all the machinery
12668 necessary to convert from character files to tokens. At a given time we
12669 may be only partially finished with the reading of several files (for
12670 which \&{input} was specified), and partially finished with the expansion
12671 of some user-defined macros and/or some macro parameters, and partially
12672 finished reading some text that the user has inserted online,
12673 and so on. When reading a character file, the characters must be
12674 converted to tokens; comments and blank spaces must
12675 be removed, numeric and string tokens must be evaluated.
12676
12677 To handle these situations, which might all be present simultaneously,
12678 \MP\ uses various stacks that hold information about the incomplete
12679 activities, and there is a finite state control for each level of the
12680 input mechanism. These stacks record the current state of an implicitly
12681 recursive process, but the |get_next| procedure is not recursive.
12682
12683 @<Glob...@>=
12684 eight_bits cur_cmd; /* current command set by |get_next| */
12685 integer cur_mod; /* operand of current command */
12686 halfword cur_sym; /* hash address of current symbol */
12687
12688 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12689 command code and its modifier.
12690 It consists of a rather tedious sequence of print
12691 commands, and most of it is essentially an inverse to the |primitive|
12692 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12693 all of this procedure appears elsewhere in the program, together with the
12694 corresponding |primitive| calls.
12695
12696 @<Declare the procedure called |print_cmd_mod|@>=
12697 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12698  switch (c) {
12699   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12700   default: mp_print(mp, "[unknown command code!]"); break;
12701   }
12702 }
12703
12704 @ Here is a procedure that displays a given command in braces, in the
12705 user's transcript file.
12706
12707 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12708
12709 @c 
12710 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12711   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12712   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12713   mp_end_diagnostic(mp, false);
12714 }
12715
12716 @* \[27] Input stacks and states.
12717 The state of \MP's input mechanism appears in the input stack, whose
12718 entries are records with five fields, called |index|, |start|, |loc|,
12719 |limit|, and |name|. The top element of this stack is maintained in a
12720 global variable for which no subscripting needs to be done; the other
12721 elements of the stack appear in an array. Hence the stack is declared thus:
12722
12723 @<Types...@>=
12724 typedef struct {
12725   quarterword index_field;
12726   halfword start_field, loc_field, limit_field, name_field;
12727 } in_state_record;
12728
12729 @ @<Glob...@>=
12730 in_state_record *input_stack;
12731 integer input_ptr; /* first unused location of |input_stack| */
12732 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12733 in_state_record cur_input; /* the ``top'' input state */
12734 int stack_size; /* maximum number of simultaneous input sources */
12735
12736 @ @<Allocate or initialize ...@>=
12737 mp->stack_size = 300;
12738 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12739
12740 @ @<Dealloc variables@>=
12741 xfree(mp->input_stack);
12742
12743 @ We've already defined the special variable |loc==cur_input.loc_field|
12744 in our discussion of basic input-output routines. The other components of
12745 |cur_input| are defined in the same way:
12746
12747 @d index mp->cur_input.index_field /* reference for buffer information */
12748 @d start mp->cur_input.start_field /* starting position in |buffer| */
12749 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12750 @d name mp->cur_input.name_field /* name of the current file */
12751
12752 @ Let's look more closely now at the five control variables
12753 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12754 assuming that \MP\ is reading a line of characters that have been input
12755 from some file or from the user's terminal. There is an array called
12756 |buffer| that acts as a stack of all lines of characters that are
12757 currently being read from files, including all lines on subsidiary
12758 levels of the input stack that are not yet completed. \MP\ will return to
12759 the other lines when it is finished with the present input file.
12760
12761 (Incidentally, on a machine with byte-oriented addressing, it would be
12762 appropriate to combine |buffer| with the |str_pool| array,
12763 letting the buffer entries grow downward from the top of the string pool
12764 and checking that these two tables don't bump into each other.)
12765
12766 The line we are currently working on begins in position |start| of the
12767 buffer; the next character we are about to read is |buffer[loc]|; and
12768 |limit| is the location of the last character present. We always have
12769 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12770 that the end of a line is easily sensed.
12771
12772 The |name| variable is a string number that designates the name of
12773 the current file, if we are reading an ordinary text file.  Special codes
12774 |is_term..max_spec_src| indicate other sources of input text.
12775
12776 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12777 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12778 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12779 @d max_spec_src is_scantok
12780
12781 @ Additional information about the current line is available via the
12782 |index| variable, which counts how many lines of characters are present
12783 in the buffer below the current level. We have |index=0| when reading
12784 from the terminal and prompting the user for each line; then if the user types,
12785 e.g., `\.{input figs}', we will have |index=1| while reading
12786 the file \.{figs.mp}. However, it does not follow that |index| is the
12787 same as the input stack pointer, since many of the levels on the input
12788 stack may come from token lists and some |index| values may correspond
12789 to \.{MPX} files that are not currently on the stack.
12790
12791 The global variable |in_open| is equal to the highest |index| value counting
12792 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12793 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12794 when we are not reading a token list.
12795
12796 If we are not currently reading from the terminal,
12797 we are reading from the file variable |input_file[index]|. We use
12798 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12799 and |cur_file| as an abbreviation for |input_file[index]|.
12800
12801 When \MP\ is not reading from the terminal, the global variable |line| contains
12802 the line number in the current file, for use in error messages. More precisely,
12803 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12804 the line number for each file in the |input_file| array.
12805
12806 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12807 array so that the name doesn't get lost when the file is temporarily removed
12808 from the input stack.
12809 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12810 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12811 Since this is not an \.{MPX} file, we have
12812 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12813 This |name| field is set to |finished| when |input_file[k]| is completely
12814 read.
12815
12816 If more information about the input state is needed, it can be
12817 included in small arrays like those shown here. For example,
12818 the current page or segment number in the input file might be put
12819 into a variable |page|, that is really a macro for the current entry
12820 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12821 by analogy with |line_stack|.
12822 @^system dependencies@>
12823
12824 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12825 @d cur_file mp->input_file[index] /* the current |void *| variable */
12826 @d line mp->line_stack[index] /* current line number in the current source file */
12827 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12828 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12829 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12830 @d mpx_reading (mp->mpx_name[index]>absent)
12831   /* when reading a file, is it an \.{MPX} file? */
12832 @d finished 0
12833   /* |name_field| value when the corresponding \.{MPX} file is finished */
12834
12835 @<Glob...@>=
12836 integer in_open; /* the number of lines in the buffer, less one */
12837 unsigned int open_parens; /* the number of open text files */
12838 void  * *input_file ;
12839 integer *line_stack ; /* the line number for each file */
12840 char *  *iname_stack; /* used for naming \.{MPX} files */
12841 char *  *iarea_stack; /* used for naming \.{MPX} files */
12842 halfword*mpx_name  ;
12843
12844 @ @<Allocate or ...@>=
12845 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
12846 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12847 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12848 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12849 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12850 {
12851   int k;
12852   for (k=0;k<=mp->max_in_open;k++) {
12853     mp->iname_stack[k] =NULL;
12854     mp->iarea_stack[k] =NULL;
12855   }
12856 }
12857
12858 @ @<Dealloc variables@>=
12859 {
12860   int l;
12861   for (l=0;l<=mp->max_in_open;l++) {
12862     xfree(mp->iname_stack[l]);
12863     xfree(mp->iarea_stack[l]);
12864   }
12865 }
12866 xfree(mp->input_file);
12867 xfree(mp->line_stack);
12868 xfree(mp->iname_stack);
12869 xfree(mp->iarea_stack);
12870 xfree(mp->mpx_name);
12871
12872
12873 @ However, all this discussion about input state really applies only to the
12874 case that we are inputting from a file. There is another important case,
12875 namely when we are currently getting input from a token list. In this case
12876 |index>max_in_open|, and the conventions about the other state variables
12877 are different:
12878
12879 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12880 the node that will be read next. If |loc=null|, the token list has been
12881 fully read.
12882
12883 \yskip\hang|start| points to the first node of the token list; this node
12884 may or may not contain a reference count, depending on the type of token
12885 list involved.
12886
12887 \yskip\hang|token_type|, which takes the place of |index| in the
12888 discussion above, is a code number that explains what kind of token list
12889 is being scanned.
12890
12891 \yskip\hang|name| points to the |eqtb| address of the control sequence
12892 being expanded, if the current token list is a macro not defined by
12893 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12894 can be deduced by looking at their first two parameters.
12895
12896 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12897 the parameters of the current macro or loop text begin in the |param_stack|.
12898
12899 \yskip\noindent The |token_type| can take several values, depending on
12900 where the current token list came from:
12901
12902 \yskip
12903 \indent|forever_text|, if the token list being scanned is the body of
12904 a \&{forever} loop;
12905
12906 \indent|loop_text|, if the token list being scanned is the body of
12907 a \&{for} or \&{forsuffixes} loop;
12908
12909 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12910
12911 \indent|backed_up|, if the token list being scanned has been inserted as
12912 `to be read again'.
12913
12914 \indent|inserted|, if the token list being scanned has been inserted as
12915 part of error recovery;
12916
12917 \indent|macro|, if the expansion of a user-defined symbolic token is being
12918 scanned.
12919
12920 \yskip\noindent
12921 The token list begins with a reference count if and only if |token_type=
12922 macro|.
12923 @^reference counts@>
12924
12925 @d token_type index /* type of current token list */
12926 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12927 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12928 @d param_start limit /* base of macro parameters in |param_stack| */
12929 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12930 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12931 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12932 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12933 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12934 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12935
12936 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12937 lists for parameters at the current level and subsidiary levels of input.
12938 This stack grows at a different rate from the others.
12939
12940 @<Glob...@>=
12941 pointer *param_stack;  /* token list pointers for parameters */
12942 integer param_ptr; /* first unused entry in |param_stack| */
12943 integer max_param_stack;  /* largest value of |param_ptr| */
12944
12945 @ @<Allocate or initialize ...@>=
12946 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12947
12948 @ @<Dealloc variables@>=
12949 xfree(mp->param_stack);
12950
12951 @ Notice that the |line| isn't valid when |token_state| is true because it
12952 depends on |index|.  If we really need to know the line number for the
12953 topmost file in the index stack we use the following function.  If a page
12954 number or other information is needed, this routine should be modified to
12955 compute it as well.
12956 @^system dependencies@>
12957
12958 @<Declare a function called |true_line|@>=
12959 integer mp_true_line (MP mp) {
12960   int k; /* an index into the input stack */
12961   if ( file_state && (name>max_spec_src) ) {
12962      return line;
12963   } else { 
12964     k=mp->input_ptr;
12965     while ((k>0) &&
12966            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12967             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12968       decr(k);
12969     }
12970     return mp->line_stack[(k-1)];
12971   }
12972   return 0; 
12973 }
12974
12975 @ Thus, the ``current input state'' can be very complicated indeed; there
12976 can be many levels and each level can arise in a variety of ways. The
12977 |show_context| procedure, which is used by \MP's error-reporting routine to
12978 print out the current input state on all levels down to the most recent
12979 line of characters from an input file, illustrates most of these conventions.
12980 The global variable |file_ptr| contains the lowest level that was
12981 displayed by this procedure.
12982
12983 @<Glob...@>=
12984 integer file_ptr; /* shallowest level shown by |show_context| */
12985
12986 @ The status at each level is indicated by printing two lines, where the first
12987 line indicates what was read so far and the second line shows what remains
12988 to be read. The context is cropped, if necessary, so that the first line
12989 contains at most |half_error_line| characters, and the second contains
12990 at most |error_line|. Non-current input levels whose |token_type| is
12991 `|backed_up|' are shown only if they have not been fully read.
12992
12993 @c void mp_show_context (MP mp) { /* prints where the scanner is */
12994   int old_setting; /* saved |selector| setting */
12995   @<Local variables for formatting calculations@>
12996   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
12997   /* store current state */
12998   while (1) { 
12999     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13000     @<Display the current context@>;
13001     if ( file_state )
13002       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13003     decr(mp->file_ptr);
13004   }
13005   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13006 }
13007
13008 @ @<Display the current context@>=
13009 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13010    (token_type!=backed_up) || (loc!=null) ) {
13011     /* we omit backed-up token lists that have already been read */
13012   mp->tally=0; /* get ready to count characters */
13013   old_setting=mp->selector;
13014   if ( file_state ) {
13015     @<Print location of current line@>;
13016     @<Pseudoprint the line@>;
13017   } else { 
13018     @<Print type of token list@>;
13019     @<Pseudoprint the token list@>;
13020   }
13021   mp->selector=old_setting; /* stop pseudoprinting */
13022   @<Print two lines using the tricky pseudoprinted information@>;
13023 }
13024
13025 @ This routine should be changed, if necessary, to give the best possible
13026 indication of where the current line resides in the input file.
13027 For example, on some systems it is best to print both a page and line number.
13028 @^system dependencies@>
13029
13030 @<Print location of current line@>=
13031 if ( name>max_spec_src ) {
13032   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13033 } else if ( terminal_input ) {
13034   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13035   else mp_print_nl(mp, "<insert>");
13036 } else if ( name==is_scantok ) {
13037   mp_print_nl(mp, "<scantokens>");
13038 } else {
13039   mp_print_nl(mp, "<read>");
13040 }
13041 mp_print_char(mp, ' ')
13042
13043 @ Can't use case statement here because the |token_type| is not
13044 a constant expression.
13045
13046 @<Print type of token list@>=
13047 {
13048   if(token_type==forever_text) {
13049     mp_print_nl(mp, "<forever> ");
13050   } else if (token_type==loop_text) {
13051     @<Print the current loop value@>;
13052   } else if (token_type==parameter) {
13053     mp_print_nl(mp, "<argument> "); 
13054   } else if (token_type==backed_up) { 
13055     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13056     else mp_print_nl(mp, "<to be read again> ");
13057   } else if (token_type==inserted) {
13058     mp_print_nl(mp, "<inserted text> ");
13059   } else if (token_type==macro) {
13060     mp_print_ln(mp);
13061     if ( name!=null ) mp_print_text(name);
13062     else @<Print the name of a \&{vardef}'d macro@>;
13063     mp_print(mp, "->");
13064   } else {
13065     mp_print_nl(mp, "?");/* this should never happen */
13066 @.?\relax@>
13067   }
13068 }
13069
13070 @ The parameter that corresponds to a loop text is either a token list
13071 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13072 We'll discuss capsules later; for now, all we need to know is that
13073 the |link| field in a capsule parameter is |void| and that
13074 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13075
13076 @<Print the current loop value@>=
13077 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13078   if ( p!=null ) {
13079     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13080     else mp_show_token_list(mp, p,null,20,mp->tally);
13081   }
13082   mp_print(mp, ")> ");
13083 }
13084
13085 @ The first two parameters of a macro defined by \&{vardef} will be token
13086 lists representing the macro's prefix and ``at point.'' By putting these
13087 together, we get the macro's full name.
13088
13089 @<Print the name of a \&{vardef}'d macro@>=
13090 { p=mp->param_stack[param_start];
13091   if ( p==null ) {
13092     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13093   } else { 
13094     q=p;
13095     while ( link(q)!=null ) q=link(q);
13096     link(q)=mp->param_stack[param_start+1];
13097     mp_show_token_list(mp, p,null,20,mp->tally);
13098     link(q)=null;
13099   }
13100 }
13101
13102 @ Now it is necessary to explain a little trick. We don't want to store a long
13103 string that corresponds to a token list, because that string might take up
13104 lots of memory; and we are printing during a time when an error message is
13105 being given, so we dare not do anything that might overflow one of \MP's
13106 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13107 that stores characters into a buffer of length |error_line|, where character
13108 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13109 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13110 |tally:=0| and |trick_count:=1000000|; then when we reach the
13111 point where transition from line 1 to line 2 should occur, we
13112 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13113 tally+1+error_line-half_error_line)|. At the end of the
13114 pseudoprinting, the values of |first_count|, |tally|, and
13115 |trick_count| give us all the information we need to print the two lines,
13116 and all of the necessary text is in |trick_buf|.
13117
13118 Namely, let |l| be the length of the descriptive information that appears
13119 on the first line. The length of the context information gathered for that
13120 line is |k=first_count|, and the length of the context information
13121 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13122 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13123 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13124 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13125 and print `\.{...}' followed by
13126 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13127 where subscripts of |trick_buf| are circular modulo |error_line|. The
13128 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13129 unless |n+m>error_line|; in the latter case, further cropping is done.
13130 This is easier to program than to explain.
13131
13132 @<Local variables for formatting...@>=
13133 int i; /* index into |buffer| */
13134 integer l; /* length of descriptive information on line 1 */
13135 integer m; /* context information gathered for line 2 */
13136 int n; /* length of line 1 */
13137 integer p; /* starting or ending place in |trick_buf| */
13138 integer q; /* temporary index */
13139
13140 @ The following code tells the print routines to gather
13141 the desired information.
13142
13143 @d begin_pseudoprint { 
13144   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13145   mp->trick_count=1000000;
13146 }
13147 @d set_trick_count {
13148   mp->first_count=mp->tally;
13149   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13150   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13151 }
13152
13153 @ And the following code uses the information after it has been gathered.
13154
13155 @<Print two lines using the tricky pseudoprinted information@>=
13156 if ( mp->trick_count==1000000 ) set_trick_count;
13157   /* |set_trick_count| must be performed */
13158 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13159 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13160 if ( l+mp->first_count<=mp->half_error_line ) {
13161   p=0; n=l+mp->first_count;
13162 } else  { 
13163   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13164   n=mp->half_error_line;
13165 }
13166 for (q=p;q<=mp->first_count-1;q++) {
13167   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13168 }
13169 mp_print_ln(mp);
13170 for (q=1;q<=n;q++) {
13171   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13172 }
13173 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13174 else p=mp->first_count+(mp->error_line-n-3);
13175 for (q=mp->first_count;q<=p-1;q++) {
13176   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13177 }
13178 if ( m+n>mp->error_line ) mp_print(mp, "...")
13179
13180 @ But the trick is distracting us from our current goal, which is to
13181 understand the input state. So let's concentrate on the data structures that
13182 are being pseudoprinted as we finish up the |show_context| procedure.
13183
13184 @<Pseudoprint the line@>=
13185 begin_pseudoprint;
13186 if ( limit>0 ) {
13187   for (i=start;i<=limit-1;i++) {
13188     if ( i==loc ) set_trick_count;
13189     mp_print_str(mp, mp->buffer[i]);
13190   }
13191 }
13192
13193 @ @<Pseudoprint the token list@>=
13194 begin_pseudoprint;
13195 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13196 else mp_show_macro(mp, start,loc,100000)
13197
13198 @ Here is the missing piece of |show_token_list| that is activated when the
13199 token beginning line~2 is about to be shown:
13200
13201 @<Do magic computation@>=set_trick_count
13202
13203 @* \[28] Maintaining the input stacks.
13204 The following subroutines change the input status in commonly needed ways.
13205
13206 First comes |push_input|, which stores the current state and creates a
13207 new level (having, initially, the same properties as the old).
13208
13209 @d push_input  { /* enter a new input level, save the old */
13210   if ( mp->input_ptr>mp->max_in_stack ) {
13211     mp->max_in_stack=mp->input_ptr;
13212     if ( mp->input_ptr==mp->stack_size ) {
13213       int l = (mp->stack_size+(mp->stack_size>>2));
13214       XREALLOC(mp->input_stack, l, in_state_record);
13215       mp->stack_size = l;
13216     }         
13217   }
13218   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13219   incr(mp->input_ptr);
13220 }
13221
13222 @ And of course what goes up must come down.
13223
13224 @d pop_input { /* leave an input level, re-enter the old */
13225     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13226   }
13227
13228 @ Here is a procedure that starts a new level of token-list input, given
13229 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13230 set |name|, reset~|loc|, and increase the macro's reference count.
13231
13232 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13233
13234 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13235   push_input; start=p; token_type=t;
13236   param_start=mp->param_ptr; loc=p;
13237 }
13238
13239 @ When a token list has been fully scanned, the following computations
13240 should be done as we leave that level of input.
13241 @^inner loop@>
13242
13243 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13244   pointer p; /* temporary register */
13245   if ( token_type>=backed_up ) { /* token list to be deleted */
13246     if ( token_type<=inserted ) { 
13247       mp_flush_token_list(mp, start); goto DONE;
13248     } else {
13249       mp_delete_mac_ref(mp, start); /* update reference count */
13250     }
13251   }
13252   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13253     decr(mp->param_ptr);
13254     p=mp->param_stack[mp->param_ptr];
13255     if ( p!=null ) {
13256       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13257         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13258       } else {
13259         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13260       }
13261     }
13262   }
13263 DONE: 
13264   pop_input; check_interrupt;
13265 }
13266
13267 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13268 token by the |cur_tok| routine.
13269 @^inner loop@>
13270
13271 @c @<Declare the procedure called |make_exp_copy|@>;
13272 pointer mp_cur_tok (MP mp) {
13273   pointer p; /* a new token node */
13274   small_number save_type; /* |cur_type| to be restored */
13275   integer save_exp; /* |cur_exp| to be restored */
13276   if ( mp->cur_sym==0 ) {
13277     if ( mp->cur_cmd==capsule_token ) {
13278       save_type=mp->cur_type; save_exp=mp->cur_exp;
13279       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13280       mp->cur_type=save_type; mp->cur_exp=save_exp;
13281     } else { 
13282       p=mp_get_node(mp, token_node_size);
13283       value(p)=mp->cur_mod; name_type(p)=mp_token;
13284       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13285       else type(p)=mp_string_type;
13286     }
13287   } else { 
13288     fast_get_avail(p); info(p)=mp->cur_sym;
13289   }
13290   return p;
13291 }
13292
13293 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13294 seen. The |back_input| procedure takes care of this by putting the token
13295 just scanned back into the input stream, ready to be read again.
13296 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13297
13298 @<Declarations@>= 
13299 void mp_back_input (MP mp);
13300
13301 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13302   pointer p; /* a token list of length one */
13303   p=mp_cur_tok(mp);
13304   while ( token_state &&(loc==null) ) 
13305     mp_end_token_list(mp); /* conserve stack space */
13306   back_list(p);
13307 }
13308
13309 @ The |back_error| routine is used when we want to restore or replace an
13310 offending token just before issuing an error message.  We disable interrupts
13311 during the call of |back_input| so that the help message won't be lost.
13312
13313 @<Declarations@>=
13314 void mp_error (MP mp);
13315 void mp_back_error (MP mp);
13316
13317 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13318   mp->OK_to_interrupt=false; 
13319   mp_back_input(mp); 
13320   mp->OK_to_interrupt=true; mp_error(mp);
13321 }
13322 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13323   mp->OK_to_interrupt=false; 
13324   mp_back_input(mp); token_type=inserted;
13325   mp->OK_to_interrupt=true; mp_error(mp);
13326 }
13327
13328 @ The |begin_file_reading| procedure starts a new level of input for lines
13329 of characters to be read from a file, or as an insertion from the
13330 terminal. It does not take care of opening the file, nor does it set |loc|
13331 or |limit| or |line|.
13332 @^system dependencies@>
13333
13334 @c void mp_begin_file_reading (MP mp) { 
13335   if ( mp->in_open==mp->max_in_open ) 
13336     mp_overflow(mp, "text input levels",mp->max_in_open);
13337 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13338   if ( mp->first==mp->buf_size ) 
13339     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13340   incr(mp->in_open); push_input; index=mp->in_open;
13341   mp->mpx_name[index]=absent;
13342   start=mp->first;
13343   name=is_term; /* |terminal_input| is now |true| */
13344 }
13345
13346 @ Conversely, the variables must be downdated when such a level of input
13347 is finished.  Any associated \.{MPX} file must also be closed and popped
13348 off the file stack.
13349
13350 @c void mp_end_file_reading (MP mp) { 
13351   if ( mp->in_open>index ) {
13352     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13353       mp_confusion(mp, "endinput");
13354 @:this can't happen endinput}{\quad endinput@>
13355     } else { 
13356       (mp->close_file)(mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13357       delete_str_ref(mp->mpx_name[mp->in_open]);
13358       decr(mp->in_open);
13359     }
13360   }
13361   mp->first=start;
13362   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13363   if ( name>max_spec_src ) {
13364     (mp->close_file)(cur_file);
13365     delete_str_ref(name);
13366     xfree(in_name); 
13367     xfree(in_area);
13368   }
13369   pop_input; decr(mp->in_open);
13370 }
13371
13372 @ Here is a function that tries to resume input from an \.{MPX} file already
13373 associated with the current input file.  It returns |false| if this doesn't
13374 work.
13375
13376 @c boolean mp_begin_mpx_reading (MP mp) { 
13377   if ( mp->in_open!=index+1 ) {
13378      return false;
13379   } else { 
13380     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13381 @:this can't happen mpx}{\quad mpx@>
13382     if ( mp->first==mp->buf_size ) 
13383       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13384     push_input; index=mp->in_open;
13385     start=mp->first;
13386     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13387     @<Put an empty line in the input buffer@>;
13388     return true;
13389   }
13390 }
13391
13392 @ This procedure temporarily stops reading an \.{MPX} file.
13393
13394 @c void mp_end_mpx_reading (MP mp) { 
13395   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13396 @:this can't happen mpx}{\quad mpx@>
13397   if ( loc<limit ) {
13398     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13399   }
13400   mp->first=start;
13401   pop_input;
13402 }
13403
13404 @ Here we enforce a restriction that simplifies the input stacks considerably.
13405 This should not inconvenience the user because \.{MPX} files are generated
13406 by an auxiliary program called \.{DVItoMP}.
13407
13408 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13409
13410 print_err("`mpxbreak' must be at the end of a line");
13411 help4("This file contains picture expressions for btex...etex")
13412   ("blocks.  Such files are normally generated automatically")
13413   ("but this one seems to be messed up.  I'm going to ignore")
13414   ("the rest of this line.");
13415 mp_error(mp);
13416 }
13417
13418 @ In order to keep the stack from overflowing during a long sequence of
13419 inserted `\.{show}' commands, the following routine removes completed
13420 error-inserted lines from memory.
13421
13422 @c void mp_clear_for_error_prompt (MP mp) { 
13423   while ( file_state && terminal_input &&
13424     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13425   mp_print_ln(mp); clear_terminal;
13426 }
13427
13428 @ To get \MP's whole input mechanism going, we perform the following
13429 actions.
13430
13431 @<Initialize the input routines@>=
13432 { mp->input_ptr=0; mp->max_in_stack=0;
13433   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13434   mp->param_ptr=0; mp->max_param_stack=0;
13435   mp->first=1;
13436   start=1; index=0; line=0; name=is_term;
13437   mp->mpx_name[0]=absent;
13438   mp->force_eof=false;
13439   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13440   limit=mp->last; mp->first=mp->last+1; 
13441   /* |init_terminal| has set |loc| and |last| */
13442 }
13443
13444 @* \[29] Getting the next token.
13445 The heart of \MP's input mechanism is the |get_next| procedure, which
13446 we shall develop in the next few sections of the program. Perhaps we
13447 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13448 eyes and mouth, reading the source files and gobbling them up. And it also
13449 helps \MP\ to regurgitate stored token lists that are to be processed again.
13450
13451 The main duty of |get_next| is to input one token and to set |cur_cmd|
13452 and |cur_mod| to that token's command code and modifier. Furthermore, if
13453 the input token is a symbolic token, that token's |hash| address
13454 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13455
13456 Underlying this simple description is a certain amount of complexity
13457 because of all the cases that need to be handled.
13458 However, the inner loop of |get_next| is reasonably short and fast.
13459
13460 @ Before getting into |get_next|, we need to consider a mechanism by which
13461 \MP\ helps keep errors from propagating too far. Whenever the program goes
13462 into a mode where it keeps calling |get_next| repeatedly until a certain
13463 condition is met, it sets |scanner_status| to some value other than |normal|.
13464 Then if an input file ends, or if an `\&{outer}' symbol appears,
13465 an appropriate error recovery will be possible.
13466
13467 The global variable |warning_info| helps in this error recovery by providing
13468 additional information. For example, |warning_info| might indicate the
13469 name of a macro whose replacement text is being scanned.
13470
13471 @d normal 0 /* |scanner_status| at ``quiet times'' */
13472 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13473 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13474 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13475 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13476 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13477 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13478 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13479
13480 @<Glob...@>=
13481 integer scanner_status; /* are we scanning at high speed? */
13482 integer warning_info; /* if so, what else do we need to know,
13483     in case an error occurs? */
13484
13485 @ @<Initialize the input routines@>=
13486 mp->scanner_status=normal;
13487
13488 @ The following subroutine
13489 is called when an `\&{outer}' symbolic token has been scanned or
13490 when the end of a file has been reached. These two cases are distinguished
13491 by |cur_sym|, which is zero at the end of a file.
13492
13493 @c boolean mp_check_outer_validity (MP mp) {
13494   pointer p; /* points to inserted token list */
13495   if ( mp->scanner_status==normal ) {
13496     return true;
13497   } else if ( mp->scanner_status==tex_flushing ) {
13498     @<Check if the file has ended while flushing \TeX\ material and set the
13499       result value for |check_outer_validity|@>;
13500   } else { 
13501     mp->deletions_allowed=false;
13502     @<Back up an outer symbolic token so that it can be reread@>;
13503     if ( mp->scanner_status>skipping ) {
13504       @<Tell the user what has run away and try to recover@>;
13505     } else { 
13506       print_err("Incomplete if; all text was ignored after line ");
13507 @.Incomplete if...@>
13508       mp_print_int(mp, mp->warning_info);
13509       help3("A forbidden `outer' token occurred in skipped text.")
13510         ("This kind of error happens when you say `if...' and forget")
13511         ("the matching `fi'. I've inserted a `fi'; this might work.");
13512       if ( mp->cur_sym==0 ) 
13513         mp->help_line[2]="The file ended while I was skipping conditional text.";
13514       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13515     }
13516     mp->deletions_allowed=true; 
13517         return false;
13518   }
13519 }
13520
13521 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13522 if ( mp->cur_sym!=0 ) { 
13523    return true;
13524 } else { 
13525   mp->deletions_allowed=false;
13526   print_err("TeX mode didn't end; all text was ignored after line ");
13527   mp_print_int(mp, mp->warning_info);
13528   help2("The file ended while I was looking for the `etex' to")
13529     ("finish this TeX material.  I've inserted `etex' now.");
13530   mp->cur_sym = frozen_etex;
13531   mp_ins_error(mp);
13532   mp->deletions_allowed=true;
13533   return false;
13534 }
13535
13536 @ @<Back up an outer symbolic token so that it can be reread@>=
13537 if ( mp->cur_sym!=0 ) {
13538   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13539   back_list(p); /* prepare to read the symbolic token again */
13540 }
13541
13542 @ @<Tell the user what has run away...@>=
13543
13544   mp_runaway(mp); /* print the definition-so-far */
13545   if ( mp->cur_sym==0 ) {
13546     print_err("File ended");
13547 @.File ended while scanning...@>
13548   } else { 
13549     print_err("Forbidden token found");
13550 @.Forbidden token found...@>
13551   }
13552   mp_print(mp, " while scanning ");
13553   help4("I suspect you have forgotten an `enddef',")
13554     ("causing me to read past where you wanted me to stop.")
13555     ("I'll try to recover; but if the error is serious,")
13556     ("you'd better type `E' or `X' now and fix your file.");
13557   switch (mp->scanner_status) {
13558     @<Complete the error message,
13559       and set |cur_sym| to a token that might help recover from the error@>
13560   } /* there are no other cases */
13561   mp_ins_error(mp);
13562 }
13563
13564 @ As we consider various kinds of errors, it is also appropriate to
13565 change the first line of the help message just given; |help_line[3]|
13566 points to the string that might be changed.
13567
13568 @<Complete the error message,...@>=
13569 case flushing: 
13570   mp_print(mp, "to the end of the statement");
13571   mp->help_line[3]="A previous error seems to have propagated,";
13572   mp->cur_sym=frozen_semicolon;
13573   break;
13574 case absorbing: 
13575   mp_print(mp, "a text argument");
13576   mp->help_line[3]="It seems that a right delimiter was left out,";
13577   if ( mp->warning_info==0 ) {
13578     mp->cur_sym=frozen_end_group;
13579   } else { 
13580     mp->cur_sym=frozen_right_delimiter;
13581     equiv(frozen_right_delimiter)=mp->warning_info;
13582   }
13583   break;
13584 case var_defining:
13585 case op_defining: 
13586   mp_print(mp, "the definition of ");
13587   if ( mp->scanner_status==op_defining ) 
13588      mp_print_text(mp->warning_info);
13589   else 
13590      mp_print_variable_name(mp, mp->warning_info);
13591   mp->cur_sym=frozen_end_def;
13592   break;
13593 case loop_defining: 
13594   mp_print(mp, "the text of a "); 
13595   mp_print_text(mp->warning_info);
13596   mp_print(mp, " loop");
13597   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13598   mp->cur_sym=frozen_end_for;
13599   break;
13600
13601 @ The |runaway| procedure displays the first part of the text that occurred
13602 when \MP\ began its special |scanner_status|, if that text has been saved.
13603
13604 @<Declare the procedure called |runaway|@>=
13605 void mp_runaway (MP mp) { 
13606   if ( mp->scanner_status>flushing ) { 
13607      mp_print_nl(mp, "Runaway ");
13608          switch (mp->scanner_status) { 
13609          case absorbing: mp_print(mp, "text?"); break;
13610          case var_defining: 
13611      case op_defining: mp_print(mp,"definition?"); break;
13612      case loop_defining: mp_print(mp, "loop?"); break;
13613      } /* there are no other cases */
13614      mp_print_ln(mp); 
13615      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13616   }
13617 }
13618
13619 @ We need to mention a procedure that may be called by |get_next|.
13620
13621 @<Declarations@>= 
13622 void mp_firm_up_the_line (MP mp);
13623
13624 @ And now we're ready to take the plunge into |get_next| itself.
13625 Note that the behavior depends on the |scanner_status| because percent signs
13626 and double quotes need to be passed over when skipping TeX material.
13627
13628 @c 
13629 void mp_get_next (MP mp) {
13630   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13631 @^inner loop@>
13632   /*restart*/ /* go here to get the next input token */
13633   /*exit*/ /* go here when the next input token has been got */
13634   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13635   /*found*/ /* go here when the end of a symbolic token has been found */
13636   /*switch*/ /* go here to branch on the class of an input character */
13637   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13638     /* go here at crucial stages when scanning a number */
13639   int k; /* an index into |buffer| */
13640   ASCII_code c; /* the current character in the buffer */
13641   ASCII_code class; /* its class number */
13642   integer n,f; /* registers for decimal-to-binary conversion */
13643 RESTART: 
13644   mp->cur_sym=0;
13645   if ( file_state ) {
13646     @<Input from external file; |goto restart| if no input found,
13647     or |return| if a non-symbolic token is found@>;
13648   } else {
13649     @<Input from token list; |goto restart| if end of list or
13650       if a parameter needs to be expanded,
13651       or |return| if a non-symbolic token is found@>;
13652   }
13653 COMMON_ENDING: 
13654   @<Finish getting the symbolic token in |cur_sym|;
13655    |goto restart| if it is illegal@>;
13656 }
13657
13658 @ When a symbolic token is declared to be `\&{outer}', its command code
13659 is increased by |outer_tag|.
13660 @^inner loop@>
13661
13662 @<Finish getting the symbolic token in |cur_sym|...@>=
13663 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13664 if ( mp->cur_cmd>=outer_tag ) {
13665   if ( mp_check_outer_validity(mp) ) 
13666     mp->cur_cmd=mp->cur_cmd-outer_tag;
13667   else 
13668     goto RESTART;
13669 }
13670
13671 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13672 to have a special test for end-of-line.
13673 @^inner loop@>
13674
13675 @<Input from external file;...@>=
13676
13677 SWITCH: 
13678   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13679   switch (class) {
13680   case digit_class: goto START_NUMERIC_TOKEN; break;
13681   case period_class: 
13682     class=mp->char_class[mp->buffer[loc]];
13683     if ( class>period_class ) {
13684       goto SWITCH;
13685     } else if ( class<period_class ) { /* |class=digit_class| */
13686       n=0; goto START_DECIMAL_TOKEN;
13687     }
13688 @:. }{\..\ token@>
13689     break;
13690   case space_class: goto SWITCH; break;
13691   case percent_class: 
13692     if ( mp->scanner_status==tex_flushing ) {
13693       if ( loc<limit ) goto SWITCH;
13694     }
13695     @<Move to next line of file, or |goto restart| if there is no next line@>;
13696     check_interrupt;
13697     goto SWITCH;
13698     break;
13699   case string_class: 
13700     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13701     else @<Get a string token and |return|@>;
13702     break;
13703   case isolated_classes: 
13704     k=loc-1; goto FOUND; break;
13705   case invalid_class: 
13706     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13707     else @<Decry the invalid character and |goto restart|@>;
13708     break;
13709   default: break; /* letters, etc. */
13710   }
13711   k=loc-1;
13712   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13713   goto FOUND;
13714 START_NUMERIC_TOKEN:
13715   @<Get the integer part |n| of a numeric token;
13716     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13717 START_DECIMAL_TOKEN:
13718   @<Get the fraction part |f| of a numeric token@>;
13719 FIN_NUMERIC_TOKEN:
13720   @<Pack the numeric and fraction parts of a numeric token
13721     and |return|@>;
13722 FOUND: 
13723   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13724 }
13725
13726 @ We go to |restart| instead of to |SWITCH|, because |state| might equal
13727 |token_list| after the error has been dealt with
13728 (cf.\ |clear_for_error_prompt|).
13729
13730 @<Decry the invalid...@>=
13731
13732   print_err("Text line contains an invalid character");
13733 @.Text line contains...@>
13734   help2("A funny symbol that I can\'t read has just been input.")
13735     ("Continue, and I'll forget that it ever happened.");
13736   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13737   goto RESTART;
13738 }
13739
13740 @ @<Get a string token and |return|@>=
13741
13742   if ( mp->buffer[loc]=='"' ) {
13743     mp->cur_mod=rts("");
13744   } else { 
13745     k=loc; mp->buffer[limit+1]='"';
13746     do {  
13747      incr(loc);
13748     } while (mp->buffer[loc]!='"');
13749     if ( loc>limit ) {
13750       @<Decry the missing string delimiter and |goto restart|@>;
13751     }
13752     if ( loc==k+1 ) {
13753       mp->cur_mod=mp->buffer[k];
13754     } else { 
13755       str_room(loc-k);
13756       do {  
13757         append_char(mp->buffer[k]); incr(k);
13758       } while (k!=loc);
13759       mp->cur_mod=mp_make_string(mp);
13760     }
13761   }
13762   incr(loc); mp->cur_cmd=string_token; 
13763   return;
13764 }
13765
13766 @ We go to |restart| after this error message, not to |SWITCH|,
13767 because the |clear_for_error_prompt| routine might have reinstated
13768 |token_state| after |error| has finished.
13769
13770 @<Decry the missing string delimiter and |goto restart|@>=
13771
13772   loc=limit; /* the next character to be read on this line will be |"%"| */
13773   print_err("Incomplete string token has been flushed");
13774 @.Incomplete string token...@>
13775   help3("Strings should finish on the same line as they began.")
13776     ("I've deleted the partial string; you might want to")
13777     ("insert another by typing, e.g., `I\"new string\"'.");
13778   mp->deletions_allowed=false; mp_error(mp);
13779   mp->deletions_allowed=true; 
13780   goto RESTART;
13781 }
13782
13783 @ @<Get the integer part |n| of a numeric token...@>=
13784 n=c-'0';
13785 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13786   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13787   incr(loc);
13788 }
13789 if ( mp->buffer[loc]=='.' ) 
13790   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13791     goto DONE;
13792 f=0; 
13793 goto FIN_NUMERIC_TOKEN;
13794 DONE: incr(loc)
13795
13796 @ @<Get the fraction part |f| of a numeric token@>=
13797 k=0;
13798 do { 
13799   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13800     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13801   }
13802   incr(loc);
13803 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13804 f=mp_round_decimals(mp, k);
13805 if ( f==unity ) {
13806   incr(n); f=0;
13807 }
13808
13809 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13810 if ( n<32768 ) {
13811   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13812 } else if ( mp->scanner_status!=tex_flushing ) {
13813   print_err("Enormous number has been reduced");
13814 @.Enormous number...@>
13815   help2("I can\'t handle numbers bigger than 32767.99998;")
13816     ("so I've changed your constant to that maximum amount.");
13817   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13818   mp->cur_mod=el_gordo;
13819 }
13820 mp->cur_cmd=numeric_token; return
13821
13822 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13823
13824   mp->cur_mod=n*unity+f;
13825   if ( mp->cur_mod>=fraction_one ) {
13826     if ( (mp->internal[mp_warning_check]>0) &&
13827          (mp->scanner_status!=tex_flushing) ) {
13828       print_err("Number is too large (");
13829       mp_print_scaled(mp, mp->cur_mod);
13830       mp_print_char(mp, ')');
13831       help3("It is at least 4096. Continue and I'll try to cope")
13832       ("with that big value; but it might be dangerous.")
13833       ("(Set warningcheck:=0 to suppress this message.)");
13834       mp_error(mp);
13835     }
13836   }
13837 }
13838
13839 @ Let's consider now what happens when |get_next| is looking at a token list.
13840 @^inner loop@>
13841
13842 @<Input from token list;...@>=
13843 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13844   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13845   if ( mp->cur_sym>=expr_base ) {
13846     if ( mp->cur_sym>=suffix_base ) {
13847       @<Insert a suffix or text parameter and |goto restart|@>;
13848     } else { 
13849       mp->cur_cmd=capsule_token;
13850       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13851       mp->cur_sym=0; return;
13852     }
13853   }
13854 } else if ( loc>null ) {
13855   @<Get a stored numeric or string or capsule token and |return|@>
13856 } else { /* we are done with this token list */
13857   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13858 }
13859
13860 @ @<Insert a suffix or text parameter...@>=
13861
13862   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13863   /* |param_size=text_base-suffix_base| */
13864   mp_begin_token_list(mp,
13865                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13866                       parameter);
13867   goto RESTART;
13868 }
13869
13870 @ @<Get a stored numeric or string or capsule token...@>=
13871
13872   if ( name_type(loc)==mp_token ) {
13873     mp->cur_mod=value(loc);
13874     if ( type(loc)==mp_known ) {
13875       mp->cur_cmd=numeric_token;
13876     } else { 
13877       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13878     }
13879   } else { 
13880     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13881   };
13882   loc=link(loc); return;
13883 }
13884
13885 @ All of the easy branches of |get_next| have now been taken care of.
13886 There is one more branch.
13887
13888 @<Move to next line of file, or |goto restart|...@>=
13889 if ( name>max_spec_src ) {
13890   @<Read next line of file into |buffer|, or
13891     |goto restart| if the file has ended@>;
13892 } else { 
13893   if ( mp->input_ptr>0 ) {
13894      /* text was inserted during error recovery or by \&{scantokens} */
13895     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13896   }
13897   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13898   if ( mp->interaction>mp_nonstop_mode ) {
13899     if ( limit==start ) /* previous line was empty */
13900       mp_print_nl(mp, "(Please type a command or say `end')");
13901 @.Please type...@>
13902     mp_print_ln(mp); mp->first=start;
13903     prompt_input("*"); /* input on-line into |buffer| */
13904 @.*\relax@>
13905     limit=mp->last; mp->buffer[limit]='%';
13906     mp->first=limit+1; loc=start;
13907   } else {
13908     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13909 @.job aborted@>
13910     /* nonstop mode, which is intended for overnight batch processing,
13911     never waits for on-line input */
13912   }
13913 }
13914
13915 @ The global variable |force_eof| is normally |false|; it is set |true|
13916 by an \&{endinput} command.
13917
13918 @<Glob...@>=
13919 boolean force_eof; /* should the next \&{input} be aborted early? */
13920
13921 @ We must decrement |loc| in order to leave the buffer in a valid state
13922 when an error condition causes us to |goto restart| without calling
13923 |end_file_reading|.
13924
13925 @<Read next line of file into |buffer|, or
13926   |goto restart| if the file has ended@>=
13927
13928   incr(line); mp->first=start;
13929   if ( ! mp->force_eof ) {
13930     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
13931       mp_firm_up_the_line(mp); /* this sets |limit| */
13932     else 
13933       mp->force_eof=true;
13934   };
13935   if ( mp->force_eof ) {
13936     mp->force_eof=false;
13937     decr(loc);
13938     if ( mpx_reading ) {
13939       @<Complain that the \.{MPX} file ended unexpectly; then set
13940         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13941     } else { 
13942       mp_print_char(mp, ')'); decr(mp->open_parens);
13943       update_terminal; /* show user that file has been read */
13944       mp_end_file_reading(mp); /* resume previous level */
13945       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13946       else goto RESTART;
13947     }
13948   }
13949   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13950 }
13951
13952 @ We should never actually come to the end of an \.{MPX} file because such
13953 files should have an \&{mpxbreak} after the translation of the last
13954 \&{btex}$\,\ldots\,$\&{etex} block.
13955
13956 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13957
13958   mp->mpx_name[index]=finished;
13959   print_err("mpx file ended unexpectedly");
13960   help4("The file had too few picture expressions for btex...etex")
13961     ("blocks.  Such files are normally generated automatically")
13962     ("but this one got messed up.  You might want to insert a")
13963     ("picture expression now.");
13964   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13965   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13966 }
13967
13968 @ Sometimes we want to make it look as though we have just read a blank line
13969 without really doing so.
13970
13971 @<Put an empty line in the input buffer@>=
13972 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13973 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13974
13975 @ If the user has set the |mp_pausing| parameter to some positive value,
13976 and if nonstop mode has not been selected, each line of input is displayed
13977 on the terminal and the transcript file, followed by `\.{=>}'.
13978 \MP\ waits for a response. If the response is null (i.e., if nothing is
13979 typed except perhaps a few blank spaces), the original
13980 line is accepted as it stands; otherwise the line typed is
13981 used instead of the line in the file.
13982
13983 @c void mp_firm_up_the_line (MP mp) {
13984   size_t k; /* an index into |buffer| */
13985   limit=mp->last;
13986   if ( mp->internal[mp_pausing]>0) if ( mp->interaction>mp_nonstop_mode ) {
13987     wake_up_terminal; mp_print_ln(mp);
13988     if ( start<limit ) {
13989       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
13990         mp_print_str(mp, mp->buffer[k]);
13991       } 
13992     }
13993     mp->first=limit; prompt_input("=>"); /* wait for user response */
13994 @.=>@>
13995     if ( mp->last>mp->first ) {
13996       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
13997         mp->buffer[k+start-mp->first]=mp->buffer[k];
13998       }
13999       limit=start+mp->last-mp->first;
14000     }
14001   }
14002 }
14003
14004 @* \[30] Dealing with \TeX\ material.
14005 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14006 features need to be implemented at a low level in the scanning process
14007 so that \MP\ can stay in synch with the a preprocessor that treats
14008 blocks of \TeX\ material as they occur in the input file without trying
14009 to expand \MP\ macros.  Thus we need a special version of |get_next|
14010 that does not expand macros and such but does handle \&{btex},
14011 \&{verbatimtex}, etc.
14012
14013 The special version of |get_next| is called |get_t_next|.  It works by flushing
14014 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14015 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14016 \&{btex}, and switching back when it sees \&{mpxbreak}.
14017
14018 @d btex_code 0
14019 @d verbatim_code 1
14020
14021 @ @<Put each...@>=
14022 mp_primitive(mp, "btex",start_tex,btex_code);
14023 @:btex_}{\&{btex} primitive@>
14024 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14025 @:verbatimtex_}{\&{verbatimtex} primitive@>
14026 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14027 @:etex_}{\&{etex} primitive@>
14028 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14029 @:mpx_break_}{\&{mpxbreak} primitive@>
14030
14031 @ @<Cases of |print_cmd...@>=
14032 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14033   else mp_print(mp, "verbatimtex"); break;
14034 case etex_marker: mp_print(mp, "etex"); break;
14035 case mpx_break: mp_print(mp, "mpxbreak"); break;
14036
14037 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14038 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14039 is encountered.
14040
14041 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14042
14043 @<Declarations@>=
14044 void mp_start_mpx_input (MP mp);
14045
14046 @ @c 
14047 void mp_t_next (MP mp) {
14048   int old_status; /* saves the |scanner_status| */
14049   integer old_info; /* saves the |warning_info| */
14050   while ( mp->cur_cmd<=max_pre_command ) {
14051     if ( mp->cur_cmd==mpx_break ) {
14052       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14053         @<Complain about a misplaced \&{mpxbreak}@>;
14054       } else { 
14055         mp_end_mpx_reading(mp); 
14056         goto TEX_FLUSH;
14057       }
14058     } else if ( mp->cur_cmd==start_tex ) {
14059       if ( token_state || (name<=max_spec_src) ) {
14060         @<Complain that we are not reading a file@>;
14061       } else if ( mpx_reading ) {
14062         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14063       } else if ( (mp->cur_mod!=verbatim_code)&&
14064                   (mp->mpx_name[index]!=finished) ) {
14065         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14066       } else {
14067         goto TEX_FLUSH;
14068       }
14069     } else {
14070        @<Complain about a misplaced \&{etex}@>;
14071     }
14072     goto COMMON_ENDING;
14073   TEX_FLUSH: 
14074     @<Flush the \TeX\ material@>;
14075   COMMON_ENDING: 
14076     mp_get_next(mp);
14077   }
14078 }
14079
14080 @ We could be in the middle of an operation such as skipping false conditional
14081 text when \TeX\ material is encountered, so we must be careful to save the
14082 |scanner_status|.
14083
14084 @<Flush the \TeX\ material@>=
14085 old_status=mp->scanner_status;
14086 old_info=mp->warning_info;
14087 mp->scanner_status=tex_flushing;
14088 mp->warning_info=line;
14089 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14090 mp->scanner_status=old_status;
14091 mp->warning_info=old_info
14092
14093 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14094 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14095 help4("This file contains picture expressions for btex...etex")
14096   ("blocks.  Such files are normally generated automatically")
14097   ("but this one seems to be messed up.  I'll just keep going")
14098   ("and hope for the best.");
14099 mp_error(mp);
14100 }
14101
14102 @ @<Complain that we are not reading a file@>=
14103 { print_err("You can only use `btex' or `verbatimtex' in a file");
14104 help3("I'll have to ignore this preprocessor command because it")
14105   ("only works when there is a file to preprocess.  You might")
14106   ("want to delete everything up to the next `etex`.");
14107 mp_error(mp);
14108 }
14109
14110 @ @<Complain about a misplaced \&{mpxbreak}@>=
14111 { print_err("Misplaced mpxbreak");
14112 help2("I'll ignore this preprocessor command because it")
14113   ("doesn't belong here");
14114 mp_error(mp);
14115 }
14116
14117 @ @<Complain about a misplaced \&{etex}@>=
14118 { print_err("Extra etex will be ignored");
14119 help1("There is no btex or verbatimtex for this to match");
14120 mp_error(mp);
14121 }
14122
14123 @* \[31] Scanning macro definitions.
14124 \MP\ has a variety of ways to tuck tokens away into token lists for later
14125 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14126 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14127 All such operations are handled by the routines in this part of the program.
14128
14129 The modifier part of each command code is zero for the ``ending delimiters''
14130 like \&{enddef} and \&{endfor}.
14131
14132 @d start_def 1 /* command modifier for \&{def} */
14133 @d var_def 2 /* command modifier for \&{vardef} */
14134 @d end_def 0 /* command modifier for \&{enddef} */
14135 @d start_forever 1 /* command modifier for \&{forever} */
14136 @d end_for 0 /* command modifier for \&{endfor} */
14137
14138 @<Put each...@>=
14139 mp_primitive(mp, "def",macro_def,start_def);
14140 @:def_}{\&{def} primitive@>
14141 mp_primitive(mp, "vardef",macro_def,var_def);
14142 @:var_def_}{\&{vardef} primitive@>
14143 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14144 @:primary_def_}{\&{primarydef} primitive@>
14145 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14146 @:secondary_def_}{\&{secondarydef} primitive@>
14147 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14148 @:tertiary_def_}{\&{tertiarydef} primitive@>
14149 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14150 @:end_def_}{\&{enddef} primitive@>
14151 @#
14152 mp_primitive(mp, "for",iteration,expr_base);
14153 @:for_}{\&{for} primitive@>
14154 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14155 @:for_suffixes_}{\&{forsuffixes} primitive@>
14156 mp_primitive(mp, "forever",iteration,start_forever);
14157 @:forever_}{\&{forever} primitive@>
14158 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14159 @:end_for_}{\&{endfor} primitive@>
14160
14161 @ @<Cases of |print_cmd...@>=
14162 case macro_def:
14163   if ( m<=var_def ) {
14164     if ( m==start_def ) mp_print(mp, "def");
14165     else if ( m<start_def ) mp_print(mp, "enddef");
14166     else mp_print(mp, "vardef");
14167   } else if ( m==secondary_primary_macro ) { 
14168     mp_print(mp, "primarydef");
14169   } else if ( m==tertiary_secondary_macro ) { 
14170     mp_print(mp, "secondarydef");
14171   } else { 
14172     mp_print(mp, "tertiarydef");
14173   }
14174   break;
14175 case iteration: 
14176   if ( m<=start_forever ) {
14177     if ( m==start_forever ) mp_print(mp, "forever"); 
14178     else mp_print(mp, "endfor");
14179   } else if ( m==expr_base ) {
14180     mp_print(mp, "for"); 
14181   } else { 
14182     mp_print(mp, "forsuffixes");
14183   }
14184   break;
14185
14186 @ Different macro-absorbing operations have different syntaxes, but they
14187 also have a lot in common. There is a list of special symbols that are to
14188 be replaced by parameter tokens; there is a special command code that
14189 ends the definition; the quotation conventions are identical.  Therefore
14190 it makes sense to have most of the work done by a single subroutine. That
14191 subroutine is called |scan_toks|.
14192
14193 The first parameter to |scan_toks| is the command code that will
14194 terminate scanning (either |macro_def|, |loop_repeat|, or |iteration|).
14195
14196 The second parameter, |subst_list|, points to a (possibly empty) list
14197 of two-word nodes whose |info| and |value| fields specify symbol tokens
14198 before and after replacement. The list will be returned to free storage
14199 by |scan_toks|.
14200
14201 The third parameter is simply appended to the token list that is built.
14202 And the final parameter tells how many of the special operations
14203 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14204 When such parameters are present, they are called \.{(SUFFIX0)},
14205 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14206
14207 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14208   subst_list, pointer tail_end, small_number suffix_count) {
14209   pointer p; /* tail of the token list being built */
14210   pointer q; /* temporary for link management */
14211   integer balance; /* left delimiters minus right delimiters */
14212   p=hold_head; balance=1; link(hold_head)=null;
14213   while (1) { 
14214     get_t_next;
14215     if ( mp->cur_sym>0 ) {
14216       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14217       if ( mp->cur_cmd==terminator ) {
14218         @<Adjust the balance; |break| if it's zero@>;
14219       } else if ( mp->cur_cmd==macro_special ) {
14220         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14221       }
14222     }
14223     link(p)=mp_cur_tok(mp); p=link(p);
14224   }
14225   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14226   return link(hold_head);
14227 }
14228
14229 @ @<Substitute for |cur_sym|...@>=
14230
14231   q=subst_list;
14232   while ( q!=null ) {
14233     if ( info(q)==mp->cur_sym ) {
14234       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14235     }
14236     q=link(q);
14237   }
14238 }
14239
14240 @ @<Adjust the balance; |break| if it's zero@>=
14241 if ( mp->cur_mod>0 ) {
14242   incr(balance);
14243 } else { 
14244   decr(balance);
14245   if ( balance==0 )
14246     break;
14247 }
14248
14249 @ Four commands are intended to be used only within macro texts: \&{quote},
14250 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14251 code called |macro_special|.
14252
14253 @d quote 0 /* |macro_special| modifier for \&{quote} */
14254 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14255 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14256 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14257
14258 @<Put each...@>=
14259 mp_primitive(mp, "quote",macro_special,quote);
14260 @:quote_}{\&{quote} primitive@>
14261 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14262 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14263 mp_primitive(mp, "@@",macro_special,macro_at);
14264 @:]]]\AT!_}{\.{\AT!} primitive@>
14265 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14266 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14267
14268 @ @<Cases of |print_cmd...@>=
14269 case macro_special: 
14270   switch (m) {
14271   case macro_prefix: mp_print(mp, "#@@"); break;
14272   case macro_at: mp_print_char(mp, '@@'); break;
14273   case macro_suffix: mp_print(mp, "@@#"); break;
14274   default: mp_print(mp, "quote"); break;
14275   }
14276   break;
14277
14278 @ @<Handle quoted...@>=
14279
14280   if ( mp->cur_mod==quote ) { get_t_next; } 
14281   else if ( mp->cur_mod<=suffix_count ) 
14282     mp->cur_sym=suffix_base-1+mp->cur_mod;
14283 }
14284
14285 @ Here is a routine that's used whenever a token will be redefined. If
14286 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14287 substituted; the latter is redefinable but essentially impossible to use,
14288 hence \MP's tables won't get fouled up.
14289
14290 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14291 RESTART: 
14292   get_t_next;
14293   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14294     print_err("Missing symbolic token inserted");
14295 @.Missing symbolic token...@>
14296     help3("Sorry: You can\'t redefine a number, string, or expr.")
14297       ("I've inserted an inaccessible symbol so that your")
14298       ("definition will be completed without mixing me up too badly.");
14299     if ( mp->cur_sym>0 )
14300       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14301     else if ( mp->cur_cmd==string_token ) 
14302       delete_str_ref(mp->cur_mod);
14303     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14304   }
14305 }
14306
14307 @ Before we actually redefine a symbolic token, we need to clear away its
14308 former value, if it was a variable. The following stronger version of
14309 |get_symbol| does that.
14310
14311 @c void mp_get_clear_symbol (MP mp) { 
14312   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14313 }
14314
14315 @ Here's another little subroutine; it checks that an equals sign
14316 or assignment sign comes along at the proper place in a macro definition.
14317
14318 @c void mp_check_equals (MP mp) { 
14319   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14320      mp_missing_err(mp, "=");
14321 @.Missing `='@>
14322     help5("The next thing in this `def' should have been `=',")
14323       ("because I've already looked at the definition heading.")
14324       ("But don't worry; I'll pretend that an equals sign")
14325       ("was present. Everything from here to `enddef'")
14326       ("will be the replacement text of this macro.");
14327     mp_back_error(mp);
14328   }
14329 }
14330
14331 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14332 handled now that we have |scan_toks|.  In this case there are
14333 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14334 |expr_base| and |expr_base+1|).
14335
14336 @c void mp_make_op_def (MP mp) {
14337   command_code m; /* the type of definition */
14338   pointer p,q,r; /* for list manipulation */
14339   m=mp->cur_mod;
14340   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14341   info(q)=mp->cur_sym; value(q)=expr_base;
14342   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14343   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14344   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14345   get_t_next; mp_check_equals(mp);
14346   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14347   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14348   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14349   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14350   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14351 }
14352
14353 @ Parameters to macros are introduced by the keywords \&{expr},
14354 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14355
14356 @<Put each...@>=
14357 mp_primitive(mp, "expr",param_type,expr_base);
14358 @:expr_}{\&{expr} primitive@>
14359 mp_primitive(mp, "suffix",param_type,suffix_base);
14360 @:suffix_}{\&{suffix} primitive@>
14361 mp_primitive(mp, "text",param_type,text_base);
14362 @:text_}{\&{text} primitive@>
14363 mp_primitive(mp, "primary",param_type,primary_macro);
14364 @:primary_}{\&{primary} primitive@>
14365 mp_primitive(mp, "secondary",param_type,secondary_macro);
14366 @:secondary_}{\&{secondary} primitive@>
14367 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14368 @:tertiary_}{\&{tertiary} primitive@>
14369
14370 @ @<Cases of |print_cmd...@>=
14371 case param_type:
14372   if ( m>=expr_base ) {
14373     if ( m==expr_base ) mp_print(mp, "expr");
14374     else if ( m==suffix_base ) mp_print(mp, "suffix");
14375     else mp_print(mp, "text");
14376   } else if ( m<secondary_macro ) {
14377     mp_print(mp, "primary");
14378   } else if ( m==secondary_macro ) {
14379     mp_print(mp, "secondary");
14380   } else {
14381     mp_print(mp, "tertiary");
14382   }
14383   break;
14384
14385 @ Let's turn next to the more complex processing associated with \&{def}
14386 and \&{vardef}. When the following procedure is called, |cur_mod|
14387 should be either |start_def| or |var_def|.
14388
14389 @c @<Declare the procedure called |check_delimiter|@>;
14390 @<Declare the function called |scan_declared_variable|@>;
14391 void mp_scan_def (MP mp) {
14392   int m; /* the type of definition */
14393   int n; /* the number of special suffix parameters */
14394   int k; /* the total number of parameters */
14395   int c; /* the kind of macro we're defining */
14396   pointer r; /* parameter-substitution list */
14397   pointer q; /* tail of the macro token list */
14398   pointer p; /* temporary storage */
14399   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14400   pointer l_delim,r_delim; /* matching delimiters */
14401   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14402   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14403   @<Scan the token or variable to be defined;
14404     set |n|, |scanner_status|, and |warning_info|@>;
14405   k=n;
14406   if ( mp->cur_cmd==left_delimiter ) {
14407     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14408   }
14409   if ( mp->cur_cmd==param_type ) {
14410     @<Absorb undelimited parameters, putting them into list |r|@>;
14411   }
14412   mp_check_equals(mp);
14413   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14414   @<Attach the replacement text to the tail of node |p|@>;
14415   mp->scanner_status=normal; mp_get_x_next(mp);
14416 }
14417
14418 @ We don't put `|frozen_end_group|' into the replacement text of
14419 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14420
14421 @<Attach the replacement text to the tail of node |p|@>=
14422 if ( m==start_def ) {
14423   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14424 } else { 
14425   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14426   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14427   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14428 }
14429 if ( mp->warning_info==bad_vardef ) 
14430   mp_flush_token_list(mp, value(bad_vardef))
14431
14432 @ @<Glob...@>=
14433 int bg_loc;
14434 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14435
14436 @ @<Scan the token or variable to be defined;...@>=
14437 if ( m==start_def ) {
14438   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14439   mp->scanner_status=op_defining; n=0;
14440   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14441 } else { 
14442   p=mp_scan_declared_variable(mp);
14443   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14444   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14445   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14446   mp->scanner_status=var_defining; n=2;
14447   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14448     n=3; get_t_next;
14449   }
14450   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14451 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14452
14453 @ @<Change to `\.{a bad variable}'@>=
14454
14455   print_err("This variable already starts with a macro");
14456 @.This variable already...@>
14457   help2("After `vardef a' you can\'t say `vardef a.b'.")
14458     ("So I'll have to discard this definition.");
14459   mp_error(mp); mp->warning_info=bad_vardef;
14460 }
14461
14462 @ @<Initialize table entries...@>=
14463 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14464 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14465
14466 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14467 do {  
14468   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14469   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14470    base=mp->cur_mod;
14471   } else { 
14472     print_err("Missing parameter type; `expr' will be assumed");
14473 @.Missing parameter type@>
14474     help1("You should've had `expr' or `suffix' or `text' here.");
14475     mp_back_error(mp); base=expr_base;
14476   }
14477   @<Absorb parameter tokens for type |base|@>;
14478   mp_check_delimiter(mp, l_delim,r_delim);
14479   get_t_next;
14480 } while (mp->cur_cmd==left_delimiter)
14481
14482 @ @<Absorb parameter tokens for type |base|@>=
14483 do { 
14484   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14485   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14486   value(p)=base+k; info(p)=mp->cur_sym;
14487   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14488 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14489   incr(k); link(p)=r; r=p; get_t_next;
14490 } while (mp->cur_cmd==comma)
14491
14492 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14493
14494   p=mp_get_node(mp, token_node_size);
14495   if ( mp->cur_mod<expr_base ) {
14496     c=mp->cur_mod; value(p)=expr_base+k;
14497   } else { 
14498     value(p)=mp->cur_mod+k;
14499     if ( mp->cur_mod==expr_base ) c=expr_macro;
14500     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14501     else c=text_macro;
14502   }
14503   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14504   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14505   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14506     c=of_macro; p=mp_get_node(mp, token_node_size);
14507     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14508     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14509     link(p)=r; r=p; get_t_next;
14510   }
14511 }
14512
14513 @* \[32] Expanding the next token.
14514 Only a few command codes |<min_command| can possibly be returned by
14515 |get_t_next|; in increasing order, they are
14516 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14517 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14518
14519 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14520 like |get_t_next| except that it keeps getting more tokens until
14521 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14522 macros and removes conditionals or iterations or input instructions that
14523 might be present.
14524
14525 It follows that |get_x_next| might invoke itself recursively. In fact,
14526 there is massive recursion, since macro expansion can involve the
14527 scanning of arbitrarily complex expressions, which in turn involve
14528 macro expansion and conditionals, etc.
14529 @^recursion@>
14530
14531 Therefore it's necessary to declare a whole bunch of |forward|
14532 procedures at this point, and to insert some other procedures
14533 that will be invoked by |get_x_next|.
14534
14535 @<Declarations@>= 
14536 void mp_scan_primary (MP mp);
14537 void mp_scan_secondary (MP mp);
14538 void mp_scan_tertiary (MP mp);
14539 void mp_scan_expression (MP mp);
14540 void mp_scan_suffix (MP mp);
14541 @<Declare the procedure called |macro_call|@>;
14542 void mp_get_boolean (MP mp);
14543 void mp_pass_text (MP mp);
14544 void mp_conditional (MP mp);
14545 void mp_start_input (MP mp);
14546 void mp_begin_iteration (MP mp);
14547 void mp_resume_iteration (MP mp);
14548 void mp_stop_iteration (MP mp);
14549
14550 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14551 when it has to do exotic expansion commands.
14552
14553 @c void mp_expand (MP mp) {
14554   pointer p; /* for list manipulation */
14555   size_t k; /* something that we hope is |<=buf_size| */
14556   pool_pointer j; /* index into |str_pool| */
14557   if ( mp->internal[mp_tracing_commands]>unity ) 
14558     if ( mp->cur_cmd!=defined_macro )
14559       show_cur_cmd_mod;
14560   switch (mp->cur_cmd)  {
14561   case if_test:
14562     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14563     break;
14564   case fi_or_else:
14565     @<Terminate the current conditional and skip to \&{fi}@>;
14566     break;
14567   case input:
14568     @<Initiate or terminate input from a file@>;
14569     break;
14570   case iteration:
14571     if ( mp->cur_mod==end_for ) {
14572       @<Scold the user for having an extra \&{endfor}@>;
14573     } else {
14574       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14575     }
14576     break;
14577   case repeat_loop: 
14578     @<Repeat a loop@>;
14579     break;
14580   case exit_test: 
14581     @<Exit a loop if the proper time has come@>;
14582     break;
14583   case relax: 
14584     break;
14585   case expand_after: 
14586     @<Expand the token after the next token@>;
14587     break;
14588   case scan_tokens: 
14589     @<Put a string into the input buffer@>;
14590     break;
14591   case defined_macro:
14592    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14593    break;
14594   }; /* there are no other cases */
14595 };
14596
14597 @ @<Scold the user...@>=
14598
14599   print_err("Extra `endfor'");
14600 @.Extra `endfor'@>
14601   help2("I'm not currently working on a for loop,")
14602     ("so I had better not try to end anything.");
14603   mp_error(mp);
14604 }
14605
14606 @ The processing of \&{input} involves the |start_input| subroutine,
14607 which will be declared later; the processing of \&{endinput} is trivial.
14608
14609 @<Put each...@>=
14610 mp_primitive(mp, "input",input,0);
14611 @:input_}{\&{input} primitive@>
14612 mp_primitive(mp, "endinput",input,1);
14613 @:end_input_}{\&{endinput} primitive@>
14614
14615 @ @<Cases of |print_cmd_mod|...@>=
14616 case input: 
14617   if ( m==0 ) mp_print(mp, "input");
14618   else mp_print(mp, "endinput");
14619   break;
14620
14621 @ @<Initiate or terminate input...@>=
14622 if ( mp->cur_mod>0 ) mp->force_eof=true;
14623 else mp_start_input(mp)
14624
14625 @ We'll discuss the complicated parts of loop operations later. For now
14626 it suffices to know that there's a global variable called |loop_ptr|
14627 that will be |null| if no loop is in progress.
14628
14629 @<Repeat a loop@>=
14630 { while ( token_state &&(loc==null) ) 
14631     mp_end_token_list(mp); /* conserve stack space */
14632   if ( mp->loop_ptr==null ) {
14633     print_err("Lost loop");
14634 @.Lost loop@>
14635     help2("I'm confused; after exiting from a loop, I still seem")
14636       ("to want to repeat it. I'll try to forget the problem.");
14637     mp_error(mp);
14638   } else {
14639     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14640   }
14641 }
14642
14643 @ @<Exit a loop if the proper time has come@>=
14644 { mp_get_boolean(mp);
14645   if ( mp->internal[mp_tracing_commands]>unity ) 
14646     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14647   if ( mp->cur_exp==true_code ) {
14648     if ( mp->loop_ptr==null ) {
14649       print_err("No loop is in progress");
14650 @.No loop is in progress@>
14651       help1("Why say `exitif' when there's nothing to exit from?");
14652       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14653     } else {
14654      @<Exit prematurely from an iteration@>;
14655     }
14656   } else if ( mp->cur_cmd!=semicolon ) {
14657     mp_missing_err(mp, ";");
14658 @.Missing `;'@>
14659     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14660     ("I shall pretend that one was there."); mp_back_error(mp);
14661   }
14662 }
14663
14664 @ Here we use the fact that |forever_text| is the only |token_type| that
14665 is less than |loop_text|.
14666
14667 @<Exit prematurely...@>=
14668 { p=null;
14669   do {  
14670     if ( file_state ) {
14671       mp_end_file_reading(mp);
14672     } else { 
14673       if ( token_type<=loop_text ) p=start;
14674       mp_end_token_list(mp);
14675     }
14676   } while (p==null);
14677   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14678 @.loop confusion@>
14679   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14680 }
14681
14682 @ @<Expand the token after the next token@>=
14683 { get_t_next;
14684   p=mp_cur_tok(mp); get_t_next;
14685   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14686   else mp_back_input(mp);
14687   back_list(p);
14688 }
14689
14690 @ @<Put a string into the input buffer@>=
14691 { mp_get_x_next(mp); mp_scan_primary(mp);
14692   if ( mp->cur_type!=mp_string_type ) {
14693     mp_disp_err(mp, null,"Not a string");
14694 @.Not a string@>
14695     help2("I'm going to flush this expression, since")
14696        ("scantokens should be followed by a known string.");
14697     mp_put_get_flush_error(mp, 0);
14698   } else { 
14699     mp_back_input(mp);
14700     if ( length(mp->cur_exp)>0 )
14701        @<Pretend we're reading a new one-line file@>;
14702   }
14703 }
14704
14705 @ @<Pretend we're reading a new one-line file@>=
14706 { mp_begin_file_reading(mp); name=is_scantok;
14707   k=mp->first+length(mp->cur_exp);
14708   if ( k>=mp->max_buf_stack ) {
14709     while ( k>=mp->buf_size ) {
14710       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14711     }
14712     mp->max_buf_stack=k+1;
14713   }
14714   j=mp->str_start[mp->cur_exp]; limit=k;
14715   while ( mp->first<(size_t)limit ) {
14716     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14717   }
14718   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14719   mp_flush_cur_exp(mp, 0);
14720 }
14721
14722 @ Here finally is |get_x_next|.
14723
14724 The expression scanning routines to be considered later
14725 communicate via the global quantities |cur_type| and |cur_exp|;
14726 we must be very careful to save and restore these quantities while
14727 macros are being expanded.
14728 @^inner loop@>
14729
14730 @<Declarations@>=
14731 void mp_get_x_next (MP mp);
14732
14733 @ @c void mp_get_x_next (MP mp) {
14734   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14735   get_t_next;
14736   if ( mp->cur_cmd<min_command ) {
14737     save_exp=mp_stash_cur_exp(mp);
14738     do {  
14739       if ( mp->cur_cmd==defined_macro ) 
14740         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14741       else 
14742         mp_expand(mp);
14743       get_t_next;
14744      } while (mp->cur_cmd<min_command);
14745      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14746   }
14747 }
14748
14749 @ Now let's consider the |macro_call| procedure, which is used to start up
14750 all user-defined macros. Since the arguments to a macro might be expressions,
14751 |macro_call| is recursive.
14752 @^recursion@>
14753
14754 The first parameter to |macro_call| points to the reference count of the
14755 token list that defines the macro. The second parameter contains any
14756 arguments that have already been parsed (see below).  The third parameter
14757 points to the symbolic token that names the macro. If the third parameter
14758 is |null|, the macro was defined by \&{vardef}, so its name can be
14759 reconstructed from the prefix and ``at'' arguments found within the
14760 second parameter.
14761
14762 What is this second parameter? It's simply a linked list of one-word items,
14763 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14764 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14765 the first scanned argument, and |link(arg_list)| points to the list of
14766 further arguments (if any).
14767
14768 Arguments of type \&{expr} are so-called capsules, which we will
14769 discuss later when we concentrate on expressions; they can be
14770 recognized easily because their |link| field is |void|. Arguments of type
14771 \&{suffix} and \&{text} are token lists without reference counts.
14772
14773 @ After argument scanning is complete, the arguments are moved to the
14774 |param_stack|. (They can't be put on that stack any sooner, because
14775 the stack is growing and shrinking in unpredictable ways as more arguments
14776 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14777 the replacement text of the macro is placed at the top of the \MP's
14778 input stack, so that |get_t_next| will proceed to read it next.
14779
14780 @<Declare the procedure called |macro_call|@>=
14781 @<Declare the procedure called |print_macro_name|@>;
14782 @<Declare the procedure called |print_arg|@>;
14783 @<Declare the procedure called |scan_text_arg|@>;
14784 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14785                     pointer macro_name) ;
14786
14787 @ @c
14788 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14789                     pointer macro_name) {
14790   /* invokes a user-defined control sequence */
14791   pointer r; /* current node in the macro's token list */
14792   pointer p,q; /* for list manipulation */
14793   integer n; /* the number of arguments */
14794   pointer tail = 0; /* tail of the argument list */
14795   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14796   r=link(def_ref); add_mac_ref(def_ref);
14797   if ( arg_list==null ) {
14798     n=0;
14799   } else {
14800    @<Determine the number |n| of arguments already supplied,
14801     and set |tail| to the tail of |arg_list|@>;
14802   }
14803   if ( mp->internal[mp_tracing_macros]>0 ) {
14804     @<Show the text of the macro being expanded, and the existing arguments@>;
14805   }
14806   @<Scan the remaining arguments, if any; set |r| to the first token
14807     of the replacement text@>;
14808   @<Feed the arguments and replacement text to the scanner@>;
14809 }
14810
14811 @ @<Show the text of the macro...@>=
14812 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14813 mp_print_macro_name(mp, arg_list,macro_name);
14814 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14815 mp_show_macro(mp, def_ref,null,100000);
14816 if ( arg_list!=null ) {
14817   n=0; p=arg_list;
14818   do {  
14819     q=info(p);
14820     mp_print_arg(mp, q,n,0);
14821     incr(n); p=link(p);
14822   } while (p!=null);
14823 }
14824 mp_end_diagnostic(mp, false)
14825
14826
14827 @ @<Declare the procedure called |print_macro_name|@>=
14828 void mp_print_macro_name (MP mp,pointer a, pointer n);
14829
14830 @ @c
14831 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14832   pointer p,q; /* they traverse the first part of |a| */
14833   if ( n!=null ) {
14834     mp_print_text(n);
14835   } else  { 
14836     p=info(a);
14837     if ( p==null ) {
14838       mp_print_text(info(info(link(a))));
14839     } else { 
14840       q=p;
14841       while ( link(q)!=null ) q=link(q);
14842       link(q)=info(link(a));
14843       mp_show_token_list(mp, p,null,1000,0);
14844       link(q)=null;
14845     }
14846   }
14847 }
14848
14849 @ @<Declare the procedure called |print_arg|@>=
14850 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14851
14852 @ @c
14853 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14854   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14855   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14856   else mp_print_nl(mp, "(TEXT");
14857   mp_print_int(mp, n); mp_print(mp, ")<-");
14858   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14859   else mp_show_token_list(mp, q,null,1000,0);
14860 }
14861
14862 @ @<Determine the number |n| of arguments already supplied...@>=
14863 {  
14864   n=1; tail=arg_list;
14865   while ( link(tail)!=null ) { 
14866     incr(n); tail=link(tail);
14867   }
14868 }
14869
14870 @ @<Scan the remaining arguments, if any; set |r|...@>=
14871 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14872 while ( info(r)>=expr_base ) { 
14873   @<Scan the delimited argument represented by |info(r)|@>;
14874   r=link(r);
14875 };
14876 if ( mp->cur_cmd==comma ) {
14877   print_err("Too many arguments to ");
14878 @.Too many arguments...@>
14879   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14880   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14881 @.Missing `)'...@>
14882   mp_print(mp, "' has been inserted");
14883   help3("I'm going to assume that the comma I just read was a")
14884    ("right delimiter, and then I'll begin expanding the macro.")
14885    ("You might want to delete some tokens before continuing.");
14886   mp_error(mp);
14887 }
14888 if ( info(r)!=general_macro ) {
14889   @<Scan undelimited argument(s)@>;
14890 }
14891 r=link(r)
14892
14893 @ At this point, the reader will find it advisable to review the explanation
14894 of token list format that was presented earlier, paying special attention to
14895 the conventions that apply only at the beginning of a macro's token list.
14896
14897 On the other hand, the reader will have to take the expression-parsing
14898 aspects of the following program on faith; we will explain |cur_type|
14899 and |cur_exp| later. (Several things in this program depend on each other,
14900 and it's necessary to jump into the circle somewhere.)
14901
14902 @<Scan the delimited argument represented by |info(r)|@>=
14903 if ( mp->cur_cmd!=comma ) {
14904   mp_get_x_next(mp);
14905   if ( mp->cur_cmd!=left_delimiter ) {
14906     print_err("Missing argument to ");
14907 @.Missing argument...@>
14908     mp_print_macro_name(mp, arg_list,macro_name);
14909     help3("That macro has more parameters than you thought.")
14910      ("I'll continue by pretending that each missing argument")
14911      ("is either zero or null.");
14912     if ( info(r)>=suffix_base ) {
14913       mp->cur_exp=null; mp->cur_type=mp_token_list;
14914     } else { 
14915       mp->cur_exp=0; mp->cur_type=mp_known;
14916     }
14917     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14918     goto FOUND;
14919   }
14920   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14921 }
14922 @<Scan the argument represented by |info(r)|@>;
14923 if ( mp->cur_cmd!=comma ) 
14924   @<Check that the proper right delimiter was present@>;
14925 FOUND:  
14926 @<Append the current expression to |arg_list|@>
14927
14928 @ @<Check that the proper right delim...@>=
14929 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14930   if ( info(link(r))>=expr_base ) {
14931     mp_missing_err(mp, ",");
14932 @.Missing `,'@>
14933     help3("I've finished reading a macro argument and am about to")
14934       ("read another; the arguments weren't delimited correctly.")
14935        ("You might want to delete some tokens before continuing.");
14936     mp_back_error(mp); mp->cur_cmd=comma;
14937   } else { 
14938     mp_missing_err(mp, str(text(r_delim)));
14939 @.Missing `)'@>
14940     help2("I've gotten to the end of the macro parameter list.")
14941        ("You might want to delete some tokens before continuing.");
14942     mp_back_error(mp);
14943   }
14944 }
14945
14946 @ A \&{suffix} or \&{text} parameter will be have been scanned as
14947 a token list pointed to by |cur_exp|, in which case we will have
14948 |cur_type=token_list|.
14949
14950 @<Append the current expression to |arg_list|@>=
14951
14952   p=mp_get_avail(mp);
14953   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14954   else info(p)=mp_stash_cur_exp(mp);
14955   if ( mp->internal[mp_tracing_macros]>0 ) {
14956     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14957     mp_end_diagnostic(mp, false);
14958   }
14959   if ( arg_list==null ) arg_list=p;
14960   else link(tail)=p;
14961   tail=p; incr(n);
14962 }
14963
14964 @ @<Scan the argument represented by |info(r)|@>=
14965 if ( info(r)>=text_base ) {
14966   mp_scan_text_arg(mp, l_delim,r_delim);
14967 } else { 
14968   mp_get_x_next(mp);
14969   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14970   else mp_scan_expression(mp);
14971 }
14972
14973 @ The parameters to |scan_text_arg| are either a pair of delimiters
14974 or zero; the latter case is for undelimited text arguments, which
14975 end with the first semicolon or \&{endgroup} or \&{end} that is not
14976 contained in a group.
14977
14978 @<Declare the procedure called |scan_text_arg|@>=
14979 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14980
14981 @ @c
14982 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
14983   integer balance; /* excess of |l_delim| over |r_delim| */
14984   pointer p; /* list tail */
14985   mp->warning_info=l_delim; mp->scanner_status=absorbing;
14986   p=hold_head; balance=1; link(hold_head)=null;
14987   while (1)  { 
14988     get_t_next;
14989     if ( l_delim==0 ) {
14990       @<Adjust the balance for an undelimited argument; |break| if done@>;
14991     } else {
14992           @<Adjust the balance for a delimited argument; |break| if done@>;
14993     }
14994     link(p)=mp_cur_tok(mp); p=link(p);
14995   }
14996   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
14997   mp->scanner_status=normal;
14998 };
14999
15000 @ @<Adjust the balance for a delimited argument...@>=
15001 if ( mp->cur_cmd==right_delimiter ) { 
15002   if ( mp->cur_mod==l_delim ) { 
15003     decr(balance);
15004     if ( balance==0 ) break;
15005   }
15006 } else if ( mp->cur_cmd==left_delimiter ) {
15007   if ( mp->cur_mod==r_delim ) incr(balance);
15008 }
15009
15010 @ @<Adjust the balance for an undelimited...@>=
15011 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15012   if ( balance==1 ) { break; }
15013   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15014 } else if ( mp->cur_cmd==begin_group ) { 
15015   incr(balance); 
15016 }
15017
15018 @ @<Scan undelimited argument(s)@>=
15019
15020   if ( info(r)<text_macro ) {
15021     mp_get_x_next(mp);
15022     if ( info(r)!=suffix_macro ) {
15023       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15024     }
15025   }
15026   switch (info(r)) {
15027   case primary_macro:mp_scan_primary(mp); break;
15028   case secondary_macro:mp_scan_secondary(mp); break;
15029   case tertiary_macro:mp_scan_tertiary(mp); break;
15030   case expr_macro:mp_scan_expression(mp); break;
15031   case of_macro:
15032     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15033     break;
15034   case suffix_macro:
15035     @<Scan a suffix with optional delimiters@>;
15036     break;
15037   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15038   } /* there are no other cases */
15039   mp_back_input(mp); 
15040   @<Append the current expression to |arg_list|@>;
15041 }
15042
15043 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15044
15045   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15046   if ( mp->internal[mp_tracing_macros]>0 ) { 
15047     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15048     mp_end_diagnostic(mp, false);
15049   }
15050   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15051   tail=p;incr(n);
15052   if ( mp->cur_cmd!=of_token ) {
15053     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15054 @.Missing `of'@>
15055     mp_print_macro_name(mp, arg_list,macro_name);
15056     help1("I've got the first argument; will look now for the other.");
15057     mp_back_error(mp);
15058   }
15059   mp_get_x_next(mp); mp_scan_primary(mp);
15060 }
15061
15062 @ @<Scan a suffix with optional delimiters@>=
15063
15064   if ( mp->cur_cmd!=left_delimiter ) {
15065     l_delim=null;
15066   } else { 
15067     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15068   };
15069   mp_scan_suffix(mp);
15070   if ( l_delim!=null ) {
15071     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15072       mp_missing_err(mp, str(text(r_delim)));
15073 @.Missing `)'@>
15074       help2("I've gotten to the end of the macro parameter list.")
15075          ("You might want to delete some tokens before continuing.");
15076       mp_back_error(mp);
15077     }
15078     mp_get_x_next(mp);
15079   }
15080 }
15081
15082 @ Before we put a new token list on the input stack, it is wise to clean off
15083 all token lists that have recently been depleted. Then a user macro that ends
15084 with a call to itself will not require unbounded stack space.
15085
15086 @<Feed the arguments and replacement text to the scanner@>=
15087 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15088 if ( mp->param_ptr+n>mp->max_param_stack ) {
15089   mp->max_param_stack=mp->param_ptr+n;
15090   if ( mp->max_param_stack>mp->param_size )
15091     mp_overflow(mp, "parameter stack size",mp->param_size);
15092 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15093 }
15094 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15095 if ( n>0 ) {
15096   p=arg_list;
15097   do {  
15098    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15099   } while (p!=null);
15100   mp_flush_list(mp, arg_list);
15101 }
15102
15103 @ It's sometimes necessary to put a single argument onto |param_stack|.
15104 The |stack_argument| subroutine does this.
15105
15106 @c void mp_stack_argument (MP mp,pointer p) { 
15107   if ( mp->param_ptr==mp->max_param_stack ) {
15108     incr(mp->max_param_stack);
15109     if ( mp->max_param_stack>mp->param_size )
15110       mp_overflow(mp, "parameter stack size",mp->param_size);
15111 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15112   }
15113   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15114 }
15115
15116 @* \[33] Conditional processing.
15117 Let's consider now the way \&{if} commands are handled.
15118
15119 Conditions can be inside conditions, and this nesting has a stack
15120 that is independent of other stacks.
15121 Four global variables represent the top of the condition stack:
15122 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15123 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15124 the largest code of a |fi_or_else| command that is syntactically legal;
15125 and |if_line| is the line number at which the current conditional began.
15126
15127 If no conditions are currently in progress, the condition stack has the
15128 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15129 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15130 |link| fields of the first word contain |if_limit|, |cur_if|, and
15131 |cond_ptr| at the next level, and the second word contains the
15132 corresponding |if_line|.
15133
15134 @d if_node_size 2 /* number of words in stack entry for conditionals */
15135 @d if_line_field(A) mp->mem[(A)+1].cint
15136 @d if_code 1 /* code for \&{if} being evaluated */
15137 @d fi_code 2 /* code for \&{fi} */
15138 @d else_code 3 /* code for \&{else} */
15139 @d else_if_code 4 /* code for \&{elseif} */
15140
15141 @<Glob...@>=
15142 pointer cond_ptr; /* top of the condition stack */
15143 integer if_limit; /* upper bound on |fi_or_else| codes */
15144 small_number cur_if; /* type of conditional being worked on */
15145 integer if_line; /* line where that conditional began */
15146
15147 @ @<Set init...@>=
15148 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15149
15150 @ @<Put each...@>=
15151 mp_primitive(mp, "if",if_test,if_code);
15152 @:if_}{\&{if} primitive@>
15153 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15154 @:fi_}{\&{fi} primitive@>
15155 mp_primitive(mp, "else",fi_or_else,else_code);
15156 @:else_}{\&{else} primitive@>
15157 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15158 @:else_if_}{\&{elseif} primitive@>
15159
15160 @ @<Cases of |print_cmd_mod|...@>=
15161 case if_test:
15162 case fi_or_else: 
15163   switch (m) {
15164   case if_code:mp_print(mp, "if"); break;
15165   case fi_code:mp_print(mp, "fi");  break;
15166   case else_code:mp_print(mp, "else"); break;
15167   default: mp_print(mp, "elseif"); break;
15168   }
15169   break;
15170
15171 @ Here is a procedure that ignores text until coming to an \&{elseif},
15172 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15173 nesting. After it has acted, |cur_mod| will indicate the token that
15174 was found.
15175
15176 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15177 makes the skipping process a bit simpler.
15178
15179 @c 
15180 void mp_pass_text (MP mp) {
15181   integer l = 0;
15182   mp->scanner_status=skipping;
15183   mp->warning_info=mp_true_line(mp);
15184   while (1)  { 
15185     get_t_next;
15186     if ( mp->cur_cmd<=fi_or_else ) {
15187       if ( mp->cur_cmd<fi_or_else ) {
15188         incr(l);
15189       } else { 
15190         if ( l==0 ) break;
15191         if ( mp->cur_mod==fi_code ) decr(l);
15192       }
15193     } else {
15194       @<Decrease the string reference count,
15195        if the current token is a string@>;
15196     }
15197   }
15198   mp->scanner_status=normal;
15199 }
15200
15201 @ @<Decrease the string reference count...@>=
15202 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15203
15204 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15205 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15206 condition has been evaluated, a colon will be inserted.
15207 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15208
15209 @<Push the condition stack@>=
15210 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15211   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15212   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15213   mp->cur_if=if_code;
15214 }
15215
15216 @ @<Pop the condition stack@>=
15217 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15218   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15219   mp_free_node(mp, p,if_node_size);
15220 }
15221
15222 @ Here's a procedure that changes the |if_limit| code corresponding to
15223 a given value of |cond_ptr|.
15224
15225 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15226   pointer q;
15227   if ( p==mp->cond_ptr ) {
15228     mp->if_limit=l; /* that's the easy case */
15229   } else  { 
15230     q=mp->cond_ptr;
15231     while (1) { 
15232       if ( q==null ) mp_confusion(mp, "if");
15233 @:this can't happen if}{\quad if@>
15234       if ( link(q)==p ) { 
15235         type(q)=l; return;
15236       }
15237       q=link(q);
15238     }
15239   }
15240 }
15241
15242 @ The user is supposed to put colons into the proper parts of conditional
15243 statements. Therefore, \MP\ has to check for their presence.
15244
15245 @c 
15246 void mp_check_colon (MP mp) { 
15247   if ( mp->cur_cmd!=colon ) { 
15248     mp_missing_err(mp, ":");
15249 @.Missing `:'@>
15250     help2("There should've been a colon after the condition.")
15251          ("I shall pretend that one was there.");;
15252     mp_back_error(mp);
15253   }
15254 }
15255
15256 @ A condition is started when the |get_x_next| procedure encounters
15257 an |if_test| command; in that case |get_x_next| calls |conditional|,
15258 which is a recursive procedure.
15259 @^recursion@>
15260
15261 @c void mp_conditional (MP mp) {
15262   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15263   int new_if_limit; /* future value of |if_limit| */
15264   pointer p; /* temporary register */
15265   @<Push the condition stack@>; 
15266   save_cond_ptr=mp->cond_ptr;
15267 RESWITCH: 
15268   mp_get_boolean(mp); new_if_limit=else_if_code;
15269   if ( mp->internal[mp_tracing_commands]>unity ) {
15270     @<Display the boolean value of |cur_exp|@>;
15271   }
15272 FOUND: 
15273   mp_check_colon(mp);
15274   if ( mp->cur_exp==true_code ) {
15275     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15276     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15277   };
15278   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15279 DONE: 
15280   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15281   if ( mp->cur_mod==fi_code ) {
15282     @<Pop the condition stack@>
15283   } else if ( mp->cur_mod==else_if_code ) {
15284     goto RESWITCH;
15285   } else  { 
15286     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15287     goto FOUND;
15288   }
15289 }
15290
15291 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15292 \&{else}: \\{bar} \&{fi}', the first \&{else}
15293 that we come to after learning that the \&{if} is false is not the
15294 \&{else} we're looking for. Hence the following curious logic is needed.
15295
15296 @<Skip to \&{elseif}...@>=
15297 while (1) { 
15298   mp_pass_text(mp);
15299   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15300   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15301 }
15302
15303
15304 @ @<Display the boolean value...@>=
15305 { mp_begin_diagnostic(mp);
15306   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15307   else mp_print(mp, "{false}");
15308   mp_end_diagnostic(mp, false);
15309 }
15310
15311 @ The processing of conditionals is complete except for the following
15312 code, which is actually part of |get_x_next|. It comes into play when
15313 \&{elseif}, \&{else}, or \&{fi} is scanned.
15314
15315 @<Terminate the current conditional and skip to \&{fi}@>=
15316 if ( mp->cur_mod>mp->if_limit ) {
15317   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15318     mp_missing_err(mp, ":");
15319 @.Missing `:'@>
15320     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15321   } else  { 
15322     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15323 @.Extra else@>
15324 @.Extra elseif@>
15325 @.Extra fi@>
15326     help1("I'm ignoring this; it doesn't match any if.");
15327     mp_error(mp);
15328   }
15329 } else  { 
15330   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15331   @<Pop the condition stack@>;
15332 }
15333
15334 @* \[34] Iterations.
15335 To bring our treatment of |get_x_next| to a close, we need to consider what
15336 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15337
15338 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15339 that are currently active. If |loop_ptr=null|, no loops are in progress;
15340 otherwise |info(loop_ptr)| points to the iterative text of the current
15341 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15342 loops that enclose the current one.
15343
15344 A loop-control node also has two other fields, called |loop_type| and
15345 |loop_list|, whose contents depend on the type of loop:
15346
15347 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15348 points to a list of one-word nodes whose |info| fields point to the
15349 remaining argument values of a suffix list and expression list.
15350
15351 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15352 `\&{forever}'.
15353
15354 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15355 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15356 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15357 progression.
15358
15359 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15360 header and |loop_list(loop_ptr)| points into the graphical object list for
15361 that edge header.
15362
15363 \yskip\noindent In the case of a progression node, the first word is not used
15364 because the link field of words in the dynamic memory area cannot be arbitrary.
15365
15366 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15367 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15368 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15369 @d loop_node_size 2 /* the number of words in a loop control node */
15370 @d progression_node_size 4 /* the number of words in a progression node */
15371 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15372 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15373 @d progression_flag (null+2)
15374   /* |loop_type| value when |loop_list| points to a progression node */
15375
15376 @<Glob...@>=
15377 pointer loop_ptr; /* top of the loop-control-node stack */
15378
15379 @ @<Set init...@>=
15380 mp->loop_ptr=null;
15381
15382 @ If the expressions that define an arithmetic progression in
15383 a \&{for} loop don't have known numeric values, the |bad_for|
15384 subroutine screams at the user.
15385
15386 @c void mp_bad_for (MP mp, char * s) {
15387   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15388 @.Improper...replaced by 0@>
15389   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15390   help4("When you say `for x=a step b until c',")
15391     ("the initial value `a' and the step size `b'")
15392     ("and the final value `c' must have known numeric values.")
15393     ("I'm zeroing this one. Proceed, with fingers crossed.");
15394   mp_put_get_flush_error(mp, 0);
15395 };
15396
15397 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15398 has just been scanned. (This code requires slight familiarity with
15399 expression-parsing routines that we have not yet discussed; but it seems
15400 to belong in the present part of the program, even though the original author
15401 didn't write it until later. The reader may wish to come back to it.)
15402
15403 @c void mp_begin_iteration (MP mp) {
15404   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15405   halfword n; /* hash address of the current symbol */
15406   pointer s; /* the new loop-control node */
15407   pointer p; /* substitution list for |scan_toks| */
15408   pointer q;  /* link manipulation register */
15409   pointer pp; /* a new progression node */
15410   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15411   if ( m==start_forever ){ 
15412     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15413   } else { 
15414     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15415     info(p)=mp->cur_sym; value(p)=m;
15416     mp_get_x_next(mp);
15417     if ( mp->cur_cmd==within_token ) {
15418       @<Set up a picture iteration@>;
15419     } else { 
15420       @<Check for the |"="| or |":="| in a loop header@>;
15421       @<Scan the values to be used in the loop@>;
15422     }
15423   }
15424   @<Check for the presence of a colon@>;
15425   @<Scan the loop text and put it on the loop control stack@>;
15426   mp_resume_iteration(mp);
15427 }
15428
15429 @ @<Check for the |"="| or |":="| in a loop header@>=
15430 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15431   mp_missing_err(mp, "=");
15432 @.Missing `='@>
15433   help3("The next thing in this loop should have been `=' or `:='.")
15434     ("But don't worry; I'll pretend that an equals sign")
15435     ("was present, and I'll look for the values next.");
15436   mp_back_error(mp);
15437 }
15438
15439 @ @<Check for the presence of a colon@>=
15440 if ( mp->cur_cmd!=colon ) { 
15441   mp_missing_err(mp, ":");
15442 @.Missing `:'@>
15443   help3("The next thing in this loop should have been a `:'.")
15444     ("So I'll pretend that a colon was present;")
15445     ("everything from here to `endfor' will be iterated.");
15446   mp_back_error(mp);
15447 }
15448
15449 @ We append a special |frozen_repeat_loop| token in place of the
15450 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15451 at the proper time to cause the loop to be repeated.
15452
15453 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15454 he will be foiled by the |get_symbol| routine, which keeps frozen
15455 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15456 token, so it won't be lost accidentally.)
15457
15458 @ @<Scan the loop text...@>=
15459 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15460 mp->scanner_status=loop_defining; mp->warning_info=n;
15461 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15462 link(s)=mp->loop_ptr; mp->loop_ptr=s
15463
15464 @ @<Initialize table...@>=
15465 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15466 text(frozen_repeat_loop)=intern(" ENDFOR");
15467
15468 @ The loop text is inserted into \MP's scanning apparatus by the
15469 |resume_iteration| routine.
15470
15471 @c void mp_resume_iteration (MP mp) {
15472   pointer p,q; /* link registers */
15473   p=loop_type(mp->loop_ptr);
15474   if ( p==progression_flag ) { 
15475     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15476     mp->cur_exp=value(p);
15477     if ( @<The arithmetic progression has ended@> ) {
15478       mp_stop_iteration(mp);
15479       return;
15480     }
15481     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15482     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15483   } else if ( p==null ) { 
15484     p=loop_list(mp->loop_ptr);
15485     if ( p==null ) {
15486       mp_stop_iteration(mp);
15487       return;
15488     }
15489     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15490   } else if ( p==mp_void ) { 
15491     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15492   } else {
15493     @<Make |q| a capsule containing the next picture component from
15494       |loop_list(loop_ptr)| or |goto not_found|@>;
15495   }
15496   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15497   mp_stack_argument(mp, q);
15498   if ( mp->internal[mp_tracing_commands]>unity ) {
15499      @<Trace the start of a loop@>;
15500   }
15501   return;
15502 NOT_FOUND:
15503   mp_stop_iteration(mp);
15504 }
15505
15506 @ @<The arithmetic progression has ended@>=
15507 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15508  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15509
15510 @ @<Trace the start of a loop@>=
15511
15512   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15513 @.loop value=n@>
15514   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15515   else mp_show_token_list(mp, q,null,50,0);
15516   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15517 }
15518
15519 @ @<Make |q| a capsule containing the next picture component from...@>=
15520 { q=loop_list(mp->loop_ptr);
15521   if ( q==null ) goto NOT_FOUND;
15522   skip_component(q) goto NOT_FOUND;
15523   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15524   mp_init_bbox(mp, mp->cur_exp);
15525   mp->cur_type=mp_picture_type;
15526   loop_list(mp->loop_ptr)=q;
15527   q=mp_stash_cur_exp(mp);
15528 }
15529
15530 @ A level of loop control disappears when |resume_iteration| has decided
15531 not to resume, or when an \&{exitif} construction has removed the loop text
15532 from the input stack.
15533
15534 @c void mp_stop_iteration (MP mp) {
15535   pointer p,q; /* the usual */
15536   p=loop_type(mp->loop_ptr);
15537   if ( p==progression_flag )  {
15538     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15539   } else if ( p==null ){ 
15540     q=loop_list(mp->loop_ptr);
15541     while ( q!=null ) {
15542       p=info(q);
15543       if ( p!=null ) {
15544         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15545           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15546         } else {
15547           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15548         }
15549       }
15550       p=q; q=link(q); free_avail(p);
15551     }
15552   } else if ( p>progression_flag ) {
15553     delete_edge_ref(p);
15554   }
15555   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15556   mp_free_node(mp, p,loop_node_size);
15557 }
15558
15559 @ Now that we know all about loop control, we can finish up
15560 the missing portion of |begin_iteration| and we'll be done.
15561
15562 The following code is performed after the `\.=' has been scanned in
15563 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15564 (if |m=suffix_base|).
15565
15566 @<Scan the values to be used in the loop@>=
15567 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15568 do {  
15569   mp_get_x_next(mp);
15570   if ( m!=expr_base ) {
15571     mp_scan_suffix(mp);
15572   } else { 
15573     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15574           goto CONTINUE;
15575     mp_scan_expression(mp);
15576     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15577       @<Prepare for step-until construction and |break|@>;
15578     }
15579     mp->cur_exp=mp_stash_cur_exp(mp);
15580   }
15581   link(q)=mp_get_avail(mp); q=link(q); 
15582   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15583 CONTINUE:
15584   ;
15585 } while (mp->cur_cmd==comma)
15586
15587 @ @<Prepare for step-until construction and |break|@>=
15588
15589   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15590   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15591   mp_get_x_next(mp); mp_scan_expression(mp);
15592   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15593   step_size(pp)=mp->cur_exp;
15594   if ( mp->cur_cmd!=until_token ) { 
15595     mp_missing_err(mp, "until");
15596 @.Missing `until'@>
15597     help2("I assume you meant to say `until' after `step'.")
15598       ("So I'll look for the final value and colon next.");
15599     mp_back_error(mp);
15600   }
15601   mp_get_x_next(mp); mp_scan_expression(mp);
15602   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15603   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15604   loop_type(s)=progression_flag; 
15605   break;
15606 }
15607
15608 @ The last case is when we have just seen ``\&{within}'', and we need to
15609 parse a picture expression and prepare to iterate over it.
15610
15611 @<Set up a picture iteration@>=
15612 { mp_get_x_next(mp);
15613   mp_scan_expression(mp);
15614   @<Make sure the current expression is a known picture@>;
15615   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15616   q=link(dummy_loc(mp->cur_exp));
15617   if ( q!= null ) 
15618     if ( is_start_or_stop(q) )
15619       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15620   loop_list(s)=q;
15621 }
15622
15623 @ @<Make sure the current expression is a known picture@>=
15624 if ( mp->cur_type!=mp_picture_type ) {
15625   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15626   help1("When you say `for x in p', p must be a known picture.");
15627   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15628   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15629 }
15630
15631 @* \[35] File names.
15632 It's time now to fret about file names.  Besides the fact that different
15633 operating systems treat files in different ways, we must cope with the
15634 fact that completely different naming conventions are used by different
15635 groups of people. The following programs show what is required for one
15636 particular operating system; similar routines for other systems are not
15637 difficult to devise.
15638 @^system dependencies@>
15639
15640 \MP\ assumes that a file name has three parts: the name proper; its
15641 ``extension''; and a ``file area'' where it is found in an external file
15642 system.  The extension of an input file is assumed to be
15643 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15644 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15645 metric files that describe characters in any fonts created by \MP; it is
15646 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15647 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15648 The file area can be arbitrary on input files, but files are usually
15649 output to the user's current area.  If an input file cannot be
15650 found on the specified area, \MP\ will look for it on a special system
15651 area; this special area is intended for commonly used input files.
15652
15653 Simple uses of \MP\ refer only to file names that have no explicit
15654 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15655 instead of `\.{input} \.{cmr10.new}'. Simple file
15656 names are best, because they make the \MP\ source files portable;
15657 whenever a file name consists entirely of letters and digits, it should be
15658 treated in the same way by all implementations of \MP. However, users
15659 need the ability to refer to other files in their environment, especially
15660 when responding to error messages concerning unopenable files; therefore
15661 we want to let them use the syntax that appears in their favorite
15662 operating system.
15663
15664 @ \MP\ uses the same conventions that have proved to be satisfactory for
15665 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15666 @^system dependencies@>
15667 the system-independent parts of \MP\ are expressed in terms
15668 of three system-dependent
15669 procedures called |begin_name|, |more_name|, and |end_name|. In
15670 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15671 the system-independent driver program does the operations
15672 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
15673 \,|end_name|.$$
15674 These three procedures communicate with each other via global variables.
15675 Afterwards the file name will appear in the string pool as three strings
15676 called |cur_name|\penalty10000\hskip-.05em,
15677 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15678 |""|), unless they were explicitly specified by the user.
15679
15680 Actually the situation is slightly more complicated, because \MP\ needs
15681 to know when the file name ends. The |more_name| routine is a function
15682 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15683 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15684 returns |false|; or, it returns |true| and $c_n$ is the last character
15685 on the current input line. In other words,
15686 |more_name| is supposed to return |true| unless it is sure that the
15687 file name has been completely scanned; and |end_name| is supposed to be able
15688 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15689 whether $|more_name|(c_n)$ returned |true| or |false|.
15690
15691 @<Glob...@>=
15692 char * cur_name; /* name of file just scanned */
15693 char * cur_area; /* file area just scanned, or \.{""} */
15694 char * cur_ext; /* file extension just scanned, or \.{""} */
15695
15696 @ It is easier to maintain reference counts if we assign initial values.
15697
15698 @<Set init...@>=
15699 mp->cur_name=xstrdup(""); 
15700 mp->cur_area=xstrdup(""); 
15701 mp->cur_ext=xstrdup("");
15702
15703 @ @<Dealloc variables@>=
15704 xfree(mp->cur_area);
15705 xfree(mp->cur_name);
15706 xfree(mp->cur_ext);
15707
15708 @ The file names we shall deal with for illustrative purposes have the
15709 following structure:  If the name contains `\.>' or `\.:', the file area
15710 consists of all characters up to and including the final such character;
15711 otherwise the file area is null.  If the remaining file name contains
15712 `\..', the file extension consists of all such characters from the first
15713 remaining `\..' to the end, otherwise the file extension is null.
15714 @^system dependencies@>
15715
15716 We can scan such file names easily by using two global variables that keep track
15717 of the occurrences of area and extension delimiters.  Note that these variables
15718 cannot be of type |pool_pointer| because a string pool compaction could occur
15719 while scanning a file name.
15720
15721 @<Glob...@>=
15722 integer area_delimiter;
15723   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15724 integer ext_delimiter; /* the relevant `\..', if any */
15725
15726 @ Input files that can't be found in the user's area may appear in standard
15727 system areas called |MP_area| and |MF_area|.  (The latter is used when the file
15728 extension is |".mf"|.)  The standard system area for font metric files
15729 to be read is |MP_font_area|.
15730 This system area name will, of course, vary from place to place.
15731 @^system dependencies@>
15732
15733 @d MP_area "MPinputs:"
15734 @.MPinputs@>
15735 @d MF_area "MFinputs:"
15736 @.MFinputs@>
15737 @d MP_font_area ""
15738 @.TeXfonts@>
15739
15740 @ Here now is the first of the system-dependent routines for file name scanning.
15741 @^system dependencies@>
15742
15743 @<Declare subroutines for parsing file names@>=
15744 void mp_begin_name (MP mp) { 
15745   xfree(mp->cur_name); 
15746   xfree(mp->cur_area); 
15747   xfree(mp->cur_ext);
15748   mp->area_delimiter=-1; 
15749   mp->ext_delimiter=-1;
15750 }
15751
15752 @ And here's the second.
15753 @^system dependencies@>
15754
15755 @<Declare subroutines for parsing file names@>=
15756 boolean mp_more_name (MP mp, ASCII_code c) { 
15757   if (c==' ') {
15758     return false;
15759   } else { 
15760     if ( (c=='>')||(c==':') ) { 
15761       mp->area_delimiter=mp->pool_ptr; 
15762       mp->ext_delimiter=-1;
15763     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15764       mp->ext_delimiter=mp->pool_ptr;
15765     }
15766     str_room(1); append_char(c); /* contribute |c| to the current string */
15767     return true;
15768   }
15769 }
15770
15771 @ The third.
15772 @^system dependencies@>
15773
15774 @d copy_pool_segment(A,B,C) { 
15775       A = xmalloc(C+1,sizeof(char)); 
15776       strncpy(A,(char *)(mp->str_pool+B),C);  
15777       A[C] = 0;}
15778
15779 @<Declare subroutines for parsing file names@>=
15780 void mp_end_name (MP mp) {
15781   pool_pointer s; /* length of area, name, and extension */
15782   unsigned int len;
15783   /* "my/w.mp" */
15784   s = mp->str_start[mp->str_ptr];
15785   if ( mp->area_delimiter<0 ) {    
15786     mp->cur_area=xstrdup("");
15787   } else {
15788     len = mp->area_delimiter-s; 
15789     copy_pool_segment(mp->cur_area,s,len);
15790     s += len+1;
15791   }
15792   if ( mp->ext_delimiter<0 ) {
15793     mp->cur_ext=xstrdup("");
15794     len = mp->pool_ptr-s; 
15795   } else {
15796     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15797     len = mp->ext_delimiter-s;
15798   }
15799   copy_pool_segment(mp->cur_name,s,len);
15800   mp->pool_ptr=s; /* don't need this partial string */
15801 }
15802
15803 @ Conversely, here is a routine that takes three strings and prints a file
15804 name that might have produced them. (The routine is system dependent, because
15805 some operating systems put the file area last instead of first.)
15806 @^system dependencies@>
15807
15808 @<Basic printing...@>=
15809 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15810   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15811 };
15812
15813 @ Another system-dependent routine is needed to convert three internal
15814 \MP\ strings
15815 to the |name_of_file| value that is used to open files. The present code
15816 allows both lowercase and uppercase letters in the file name.
15817 @^system dependencies@>
15818
15819 @d append_to_name(A) { c=(A); 
15820   if ( k<file_name_size ) {
15821     mp->name_of_file[k]=xchr(c);
15822     incr(k);
15823   }
15824 }
15825
15826 @<Declare subroutines for parsing file names@>=
15827 void mp_pack_file_name (MP mp, char *n, char *a, char *e) {
15828   integer k; /* number of positions filled in |name_of_file| */
15829   ASCII_code c; /* character being packed */
15830   char *j; /* a character  index */
15831   k=0;
15832   assert(n);
15833   if (a!=NULL) {
15834     for (j=a;*j;j++) { append_to_name(*j); }
15835   }
15836   for (j=n;*j;j++) { append_to_name(*j); }
15837   if (e!=NULL) {
15838     for (j=e;*j;j++) { append_to_name(*j); }
15839   }
15840   mp->name_of_file[k]=0;
15841   mp->name_length=k; 
15842 }
15843
15844 @ @<Internal library declarations@>=
15845 void mp_pack_file_name (MP mp, char *n, char *a, char *e) ;
15846
15847 @ A messier routine is also needed, since mem file names must be scanned
15848 before \MP's string mechanism has been initialized. We shall use the
15849 global variable |MP_mem_default| to supply the text for default system areas
15850 and extensions related to mem files.
15851 @^system dependencies@>
15852
15853 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15854 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15855 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15856
15857 @<Glob...@>=
15858 char *MP_mem_default;
15859
15860 @ @<Option variables@>=
15861 char *mem_name; /* for commandline */
15862
15863 @ @<Allocate or initialize ...@>=
15864 mp->MP_mem_default = xstrdup("plain.mem");
15865 mp->mem_name = xstrdup(opt->mem_name);
15866 @.plain@>
15867 @^system dependencies@>
15868
15869 @ @<Dealloc variables@>=
15870 xfree(mp->MP_mem_default);
15871 xfree(mp->mem_name);
15872
15873 @ @<Check the ``constant'' values for consistency@>=
15874 if ( mem_default_length>file_name_size ) mp->bad=20;
15875
15876 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15877 from the first |n| characters of |MP_mem_default|, followed by
15878 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15879 |MP_mem_default|.
15880
15881 We dare not give error messages here, since \MP\ calls this routine before
15882 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15883 since the error will be detected in another way when a strange file name
15884 isn't found.
15885 @^system dependencies@>
15886
15887 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15888                                integer b) {
15889   integer k; /* number of positions filled in |name_of_file| */
15890   ASCII_code c; /* character being packed */
15891   integer j; /* index into |buffer| or |MP_mem_default| */
15892   if ( n+b-a+1+mem_ext_length>file_name_size )
15893     b=a+file_name_size-n-1-mem_ext_length;
15894   k=0;
15895   for (j=0;j<n;j++) {
15896     append_to_name(xord((int)mp->MP_mem_default[j]));
15897   }
15898   for (j=a;j<b;j++) {
15899     append_to_name(mp->buffer[j]);
15900   }
15901   for (j=mem_default_length-mem_ext_length;
15902       j<mem_default_length;j++) {
15903     append_to_name(xord((int)mp->MP_mem_default[j]));
15904   } 
15905   mp->name_of_file[k]=0;
15906   mp->name_length=k; 
15907 }
15908
15909 @ Here is the only place we use |pack_buffered_name|. This part of the program
15910 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15911 the preliminary initialization, or when the user is substituting another
15912 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15913 contains the first line of input in |buffer[loc..(last-1)]|, where
15914 |loc<last| and |buffer[loc]<>" "|.
15915
15916 @<Declarations@>=
15917 boolean mp_open_mem_file (MP mp) ;
15918
15919 @ @c
15920 boolean mp_open_mem_file (MP mp) {
15921   int j; /* the first space after the file name */
15922   if (mp->mem_name!=NULL) {
15923     mp->mem_file = (mp->open_file)(mp->mem_name, "rb", mp_filetype_memfile);
15924     if ( mp->mem_file ) return true;
15925   }
15926   j=loc;
15927   if ( mp->buffer[loc]=='&' ) {
15928     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15929     while ( mp->buffer[j]!=' ' ) incr(j);
15930     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15931     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15932     wake_up_terminal;
15933     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15934 @.Sorry, I can't find...@>
15935     update_terminal;
15936   }
15937   /* now pull out all the stops: try for the system \.{plain} file */
15938   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15939   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15940     wake_up_terminal;
15941     wterm_ln("I can\'t find the PLAIN mem file!\n");
15942 @.I can't find PLAIN...@>
15943 @.plain@>
15944     return false;
15945   }
15946 FOUND:
15947   loc=j; return true;
15948 }
15949
15950 @ Operating systems often make it possible to determine the exact name (and
15951 possible version number) of a file that has been opened. The following routine,
15952 which simply makes a \MP\ string from the value of |name_of_file|, should
15953 ideally be changed to deduce the full name of file~|f|, which is the file
15954 most recently opened, if it is possible to do this.
15955 @^system dependencies@>
15956
15957 @<Declarations@>=
15958 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15959 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15960 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15961
15962 @ @c 
15963 str_number mp_make_name_string (MP mp) {
15964   int k; /* index into |name_of_file| */
15965   str_room(mp->name_length);
15966   for (k=0;k<mp->name_length;k++) {
15967     append_char(xord((int)mp->name_of_file[k]));
15968   }
15969   return mp_make_string(mp);
15970 }
15971
15972 @ Now let's consider the ``driver''
15973 routines by which \MP\ deals with file names
15974 in a system-independent manner.  First comes a procedure that looks for a
15975 file name in the input by taking the information from the input buffer.
15976 (We can't use |get_next|, because the conversion to tokens would
15977 destroy necessary information.)
15978
15979 This procedure doesn't allow semicolons or percent signs to be part of
15980 file names, because of other conventions of \MP.
15981 {\sl The {\logos METAFONT\/}book} doesn't
15982 use semicolons or percents immediately after file names, but some users
15983 no doubt will find it natural to do so; therefore system-dependent
15984 changes to allow such characters in file names should probably
15985 be made with reluctance, and only when an entire file name that
15986 includes special characters is ``quoted'' somehow.
15987 @^system dependencies@>
15988
15989 @c void mp_scan_file_name (MP mp) { 
15990   mp_begin_name(mp);
15991   while ( mp->buffer[loc]==' ' ) incr(loc);
15992   while (1) { 
15993     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15994     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15995     incr(loc);
15996   }
15997   mp_end_name(mp);
15998 }
15999
16000 @ Here is another version that takes its input from a string.
16001
16002 @<Declare subroutines for parsing file names@>=
16003 void mp_str_scan_file (MP mp,  str_number s) {
16004   pool_pointer p,q; /* current position and stopping point */
16005   mp_begin_name(mp);
16006   p=mp->str_start[s]; q=str_stop(s);
16007   while ( p<q ){ 
16008     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16009     incr(p);
16010   }
16011   mp_end_name(mp);
16012 }
16013
16014 @ And one that reads from a |char*|.
16015
16016 @<Declare subroutines for parsing file names@>=
16017 void mp_ptr_scan_file (MP mp,  char *s) {
16018   char *p, *q; /* current position and stopping point */
16019   mp_begin_name(mp);
16020   p=s; q=p+strlen(s);
16021   while ( p<q ){ 
16022     if ( ! mp_more_name(mp, *p)) break;
16023     p++;
16024   }
16025   mp_end_name(mp);
16026 }
16027
16028
16029 @ The global variable |job_name| contains the file name that was first
16030 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16031 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16032
16033 @<Glob...@>=
16034 boolean log_opened; /* has the transcript file been opened? */
16035 char *log_name; /* full name of the log file */
16036
16037 @ @<Option variables@>=
16038 char *job_name; /* principal file name */
16039
16040 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16041 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16042 except of course for a short time just after |job_name| has become nonzero.
16043
16044 @<Allocate or ...@>=
16045 mp->job_name=opt->job_name; 
16046 mp->log_opened=false;
16047
16048 @ @<Dealloc variables@>=
16049 xfree(mp->job_name);
16050
16051 @ Here is a routine that manufactures the output file names, assuming that
16052 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16053 and |cur_ext|.
16054
16055 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16056
16057 @<Declarations@>=
16058 void mp_pack_job_name (MP mp, char *s) ;
16059
16060 @ @c void mp_pack_job_name (MP mp, char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16061   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16062   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16063   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16064   pack_cur_name;
16065 }
16066
16067 @ If some trouble arises when \MP\ tries to open a file, the following
16068 routine calls upon the user to supply another file name. Parameter~|s|
16069 is used in the error message to identify the type of file; parameter~|e|
16070 is the default extension if none is given. Upon exit from the routine,
16071 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16072 ready for another attempt at file opening.
16073
16074 @<Declarations@>=
16075 void mp_prompt_file_name (MP mp,char * s, char * e) ;
16076
16077 @ @c void mp_prompt_file_name (MP mp,char * s, char * e) {
16078   size_t k; /* index into |buffer| */
16079   char * saved_cur_name;
16080   if ( mp->interaction==mp_scroll_mode ) 
16081         wake_up_terminal;
16082   if (strcmp(s,"input file name")==0) {
16083         print_err("I can\'t find file `");
16084 @.I can't find file x@>
16085   } else {
16086         print_err("I can\'t write on file `");
16087   }
16088 @.I can't write on file x@>
16089   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16090   mp_print(mp, "'.");
16091   if (strcmp(e,"")==0) 
16092         mp_show_context(mp);
16093   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16094 @.Please type...@>
16095   if ( mp->interaction<mp_scroll_mode )
16096     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16097 @.job aborted, file error...@>
16098   saved_cur_name = xstrdup(mp->cur_name);
16099   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16100   if (strcmp(mp->cur_ext,"")==0) 
16101         mp->cur_ext=e;
16102   if (strlen(mp->cur_name)==0) {
16103     mp->cur_name=saved_cur_name;
16104   } else {
16105     xfree(saved_cur_name);
16106   }
16107   pack_cur_name;
16108 }
16109
16110 @ @<Scan file name in the buffer@>=
16111
16112   mp_begin_name(mp); k=mp->first;
16113   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16114   while (1) { 
16115     if ( k==mp->last ) break;
16116     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16117     incr(k);
16118   }
16119   mp_end_name(mp);
16120 }
16121
16122 @ The |open_log_file| routine is used to open the transcript file and to help
16123 it catch up to what has previously been printed on the terminal.
16124
16125 @c void mp_open_log_file (MP mp) {
16126   int old_setting; /* previous |selector| setting */
16127   int k; /* index into |months| and |buffer| */
16128   int l; /* end of first input line */
16129   integer m; /* the current month */
16130   char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16131     /* abbreviations of month names */
16132   old_setting=mp->selector;
16133   if ( mp->job_name==NULL ) {
16134      mp->job_name=xstrdup("mpout");
16135   }
16136   mp_pack_job_name(mp,".log");
16137   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16138     @<Try to get a different log file name@>;
16139   }
16140   mp->log_name=xstrdup(mp->name_of_file);
16141   mp->selector=log_only; mp->log_opened=true;
16142   @<Print the banner line, including the date and time@>;
16143   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16144     /* make sure bottom level is in memory */
16145 @.**@>
16146   if (!mp->noninteractive) {
16147     mp_print_nl(mp, "**");
16148     l=mp->input_stack[0].limit_field-1; /* last position of first line */
16149     for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16150     mp_print_ln(mp); /* now the transcript file contains the first line of input */
16151   }
16152   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16153 }
16154
16155 @ @<Dealloc variables@>=
16156 xfree(mp->log_name);
16157
16158 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16159 unable to print error messages or even to |show_context|.
16160 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16161 routine will not be invoked because |log_opened| will be false.
16162
16163 The normal idea of |mp_batch_mode| is that nothing at all should be written
16164 on the terminal. However, in the unusual case that
16165 no log file could be opened, we make an exception and allow
16166 an explanatory message to be seen.
16167
16168 Incidentally, the program always refers to the log file as a `\.{transcript
16169 file}', because some systems cannot use the extension `\.{.log}' for
16170 this file.
16171
16172 @<Try to get a different log file name@>=
16173 {  
16174   mp->selector=term_only;
16175   mp_prompt_file_name(mp, "transcript file name",".log");
16176 }
16177
16178 @ @<Print the banner...@>=
16179
16180   wlog(banner);
16181   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16182   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16183   mp_print_char(mp, ' ');
16184   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16185   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16186   mp_print_char(mp, ' '); 
16187   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16188   mp_print_char(mp, ' ');
16189   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16190   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16191 }
16192
16193 @ The |try_extension| function tries to open an input file determined by
16194 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16195 can't find the file in |cur_area| or the appropriate system area.
16196
16197 @c boolean mp_try_extension (MP mp,char *ext) { 
16198   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16199   in_name=xstrdup(mp->cur_name); 
16200   in_area=xstrdup(mp->cur_area);
16201   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16202     return true;
16203   } else { 
16204     if (strcmp(ext,".mf")==0 ) in_area=xstrdup(MF_area);
16205     else in_area=xstrdup(MP_area);
16206     mp_pack_file_name(mp, mp->cur_name,in_area,ext);
16207     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16208   }
16209   return false;
16210 }
16211
16212 @ Let's turn now to the procedure that is used to initiate file reading
16213 when an `\.{input}' command is being processed.
16214
16215 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16216   char *fname = NULL;
16217   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16218   while (1) { 
16219     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16220     if ( strlen(mp->cur_ext)==0 ) {
16221       if ( mp_try_extension(mp, ".mp") ) break;
16222       else if ( mp_try_extension(mp, "") ) break;
16223       else if ( mp_try_extension(mp, ".mf") ) break;
16224       /* |else do_nothing; | */
16225     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16226       break;
16227     }
16228     mp_end_file_reading(mp); /* remove the level that didn't work */
16229     mp_prompt_file_name(mp, "input file name","");
16230   }
16231   name=mp_a_make_name_string(mp, cur_file);
16232   fname = xstrdup(mp->name_of_file);
16233   if ( mp->job_name==NULL ) {
16234     mp->job_name=xstrdup(mp->cur_name); 
16235     mp_open_log_file(mp);
16236   } /* |open_log_file| doesn't |show_context|, so |limit|
16237         and |loc| needn't be set to meaningful values yet */
16238   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16239   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16240   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16241   xfree(fname);
16242   update_terminal;
16243   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16244   @<Read the first line of the new file@>;
16245 }
16246
16247 @ This code should be omitted if |a_make_name_string| returns something other
16248 than just a copy of its argument and the full file name is needed for opening
16249 \.{MPX} files or implementing the switch-to-editor option.
16250 @^system dependencies@>
16251
16252 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16253 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16254
16255 @ If the file is empty, it is considered to contain a single blank line,
16256 so there is no need to test the return value.
16257
16258 @<Read the first line...@>=
16259
16260   line=1;
16261   (void)mp_input_ln(mp, cur_file ); 
16262   mp_firm_up_the_line(mp);
16263   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16264 }
16265
16266 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16267 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16268 if ( token_state ) { 
16269   print_err("File names can't appear within macros");
16270 @.File names can't...@>
16271   help3("Sorry...I've converted what follows to tokens,")
16272     ("possibly garbaging the name you gave.")
16273     ("Please delete the tokens and insert the name again.");
16274   mp_error(mp);
16275 }
16276 if ( file_state ) {
16277   mp_scan_file_name(mp);
16278 } else { 
16279    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16280    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16281    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16282 }
16283
16284 @ The following simple routine starts reading the \.{MPX} file associated
16285 with the current input file.
16286
16287 @c void mp_start_mpx_input (MP mp) {
16288   char *origname = NULL; /* a copy of nameoffile */
16289   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16290   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16291     |goto not_found| if there is a problem@>;
16292   mp_begin_file_reading(mp);
16293   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16294     mp_end_file_reading(mp);
16295     goto NOT_FOUND;
16296   }
16297   name=mp_a_make_name_string(mp, cur_file);
16298   mp->mpx_name[index]=name; add_str_ref(name);
16299   @<Read the first line of the new file@>;
16300   return;
16301 NOT_FOUND: 
16302     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16303   xfree(origname);
16304 }
16305
16306 @ This should ideally be changed to do whatever is necessary to create the
16307 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16308 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16309 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16310 completely different typesetting program if suitable postprocessor is
16311 available to perform the function of \.{DVItoMP}.)
16312 @^system dependencies@>
16313
16314 @ @<Exported types@>=
16315 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16316
16317 @ @<Option variables@>=
16318 mp_run_make_mpx_command run_make_mpx;
16319
16320 @ @<Allocate or initialize ...@>=
16321 set_callback_option(run_make_mpx);
16322
16323 @ @<Internal library declarations@>=
16324 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16325
16326 @ The default does nothing.
16327 @c 
16328 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16329   if (mp && origname && mtxname) /* for -W */
16330     return false;
16331   return false;
16332 }
16333
16334 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16335   |goto not_found| if there is a problem@>=
16336 origname = mp_xstrdup(mp,mp->name_of_file);
16337 *(origname+strlen(origname)-1)=0; /* drop the x */
16338 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16339   goto NOT_FOUND 
16340
16341 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16342 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16343 mp_print_nl(mp, ">> ");
16344 mp_print(mp, origname);
16345 mp_print_nl(mp, ">> ");
16346 mp_print(mp, mp->name_of_file);
16347 mp_print_nl(mp, "! Unable to make mpx file");
16348 help4("The two files given above are one of your source files")
16349   ("and an auxiliary file I need to read to find out what your")
16350   ("btex..etex blocks mean. If you don't know why I had trouble,")
16351   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16352 succumb;
16353
16354 @ The last file-opening commands are for files accessed via the \&{readfrom}
16355 @:read_from_}{\&{readfrom} primitive@>
16356 operator and the \&{write} command.  Such files are stored in separate arrays.
16357 @:write_}{\&{write} primitive@>
16358
16359 @<Types in the outer block@>=
16360 typedef unsigned int readf_index; /* |0..max_read_files| */
16361 typedef unsigned int write_index;  /* |0..max_write_files| */
16362
16363 @ @<Glob...@>=
16364 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16365 void ** rd_file; /* \&{readfrom} files */
16366 char ** rd_fname; /* corresponding file name or 0 if file not open */
16367 readf_index read_files; /* number of valid entries in the above arrays */
16368 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16369 void ** wr_file; /* \&{write} files */
16370 char ** wr_fname; /* corresponding file name or 0 if file not open */
16371 write_index write_files; /* number of valid entries in the above arrays */
16372
16373 @ @<Allocate or initialize ...@>=
16374 mp->max_read_files=8;
16375 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16376 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16377 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16378 mp->read_files=0;
16379 mp->max_write_files=8;
16380 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16381 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16382 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16383 mp->write_files=0;
16384
16385
16386 @ This routine starts reading the file named by string~|s| without setting
16387 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16388 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16389
16390 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16391   mp_ptr_scan_file(mp, s);
16392   pack_cur_name;
16393   mp_begin_file_reading(mp);
16394   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (mp_filetype_text+n)) ) 
16395         goto NOT_FOUND;
16396   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16397     (mp->close_file)(mp->rd_file[n]); 
16398         goto NOT_FOUND; 
16399   }
16400   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16401   return true;
16402 NOT_FOUND: 
16403   mp_end_file_reading(mp);
16404   return false;
16405 }
16406
16407 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16408
16409 @<Declarations@>=
16410 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16411
16412 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16413   mp_ptr_scan_file(mp, s);
16414   pack_cur_name;
16415   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (mp_filetype_text+n)) )
16416     mp_prompt_file_name(mp, "file name for write output","");
16417   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16418 }
16419
16420
16421 @* \[36] Introduction to the parsing routines.
16422 We come now to the central nervous system that sparks many of \MP's activities.
16423 By evaluating expressions, from their primary constituents to ever larger
16424 subexpressions, \MP\ builds the structures that ultimately define complete
16425 pictures or fonts of type.
16426
16427 Four mutually recursive subroutines are involved in this process: We call them
16428 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16429 and |scan_expression|.}$$
16430 @^recursion@>
16431 Each of them is parameterless and begins with the first token to be scanned
16432 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16433 the value of the primary or secondary or tertiary or expression that was
16434 found will appear in the global variables |cur_type| and |cur_exp|. The
16435 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16436 and |cur_sym|.
16437
16438 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16439 backup mechanisms have been added in order to provide reasonable error
16440 recovery.
16441
16442 @<Glob...@>=
16443 small_number cur_type; /* the type of the expression just found */
16444 integer cur_exp; /* the value of the expression just found */
16445
16446 @ @<Set init...@>=
16447 mp->cur_exp=0;
16448
16449 @ Many different kinds of expressions are possible, so it is wise to have
16450 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16451
16452 \smallskip\hang
16453 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16454 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16455 construction in which there was no expression before the \&{endgroup}.
16456 In this case |cur_exp| has some irrelevant value.
16457
16458 \smallskip\hang
16459 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16460 or |false_code|.
16461
16462 \smallskip\hang
16463 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16464 node that is in the ring of variables equivalent
16465 to at least one undefined boolean variable.
16466
16467 \smallskip\hang
16468 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16469 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16470 includes this particular reference.
16471
16472 \smallskip\hang
16473 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16474 node that is in the ring of variables equivalent
16475 to at least one undefined string variable.
16476
16477 \smallskip\hang
16478 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16479 else points to any of the nodes in this pen.  The pen may be polygonal or
16480 elliptical.
16481
16482 \smallskip\hang
16483 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16484 node that is in the ring of variables equivalent
16485 to at least one undefined pen variable.
16486
16487 \smallskip\hang
16488 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16489 a path; nobody else points to this particular path. The control points of
16490 the path will have been chosen.
16491
16492 \smallskip\hang
16493 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16494 node that is in the ring of variables equivalent
16495 to at least one undefined path variable.
16496
16497 \smallskip\hang
16498 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16499 There may be other pointers to this particular set of edges.  The header node
16500 contains a reference count that includes this particular reference.
16501
16502 \smallskip\hang
16503 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16504 node that is in the ring of variables equivalent
16505 to at least one undefined picture variable.
16506
16507 \smallskip\hang
16508 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16509 capsule node. The |value| part of this capsule
16510 points to a transform node that contains six numeric values,
16511 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16512
16513 \smallskip\hang
16514 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16515 capsule node. The |value| part of this capsule
16516 points to a color node that contains three numeric values,
16517 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16518
16519 \smallskip\hang
16520 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16521 capsule node. The |value| part of this capsule
16522 points to a color node that contains four numeric values,
16523 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16524
16525 \smallskip\hang
16526 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16527 node whose type is |mp_pair_type|. The |value| part of this capsule
16528 points to a pair node that contains two numeric values,
16529 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16530
16531 \smallskip\hang
16532 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16533
16534 \smallskip\hang
16535 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16536 is |dependent|. The |dep_list| field in this capsule points to the associated
16537 dependency list.
16538
16539 \smallskip\hang
16540 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16541 capsule node. The |dep_list| field in this capsule
16542 points to the associated dependency list.
16543
16544 \smallskip\hang
16545 |cur_type=independent| means that |cur_exp| points to a capsule node
16546 whose type is |independent|. This somewhat unusual case can arise, for
16547 example, in the expression
16548 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16549
16550 \smallskip\hang
16551 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16552 tokens. This case arises only on the left-hand side of an assignment
16553 (`\.{:=}') operation, under very special circumstances.
16554
16555 \smallskip\noindent
16556 The possible settings of |cur_type| have been listed here in increasing
16557 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16558 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16559 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16560 |token_list|.
16561
16562 @ Capsules are two-word nodes that have a similar meaning
16563 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|
16564 and |link<=mp_void|; and their |type| field is one of the possibilities for
16565 |cur_type| listed above.
16566
16567 The |value| field of a capsule is, in most cases, the value that
16568 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16569 However, when |cur_exp| would point to a capsule,
16570 no extra layer of indirection is present; the |value|
16571 field is what would have been called |value(cur_exp)| if it had not been
16572 encapsulated.  Furthermore, if the type is |dependent| or
16573 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16574 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16575 always part of the general |dep_list| structure.
16576
16577 The |get_x_next| routine is careful not to change the values of |cur_type|
16578 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16579 call a macro, which might parse an expression, which might execute lots of
16580 commands in a group; hence it's possible that |cur_type| might change
16581 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16582 |known| or |independent|, during the time |get_x_next| is called. The
16583 programs below are careful to stash sensitive intermediate results in
16584 capsules, so that \MP's generality doesn't cause trouble.
16585
16586 Here's a procedure that illustrates these conventions. It takes
16587 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16588 and stashes them away in a
16589 capsule. It is not used when |cur_type=mp_token_list|.
16590 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16591 copy path lists or to update reference counts, etc.
16592
16593 The special link |mp_void| is put on the capsule returned by
16594 |stash_cur_exp|, because this procedure is used to store macro parameters
16595 that must be easily distinguishable from token lists.
16596
16597 @<Declare the stashing/unstashing routines@>=
16598 pointer mp_stash_cur_exp (MP mp) {
16599   pointer p; /* the capsule that will be returned */
16600   switch (mp->cur_type) {
16601   case unknown_types:
16602   case mp_transform_type:
16603   case mp_color_type:
16604   case mp_pair_type:
16605   case mp_dependent:
16606   case mp_proto_dependent:
16607   case mp_independent: 
16608   case mp_cmykcolor_type:
16609     p=mp->cur_exp;
16610     break;
16611   default: 
16612     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16613     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16614     break;
16615   }
16616   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16617   return p;
16618 }
16619
16620 @ The inverse of |stash_cur_exp| is the following procedure, which
16621 deletes an unnecessary capsule and puts its contents into |cur_type|
16622 and |cur_exp|.
16623
16624 The program steps of \MP\ can be divided into two categories: those in
16625 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16626 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16627 information or not. It's important not to ignore them when they're alive,
16628 and it's important not to pay attention to them when they're dead.
16629
16630 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16631 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16632 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16633 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16634 only when they are alive or dormant.
16635
16636 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16637 are alive or dormant. The \\{unstash} procedure assumes that they are
16638 dead or dormant; it resuscitates them.
16639
16640 @<Declare the stashing/unstashing...@>=
16641 void mp_unstash_cur_exp (MP mp,pointer p) ;
16642
16643 @ @c
16644 void mp_unstash_cur_exp (MP mp,pointer p) { 
16645   mp->cur_type=type(p);
16646   switch (mp->cur_type) {
16647   case unknown_types:
16648   case mp_transform_type:
16649   case mp_color_type:
16650   case mp_pair_type:
16651   case mp_dependent: 
16652   case mp_proto_dependent:
16653   case mp_independent:
16654   case mp_cmykcolor_type: 
16655     mp->cur_exp=p;
16656     break;
16657   default:
16658     mp->cur_exp=value(p);
16659     mp_free_node(mp, p,value_node_size);
16660     break;
16661   }
16662 }
16663
16664 @ The following procedure prints the values of expressions in an
16665 abbreviated format. If its first parameter |p| is null, the value of
16666 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16667 containing the desired value. The second parameter controls the amount of
16668 output. If it is~0, dependency lists will be abbreviated to
16669 `\.{linearform}' unless they consist of a single term.  If it is greater
16670 than~1, complicated structures (pens, pictures, and paths) will be displayed
16671 in full.
16672
16673 @<Declare subroutines for printing expressions@>=
16674 @<Declare the procedure called |print_dp|@>;
16675 @<Declare the stashing/unstashing routines@>;
16676 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16677   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16678   small_number t; /* the type of the expression */
16679   pointer q; /* a big node being displayed */
16680   integer v=0; /* the value of the expression */
16681   if ( p!=null ) {
16682     restore_cur_exp=false;
16683   } else { 
16684     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16685   }
16686   t=type(p);
16687   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16688   @<Print an abbreviated value of |v| with format depending on |t|@>;
16689   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16690 }
16691
16692 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16693 switch (t) {
16694 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16695 case mp_boolean_type:
16696   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16697   break;
16698 case unknown_types: case mp_numeric_type:
16699   @<Display a variable that's been declared but not defined@>;
16700   break;
16701 case mp_string_type:
16702   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16703   break;
16704 case mp_pen_type: case mp_path_type: case mp_picture_type:
16705   @<Display a complex type@>;
16706   break;
16707 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16708   if ( v==null ) mp_print_type(mp, t);
16709   else @<Display a big node@>;
16710   break;
16711 case mp_known:mp_print_scaled(mp, v); break;
16712 case mp_dependent: case mp_proto_dependent:
16713   mp_print_dp(mp, t,v,verbosity);
16714   break;
16715 case mp_independent:mp_print_variable_name(mp, p); break;
16716 default: mp_confusion(mp, "exp"); break;
16717 @:this can't happen exp}{\quad exp@>
16718 }
16719
16720 @ @<Display a big node@>=
16721
16722   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16723   do {  
16724     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16725     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16726     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16727     v=v+2;
16728     if ( v!=q ) mp_print_char(mp, ',');
16729   } while (v!=q);
16730   mp_print_char(mp, ')');
16731 }
16732
16733 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16734 in the log file only, unless the user has given a positive value to
16735 \\{tracingonline}.
16736
16737 @<Display a complex type@>=
16738 if ( verbosity<=1 ) {
16739   mp_print_type(mp, t);
16740 } else { 
16741   if ( mp->selector==term_and_log )
16742    if ( mp->internal[mp_tracing_online]<=0 ) {
16743     mp->selector=term_only;
16744     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16745     mp->selector=term_and_log;
16746   };
16747   switch (t) {
16748   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16749   case mp_path_type:mp_print_path(mp, v,"",false); break;
16750   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16751   } /* there are no other cases */
16752 }
16753
16754 @ @<Declare the procedure called |print_dp|@>=
16755 void mp_print_dp (MP mp,small_number t, pointer p, 
16756                   small_number verbosity)  {
16757   pointer q; /* the node following |p| */
16758   q=link(p);
16759   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16760   else mp_print(mp, "linearform");
16761 }
16762
16763 @ The displayed name of a variable in a ring will not be a capsule unless
16764 the ring consists entirely of capsules.
16765
16766 @<Display a variable that's been declared but not defined@>=
16767 { mp_print_type(mp, t);
16768 if ( v!=null )
16769   { mp_print_char(mp, ' ');
16770   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16771   mp_print_variable_name(mp, v);
16772   };
16773 }
16774
16775 @ When errors are detected during parsing, it is often helpful to
16776 display an expression just above the error message, using |exp_err|
16777 or |disp_err| instead of |print_err|.
16778
16779 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16780
16781 @<Declare subroutines for printing expressions@>=
16782 void mp_disp_err (MP mp,pointer p, char *s) { 
16783   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16784   mp_print_nl(mp, ">> ");
16785 @.>>@>
16786   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16787   if (strlen(s)) { 
16788     mp_print_nl(mp, "! "); mp_print(mp, s);
16789 @.!\relax@>
16790   }
16791 }
16792
16793 @ If |cur_type| and |cur_exp| contain relevant information that should
16794 be recycled, we will use the following procedure, which changes |cur_type|
16795 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16796 and |cur_exp| as either alive or dormant after this has been done,
16797 because |cur_exp| will not contain a pointer value.
16798
16799 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16800   switch (mp->cur_type) {
16801   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16802   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16803     mp_recycle_value(mp, mp->cur_exp); 
16804     mp_free_node(mp, mp->cur_exp,value_node_size);
16805     break;
16806   case mp_string_type:
16807     delete_str_ref(mp->cur_exp); break;
16808   case mp_pen_type: case mp_path_type: 
16809     mp_toss_knot_list(mp, mp->cur_exp); break;
16810   case mp_picture_type:
16811     delete_edge_ref(mp->cur_exp); break;
16812   default: 
16813     break;
16814   }
16815   mp->cur_type=mp_known; mp->cur_exp=v;
16816 }
16817
16818 @ There's a much more general procedure that is capable of releasing
16819 the storage associated with any two-word value packet.
16820
16821 @<Declare the recycling subroutines@>=
16822 void mp_recycle_value (MP mp,pointer p) ;
16823
16824 @ @c void mp_recycle_value (MP mp,pointer p) {
16825   small_number t; /* a type code */
16826   integer vv; /* another value */
16827   pointer q,r,s,pp; /* link manipulation registers */
16828   integer v=0; /* a value */
16829   t=type(p);
16830   if ( t<mp_dependent ) v=value(p);
16831   switch (t) {
16832   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16833   case mp_numeric_type:
16834     break;
16835   case unknown_types:
16836     mp_ring_delete(mp, p); break;
16837   case mp_string_type:
16838     delete_str_ref(v); break;
16839   case mp_path_type: case mp_pen_type:
16840     mp_toss_knot_list(mp, v); break;
16841   case mp_picture_type:
16842     delete_edge_ref(v); break;
16843   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16844   case mp_transform_type:
16845     @<Recycle a big node@>; break; 
16846   case mp_dependent: case mp_proto_dependent:
16847     @<Recycle a dependency list@>; break;
16848   case mp_independent:
16849     @<Recycle an independent variable@>; break;
16850   case mp_token_list: case mp_structured:
16851     mp_confusion(mp, "recycle"); break;
16852 @:this can't happen recycle}{\quad recycle@>
16853   case mp_unsuffixed_macro: case mp_suffixed_macro:
16854     mp_delete_mac_ref(mp, value(p)); break;
16855   } /* there are no other cases */
16856   type(p)=undefined;
16857 }
16858
16859 @ @<Recycle a big node@>=
16860 if ( v!=null ){ 
16861   q=v+mp->big_node_size[t];
16862   do {  
16863     q=q-2; mp_recycle_value(mp, q);
16864   } while (q!=v);
16865   mp_free_node(mp, v,mp->big_node_size[t]);
16866 }
16867
16868 @ @<Recycle a dependency list@>=
16869
16870   q=dep_list(p);
16871   while ( info(q)!=null ) q=link(q);
16872   link(prev_dep(p))=link(q);
16873   prev_dep(link(q))=prev_dep(p);
16874   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16875 }
16876
16877 @ When an independent variable disappears, it simply fades away, unless
16878 something depends on it. In the latter case, a dependent variable whose
16879 coefficient of dependence is maximal will take its place.
16880 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16881 as part of his Ph.D. thesis (Stanford University, December 1982).
16882 @^Zabala Salelles, Ignacio Andres@>
16883
16884 For example, suppose that variable $x$ is being recycled, and that the
16885 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16886 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16887 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16888 we will print `\.{\#\#\# -2x=-y+a}'.
16889
16890 There's a slight complication, however: An independent variable $x$
16891 can occur both in dependency lists and in proto-dependency lists.
16892 This makes it necessary to be careful when deciding which coefficient
16893 is maximal.
16894
16895 Furthermore, this complication is not so slight when
16896 a proto-dependent variable is chosen to become independent. For example,
16897 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16898 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16899 large coefficient `50'.
16900
16901 In order to deal with these complications without wasting too much time,
16902 we shall link together the occurrences of~$x$ among all the linear
16903 dependencies, maintaining separate lists for the dependent and
16904 proto-dependent cases.
16905
16906 @<Recycle an independent variable@>=
16907
16908   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16909   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16910   q=link(dep_head);
16911   while ( q!=dep_head ) { 
16912     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16913     while (1) { 
16914       r=link(s);
16915       if ( info(r)==null ) break;;
16916       if ( info(r)!=p ) { 
16917        s=r;
16918       } else  { 
16919         t=type(q); link(s)=link(r); info(r)=q;
16920         if ( abs(value(r))>mp->max_c[t] ) {
16921           @<Record a new maximum coefficient of type |t|@>;
16922         } else { 
16923           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16924         }
16925       }
16926     }   
16927     q=link(r);
16928   }
16929   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16930     @<Choose a dependent variable to take the place of the disappearing
16931     independent variable, and change all remaining dependencies
16932     accordingly@>;
16933   }
16934 }
16935
16936 @ The code for independency removal makes use of three two-word arrays.
16937
16938 @<Glob...@>=
16939 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16940 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16941 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16942
16943 @ @<Record a new maximum coefficient...@>=
16944
16945   if ( mp->max_c[t]>0 ) {
16946     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16947   }
16948   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16949 }
16950
16951 @ @<Choose a dependent...@>=
16952
16953   if ( (mp->max_c[mp_dependent] / 010000 >= mp->max_c[mp_proto_dependent]) )
16954     t=mp_dependent;
16955   else 
16956     t=mp_proto_dependent;
16957   @<Determine the dependency list |s| to substitute for the independent
16958     variable~|p|@>;
16959   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16960   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16961     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16962   }
16963   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16964   else { @<Substitute new proto-dependencies in place of |p|@>;}
16965   mp_flush_node_list(mp, s);
16966   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16967   check_arith;
16968 }
16969
16970 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16971 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16972 whose dependency list we have removed node~|s|. We must reinsert
16973 node~|s| into the dependency list, with coefficient $-1.0$, and with
16974 |pp| as the new independent variable. Since |pp| will have a larger serial
16975 number than any other variable, we can put node |s| at the head of the
16976 list.
16977
16978 @<Determine the dep...@>=
16979 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16980 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16981 r=dep_list(pp); link(s)=r;
16982 while ( info(r)!=null ) r=link(r);
16983 q=link(r); link(r)=null;
16984 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16985 new_indep(pp);
16986 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16987 if ( mp->internal[mp_tracing_equations]>0 ) { 
16988   @<Show the transformed dependency@>; 
16989 }
16990
16991 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16992 by the dependency list~|s|.
16993
16994 @<Show the transformed...@>=
16995 if ( mp_interesting(mp, p) ) {
16996   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16997 @:]]]\#\#\#_}{\.{\#\#\#}@>
16998   if ( v>0 ) mp_print_char(mp, '-');
16999   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17000   else vv=mp->max_c[mp_proto_dependent];
17001   if ( vv!=unity ) mp_print_scaled(mp, vv);
17002   mp_print_variable_name(mp, p);
17003   while ( value(p) % s_scale>0 ) {
17004     mp_print(mp, "*4"); value(p)=value(p)-2;
17005   }
17006   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
17007   mp_print_dependency(mp, s,t);
17008   mp_end_diagnostic(mp, false);
17009 }
17010
17011 @ Finally, there are dependent and proto-dependent variables whose
17012 dependency lists must be brought up to date.
17013
17014 @<Substitute new dependencies...@>=
17015 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17016   r=mp->max_link[t];
17017   while ( r!=null ) {
17018     q=info(r);
17019     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17020      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17021     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17022     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17023   }
17024 }
17025
17026 @ @<Substitute new proto...@>=
17027 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17028   r=mp->max_link[t];
17029   while ( r!=null ) {
17030     q=info(r);
17031     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17032       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17033         mp->cur_type=mp_proto_dependent;
17034       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,mp_dependent,mp_proto_dependent);
17035       type(q)=mp_proto_dependent; value(r)=mp_round_fraction(mp, value(r));
17036     }
17037     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17038       mp_make_scaled(mp, value(r),-v),s,mp_proto_dependent,mp_proto_dependent);
17039     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17040     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17041   }
17042 }
17043
17044 @ Here are some routines that provide handy combinations of actions
17045 that are often needed during error recovery. For example,
17046 `|flush_error|' flushes the current expression, replaces it by
17047 a given value, and calls |error|.
17048
17049 Errors often are detected after an extra token has already been scanned.
17050 The `\\{put\_get}' routines put that token back before calling |error|;
17051 then they get it back again. (Or perhaps they get another token, if
17052 the user has changed things.)
17053
17054 @<Declarations@>=
17055 void mp_flush_error (MP mp,scaled v);
17056 void mp_put_get_error (MP mp);
17057 void mp_put_get_flush_error (MP mp,scaled v) ;
17058
17059 @ @c
17060 void mp_flush_error (MP mp,scaled v) { 
17061   mp_error(mp); mp_flush_cur_exp(mp, v); 
17062 }
17063 void mp_put_get_error (MP mp) { 
17064   mp_back_error(mp); mp_get_x_next(mp); 
17065 }
17066 void mp_put_get_flush_error (MP mp,scaled v) { 
17067   mp_put_get_error(mp);
17068   mp_flush_cur_exp(mp, v); 
17069 }
17070
17071 @ A global variable |var_flag| is set to a special command code
17072 just before \MP\ calls |scan_expression|, if the expression should be
17073 treated as a variable when this command code immediately follows. For
17074 example, |var_flag| is set to |assignment| at the beginning of a
17075 statement, because we want to know the {\sl location\/} of a variable at
17076 the left of `\.{:=}', not the {\sl value\/} of that variable.
17077
17078 The |scan_expression| subroutine calls |scan_tertiary|,
17079 which calls |scan_secondary|, which calls |scan_primary|, which sets
17080 |var_flag:=0|. In this way each of the scanning routines ``knows''
17081 when it has been called with a special |var_flag|, but |var_flag| is
17082 usually zero.
17083
17084 A variable preceding a command that equals |var_flag| is converted to a
17085 token list rather than a value. Furthermore, an `\.{=}' sign following an
17086 expression with |var_flag=assignment| is not considered to be a relation
17087 that produces boolean expressions.
17088
17089
17090 @<Glob...@>=
17091 int var_flag; /* command that wants a variable */
17092
17093 @ @<Set init...@>=
17094 mp->var_flag=0;
17095
17096 @* \[37] Parsing primary expressions.
17097 The first parsing routine, |scan_primary|, is also the most complicated one,
17098 since it involves so many different cases. But each case---with one
17099 exception---is fairly simple by itself.
17100
17101 When |scan_primary| begins, the first token of the primary to be scanned
17102 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17103 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17104 earlier. If |cur_cmd| is not between |min_primary_command| and
17105 |max_primary_command|, inclusive, a syntax error will be signaled.
17106
17107 @<Declare the basic parsing subroutines@>=
17108 void mp_scan_primary (MP mp) {
17109   pointer p,q,r; /* for list manipulation */
17110   quarterword c; /* a primitive operation code */
17111   int my_var_flag; /* initial value of |my_var_flag| */
17112   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17113   @<Other local variables for |scan_primary|@>;
17114   my_var_flag=mp->var_flag; mp->var_flag=0;
17115 RESTART:
17116   check_arith;
17117   @<Supply diagnostic information, if requested@>;
17118   switch (mp->cur_cmd) {
17119   case left_delimiter:
17120     @<Scan a delimited primary@>; break;
17121   case begin_group:
17122     @<Scan a grouped primary@>; break;
17123   case string_token:
17124     @<Scan a string constant@>; break;
17125   case numeric_token:
17126     @<Scan a primary that starts with a numeric token@>; break;
17127   case nullary:
17128     @<Scan a nullary operation@>; break;
17129   case unary: case type_name: case cycle: case plus_or_minus:
17130     @<Scan a unary operation@>; break;
17131   case primary_binary:
17132     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17133   case str_op:
17134     @<Convert a suffix to a string@>; break;
17135   case internal_quantity:
17136     @<Scan an internal numeric quantity@>; break;
17137   case capsule_token:
17138     mp_make_exp_copy(mp, mp->cur_mod); break;
17139   case tag_token:
17140     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17141   default: 
17142     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17143 @.A primary expression...@>
17144   }
17145   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17146 DONE: 
17147   if ( mp->cur_cmd==left_bracket ) {
17148     if ( mp->cur_type>=mp_known ) {
17149       @<Scan a mediation construction@>;
17150     }
17151   }
17152 }
17153
17154
17155
17156 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17157
17158 @c void mp_bad_exp (MP mp,char * s) {
17159   int save_flag;
17160   print_err(s); mp_print(mp, " expression can't begin with `");
17161   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17162   mp_print_char(mp, '\'');
17163   help4("I'm afraid I need some sort of value in order to continue,")
17164     ("so I've tentatively inserted `0'. You may want to")
17165     ("delete this zero and insert something else;")
17166     ("see Chapter 27 of The METAFONTbook for an example.");
17167 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17168   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17169   mp->cur_mod=0; mp_ins_error(mp);
17170   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17171   mp->var_flag=save_flag;
17172 }
17173
17174 @ @<Supply diagnostic information, if requested@>=
17175 #ifdef DEBUG
17176 if ( mp->panicking ) mp_check_mem(mp, false);
17177 #endif
17178 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17179   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17180 }
17181
17182 @ @<Scan a delimited primary@>=
17183
17184   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17185   mp_get_x_next(mp); mp_scan_expression(mp);
17186   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17187     @<Scan the rest of a delimited set of numerics@>;
17188   } else {
17189     mp_check_delimiter(mp, l_delim,r_delim);
17190   }
17191 }
17192
17193 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17194 within a ``big node.''
17195
17196 @c void mp_stash_in (MP mp,pointer p) {
17197   pointer q; /* temporary register */
17198   type(p)=mp->cur_type;
17199   if ( mp->cur_type==mp_known ) {
17200     value(p)=mp->cur_exp;
17201   } else { 
17202     if ( mp->cur_type==mp_independent ) {
17203       @<Stash an independent |cur_exp| into a big node@>;
17204     } else { 
17205       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17206       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17207       link(prev_dep(p))=p;
17208     }
17209     mp_free_node(mp, mp->cur_exp,value_node_size);
17210   }
17211   mp->cur_type=mp_vacuous;
17212 }
17213
17214 @ In rare cases the current expression can become |independent|. There
17215 may be many dependency lists pointing to such an independent capsule,
17216 so we can't simply move it into place within a big node. Instead,
17217 we copy it, then recycle it.
17218
17219 @ @<Stash an independent |cur_exp|...@>=
17220
17221   q=mp_single_dependency(mp, mp->cur_exp);
17222   if ( q==mp->dep_final ){ 
17223     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17224   } else { 
17225     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17226   }
17227   mp_recycle_value(mp, mp->cur_exp);
17228 }
17229
17230 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17231 are synonymous with |x_part_loc| and |y_part_loc|.
17232
17233 @<Scan the rest of a delimited set of numerics@>=
17234
17235 p=mp_stash_cur_exp(mp);
17236 mp_get_x_next(mp); mp_scan_expression(mp);
17237 @<Make sure the second part of a pair or color has a numeric type@>;
17238 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17239 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17240 else type(q)=mp_pair_type;
17241 mp_init_big_node(mp, q); r=value(q);
17242 mp_stash_in(mp, y_part_loc(r));
17243 mp_unstash_cur_exp(mp, p);
17244 mp_stash_in(mp, x_part_loc(r));
17245 if ( mp->cur_cmd==comma ) {
17246   @<Scan the last of a triplet of numerics@>;
17247 }
17248 if ( mp->cur_cmd==comma ) {
17249   type(q)=mp_cmykcolor_type;
17250   mp_init_big_node(mp, q); t=value(q);
17251   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17252   value(cyan_part_loc(t))=value(red_part_loc(r));
17253   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17254   value(magenta_part_loc(t))=value(green_part_loc(r));
17255   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17256   value(yellow_part_loc(t))=value(blue_part_loc(r));
17257   mp_recycle_value(mp, r);
17258   r=t;
17259   @<Scan the last of a quartet of numerics@>;
17260 }
17261 mp_check_delimiter(mp, l_delim,r_delim);
17262 mp->cur_type=type(q);
17263 mp->cur_exp=q;
17264 }
17265
17266 @ @<Make sure the second part of a pair or color has a numeric type@>=
17267 if ( mp->cur_type<mp_known ) {
17268   exp_err("Nonnumeric ypart has been replaced by 0");
17269 @.Nonnumeric...replaced by 0@>
17270   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17271     ("but after finding a nice `a' I found a `b' that isn't")
17272     ("of numeric type. So I've changed that part to zero.")
17273     ("(The b that I didn't like appears above the error message.)");
17274   mp_put_get_flush_error(mp, 0);
17275 }
17276
17277 @ @<Scan the last of a triplet of numerics@>=
17278
17279   mp_get_x_next(mp); mp_scan_expression(mp);
17280   if ( mp->cur_type<mp_known ) {
17281     exp_err("Nonnumeric third part has been replaced by 0");
17282 @.Nonnumeric...replaced by 0@>
17283     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17284       ("isn't of numeric type. So I've changed that part to zero.")
17285       ("(The c that I didn't like appears above the error message.)");
17286     mp_put_get_flush_error(mp, 0);
17287   }
17288   mp_stash_in(mp, blue_part_loc(r));
17289 }
17290
17291 @ @<Scan the last of a quartet of numerics@>=
17292
17293   mp_get_x_next(mp); mp_scan_expression(mp);
17294   if ( mp->cur_type<mp_known ) {
17295     exp_err("Nonnumeric blackpart has been replaced by 0");
17296 @.Nonnumeric...replaced by 0@>
17297     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17298       ("of numeric type. So I've changed that part to zero.")
17299       ("(The k that I didn't like appears above the error message.)");
17300     mp_put_get_flush_error(mp, 0);
17301   }
17302   mp_stash_in(mp, black_part_loc(r));
17303 }
17304
17305 @ The local variable |group_line| keeps track of the line
17306 where a \&{begingroup} command occurred; this will be useful
17307 in an error message if the group doesn't actually end.
17308
17309 @<Other local variables for |scan_primary|@>=
17310 integer group_line; /* where a group began */
17311
17312 @ @<Scan a grouped primary@>=
17313
17314   group_line=mp_true_line(mp);
17315   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17316   save_boundary_item(p);
17317   do {  
17318     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17319   } while (! (mp->cur_cmd!=semicolon));
17320   if ( mp->cur_cmd!=end_group ) {
17321     print_err("A group begun on line ");
17322 @.A group...never ended@>
17323     mp_print_int(mp, group_line);
17324     mp_print(mp, " never ended");
17325     help2("I saw a `begingroup' back there that hasn't been matched")
17326          ("by `endgroup'. So I've inserted `endgroup' now.");
17327     mp_back_error(mp); mp->cur_cmd=end_group;
17328   }
17329   mp_unsave(mp); 
17330     /* this might change |cur_type|, if independent variables are recycled */
17331   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17332 }
17333
17334 @ @<Scan a string constant@>=
17335
17336   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17337 }
17338
17339 @ Later we'll come to procedures that perform actual operations like
17340 addition, square root, and so on; our purpose now is to do the parsing.
17341 But we might as well mention those future procedures now, so that the
17342 suspense won't be too bad:
17343
17344 \smallskip
17345 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17346 `\&{true}' or `\&{pencircle}');
17347
17348 \smallskip
17349 |do_unary(c)| applies a primitive operation to the current expression;
17350
17351 \smallskip
17352 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17353 and the current expression.
17354
17355 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17356
17357 @ @<Scan a unary operation@>=
17358
17359   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17360   mp_do_unary(mp, c); goto DONE;
17361 }
17362
17363 @ A numeric token might be a primary by itself, or it might be the
17364 numerator of a fraction composed solely of numeric tokens, or it might
17365 multiply the primary that follows (provided that the primary doesn't begin
17366 with a plus sign or a minus sign). The code here uses the facts that
17367 |max_primary_command=plus_or_minus| and
17368 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17369 than unity, we try to retain higher precision when we use it in scalar
17370 multiplication.
17371
17372 @<Other local variables for |scan_primary|@>=
17373 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17374
17375 @ @<Scan a primary that starts with a numeric token@>=
17376
17377   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17378   if ( mp->cur_cmd!=slash ) { 
17379     num=0; denom=0;
17380   } else { 
17381     mp_get_x_next(mp);
17382     if ( mp->cur_cmd!=numeric_token ) { 
17383       mp_back_input(mp);
17384       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17385       goto DONE;
17386     }
17387     num=mp->cur_exp; denom=mp->cur_mod;
17388     if ( denom==0 ) { @<Protest division by zero@>; }
17389     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17390     check_arith; mp_get_x_next(mp);
17391   }
17392   if ( mp->cur_cmd>=min_primary_command ) {
17393    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17394      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17395      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17396        mp_do_binary(mp, p,times);
17397      } else {
17398        mp_frac_mult(mp, num,denom);
17399        mp_free_node(mp, p,value_node_size);
17400      }
17401     }
17402   }
17403   goto DONE;
17404 }
17405
17406 @ @<Protest division...@>=
17407
17408   print_err("Division by zero");
17409 @.Division by zero@>
17410   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17411 }
17412
17413 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17414
17415   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17416   if ( mp->cur_cmd!=of_token ) {
17417     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17418     mp_print_cmd_mod(mp, primary_binary,c);
17419 @.Missing `of'@>
17420     help1("I've got the first argument; will look now for the other.");
17421     mp_back_error(mp);
17422   }
17423   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17424   mp_do_binary(mp, p,c); goto DONE;
17425 }
17426
17427 @ @<Convert a suffix to a string@>=
17428
17429   mp_get_x_next(mp); mp_scan_suffix(mp); 
17430   mp->old_setting=mp->selector; mp->selector=new_string;
17431   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17432   mp_flush_token_list(mp, mp->cur_exp);
17433   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17434   mp->cur_type=mp_string_type;
17435   goto DONE;
17436 }
17437
17438 @ If an internal quantity appears all by itself on the left of an
17439 assignment, we return a token list of length one, containing the address
17440 of the internal quantity plus |hash_end|. (This accords with the conventions
17441 of the save stack, as described earlier.)
17442
17443 @<Scan an internal...@>=
17444
17445   q=mp->cur_mod;
17446   if ( my_var_flag==assignment ) {
17447     mp_get_x_next(mp);
17448     if ( mp->cur_cmd==assignment ) {
17449       mp->cur_exp=mp_get_avail(mp);
17450       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17451       goto DONE;
17452     }
17453     mp_back_input(mp);
17454   }
17455   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17456 }
17457
17458 @ The most difficult part of |scan_primary| has been saved for last, since
17459 it was necessary to build up some confidence first. We can now face the task
17460 of scanning a variable.
17461
17462 As we scan a variable, we build a token list containing the relevant
17463 names and subscript values, simultaneously following along in the
17464 ``collective'' structure to see if we are actually dealing with a macro
17465 instead of a value.
17466
17467 The local variables |pre_head| and |post_head| will point to the beginning
17468 of the prefix and suffix lists; |tail| will point to the end of the list
17469 that is currently growing.
17470
17471 Another local variable, |tt|, contains partial information about the
17472 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17473 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17474 doesn't bother to update its information about type. And if
17475 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17476
17477 @ @<Other local variables for |scan_primary|@>=
17478 pointer pre_head,post_head,tail;
17479   /* prefix and suffix list variables */
17480 small_number tt; /* approximation to the type of the variable-so-far */
17481 pointer t; /* a token */
17482 pointer macro_ref = 0; /* reference count for a suffixed macro */
17483
17484 @ @<Scan a variable primary...@>=
17485
17486   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17487   while (1) { 
17488     t=mp_cur_tok(mp); link(tail)=t;
17489     if ( tt!=undefined ) {
17490        @<Find the approximate type |tt| and corresponding~|q|@>;
17491       if ( tt>=mp_unsuffixed_macro ) {
17492         @<Either begin an unsuffixed macro call or
17493           prepare for a suffixed one@>;
17494       }
17495     }
17496     mp_get_x_next(mp); tail=t;
17497     if ( mp->cur_cmd==left_bracket ) {
17498       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17499     }
17500     if ( mp->cur_cmd>max_suffix_token ) break;
17501     if ( mp->cur_cmd<min_suffix_token ) break;
17502   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17503   @<Handle unusual cases that masquerade as variables, and |goto restart|
17504     or |goto done| if appropriate;
17505     otherwise make a copy of the variable and |goto done|@>;
17506 }
17507
17508 @ @<Either begin an unsuffixed macro call or...@>=
17509
17510   link(tail)=null;
17511   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17512     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17513     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17514   } else {
17515     @<Set up unsuffixed macro call and |goto restart|@>;
17516   }
17517 }
17518
17519 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17520
17521   mp_get_x_next(mp); mp_scan_expression(mp);
17522   if ( mp->cur_cmd!=right_bracket ) {
17523     @<Put the left bracket and the expression back to be rescanned@>;
17524   } else { 
17525     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17526     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17527   }
17528 }
17529
17530 @ The left bracket that we thought was introducing a subscript might have
17531 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17532 So we don't issue an error message at this point; but we do want to back up
17533 so as to avoid any embarrassment about our incorrect assumption.
17534
17535 @<Put the left bracket and the expression back to be rescanned@>=
17536
17537   mp_back_input(mp); /* that was the token following the current expression */
17538   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17539   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17540 }
17541
17542 @ Here's a routine that puts the current expression back to be read again.
17543
17544 @c void mp_back_expr (MP mp) {
17545   pointer p; /* capsule token */
17546   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17547 }
17548
17549 @ Unknown subscripts lead to the following error message.
17550
17551 @c void mp_bad_subscript (MP mp) { 
17552   exp_err("Improper subscript has been replaced by zero");
17553 @.Improper subscript...@>
17554   help3("A bracketed subscript must have a known numeric value;")
17555     ("unfortunately, what I found was the value that appears just")
17556     ("above this error message. So I'll try a zero subscript.");
17557   mp_flush_error(mp, 0);
17558 }
17559
17560 @ Every time we call |get_x_next|, there's a chance that the variable we've
17561 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17562 into the variable structure; we need to start searching from the root each time.
17563
17564 @<Find the approximate type |tt| and corresponding~|q|@>=
17565 @^inner loop@>
17566
17567   p=link(pre_head); q=info(p); tt=undefined;
17568   if ( eq_type(q) % outer_tag==tag_token ) {
17569     q=equiv(q);
17570     if ( q==null ) goto DONE2;
17571     while (1) { 
17572       p=link(p);
17573       if ( p==null ) {
17574         tt=type(q); goto DONE2;
17575       };
17576       if ( type(q)!=mp_structured ) goto DONE2;
17577       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17578       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17579         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17580         if ( attr_loc(q)>info(p) ) goto DONE2;
17581       }
17582     }
17583   }
17584 DONE2:
17585   ;
17586 }
17587
17588 @ How do things stand now? Well, we have scanned an entire variable name,
17589 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17590 |cur_sym| represent the token that follows. If |post_head=null|, a
17591 token list for this variable name starts at |link(pre_head)|, with all
17592 subscripts evaluated. But if |post_head<>null|, the variable turned out
17593 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17594 |post_head| is the head of a token list containing both `\.{\AT!}' and
17595 the suffix.
17596
17597 Our immediate problem is to see if this variable still exists. (Variable
17598 structures can change drastically whenever we call |get_x_next|; users
17599 aren't supposed to do this, but the fact that it is possible means that
17600 we must be cautious.)
17601
17602 The following procedure prints an error message when a variable
17603 unexpectedly disappears. Its help message isn't quite right for
17604 our present purposes, but we'll be able to fix that up.
17605
17606 @c 
17607 void mp_obliterated (MP mp,pointer q) { 
17608   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17609   mp_print(mp, " has been obliterated");
17610 @.Variable...obliterated@>
17611   help5("It seems you did a nasty thing---probably by accident,")
17612     ("but nevertheless you nearly hornswoggled me...")
17613     ("While I was evaluating the right-hand side of this")
17614     ("command, something happened, and the left-hand side")
17615     ("is no longer a variable! So I won't change anything.");
17616 }
17617
17618 @ If the variable does exist, we also need to check
17619 for a few other special cases before deciding that a plain old ordinary
17620 variable has, indeed, been scanned.
17621
17622 @<Handle unusual cases that masquerade as variables...@>=
17623 if ( post_head!=null ) {
17624   @<Set up suffixed macro call and |goto restart|@>;
17625 }
17626 q=link(pre_head); free_avail(pre_head);
17627 if ( mp->cur_cmd==my_var_flag ) { 
17628   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17629 }
17630 p=mp_find_variable(mp, q);
17631 if ( p!=null ) {
17632   mp_make_exp_copy(mp, p);
17633 } else { 
17634   mp_obliterated(mp, q);
17635   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17636   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17637   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17638   mp_put_get_flush_error(mp, 0);
17639 }
17640 mp_flush_node_list(mp, q); 
17641 goto DONE
17642
17643 @ The only complication associated with macro calling is that the prefix
17644 and ``at'' parameters must be packaged in an appropriate list of lists.
17645
17646 @<Set up unsuffixed macro call and |goto restart|@>=
17647
17648   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17649   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17650   mp_get_x_next(mp); 
17651   goto RESTART;
17652 }
17653
17654 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17655 we don't care, because we have reserved a pointer (|macro_ref|) to its
17656 token list.
17657
17658 @<Set up suffixed macro call and |goto restart|@>=
17659
17660   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17661   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17662   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17663   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17664   mp_get_x_next(mp); goto RESTART;
17665 }
17666
17667 @ Our remaining job is simply to make a copy of the value that has been
17668 found. Some cases are harder than others, but complexity arises solely
17669 because of the multiplicity of possible cases.
17670
17671 @<Declare the procedure called |make_exp_copy|@>=
17672 @<Declare subroutines needed by |make_exp_copy|@>;
17673 void mp_make_exp_copy (MP mp,pointer p) {
17674   pointer q,r,t; /* registers for list manipulation */
17675 RESTART: 
17676   mp->cur_type=type(p);
17677   switch (mp->cur_type) {
17678   case mp_vacuous: case mp_boolean_type: case mp_known:
17679     mp->cur_exp=value(p); break;
17680   case unknown_types:
17681     mp->cur_exp=mp_new_ring_entry(mp, p);
17682     break;
17683   case mp_string_type: 
17684     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17685     break;
17686   case mp_picture_type:
17687     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17688     break;
17689   case mp_pen_type:
17690     mp->cur_exp=copy_pen(value(p));
17691     break; 
17692   case mp_path_type:
17693     mp->cur_exp=mp_copy_path(mp, value(p));
17694     break;
17695   case mp_transform_type: case mp_color_type: 
17696   case mp_cmykcolor_type: case mp_pair_type:
17697     @<Copy the big node |p|@>;
17698     break;
17699   case mp_dependent: case mp_proto_dependent:
17700     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17701     break;
17702   case mp_numeric_type: 
17703     new_indep(p); goto RESTART;
17704     break;
17705   case mp_independent: 
17706     q=mp_single_dependency(mp, p);
17707     if ( q==mp->dep_final ){ 
17708       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,value_node_size);
17709     } else { 
17710       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17711     }
17712     break;
17713   default: 
17714     mp_confusion(mp, "copy");
17715 @:this can't happen copy}{\quad copy@>
17716     break;
17717   }
17718 }
17719
17720 @ The |encapsulate| subroutine assumes that |dep_final| is the
17721 tail of dependency list~|p|.
17722
17723 @<Declare subroutines needed by |make_exp_copy|@>=
17724 void mp_encapsulate (MP mp,pointer p) { 
17725   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17726   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17727 }
17728
17729 @ The most tedious case arises when the user refers to a
17730 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17731 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17732 or |known|.
17733
17734 @<Copy the big node |p|@>=
17735
17736   if ( value(p)==null ) 
17737     mp_init_big_node(mp, p);
17738   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17739   mp_init_big_node(mp, t);
17740   q=value(p)+mp->big_node_size[mp->cur_type]; 
17741   r=value(t)+mp->big_node_size[mp->cur_type];
17742   do {  
17743     q=q-2; r=r-2; mp_install(mp, r,q);
17744   } while (q!=value(p));
17745   mp->cur_exp=t;
17746 }
17747
17748 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17749 a big node that will be part of a capsule.
17750
17751 @<Declare subroutines needed by |make_exp_copy|@>=
17752 void mp_install (MP mp,pointer r, pointer q) {
17753   pointer p; /* temporary register */
17754   if ( type(q)==mp_known ){ 
17755     value(r)=value(q); type(r)=mp_known;
17756   } else  if ( type(q)==mp_independent ) {
17757     p=mp_single_dependency(mp, q);
17758     if ( p==mp->dep_final ) {
17759       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,value_node_size);
17760     } else  { 
17761       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17762     }
17763   } else {
17764     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17765   }
17766 }
17767
17768 @ Expressions of the form `\.{a[b,c]}' are converted into
17769 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17770 provided that \.a is numeric.
17771
17772 @<Scan a mediation...@>=
17773
17774   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17775   if ( mp->cur_cmd!=comma ) {
17776     @<Put the left bracket and the expression back...@>;
17777     mp_unstash_cur_exp(mp, p);
17778   } else { 
17779     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17780     if ( mp->cur_cmd!=right_bracket ) {
17781       mp_missing_err(mp, "]");
17782 @.Missing `]'@>
17783       help3("I've scanned an expression of the form `a[b,c',")
17784       ("so a right bracket should have come next.")
17785       ("I shall pretend that one was there.");
17786       mp_back_error(mp);
17787     }
17788     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17789     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17790     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17791   }
17792 }
17793
17794 @ Here is a comparatively simple routine that is used to scan the
17795 \&{suffix} parameters of a macro.
17796
17797 @<Declare the basic parsing subroutines@>=
17798 void mp_scan_suffix (MP mp) {
17799   pointer h,t; /* head and tail of the list being built */
17800   pointer p; /* temporary register */
17801   h=mp_get_avail(mp); t=h;
17802   while (1) { 
17803     if ( mp->cur_cmd==left_bracket ) {
17804       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17805     }
17806     if ( mp->cur_cmd==numeric_token ) {
17807       p=mp_new_num_tok(mp, mp->cur_mod);
17808     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17809        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17810     } else {
17811       break;
17812     }
17813     link(t)=p; t=p; mp_get_x_next(mp);
17814   }
17815   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17816 }
17817
17818 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17819
17820   mp_get_x_next(mp); mp_scan_expression(mp);
17821   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17822   if ( mp->cur_cmd!=right_bracket ) {
17823      mp_missing_err(mp, "]");
17824 @.Missing `]'@>
17825     help3("I've seen a `[' and a subscript value, in a suffix,")
17826       ("so a right bracket should have come next.")
17827       ("I shall pretend that one was there.");
17828     mp_back_error(mp);
17829   }
17830   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17831 }
17832
17833 @* \[38] Parsing secondary and higher expressions.
17834
17835 After the intricacies of |scan_primary|\kern-1pt,
17836 the |scan_secondary| routine is
17837 refreshingly simple. It's not trivial, but the operations are relatively
17838 straightforward; the main difficulty is, again, that expressions and data
17839 structures might change drastically every time we call |get_x_next|, so a
17840 cautious approach is mandatory. For example, a macro defined by
17841 \&{primarydef} might have disappeared by the time its second argument has
17842 been scanned; we solve this by increasing the reference count of its token
17843 list, so that the macro can be called even after it has been clobbered.
17844
17845 @<Declare the basic parsing subroutines@>=
17846 void mp_scan_secondary (MP mp) {
17847   pointer p; /* for list manipulation */
17848   halfword c,d; /* operation codes or modifiers */
17849   pointer mac_name; /* token defined with \&{primarydef} */
17850 RESTART:
17851   if ((mp->cur_cmd<min_primary_command)||
17852       (mp->cur_cmd>max_primary_command) )
17853     mp_bad_exp(mp, "A secondary");
17854 @.A secondary expression...@>
17855   mp_scan_primary(mp);
17856 CONTINUE: 
17857   if ( mp->cur_cmd<=max_secondary_command )
17858     if ( mp->cur_cmd>=min_secondary_command ) {
17859       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17860       if ( d==secondary_primary_macro ) { 
17861         mac_name=mp->cur_sym; add_mac_ref(c);
17862      }
17863      mp_get_x_next(mp); mp_scan_primary(mp);
17864      if ( d!=secondary_primary_macro ) {
17865        mp_do_binary(mp, p,c);
17866      } else  { 
17867        mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17868        decr(ref_count(c)); mp_get_x_next(mp); 
17869        goto RESTART;
17870     }
17871     goto CONTINUE;
17872   }
17873 }
17874
17875 @ The following procedure calls a macro that has two parameters,
17876 |p| and |cur_exp|.
17877
17878 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17879   pointer q,r; /* nodes in the parameter list */
17880   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17881   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17882   mp_macro_call(mp, c,q,n);
17883 }
17884
17885 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17886
17887 @<Declare the basic parsing subroutines@>=
17888 void mp_scan_tertiary (MP mp) {
17889   pointer p; /* for list manipulation */
17890   halfword c,d; /* operation codes or modifiers */
17891   pointer mac_name; /* token defined with \&{secondarydef} */
17892 RESTART:
17893   if ((mp->cur_cmd<min_primary_command)||
17894       (mp->cur_cmd>max_primary_command) )
17895     mp_bad_exp(mp, "A tertiary");
17896 @.A tertiary expression...@>
17897   mp_scan_secondary(mp);
17898 CONTINUE: 
17899   if ( mp->cur_cmd<=max_tertiary_command ) {
17900     if ( mp->cur_cmd>=min_tertiary_command ) {
17901       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17902       if ( d==tertiary_secondary_macro ) { 
17903         mac_name=mp->cur_sym; add_mac_ref(c);
17904       };
17905       mp_get_x_next(mp); mp_scan_secondary(mp);
17906       if ( d!=tertiary_secondary_macro ) {
17907         mp_do_binary(mp, p,c);
17908       } else { 
17909         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17910         decr(ref_count(c)); mp_get_x_next(mp); 
17911         goto RESTART;
17912       }
17913       goto CONTINUE;
17914     }
17915   }
17916 }
17917
17918 @ Finally we reach the deepest level in our quartet of parsing routines.
17919 This one is much like the others; but it has an extra complication from
17920 paths, which materialize here.
17921
17922 @d continue_path 25 /* a label inside of |scan_expression| */
17923 @d finish_path 26 /* another */
17924
17925 @<Declare the basic parsing subroutines@>=
17926 void mp_scan_expression (MP mp) {
17927   pointer p,q,r,pp,qq; /* for list manipulation */
17928   halfword c,d; /* operation codes or modifiers */
17929   int my_var_flag; /* initial value of |var_flag| */
17930   pointer mac_name; /* token defined with \&{tertiarydef} */
17931   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17932   scaled x,y; /* explicit coordinates or tension at a path join */
17933   int t; /* knot type following a path join */
17934   t=0; y=0; x=0;
17935   my_var_flag=mp->var_flag; mac_name=null;
17936 RESTART:
17937   if ((mp->cur_cmd<min_primary_command)||
17938       (mp->cur_cmd>max_primary_command) )
17939     mp_bad_exp(mp, "An");
17940 @.An expression...@>
17941   mp_scan_tertiary(mp);
17942 CONTINUE: 
17943   if ( mp->cur_cmd<=max_expression_command )
17944     if ( mp->cur_cmd>=min_expression_command ) {
17945       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17946         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17947         if ( d==expression_tertiary_macro ) {
17948           mac_name=mp->cur_sym; add_mac_ref(c);
17949         }
17950         if ( (d<ampersand)||((d==ampersand)&&
17951              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17952           @<Scan a path construction operation;
17953             but |return| if |p| has the wrong type@>;
17954         } else { 
17955           mp_get_x_next(mp); mp_scan_tertiary(mp);
17956           if ( d!=expression_tertiary_macro ) {
17957             mp_do_binary(mp, p,c);
17958           } else  { 
17959             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17960             decr(ref_count(c)); mp_get_x_next(mp); 
17961             goto RESTART;
17962           }
17963         }
17964         goto CONTINUE;
17965      }
17966   }
17967 }
17968
17969 @ The reader should review the data structure conventions for paths before
17970 hoping to understand the next part of this code.
17971
17972 @<Scan a path construction operation...@>=
17973
17974   cycle_hit=false;
17975   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17976     but |return| if |p| doesn't have a suitable type@>;
17977 CONTINUE_PATH: 
17978   @<Determine the path join parameters;
17979     but |goto finish_path| if there's only a direction specifier@>;
17980   if ( mp->cur_cmd==cycle ) {
17981     @<Get ready to close a cycle@>;
17982   } else { 
17983     mp_scan_tertiary(mp);
17984     @<Convert the right operand, |cur_exp|,
17985       into a partial path from |pp| to~|qq|@>;
17986   }
17987   @<Join the partial paths and reset |p| and |q| to the head and tail
17988     of the result@>;
17989   if ( mp->cur_cmd>=min_expression_command )
17990     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
17991 FINISH_PATH:
17992   @<Choose control points for the path and put the result into |cur_exp|@>;
17993 }
17994
17995 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
17996
17997   mp_unstash_cur_exp(mp, p);
17998   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
17999   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18000   else return;
18001   q=p;
18002   while ( link(q)!=p ) q=link(q);
18003   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
18004     r=mp_copy_knot(mp, p); link(q)=r; q=r;
18005   }
18006   left_type(p)=mp_open; right_type(q)=mp_open;
18007 }
18008
18009 @ A pair of numeric values is changed into a knot node for a one-point path
18010 when \MP\ discovers that the pair is part of a path.
18011
18012 @c@<Declare the procedure called |known_pair|@>;
18013 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18014   pointer q; /* the new node */
18015   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18016   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18017   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18018   return q;
18019 }
18020
18021 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18022 of the current expression, assuming that the current expression is a
18023 pair of known numerics. Unknown components are zeroed, and the
18024 current expression is flushed.
18025
18026 @<Declare the procedure called |known_pair|@>=
18027 void mp_known_pair (MP mp) {
18028   pointer p; /* the pair node */
18029   if ( mp->cur_type!=mp_pair_type ) {
18030     exp_err("Undefined coordinates have been replaced by (0,0)");
18031 @.Undefined coordinates...@>
18032     help5("I need x and y numbers for this part of the path.")
18033       ("The value I found (see above) was no good;")
18034       ("so I'll try to keep going by using zero instead.")
18035       ("(Chapter 27 of The METAFONTbook explains that")
18036 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18037       ("you might want to type `I ??" "?' now.)");
18038     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18039   } else { 
18040     p=value(mp->cur_exp);
18041      @<Make sure that both |x| and |y| parts of |p| are known;
18042        copy them into |cur_x| and |cur_y|@>;
18043     mp_flush_cur_exp(mp, 0);
18044   }
18045 }
18046
18047 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18048 if ( type(x_part_loc(p))==mp_known ) {
18049   mp->cur_x=value(x_part_loc(p));
18050 } else { 
18051   mp_disp_err(mp, x_part_loc(p),
18052     "Undefined x coordinate has been replaced by 0");
18053 @.Undefined coordinates...@>
18054   help5("I need a `known' x value for this part of the path.")
18055     ("The value I found (see above) was no good;")
18056     ("so I'll try to keep going by using zero instead.")
18057     ("(Chapter 27 of The METAFONTbook explains that")
18058 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18059     ("you might want to type `I ??" "?' now.)");
18060   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18061 }
18062 if ( type(y_part_loc(p))==mp_known ) {
18063   mp->cur_y=value(y_part_loc(p));
18064 } else { 
18065   mp_disp_err(mp, y_part_loc(p),
18066     "Undefined y coordinate has been replaced by 0");
18067   help5("I need a `known' y value for this part of the path.")
18068     ("The value I found (see above) was no good;")
18069     ("so I'll try to keep going by using zero instead.")
18070     ("(Chapter 27 of The METAFONTbook explains that")
18071     ("you might want to type `I ??" "?' now.)");
18072   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18073 }
18074
18075 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18076
18077 @<Determine the path join parameters...@>=
18078 if ( mp->cur_cmd==left_brace ) {
18079   @<Put the pre-join direction information into node |q|@>;
18080 }
18081 d=mp->cur_cmd;
18082 if ( d==path_join ) {
18083   @<Determine the tension and/or control points@>;
18084 } else if ( d!=ampersand ) {
18085   goto FINISH_PATH;
18086 }
18087 mp_get_x_next(mp);
18088 if ( mp->cur_cmd==left_brace ) {
18089   @<Put the post-join direction information into |x| and |t|@>;
18090 } else if ( right_type(q)!=mp_explicit ) {
18091   t=mp_open; x=0;
18092 }
18093
18094 @ The |scan_direction| subroutine looks at the directional information
18095 that is enclosed in braces, and also scans ahead to the following character.
18096 A type code is returned, either |open| (if the direction was $(0,0)$),
18097 or |curl| (if the direction was a curl of known value |cur_exp|), or
18098 |given| (if the direction is given by the |angle| value that now
18099 appears in |cur_exp|).
18100
18101 There's nothing difficult about this subroutine, but the program is rather
18102 lengthy because a variety of potential errors need to be nipped in the bud.
18103
18104 @c small_number mp_scan_direction (MP mp) {
18105   int t; /* the type of information found */
18106   scaled x; /* an |x| coordinate */
18107   mp_get_x_next(mp);
18108   if ( mp->cur_cmd==curl_command ) {
18109      @<Scan a curl specification@>;
18110   } else {
18111     @<Scan a given direction@>;
18112   }
18113   if ( mp->cur_cmd!=right_brace ) {
18114     mp_missing_err(mp, "}");
18115 @.Missing `\char`\}'@>
18116     help3("I've scanned a direction spec for part of a path,")
18117       ("so a right brace should have come next.")
18118       ("I shall pretend that one was there.");
18119     mp_back_error(mp);
18120   }
18121   mp_get_x_next(mp); 
18122   return t;
18123 }
18124
18125 @ @<Scan a curl specification@>=
18126 { mp_get_x_next(mp); mp_scan_expression(mp);
18127 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18128   exp_err("Improper curl has been replaced by 1");
18129 @.Improper curl@>
18130   help1("A curl must be a known, nonnegative number.");
18131   mp_put_get_flush_error(mp, unity);
18132 }
18133 t=mp_curl;
18134 }
18135
18136 @ @<Scan a given direction@>=
18137 { mp_scan_expression(mp);
18138   if ( mp->cur_type>mp_pair_type ) {
18139     @<Get given directions separated by commas@>;
18140   } else {
18141     mp_known_pair(mp);
18142   }
18143   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18144   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18145 }
18146
18147 @ @<Get given directions separated by commas@>=
18148
18149   if ( mp->cur_type!=mp_known ) {
18150     exp_err("Undefined x coordinate has been replaced by 0");
18151 @.Undefined coordinates...@>
18152     help5("I need a `known' x value for this part of the path.")
18153       ("The value I found (see above) was no good;")
18154       ("so I'll try to keep going by using zero instead.")
18155       ("(Chapter 27 of The METAFONTbook explains that")
18156 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18157       ("you might want to type `I ??" "?' now.)");
18158     mp_put_get_flush_error(mp, 0);
18159   }
18160   x=mp->cur_exp;
18161   if ( mp->cur_cmd!=comma ) {
18162     mp_missing_err(mp, ",");
18163 @.Missing `,'@>
18164     help2("I've got the x coordinate of a path direction;")
18165       ("will look for the y coordinate next.");
18166     mp_back_error(mp);
18167   }
18168   mp_get_x_next(mp); mp_scan_expression(mp);
18169   if ( mp->cur_type!=mp_known ) {
18170      exp_err("Undefined y coordinate has been replaced by 0");
18171     help5("I need a `known' y value for this part of the path.")
18172       ("The value I found (see above) was no good;")
18173       ("so I'll try to keep going by using zero instead.")
18174       ("(Chapter 27 of The METAFONTbook explains that")
18175       ("you might want to type `I ??" "?' now.)");
18176     mp_put_get_flush_error(mp, 0);
18177   }
18178   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18179 }
18180
18181 @ At this point |right_type(q)| is usually |open|, but it may have been
18182 set to some other value by a previous splicing operation. We must maintain
18183 the value of |right_type(q)| in unusual cases such as
18184 `\.{..z1\{z2\}\&\{z3\}z1\{0,0\}..}'.
18185
18186 @<Put the pre-join...@>=
18187
18188   t=mp_scan_direction(mp);
18189   if ( t!=mp_open ) {
18190     right_type(q)=t; right_given(q)=mp->cur_exp;
18191     if ( left_type(q)==mp_open ) {
18192       left_type(q)=t; left_given(q)=mp->cur_exp;
18193     } /* note that |left_given(q)=left_curl(q)| */
18194   }
18195 }
18196
18197 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18198 and since |left_given| is similarly equivalent to |left_x|, we use
18199 |x| and |y| to hold the given direction and tension information when
18200 there are no explicit control points.
18201
18202 @<Put the post-join...@>=
18203
18204   t=mp_scan_direction(mp);
18205   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18206   else t=mp_explicit; /* the direction information is superfluous */
18207 }
18208
18209 @ @<Determine the tension and/or...@>=
18210
18211   mp_get_x_next(mp);
18212   if ( mp->cur_cmd==tension ) {
18213     @<Set explicit tensions@>;
18214   } else if ( mp->cur_cmd==controls ) {
18215     @<Set explicit control points@>;
18216   } else  { 
18217     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18218     goto DONE;
18219   };
18220   if ( mp->cur_cmd!=path_join ) {
18221      mp_missing_err(mp, "..");
18222 @.Missing `..'@>
18223     help1("A path join command should end with two dots.");
18224     mp_back_error(mp);
18225   }
18226 DONE:
18227   ;
18228 }
18229
18230 @ @<Set explicit tensions@>=
18231
18232   mp_get_x_next(mp); y=mp->cur_cmd;
18233   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18234   mp_scan_primary(mp);
18235   @<Make sure that the current expression is a valid tension setting@>;
18236   if ( y==at_least ) negate(mp->cur_exp);
18237   right_tension(q)=mp->cur_exp;
18238   if ( mp->cur_cmd==and_command ) {
18239     mp_get_x_next(mp); y=mp->cur_cmd;
18240     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18241     mp_scan_primary(mp);
18242     @<Make sure that the current expression is a valid tension setting@>;
18243     if ( y==at_least ) negate(mp->cur_exp);
18244   }
18245   y=mp->cur_exp;
18246 }
18247
18248 @ @d min_tension three_quarter_unit
18249
18250 @<Make sure that the current expression is a valid tension setting@>=
18251 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18252   exp_err("Improper tension has been set to 1");
18253 @.Improper tension@>
18254   help1("The expression above should have been a number >=3/4.");
18255   mp_put_get_flush_error(mp, unity);
18256 }
18257
18258 @ @<Set explicit control points@>=
18259
18260   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18261   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18262   if ( mp->cur_cmd!=and_command ) {
18263     x=right_x(q); y=right_y(q);
18264   } else { 
18265     mp_get_x_next(mp); mp_scan_primary(mp);
18266     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18267   }
18268 }
18269
18270 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18271
18272   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18273   else pp=mp->cur_exp;
18274   qq=pp;
18275   while ( link(qq)!=pp ) qq=link(qq);
18276   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18277     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18278   }
18279   left_type(pp)=mp_open; right_type(qq)=mp_open;
18280 }
18281
18282 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18283 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18284 shouldn't have length zero.
18285
18286 @<Get ready to close a cycle@>=
18287
18288   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18289   if ( d==ampersand ) if ( p==q ) {
18290     d=path_join; right_tension(q)=unity; y=unity;
18291   }
18292 }
18293
18294 @ @<Join the partial paths and reset |p| and |q|...@>=
18295
18296 if ( d==ampersand ) {
18297   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18298     print_err("Paths don't touch; `&' will be changed to `..'");
18299 @.Paths don't touch@>
18300     help3("When you join paths `p&q', the ending point of p")
18301       ("must be exactly equal to the starting point of q.")
18302       ("So I'm going to pretend that you said `p..q' instead.");
18303     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18304   }
18305 }
18306 @<Plug an opening in |right_type(pp)|, if possible@>;
18307 if ( d==ampersand ) {
18308   @<Splice independent paths together@>;
18309 } else  { 
18310   @<Plug an opening in |right_type(q)|, if possible@>;
18311   link(q)=pp; left_y(pp)=y;
18312   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18313 }
18314 q=qq;
18315 }
18316
18317 @ @<Plug an opening in |right_type(q)|...@>=
18318 if ( right_type(q)==mp_open ) {
18319   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18320     right_type(q)=left_type(q); right_given(q)=left_given(q);
18321   }
18322 }
18323
18324 @ @<Plug an opening in |right_type(pp)|...@>=
18325 if ( right_type(pp)==mp_open ) {
18326   if ( (t==mp_curl)||(t==mp_given) ) {
18327     right_type(pp)=t; right_given(pp)=x;
18328   }
18329 }
18330
18331 @ @<Splice independent paths together@>=
18332
18333   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18334     left_type(q)=mp_curl; left_curl(q)=unity;
18335   }
18336   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18337     right_type(pp)=mp_curl; right_curl(pp)=unity;
18338   }
18339   right_type(q)=right_type(pp); link(q)=link(pp);
18340   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18341   mp_free_node(mp, pp,knot_node_size);
18342   if ( qq==pp ) qq=q;
18343 }
18344
18345 @ @<Choose control points for the path...@>=
18346 if ( cycle_hit ) { 
18347   if ( d==ampersand ) p=q;
18348 } else  { 
18349   left_type(p)=mp_endpoint;
18350   if ( right_type(p)==mp_open ) { 
18351     right_type(p)=mp_curl; right_curl(p)=unity;
18352   }
18353   right_type(q)=mp_endpoint;
18354   if ( left_type(q)==mp_open ) { 
18355     left_type(q)=mp_curl; left_curl(q)=unity;
18356   }
18357   link(q)=p;
18358 }
18359 mp_make_choices(mp, p);
18360 mp->cur_type=mp_path_type; mp->cur_exp=p
18361
18362 @ Finally, we sometimes need to scan an expression whose value is
18363 supposed to be either |true_code| or |false_code|.
18364
18365 @<Declare the basic parsing subroutines@>=
18366 void mp_get_boolean (MP mp) { 
18367   mp_get_x_next(mp); mp_scan_expression(mp);
18368   if ( mp->cur_type!=mp_boolean_type ) {
18369     exp_err("Undefined condition will be treated as `false'");
18370 @.Undefined condition...@>
18371     help2("The expression shown above should have had a definite")
18372       ("true-or-false value. I'm changing it to `false'.");
18373     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18374   }
18375 }
18376
18377 @* \[39] Doing the operations.
18378 The purpose of parsing is primarily to permit people to avoid piles of
18379 parentheses. But the real work is done after the structure of an expression
18380 has been recognized; that's when new expressions are generated. We
18381 turn now to the guts of \MP, which handles individual operators that
18382 have come through the parsing mechanism.
18383
18384 We'll start with the easy ones that take no operands, then work our way
18385 up to operators with one and ultimately two arguments. In other words,
18386 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18387 that are invoked periodically by the expression scanners.
18388
18389 First let's make sure that all of the primitive operators are in the
18390 hash table. Although |scan_primary| and its relatives made use of the
18391 \\{cmd} code for these operators, the \\{do} routines base everything
18392 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18393 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18394
18395 @<Put each...@>=
18396 mp_primitive(mp, "true",nullary,true_code);
18397 @:true_}{\&{true} primitive@>
18398 mp_primitive(mp, "false",nullary,false_code);
18399 @:false_}{\&{false} primitive@>
18400 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18401 @:null_picture_}{\&{nullpicture} primitive@>
18402 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18403 @:null_pen_}{\&{nullpen} primitive@>
18404 mp_primitive(mp, "jobname",nullary,job_name_op);
18405 @:job_name_}{\&{jobname} primitive@>
18406 mp_primitive(mp, "readstring",nullary,read_string_op);
18407 @:read_string_}{\&{readstring} primitive@>
18408 mp_primitive(mp, "pencircle",nullary,pen_circle);
18409 @:pen_circle_}{\&{pencircle} primitive@>
18410 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18411 @:normal_deviate_}{\&{normaldeviate} primitive@>
18412 mp_primitive(mp, "readfrom",unary,read_from_op);
18413 @:read_from_}{\&{readfrom} primitive@>
18414 mp_primitive(mp, "closefrom",unary,close_from_op);
18415 @:close_from_}{\&{closefrom} primitive@>
18416 mp_primitive(mp, "odd",unary,odd_op);
18417 @:odd_}{\&{odd} primitive@>
18418 mp_primitive(mp, "known",unary,known_op);
18419 @:known_}{\&{known} primitive@>
18420 mp_primitive(mp, "unknown",unary,unknown_op);
18421 @:unknown_}{\&{unknown} primitive@>
18422 mp_primitive(mp, "not",unary,not_op);
18423 @:not_}{\&{not} primitive@>
18424 mp_primitive(mp, "decimal",unary,decimal);
18425 @:decimal_}{\&{decimal} primitive@>
18426 mp_primitive(mp, "reverse",unary,reverse);
18427 @:reverse_}{\&{reverse} primitive@>
18428 mp_primitive(mp, "makepath",unary,make_path_op);
18429 @:make_path_}{\&{makepath} primitive@>
18430 mp_primitive(mp, "makepen",unary,make_pen_op);
18431 @:make_pen_}{\&{makepen} primitive@>
18432 mp_primitive(mp, "oct",unary,oct_op);
18433 @:oct_}{\&{oct} primitive@>
18434 mp_primitive(mp, "hex",unary,hex_op);
18435 @:hex_}{\&{hex} primitive@>
18436 mp_primitive(mp, "ASCII",unary,ASCII_op);
18437 @:ASCII_}{\&{ASCII} primitive@>
18438 mp_primitive(mp, "char",unary,char_op);
18439 @:char_}{\&{char} primitive@>
18440 mp_primitive(mp, "length",unary,length_op);
18441 @:length_}{\&{length} primitive@>
18442 mp_primitive(mp, "turningnumber",unary,turning_op);
18443 @:turning_number_}{\&{turningnumber} primitive@>
18444 mp_primitive(mp, "xpart",unary,x_part);
18445 @:x_part_}{\&{xpart} primitive@>
18446 mp_primitive(mp, "ypart",unary,y_part);
18447 @:y_part_}{\&{ypart} primitive@>
18448 mp_primitive(mp, "xxpart",unary,xx_part);
18449 @:xx_part_}{\&{xxpart} primitive@>
18450 mp_primitive(mp, "xypart",unary,xy_part);
18451 @:xy_part_}{\&{xypart} primitive@>
18452 mp_primitive(mp, "yxpart",unary,yx_part);
18453 @:yx_part_}{\&{yxpart} primitive@>
18454 mp_primitive(mp, "yypart",unary,yy_part);
18455 @:yy_part_}{\&{yypart} primitive@>
18456 mp_primitive(mp, "redpart",unary,red_part);
18457 @:red_part_}{\&{redpart} primitive@>
18458 mp_primitive(mp, "greenpart",unary,green_part);
18459 @:green_part_}{\&{greenpart} primitive@>
18460 mp_primitive(mp, "bluepart",unary,blue_part);
18461 @:blue_part_}{\&{bluepart} primitive@>
18462 mp_primitive(mp, "cyanpart",unary,cyan_part);
18463 @:cyan_part_}{\&{cyanpart} primitive@>
18464 mp_primitive(mp, "magentapart",unary,magenta_part);
18465 @:magenta_part_}{\&{magentapart} primitive@>
18466 mp_primitive(mp, "yellowpart",unary,yellow_part);
18467 @:yellow_part_}{\&{yellowpart} primitive@>
18468 mp_primitive(mp, "blackpart",unary,black_part);
18469 @:black_part_}{\&{blackpart} primitive@>
18470 mp_primitive(mp, "greypart",unary,grey_part);
18471 @:grey_part_}{\&{greypart} primitive@>
18472 mp_primitive(mp, "colormodel",unary,color_model_part);
18473 @:color_model_part_}{\&{colormodel} primitive@>
18474 mp_primitive(mp, "fontpart",unary,font_part);
18475 @:font_part_}{\&{fontpart} primitive@>
18476 mp_primitive(mp, "textpart",unary,text_part);
18477 @:text_part_}{\&{textpart} primitive@>
18478 mp_primitive(mp, "pathpart",unary,path_part);
18479 @:path_part_}{\&{pathpart} primitive@>
18480 mp_primitive(mp, "penpart",unary,pen_part);
18481 @:pen_part_}{\&{penpart} primitive@>
18482 mp_primitive(mp, "dashpart",unary,dash_part);
18483 @:dash_part_}{\&{dashpart} primitive@>
18484 mp_primitive(mp, "sqrt",unary,sqrt_op);
18485 @:sqrt_}{\&{sqrt} primitive@>
18486 mp_primitive(mp, "mexp",unary,m_exp_op);
18487 @:m_exp_}{\&{mexp} primitive@>
18488 mp_primitive(mp, "mlog",unary,m_log_op);
18489 @:m_log_}{\&{mlog} primitive@>
18490 mp_primitive(mp, "sind",unary,sin_d_op);
18491 @:sin_d_}{\&{sind} primitive@>
18492 mp_primitive(mp, "cosd",unary,cos_d_op);
18493 @:cos_d_}{\&{cosd} primitive@>
18494 mp_primitive(mp, "floor",unary,floor_op);
18495 @:floor_}{\&{floor} primitive@>
18496 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18497 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18498 mp_primitive(mp, "charexists",unary,char_exists_op);
18499 @:char_exists_}{\&{charexists} primitive@>
18500 mp_primitive(mp, "fontsize",unary,font_size);
18501 @:font_size_}{\&{fontsize} primitive@>
18502 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18503 @:ll_corner_}{\&{llcorner} primitive@>
18504 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18505 @:lr_corner_}{\&{lrcorner} primitive@>
18506 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18507 @:ul_corner_}{\&{ulcorner} primitive@>
18508 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18509 @:ur_corner_}{\&{urcorner} primitive@>
18510 mp_primitive(mp, "arclength",unary,arc_length);
18511 @:arc_length_}{\&{arclength} primitive@>
18512 mp_primitive(mp, "angle",unary,angle_op);
18513 @:angle_}{\&{angle} primitive@>
18514 mp_primitive(mp, "cycle",cycle,cycle_op);
18515 @:cycle_}{\&{cycle} primitive@>
18516 mp_primitive(mp, "stroked",unary,stroked_op);
18517 @:stroked_}{\&{stroked} primitive@>
18518 mp_primitive(mp, "filled",unary,filled_op);
18519 @:filled_}{\&{filled} primitive@>
18520 mp_primitive(mp, "textual",unary,textual_op);
18521 @:textual_}{\&{textual} primitive@>
18522 mp_primitive(mp, "clipped",unary,clipped_op);
18523 @:clipped_}{\&{clipped} primitive@>
18524 mp_primitive(mp, "bounded",unary,bounded_op);
18525 @:bounded_}{\&{bounded} primitive@>
18526 mp_primitive(mp, "+",plus_or_minus,plus);
18527 @:+ }{\.{+} primitive@>
18528 mp_primitive(mp, "-",plus_or_minus,minus);
18529 @:- }{\.{-} primitive@>
18530 mp_primitive(mp, "*",secondary_binary,times);
18531 @:* }{\.{*} primitive@>
18532 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18533 @:/ }{\.{/} primitive@>
18534 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18535 @:++_}{\.{++} primitive@>
18536 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18537 @:+-+_}{\.{+-+} primitive@>
18538 mp_primitive(mp, "or",tertiary_binary,or_op);
18539 @:or_}{\&{or} primitive@>
18540 mp_primitive(mp, "and",and_command,and_op);
18541 @:and_}{\&{and} primitive@>
18542 mp_primitive(mp, "<",expression_binary,less_than);
18543 @:< }{\.{<} primitive@>
18544 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18545 @:<=_}{\.{<=} primitive@>
18546 mp_primitive(mp, ">",expression_binary,greater_than);
18547 @:> }{\.{>} primitive@>
18548 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18549 @:>=_}{\.{>=} primitive@>
18550 mp_primitive(mp, "=",equals,equal_to);
18551 @:= }{\.{=} primitive@>
18552 mp_primitive(mp, "<>",expression_binary,unequal_to);
18553 @:<>_}{\.{<>} primitive@>
18554 mp_primitive(mp, "substring",primary_binary,substring_of);
18555 @:substring_}{\&{substring} primitive@>
18556 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18557 @:subpath_}{\&{subpath} primitive@>
18558 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18559 @:direction_time_}{\&{directiontime} primitive@>
18560 mp_primitive(mp, "point",primary_binary,point_of);
18561 @:point_}{\&{point} primitive@>
18562 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18563 @:precontrol_}{\&{precontrol} primitive@>
18564 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18565 @:postcontrol_}{\&{postcontrol} primitive@>
18566 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18567 @:pen_offset_}{\&{penoffset} primitive@>
18568 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18569 @:arc_time_of_}{\&{arctime} primitive@>
18570 mp_primitive(mp, "mpversion",nullary,mp_version);
18571 @:mp_verison_}{\&{mpversion} primitive@>
18572 mp_primitive(mp, "&",ampersand,concatenate);
18573 @:!!!}{\.{\&} primitive@>
18574 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18575 @:rotated_}{\&{rotated} primitive@>
18576 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18577 @:slanted_}{\&{slanted} primitive@>
18578 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18579 @:scaled_}{\&{scaled} primitive@>
18580 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18581 @:shifted_}{\&{shifted} primitive@>
18582 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18583 @:transformed_}{\&{transformed} primitive@>
18584 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18585 @:x_scaled_}{\&{xscaled} primitive@>
18586 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18587 @:y_scaled_}{\&{yscaled} primitive@>
18588 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18589 @:z_scaled_}{\&{zscaled} primitive@>
18590 mp_primitive(mp, "infont",secondary_binary,in_font);
18591 @:in_font_}{\&{infont} primitive@>
18592 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18593 @:intersection_times_}{\&{intersectiontimes} primitive@>
18594 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18595 @:envelope_}{\&{envelope} primitive@>
18596
18597 @ @<Cases of |print_cmd...@>=
18598 case nullary:
18599 case unary:
18600 case primary_binary:
18601 case secondary_binary:
18602 case tertiary_binary:
18603 case expression_binary:
18604 case cycle:
18605 case plus_or_minus:
18606 case slash:
18607 case ampersand:
18608 case equals:
18609 case and_command:
18610   mp_print_op(mp, m);
18611   break;
18612
18613 @ OK, let's look at the simplest \\{do} procedure first.
18614
18615 @c @<Declare nullary action procedure@>;
18616 void mp_do_nullary (MP mp,quarterword c) { 
18617   check_arith;
18618   if ( mp->internal[mp_tracing_commands]>two )
18619     mp_show_cmd_mod(mp, nullary,c);
18620   switch (c) {
18621   case true_code: case false_code: 
18622     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18623     break;
18624   case null_picture_code: 
18625     mp->cur_type=mp_picture_type;
18626     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18627     mp_init_edges(mp, mp->cur_exp);
18628     break;
18629   case null_pen_code: 
18630     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18631     break;
18632   case normal_deviate: 
18633     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18634     break;
18635   case pen_circle: 
18636     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18637     break;
18638   case job_name_op:  
18639     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18640     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18641     break;
18642   case mp_version: 
18643     mp->cur_type=mp_string_type; 
18644     mp->cur_exp=intern(metapost_version) ;
18645     break;
18646   case read_string_op:
18647     @<Read a string from the terminal@>;
18648     break;
18649   } /* there are no other cases */
18650   check_arith;
18651 }
18652
18653 @ @<Read a string...@>=
18654
18655   if ( mp->interaction<=mp_nonstop_mode )
18656     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18657   mp_begin_file_reading(mp); name=is_read;
18658   limit=start; prompt_input("");
18659   mp_finish_read(mp);
18660 }
18661
18662 @ @<Declare nullary action procedure@>=
18663 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18664   size_t k;
18665   str_room((int)mp->last-start);
18666   for (k=start;k<=mp->last-1;k++) {
18667    append_char(mp->buffer[k]);
18668   }
18669   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18670   mp->cur_exp=mp_make_string(mp);
18671 }
18672
18673 @ Things get a bit more interesting when there's an operand. The
18674 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18675
18676 @c @<Declare unary action procedures@>;
18677 void mp_do_unary (MP mp,quarterword c) {
18678   pointer p,q,r; /* for list manipulation */
18679   integer x; /* a temporary register */
18680   check_arith;
18681   if ( mp->internal[mp_tracing_commands]>two )
18682     @<Trace the current unary operation@>;
18683   switch (c) {
18684   case plus:
18685     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18686     break;
18687   case minus:
18688     @<Negate the current expression@>;
18689     break;
18690   @<Additional cases of unary operators@>;
18691   } /* there are no other cases */
18692   check_arith;
18693 };
18694
18695 @ The |nice_pair| function returns |true| if both components of a pair
18696 are known.
18697
18698 @<Declare unary action procedures@>=
18699 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18700   if ( t==mp_pair_type ) {
18701     p=value(p);
18702     if ( type(x_part_loc(p))==mp_known )
18703       if ( type(y_part_loc(p))==mp_known )
18704         return true;
18705   }
18706   return false;
18707 }
18708
18709 @ The |nice_color_or_pair| function is analogous except that it also accepts
18710 fully known colors.
18711
18712 @<Declare unary action procedures@>=
18713 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18714   pointer q,r; /* for scanning the big node */
18715   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18716     return false;
18717   } else { 
18718     q=value(p);
18719     r=q+mp->big_node_size[type(p)];
18720     do {  
18721       r=r-2;
18722       if ( type(r)!=mp_known )
18723         return false;
18724     } while (r!=q);
18725     return true;
18726   }
18727 }
18728
18729 @ @<Declare unary action...@>=
18730 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18731   mp_print_char(mp, '(');
18732   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18733   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18734     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18735     mp_print_type(mp, t);
18736   }
18737   mp_print_char(mp, ')');
18738 }
18739
18740 @ @<Declare unary action...@>=
18741 void mp_bad_unary (MP mp,quarterword c) { 
18742   exp_err("Not implemented: "); mp_print_op(mp, c);
18743 @.Not implemented...@>
18744   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18745   help3("I'm afraid I don't know how to apply that operation to that")
18746     ("particular type. Continue, and I'll simply return the")
18747     ("argument (shown above) as the result of the operation.");
18748   mp_put_get_error(mp);
18749 }
18750
18751 @ @<Trace the current unary operation@>=
18752
18753   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18754   mp_print_op(mp, c); mp_print_char(mp, '(');
18755   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18756   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18757 }
18758
18759 @ Negation is easy except when the current expression
18760 is of type |independent|, or when it is a pair with one or more
18761 |independent| components.
18762
18763 It is tempting to argue that the negative of an independent variable
18764 is an independent variable, hence we don't have to do anything when
18765 negating it. The fallacy is that other dependent variables pointing
18766 to the current expression must change the sign of their
18767 coefficients if we make no change to the current expression.
18768
18769 Instead, we work around the problem by copying the current expression
18770 and recycling it afterwards (cf.~the |stash_in| routine).
18771
18772 @<Negate the current expression@>=
18773 switch (mp->cur_type) {
18774 case mp_color_type:
18775 case mp_cmykcolor_type:
18776 case mp_pair_type:
18777 case mp_independent: 
18778   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18779   if ( mp->cur_type==mp_dependent ) {
18780     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18781   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18782     p=value(mp->cur_exp);
18783     r=p+mp->big_node_size[mp->cur_type];
18784     do {  
18785       r=r-2;
18786       if ( type(r)==mp_known ) negate(value(r));
18787       else mp_negate_dep_list(mp, dep_list(r));
18788     } while (r!=p);
18789   } /* if |cur_type=mp_known| then |cur_exp=0| */
18790   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18791   break;
18792 case mp_dependent:
18793 case mp_proto_dependent:
18794   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18795   break;
18796 case mp_known:
18797   negate(mp->cur_exp);
18798   break;
18799 default:
18800   mp_bad_unary(mp, minus);
18801   break;
18802 }
18803
18804 @ @<Declare unary action...@>=
18805 void mp_negate_dep_list (MP mp,pointer p) { 
18806   while (1) { 
18807     negate(value(p));
18808     if ( info(p)==null ) return;
18809     p=link(p);
18810   }
18811 }
18812
18813 @ @<Additional cases of unary operators@>=
18814 case not_op: 
18815   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18816   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18817   break;
18818
18819 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18820 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18821
18822 @<Additional cases of unary operators@>=
18823 case sqrt_op:
18824 case m_exp_op:
18825 case m_log_op:
18826 case sin_d_op:
18827 case cos_d_op:
18828 case floor_op:
18829 case  uniform_deviate:
18830 case odd_op:
18831 case char_exists_op:
18832   if ( mp->cur_type!=mp_known ) {
18833     mp_bad_unary(mp, c);
18834   } else {
18835     switch (c) {
18836     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18837     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18838     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18839     case sin_d_op:
18840     case cos_d_op:
18841       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18842       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18843       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18844       break;
18845     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18846     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18847     case odd_op: 
18848       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18849       mp->cur_type=mp_boolean_type;
18850       break;
18851     case char_exists_op:
18852       @<Determine if a character has been shipped out@>;
18853       break;
18854     } /* there are no other cases */
18855   }
18856   break;
18857
18858 @ @<Additional cases of unary operators@>=
18859 case angle_op:
18860   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18861     p=value(mp->cur_exp);
18862     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18863     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18864     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18865   } else {
18866     mp_bad_unary(mp, angle_op);
18867   }
18868   break;
18869
18870 @ If the current expression is a pair, but the context wants it to
18871 be a path, we call |pair_to_path|.
18872
18873 @<Declare unary action...@>=
18874 void mp_pair_to_path (MP mp) { 
18875   mp->cur_exp=mp_new_knot(mp); 
18876   mp->cur_type=mp_path_type;
18877 };
18878
18879 @ @<Additional cases of unary operators@>=
18880 case x_part:
18881 case y_part:
18882   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18883     mp_take_part(mp, c);
18884   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18885   else mp_bad_unary(mp, c);
18886   break;
18887 case xx_part:
18888 case xy_part:
18889 case yx_part:
18890 case yy_part: 
18891   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18892   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18893   else mp_bad_unary(mp, c);
18894   break;
18895 case red_part:
18896 case green_part:
18897 case blue_part: 
18898   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18899   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18900   else mp_bad_unary(mp, c);
18901   break;
18902 case cyan_part:
18903 case magenta_part:
18904 case yellow_part:
18905 case black_part: 
18906   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18907   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18908   else mp_bad_unary(mp, c);
18909   break;
18910 case grey_part: 
18911   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18912   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18913   else mp_bad_unary(mp, c);
18914   break;
18915 case color_model_part: 
18916   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18917   else mp_bad_unary(mp, c);
18918   break;
18919
18920 @ In the following procedure, |cur_exp| points to a capsule, which points to
18921 a big node. We want to delete all but one part of the big node.
18922
18923 @<Declare unary action...@>=
18924 void mp_take_part (MP mp,quarterword c) {
18925   pointer p; /* the big node */
18926   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18927   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18928   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18929   mp_recycle_value(mp, temp_val);
18930 }
18931
18932 @ @<Initialize table entries...@>=
18933 name_type(temp_val)=mp_capsule;
18934
18935 @ @<Additional cases of unary operators@>=
18936 case font_part:
18937 case text_part:
18938 case path_part:
18939 case pen_part:
18940 case dash_part:
18941   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18942   else mp_bad_unary(mp, c);
18943   break;
18944
18945 @ @<Declarations@>=
18946 void mp_scale_edges (MP mp);
18947
18948 @ @<Declare unary action...@>=
18949 void mp_take_pict_part (MP mp,quarterword c) {
18950   pointer p; /* first graphical object in |cur_exp| */
18951   p=link(dummy_loc(mp->cur_exp));
18952   if ( p!=null ) {
18953     switch (c) {
18954     case x_part: case y_part: case xx_part:
18955     case xy_part: case yx_part: case yy_part:
18956       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
18957       else goto NOT_FOUND;
18958       break;
18959     case red_part: case green_part: case blue_part:
18960       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
18961       else goto NOT_FOUND;
18962       break;
18963     case cyan_part: case magenta_part: case yellow_part:
18964     case black_part:
18965       if ( has_color(p) ) {
18966         if ( color_model(p)==mp_uninitialized_model )
18967           mp_flush_cur_exp(mp, unity);
18968         else
18969           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
18970       } else goto NOT_FOUND;
18971       break;
18972     case grey_part:
18973       if ( has_color(p) )
18974           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
18975       else goto NOT_FOUND;
18976       break;
18977     case color_model_part:
18978       if ( has_color(p) ) {
18979         if ( color_model(p)==mp_uninitialized_model )
18980           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
18981         else
18982           mp_flush_cur_exp(mp, color_model(p)*unity);
18983       } else goto NOT_FOUND;
18984       break;
18985     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
18986     } /* all cases have been enumerated */
18987     return;
18988   };
18989 NOT_FOUND:
18990   @<Convert the current expression to a null value appropriate
18991     for |c|@>;
18992 }
18993
18994 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
18995 case text_part: 
18996   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
18997   else { 
18998     mp_flush_cur_exp(mp, text_p(p));
18999     add_str_ref(mp->cur_exp);
19000     mp->cur_type=mp_string_type;
19001     };
19002   break;
19003 case font_part: 
19004   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19005   else { 
19006     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
19007     add_str_ref(mp->cur_exp);
19008     mp->cur_type=mp_string_type;
19009   };
19010   break;
19011 case path_part:
19012   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19013   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19014 @:this can't happen pict}{\quad pict@>
19015   else { 
19016     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19017     mp->cur_type=mp_path_type;
19018   }
19019   break;
19020 case pen_part: 
19021   if ( ! has_pen(p) ) goto NOT_FOUND;
19022   else {
19023     if ( pen_p(p)==null ) goto NOT_FOUND;
19024     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19025       mp->cur_type=mp_pen_type;
19026     };
19027   }
19028   break;
19029 case dash_part: 
19030   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19031   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19032     else { add_edge_ref(dash_p(p));
19033     mp->se_sf=dash_scale(p);
19034     mp->se_pic=dash_p(p);
19035     mp_scale_edges(mp);
19036     mp_flush_cur_exp(mp, mp->se_pic);
19037     mp->cur_type=mp_picture_type;
19038     };
19039   }
19040   break;
19041
19042 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19043 parameterless procedure even though it really takes two arguments and updates
19044 one of them.  Hence the following globals are needed.
19045
19046 @<Global...@>=
19047 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19048 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19049
19050 @ @<Convert the current expression to a null value appropriate...@>=
19051 switch (c) {
19052 case text_part: case font_part: 
19053   mp_flush_cur_exp(mp, rts(""));
19054   mp->cur_type=mp_string_type;
19055   break;
19056 case path_part: 
19057   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19058   left_type(mp->cur_exp)=mp_endpoint;
19059   right_type(mp->cur_exp)=mp_endpoint;
19060   link(mp->cur_exp)=mp->cur_exp;
19061   x_coord(mp->cur_exp)=0;
19062   y_coord(mp->cur_exp)=0;
19063   originator(mp->cur_exp)=mp_metapost_user;
19064   mp->cur_type=mp_path_type;
19065   break;
19066 case pen_part: 
19067   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19068   mp->cur_type=mp_pen_type;
19069   break;
19070 case dash_part: 
19071   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19072   mp_init_edges(mp, mp->cur_exp);
19073   mp->cur_type=mp_picture_type;
19074   break;
19075 default: 
19076    mp_flush_cur_exp(mp, 0);
19077   break;
19078 }
19079
19080 @ @<Additional cases of unary...@>=
19081 case char_op: 
19082   if ( mp->cur_type!=mp_known ) { 
19083     mp_bad_unary(mp, char_op);
19084   } else { 
19085     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19086     mp->cur_type=mp_string_type;
19087     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19088   }
19089   break;
19090 case decimal: 
19091   if ( mp->cur_type!=mp_known ) {
19092      mp_bad_unary(mp, decimal);
19093   } else { 
19094     mp->old_setting=mp->selector; mp->selector=new_string;
19095     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19096     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19097   }
19098   break;
19099 case oct_op:
19100 case hex_op:
19101 case ASCII_op: 
19102   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19103   else mp_str_to_num(mp, c);
19104   break;
19105 case font_size: 
19106   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19107   else @<Find the design size of the font whose name is |cur_exp|@>;
19108   break;
19109
19110 @ @<Declare unary action...@>=
19111 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19112   integer n; /* accumulator */
19113   ASCII_code m; /* current character */
19114   pool_pointer k; /* index into |str_pool| */
19115   int b; /* radix of conversion */
19116   boolean bad_char; /* did the string contain an invalid digit? */
19117   if ( c==ASCII_op ) {
19118     if ( length(mp->cur_exp)==0 ) n=-1;
19119     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19120   } else { 
19121     if ( c==oct_op ) b=8; else b=16;
19122     n=0; bad_char=false;
19123     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19124       m=mp->str_pool[k];
19125       if ( (m>='0')&&(m<='9') ) m=m-'0';
19126       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19127       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19128       else  { bad_char=true; m=0; };
19129       if ( m>=b ) { bad_char=true; m=0; };
19130       if ( n<32768 / b ) n=n*b+m; else n=32767;
19131     }
19132     @<Give error messages if |bad_char| or |n>=4096|@>;
19133   }
19134   mp_flush_cur_exp(mp, n*unity);
19135 }
19136
19137 @ @<Give error messages if |bad_char|...@>=
19138 if ( bad_char ) { 
19139   exp_err("String contains illegal digits");
19140 @.String contains illegal digits@>
19141   if ( c==oct_op ) {
19142     help1("I zeroed out characters that weren't in the range 0..7.");
19143   } else  {
19144     help1("I zeroed out characters that weren't hex digits.");
19145   }
19146   mp_put_get_error(mp);
19147 }
19148 if ( (n>4095) ) {
19149   if ( mp->internal[mp_warning_check]>0 ) {
19150     print_err("Number too large ("); 
19151     mp_print_int(mp, n); mp_print_char(mp, ')');
19152 @.Number too large@>
19153     help2("I have trouble with numbers greater than 4095; watch out.")
19154       ("(Set warningcheck:=0 to suppress this message.)");
19155     mp_put_get_error(mp);
19156   }
19157 }
19158
19159 @ The length operation is somewhat unusual in that it applies to a variety
19160 of different types of operands.
19161
19162 @<Additional cases of unary...@>=
19163 case length_op: 
19164   switch (mp->cur_type) {
19165   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19166   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19167   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19168   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19169   default: 
19170     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19171       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19172         value(x_part_loc(value(mp->cur_exp))),
19173         value(y_part_loc(value(mp->cur_exp)))));
19174     else mp_bad_unary(mp, c);
19175     break;
19176   }
19177   break;
19178
19179 @ @<Declare unary action...@>=
19180 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19181   scaled n; /* the path length so far */
19182   pointer p; /* traverser */
19183   p=mp->cur_exp;
19184   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19185   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19186   return n;
19187 }
19188
19189 @ @<Declare unary action...@>=
19190 scaled mp_pict_length (MP mp) { 
19191   /* counts interior components in picture |cur_exp| */
19192   scaled n; /* the count so far */
19193   pointer p; /* traverser */
19194   n=0;
19195   p=link(dummy_loc(mp->cur_exp));
19196   if ( p!=null ) {
19197     if ( is_start_or_stop(p) )
19198       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19199     while ( p!=null )  { 
19200       skip_component(p) return n; 
19201       n=n+unity;   
19202     }
19203   }
19204   return n;
19205 }
19206
19207 @ Implement |turningnumber|
19208
19209 @<Additional cases of unary...@>=
19210 case turning_op:
19211   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19212   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19213   else if ( left_type(mp->cur_exp)==mp_endpoint )
19214      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19215   else
19216     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19217   break;
19218
19219 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19220 argument is |origin|.
19221
19222 @<Declare unary action...@>=
19223 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19224   if ( (! ((xpar==0) && (ypar==0))) )
19225     return mp_n_arg(mp, xpar,ypar);
19226   return 0;
19227 }
19228
19229
19230 @ The actual turning number is (for the moment) computed in a C function
19231 that receives eight integers corresponding to the four controlling points,
19232 and returns a single angle.  Besides those, we have to account for discrete
19233 moves at the actual points.
19234
19235 @d floor(a) (a>=0 ? a : -(int)(-a))
19236 @d bezier_error (720<<20)+1
19237 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19238 @d print_roots(a) 
19239 @d out ((double)(xo>>20))
19240 @d mid ((double)(xm>>20))
19241 @d in  ((double)(xi>>20))
19242 @d divisor (256*256)
19243 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19244
19245 @<Declare unary action...@>=
19246 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19247             integer CX,integer CY,integer DX,integer DY);
19248
19249 @ @c 
19250 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19251             integer CX,integer CY,integer DX,integer DY) {
19252   double a, b, c;
19253   integer deltax,deltay;
19254   double ax,ay,bx,by,cx,cy,dx,dy;
19255   angle xi = 0, xo = 0, xm = 0;
19256   double res = 0;
19257   ax=AX/divisor;  ay=AY/divisor;
19258   bx=BX/divisor;  by=BY/divisor;
19259   cx=CX/divisor;  cy=CY/divisor;
19260   dx=DX/divisor;  dy=DY/divisor;
19261
19262   deltax = (BX-AX); deltay = (BY-AY);
19263   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19264   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19265   xi = mp_an_angle(mp,deltax,deltay);
19266
19267   deltax = (CX-BX); deltay = (CY-BY);
19268   xm = mp_an_angle(mp,deltax,deltay);
19269
19270   deltax = (DX-CX); deltay = (DY-CY);
19271   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19272   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19273   xo = mp_an_angle(mp,deltax,deltay);
19274
19275   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19276   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19277   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19278
19279   if ((a==0)&&(c==0)) {
19280     res = (b==0 ?  0 :  (out-in)); 
19281     print_roots("no roots (a)");
19282   } else if ((a==0)||(c==0)) {
19283     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19284       res = out-in; /* ? */
19285       if (res<-180.0) 
19286         res += 360.0;
19287       else if (res>180.0)
19288         res -= 360.0;
19289       print_roots("no roots (b)");
19290     } else {
19291       res = out-in; /* ? */
19292       print_roots("one root (a)");
19293     }
19294   } else if ((sign(a)*sign(c))<0) {
19295     res = out-in; /* ? */
19296       if (res<-180.0) 
19297         res += 360.0;
19298       else if (res>180.0)
19299         res -= 360.0;
19300     print_roots("one root (b)");
19301   } else {
19302     if (sign(a) == sign(b)) {
19303       res = out-in; /* ? */
19304       if (res<-180.0) 
19305         res += 360.0;
19306       else if (res>180.0)
19307         res -= 360.0;
19308       print_roots("no roots (d)");
19309     } else {
19310       if ((b*b) == (4*a*c)) {
19311         res = bezier_error;
19312         print_roots("double root"); /* cusp */
19313       } else if ((b*b) < (4*a*c)) {
19314         res = out-in; /* ? */
19315         if (res<=0.0 &&res>-180.0) 
19316           res += 360.0;
19317         else if (res>=0.0 && res<180.0)
19318           res -= 360.0;
19319         print_roots("no roots (e)");
19320       } else {
19321         res = out-in;
19322         if (res<-180.0) 
19323           res += 360.0;
19324         else if (res>180.0)
19325           res -= 360.0;
19326         print_roots("two roots"); /* two inflections */
19327       }
19328     }
19329   }
19330   return double2angle(res);
19331 }
19332
19333 @
19334 @d p_nextnext link(link(p))
19335 @d p_next link(p)
19336 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19337
19338 @<Declare unary action...@>=
19339 scaled mp_new_turn_cycles (MP mp,pointer c) {
19340   angle res,ang; /*  the angles of intermediate results  */
19341   scaled turns;  /*  the turn counter  */
19342   pointer p;     /*  for running around the path  */
19343   integer xp,yp;   /*  coordinates of next point  */
19344   integer x,y;   /*  helper coordinates  */
19345   angle in_angle,out_angle;     /*  helper angles */
19346   int old_setting; /* saved |selector| setting */
19347   res=0;
19348   turns= 0;
19349   p=c;
19350   old_setting = mp->selector; mp->selector=term_only;
19351   if ( mp->internal[mp_tracing_commands]>unity ) {
19352     mp_begin_diagnostic(mp);
19353     mp_print_nl(mp, "");
19354     mp_end_diagnostic(mp, false);
19355   }
19356   do { 
19357     xp = x_coord(p_next); yp = y_coord(p_next);
19358     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19359              left_x(p_next), left_y(p_next), xp, yp);
19360     if ( ang>seven_twenty_deg ) {
19361       print_err("Strange path");
19362       mp_error(mp);
19363       mp->selector=old_setting;
19364       return 0;
19365     }
19366     res  = res + ang;
19367     if ( res > one_eighty_deg ) {
19368       res = res - three_sixty_deg;
19369       turns = turns + unity;
19370     }
19371     if ( res <= -one_eighty_deg ) {
19372       res = res + three_sixty_deg;
19373       turns = turns - unity;
19374     }
19375     /*  incoming angle at next point  */
19376     x = left_x(p_next);  y = left_y(p_next);
19377     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19378     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19379     in_angle = mp_an_angle(mp, xp - x, yp - y);
19380     /*  outgoing angle at next point  */
19381     x = right_x(p_next);  y = right_y(p_next);
19382     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19383     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19384     out_angle = mp_an_angle(mp, x - xp, y- yp);
19385     ang  = (out_angle - in_angle);
19386     reduce_angle(ang);
19387     if ( ang!=0 ) {
19388       res  = res + ang;
19389       if ( res >= one_eighty_deg ) {
19390         res = res - three_sixty_deg;
19391         turns = turns + unity;
19392       };
19393       if ( res <= -one_eighty_deg ) {
19394         res = res + three_sixty_deg;
19395         turns = turns - unity;
19396       };
19397     };
19398     p = link(p);
19399   } while (p!=c);
19400   mp->selector=old_setting;
19401   return turns;
19402 }
19403
19404
19405 @ This code is based on Bogus\l{}av Jackowski's
19406 |emergency_turningnumber| macro, with some minor changes by Taco
19407 Hoekwater. The macro code looked more like this:
19408 {\obeylines
19409 vardef turning\_number primary p =
19410 ~~save res, ang, turns;
19411 ~~res := 0;
19412 ~~if length p <= 2:
19413 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19414 ~~else:
19415 ~~~~for t = 0 upto length p-1 :
19416 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19417 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19418 ~~~~~~if angc > 180: angc := angc - 360; fi;
19419 ~~~~~~if angc < -180: angc := angc + 360; fi;
19420 ~~~~~~res  := res + angc;
19421 ~~~~endfor;
19422 ~~res/360
19423 ~~fi
19424 enddef;}
19425 The general idea is to calculate only the sum of the angles of
19426 straight lines between the points, of a path, not worrying about cusps
19427 or self-intersections in the segments at all. If the segment is not
19428 well-behaved, the result is not necesarily correct. But the old code
19429 was not always correct either, and worse, it sometimes failed for
19430 well-behaved paths as well. All known bugs that were triggered by the
19431 original code no longer occur with this code, and it runs roughly 3
19432 times as fast because the algorithm is much simpler.
19433
19434 @ It is possible to overflow the return value of the |turn_cycles|
19435 function when the path is sufficiently long and winding, but I am not
19436 going to bother testing for that. In any case, it would only return
19437 the looped result value, which is not a big problem.
19438
19439 The macro code for the repeat loop was a bit nicer to look
19440 at than the pascal code, because it could use |point -1 of p|. In
19441 pascal, the fastest way to loop around the path is not to look
19442 backward once, but forward twice. These defines help hide the trick.
19443
19444 @d p_to link(link(p))
19445 @d p_here link(p)
19446 @d p_from p
19447
19448 @<Declare unary action...@>=
19449 scaled mp_turn_cycles (MP mp,pointer c) {
19450   angle res,ang; /*  the angles of intermediate results  */
19451   scaled turns;  /*  the turn counter  */
19452   pointer p;     /*  for running around the path  */
19453   res=0;  turns= 0; p=c;
19454   do { 
19455     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19456                             y_coord(p_to) - y_coord(p_here))
19457         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19458                            y_coord(p_here) - y_coord(p_from));
19459     reduce_angle(ang);
19460     res  = res + ang;
19461     if ( res >= three_sixty_deg )  {
19462       res = res - three_sixty_deg;
19463       turns = turns + unity;
19464     };
19465     if ( res <= -three_sixty_deg ) {
19466       res = res + three_sixty_deg;
19467       turns = turns - unity;
19468     };
19469     p = link(p);
19470   } while (p!=c);
19471   return turns;
19472 }
19473
19474 @ @<Declare unary action...@>=
19475 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19476   scaled nval,oval;
19477   scaled saved_t_o; /* tracing\_online saved  */
19478   if ( (link(c)==c)||(link(link(c))==c) ) {
19479     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19480       return unity;
19481     else
19482       return -unity;
19483   } else {
19484     nval = mp_new_turn_cycles(mp, c);
19485     oval = mp_turn_cycles(mp, c);
19486     if ( nval!=oval ) {
19487       saved_t_o=mp->internal[mp_tracing_online];
19488       mp->internal[mp_tracing_online]=unity;
19489       mp_begin_diagnostic(mp);
19490       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19491                        " The current computed value is ");
19492       mp_print_scaled(mp, nval);
19493       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19494       mp_print_scaled(mp, oval);
19495       mp_end_diagnostic(mp, false);
19496       mp->internal[mp_tracing_online]=saved_t_o;
19497     }
19498     return nval;
19499   }
19500 }
19501
19502 @ @<Declare unary action...@>=
19503 scaled mp_count_turns (MP mp,pointer c) {
19504   pointer p; /* a knot in envelope spec |c| */
19505   integer t; /* total pen offset changes counted */
19506   t=0; p=c;
19507   do {  
19508     t=t+info(p)-zero_off;
19509     p=link(p);
19510   } while (p!=c);
19511   return ((t / 3)*unity);
19512 }
19513
19514 @ @d type_range(A,B) { 
19515   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19516     mp_flush_cur_exp(mp, true_code);
19517   else mp_flush_cur_exp(mp, false_code);
19518   mp->cur_type=mp_boolean_type;
19519   }
19520 @d type_test(A) { 
19521   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19522   else mp_flush_cur_exp(mp, false_code);
19523   mp->cur_type=mp_boolean_type;
19524   }
19525
19526 @<Additional cases of unary operators@>=
19527 case mp_boolean_type: 
19528   type_range(mp_boolean_type,mp_unknown_boolean); break;
19529 case mp_string_type: 
19530   type_range(mp_string_type,mp_unknown_string); break;
19531 case mp_pen_type: 
19532   type_range(mp_pen_type,mp_unknown_pen); break;
19533 case mp_path_type: 
19534   type_range(mp_path_type,mp_unknown_path); break;
19535 case mp_picture_type: 
19536   type_range(mp_picture_type,mp_unknown_picture); break;
19537 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19538 case mp_pair_type: 
19539   type_test(c); break;
19540 case mp_numeric_type: 
19541   type_range(mp_known,mp_independent); break;
19542 case known_op: case unknown_op: 
19543   mp_test_known(mp, c); break;
19544
19545 @ @<Declare unary action procedures@>=
19546 void mp_test_known (MP mp,quarterword c) {
19547   int b; /* is the current expression known? */
19548   pointer p,q; /* locations in a big node */
19549   b=false_code;
19550   switch (mp->cur_type) {
19551   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19552   case mp_pen_type: case mp_path_type: case mp_picture_type:
19553   case mp_known: 
19554     b=true_code;
19555     break;
19556   case mp_transform_type:
19557   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19558     p=value(mp->cur_exp);
19559     q=p+mp->big_node_size[mp->cur_type];
19560     do {  
19561       q=q-2;
19562       if ( type(q)!=mp_known ) 
19563        goto DONE;
19564     } while (q!=p);
19565     b=true_code;
19566   DONE:  
19567     break;
19568   default: 
19569     break;
19570   }
19571   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19572   else mp_flush_cur_exp(mp, true_code+false_code-b);
19573   mp->cur_type=mp_boolean_type;
19574 }
19575
19576 @ @<Additional cases of unary operators@>=
19577 case cycle_op: 
19578   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19579   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19580   else mp_flush_cur_exp(mp, false_code);
19581   mp->cur_type=mp_boolean_type;
19582   break;
19583
19584 @ @<Additional cases of unary operators@>=
19585 case arc_length: 
19586   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19587   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19588   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19589   break;
19590
19591 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19592 object |type|.
19593 @^data structure assumptions@>
19594
19595 @<Additional cases of unary operators@>=
19596 case filled_op:
19597 case stroked_op:
19598 case textual_op:
19599 case clipped_op:
19600 case bounded_op:
19601   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19602   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19603   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19604     mp_flush_cur_exp(mp, true_code);
19605   else mp_flush_cur_exp(mp, false_code);
19606   mp->cur_type=mp_boolean_type;
19607   break;
19608
19609 @ @<Additional cases of unary operators@>=
19610 case make_pen_op: 
19611   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19612   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19613   else { 
19614     mp->cur_type=mp_pen_type;
19615     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19616   };
19617   break;
19618 case make_path_op: 
19619   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19620   else  { 
19621     mp->cur_type=mp_path_type;
19622     mp_make_path(mp, mp->cur_exp);
19623   };
19624   break;
19625 case reverse: 
19626   if ( mp->cur_type==mp_path_type ) {
19627     p=mp_htap_ypoc(mp, mp->cur_exp);
19628     if ( right_type(p)==mp_endpoint ) p=link(p);
19629     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19630   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19631   else mp_bad_unary(mp, reverse);
19632   break;
19633
19634 @ The |pair_value| routine changes the current expression to a
19635 given ordered pair of values.
19636
19637 @<Declare unary action procedures@>=
19638 void mp_pair_value (MP mp,scaled x, scaled y) {
19639   pointer p; /* a pair node */
19640   p=mp_get_node(mp, value_node_size); 
19641   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19642   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19643   p=value(p);
19644   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19645   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19646 }
19647
19648 @ @<Additional cases of unary operators@>=
19649 case ll_corner_op: 
19650   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19651   else mp_pair_value(mp, minx,miny);
19652   break;
19653 case lr_corner_op: 
19654   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19655   else mp_pair_value(mp, maxx,miny);
19656   break;
19657 case ul_corner_op: 
19658   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19659   else mp_pair_value(mp, minx,maxy);
19660   break;
19661 case ur_corner_op: 
19662   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19663   else mp_pair_value(mp, maxx,maxy);
19664   break;
19665
19666 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19667 box of the current expression.  The boolean result is |false| if the expression
19668 has the wrong type.
19669
19670 @<Declare unary action procedures@>=
19671 boolean mp_get_cur_bbox (MP mp) { 
19672   switch (mp->cur_type) {
19673   case mp_picture_type: 
19674     mp_set_bbox(mp, mp->cur_exp,true);
19675     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19676       minx=0; maxx=0; miny=0; maxy=0;
19677     } else { 
19678       minx=minx_val(mp->cur_exp);
19679       maxx=maxx_val(mp->cur_exp);
19680       miny=miny_val(mp->cur_exp);
19681       maxy=maxy_val(mp->cur_exp);
19682     }
19683     break;
19684   case mp_path_type: 
19685     mp_path_bbox(mp, mp->cur_exp);
19686     break;
19687   case mp_pen_type: 
19688     mp_pen_bbox(mp, mp->cur_exp);
19689     break;
19690   default: 
19691     return false;
19692   }
19693   return true;
19694 }
19695
19696 @ @<Additional cases of unary operators@>=
19697 case read_from_op:
19698 case close_from_op: 
19699   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19700   else mp_do_read_or_close(mp,c);
19701   break;
19702
19703 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19704 a line from the file or to close the file.
19705
19706 @<Declare unary action procedures@>=
19707 void mp_do_read_or_close (MP mp,quarterword c) {
19708   readf_index n,n0; /* indices for searching |rd_fname| */
19709   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19710     call |start_read_input| and |goto found| or |not_found|@>;
19711   mp_begin_file_reading(mp);
19712   name=is_read;
19713   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19714     goto FOUND;
19715   mp_end_file_reading(mp);
19716 NOT_FOUND:
19717   @<Record the end of file and set |cur_exp| to a dummy value@>;
19718   return;
19719 CLOSE_FILE:
19720   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19721   return;
19722 FOUND:
19723   mp_flush_cur_exp(mp, 0);
19724   mp_finish_read(mp);
19725 }
19726
19727 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19728 |rd_fname|.
19729
19730 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19731 {   
19732   char *fn;
19733   n=mp->read_files;
19734   n0=mp->read_files;
19735   fn = str(mp->cur_exp);
19736   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19737     if ( n>0 ) {
19738       decr(n);
19739     } else if ( c==close_from_op ) {
19740       goto CLOSE_FILE;
19741     } else {
19742       if ( n0==mp->read_files ) {
19743         if ( mp->read_files<mp->max_read_files ) {
19744           incr(mp->read_files);
19745         } else {
19746           void **rd_file;
19747           char **rd_fname;
19748               readf_index l,k;
19749           l = mp->max_read_files + (mp->max_read_files>>2);
19750           rd_file = xmalloc((l+1), sizeof(void *));
19751           rd_fname = xmalloc((l+1), sizeof(char *));
19752               for (k=0;k<=l;k++) {
19753             if (k<=mp->max_read_files) {
19754                   rd_file[k]=mp->rd_file[k]; 
19755               rd_fname[k]=mp->rd_fname[k];
19756             } else {
19757               rd_file[k]=0; 
19758               rd_fname[k]=NULL;
19759             }
19760           }
19761               xfree(mp->rd_file); xfree(mp->rd_fname);
19762           mp->max_read_files = l;
19763           mp->rd_file = rd_file;
19764           mp->rd_fname = rd_fname;
19765         }
19766       }
19767       n=n0;
19768       if ( mp_start_read_input(mp,fn,n) ) 
19769         goto FOUND;
19770       else 
19771         goto NOT_FOUND;
19772     }
19773     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19774   } 
19775   if ( c==close_from_op ) { 
19776     (mp->close_file)(mp->rd_file[n]); 
19777     goto NOT_FOUND; 
19778   }
19779 }
19780
19781 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19782 xfree(mp->rd_fname[n]);
19783 mp->rd_fname[n]=NULL;
19784 if ( n==mp->read_files-1 ) mp->read_files=n;
19785 if ( c==close_from_op ) 
19786   goto CLOSE_FILE;
19787 mp_flush_cur_exp(mp, mp->eof_line);
19788 mp->cur_type=mp_string_type
19789
19790 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19791
19792 @<Glob...@>=
19793 str_number eof_line;
19794
19795 @ @<Set init...@>=
19796 mp->eof_line=0;
19797
19798 @ Finally, we have the operations that combine a capsule~|p|
19799 with the current expression.
19800
19801 @c @<Declare binary action procedures@>;
19802 void mp_do_binary (MP mp,pointer p, quarterword c) {
19803   pointer q,r,rr; /* for list manipulation */
19804   pointer old_p,old_exp; /* capsules to recycle */
19805   integer v; /* for numeric manipulation */
19806   check_arith;
19807   if ( mp->internal[mp_tracing_commands]>two ) {
19808     @<Trace the current binary operation@>;
19809   }
19810   @<Sidestep |independent| cases in capsule |p|@>;
19811   @<Sidestep |independent| cases in the current expression@>;
19812   switch (c) {
19813   case plus: case minus:
19814     @<Add or subtract the current expression from |p|@>;
19815     break;
19816   @<Additional cases of binary operators@>;
19817   }; /* there are no other cases */
19818   mp_recycle_value(mp, p); 
19819   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19820   check_arith; 
19821   @<Recycle any sidestepped |independent| capsules@>;
19822 }
19823
19824 @ @<Declare binary action...@>=
19825 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19826   mp_disp_err(mp, p,"");
19827   exp_err("Not implemented: ");
19828 @.Not implemented...@>
19829   if ( c>=min_of ) mp_print_op(mp, c);
19830   mp_print_known_or_unknown_type(mp, type(p),p);
19831   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19832   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19833   help3("I'm afraid I don't know how to apply that operation to that")
19834        ("combination of types. Continue, and I'll return the second")
19835       ("argument (see above) as the result of the operation.");
19836   mp_put_get_error(mp);
19837 }
19838 void mp_bad_envelope_pen (MP mp) {
19839   mp_disp_err(mp, null,"");
19840   exp_err("Not implemented: envelope(elliptical pen)of(path)");
19841 @.Not implemented...@>
19842   help3("I'm afraid I don't know how to apply that operation to that")
19843        ("combination of types. Continue, and I'll return the second")
19844       ("argument (see above) as the result of the operation.");
19845   mp_put_get_error(mp);
19846 }
19847
19848 @ @<Trace the current binary operation@>=
19849
19850   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19851   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19852   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19853   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19854   mp_end_diagnostic(mp, false);
19855 }
19856
19857 @ Several of the binary operations are potentially complicated by the
19858 fact that |independent| values can sneak into capsules. For example,
19859 we've seen an instance of this difficulty in the unary operation
19860 of negation. In order to reduce the number of cases that need to be
19861 handled, we first change the two operands (if necessary)
19862 to rid them of |independent| components. The original operands are
19863 put into capsules called |old_p| and |old_exp|, which will be
19864 recycled after the binary operation has been safely carried out.
19865
19866 @<Recycle any sidestepped |independent| capsules@>=
19867 if ( old_p!=null ) { 
19868   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19869 }
19870 if ( old_exp!=null ) {
19871   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19872 }
19873
19874 @ A big node is considered to be ``tarnished'' if it contains at least one
19875 independent component. We will define a simple function called `|tarnished|'
19876 that returns |null| if and only if its argument is not tarnished.
19877
19878 @<Sidestep |independent| cases in capsule |p|@>=
19879 switch (type(p)) {
19880 case mp_transform_type:
19881 case mp_color_type:
19882 case mp_cmykcolor_type:
19883 case mp_pair_type: 
19884   old_p=mp_tarnished(mp, p);
19885   break;
19886 case mp_independent: old_p=mp_void; break;
19887 default: old_p=null; break;
19888 };
19889 if ( old_p!=null ) {
19890   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19891   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19892 }
19893
19894 @ @<Sidestep |independent| cases in the current expression@>=
19895 switch (mp->cur_type) {
19896 case mp_transform_type:
19897 case mp_color_type:
19898 case mp_cmykcolor_type:
19899 case mp_pair_type: 
19900   old_exp=mp_tarnished(mp, mp->cur_exp);
19901   break;
19902 case mp_independent:old_exp=mp_void; break;
19903 default: old_exp=null; break;
19904 };
19905 if ( old_exp!=null ) {
19906   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19907 }
19908
19909 @ @<Declare binary action...@>=
19910 pointer mp_tarnished (MP mp,pointer p) {
19911   pointer q; /* beginning of the big node */
19912   pointer r; /* current position in the big node */
19913   q=value(p); r=q+mp->big_node_size[type(p)];
19914   do {  
19915    r=r-2;
19916    if ( type(r)==mp_independent ) return mp_void; 
19917   } while (r!=q);
19918   return null;
19919 }
19920
19921 @ @<Add or subtract the current expression from |p|@>=
19922 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19923   mp_bad_binary(mp, p,c);
19924 } else  {
19925   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19926     mp_add_or_subtract(mp, p,null,c);
19927   } else {
19928     if ( mp->cur_type!=type(p) )  {
19929       mp_bad_binary(mp, p,c);
19930     } else { 
19931       q=value(p); r=value(mp->cur_exp);
19932       rr=r+mp->big_node_size[mp->cur_type];
19933       while ( r<rr ) { 
19934         mp_add_or_subtract(mp, q,r,c);
19935         q=q+2; r=r+2;
19936       }
19937     }
19938   }
19939 }
19940
19941 @ The first argument to |add_or_subtract| is the location of a value node
19942 in a capsule or pair node that will soon be recycled. The second argument
19943 is either a location within a pair or transform node of |cur_exp|,
19944 or it is null (which means that |cur_exp| itself should be the second
19945 argument).  The third argument is either |plus| or |minus|.
19946
19947 The sum or difference of the numeric quantities will replace the second
19948 operand.  Arithmetic overflow may go undetected; users aren't supposed to
19949 be monkeying around with really big values.
19950
19951 @<Declare binary action...@>=
19952 @<Declare the procedure called |dep_finish|@>;
19953 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
19954   small_number s,t; /* operand types */
19955   pointer r; /* list traverser */
19956   integer v; /* second operand value */
19957   if ( q==null ) { 
19958     t=mp->cur_type;
19959     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
19960   } else { 
19961     t=type(q);
19962     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
19963   }
19964   if ( t==mp_known ) {
19965     if ( c==minus ) negate(v);
19966     if ( type(p)==mp_known ) {
19967       v=mp_slow_add(mp, value(p),v);
19968       if ( q==null ) mp->cur_exp=v; else value(q)=v;
19969       return;
19970     }
19971     @<Add a known value to the constant term of |dep_list(p)|@>;
19972   } else  { 
19973     if ( c==minus ) mp_negate_dep_list(mp, v);
19974     @<Add operand |p| to the dependency list |v|@>;
19975   }
19976 }
19977
19978 @ @<Add a known value to the constant term of |dep_list(p)|@>=
19979 r=dep_list(p);
19980 while ( info(r)!=null ) r=link(r);
19981 value(r)=mp_slow_add(mp, value(r),v);
19982 if ( q==null ) {
19983   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
19984   name_type(q)=mp_capsule;
19985 }
19986 dep_list(q)=dep_list(p); type(q)=type(p);
19987 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
19988 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
19989
19990 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
19991 nice to retain the extra accuracy of |fraction| coefficients.
19992 But we have to handle both kinds, and mixtures too.
19993
19994 @<Add operand |p| to the dependency list |v|@>=
19995 if ( type(p)==mp_known ) {
19996   @<Add the known |value(p)| to the constant term of |v|@>;
19997 } else { 
19998   s=type(p); r=dep_list(p);
19999   if ( t==mp_dependent ) {
20000     if ( s==mp_dependent ) {
20001       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20002         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20003       } /* |fix_needed| will necessarily be false */
20004       t=mp_proto_dependent; 
20005       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20006     }
20007     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20008     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20009  DONE:  
20010     @<Output the answer, |v| (which might have become |known|)@>;
20011   }
20012
20013 @ @<Add the known |value(p)| to the constant term of |v|@>=
20014
20015   while ( info(v)!=null ) v=link(v);
20016   value(v)=mp_slow_add(mp, value(p),value(v));
20017 }
20018
20019 @ @<Output the answer, |v| (which might have become |known|)@>=
20020 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20021 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20022
20023 @ Here's the current situation: The dependency list |v| of type |t|
20024 should either be put into the current expression (if |q=null|) or
20025 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20026 or |q|) formerly held a dependency list with the same
20027 final pointer as the list |v|.
20028
20029 @<Declare the procedure called |dep_finish|@>=
20030 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20031   pointer p; /* the destination */
20032   scaled vv; /* the value, if it is |known| */
20033   if ( q==null ) p=mp->cur_exp; else p=q;
20034   dep_list(p)=v; type(p)=t;
20035   if ( info(v)==null ) { 
20036     vv=value(v);
20037     if ( q==null ) { 
20038       mp_flush_cur_exp(mp, vv);
20039     } else  { 
20040       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20041     }
20042   } else if ( q==null ) {
20043     mp->cur_type=t;
20044   }
20045   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20046 }
20047
20048 @ Let's turn now to the six basic relations of comparison.
20049
20050 @<Additional cases of binary operators@>=
20051 case less_than: case less_or_equal: case greater_than:
20052 case greater_or_equal: case equal_to: case unequal_to:
20053   check_arith; /* at this point |arith_error| should be |false|? */
20054   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20055     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20056   } else if ( mp->cur_type!=type(p) ) {
20057     mp_bad_binary(mp, p,c); goto DONE; 
20058   } else if ( mp->cur_type==mp_string_type ) {
20059     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20060   } else if ((mp->cur_type==mp_unknown_string)||
20061            (mp->cur_type==mp_unknown_boolean) ) {
20062     @<Check if unknowns have been equated@>;
20063   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20064     @<Reduce comparison of big nodes to comparison of scalars@>;
20065   } else if ( mp->cur_type==mp_boolean_type ) {
20066     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20067   } else { 
20068     mp_bad_binary(mp, p,c); goto DONE;
20069   }
20070   @<Compare the current expression with zero@>;
20071 DONE:  
20072   mp->arith_error=false; /* ignore overflow in comparisons */
20073   break;
20074
20075 @ @<Compare the current expression with zero@>=
20076 if ( mp->cur_type!=mp_known ) {
20077   if ( mp->cur_type<mp_known ) {
20078     mp_disp_err(mp, p,"");
20079     help1("The quantities shown above have not been equated.")
20080   } else  {
20081     help2("Oh dear. I can\'t decide if the expression above is positive,")
20082      ("negative, or zero. So this comparison test won't be `true'.");
20083   }
20084   exp_err("Unknown relation will be considered false");
20085 @.Unknown relation...@>
20086   mp_put_get_flush_error(mp, false_code);
20087 } else {
20088   switch (c) {
20089   case less_than: boolean_reset(mp->cur_exp<0); break;
20090   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20091   case greater_than: boolean_reset(mp->cur_exp>0); break;
20092   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20093   case equal_to: boolean_reset(mp->cur_exp==0); break;
20094   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20095   }; /* there are no other cases */
20096 }
20097 mp->cur_type=mp_boolean_type
20098
20099 @ When two unknown strings are in the same ring, we know that they are
20100 equal. Otherwise, we don't know whether they are equal or not, so we
20101 make no change.
20102
20103 @<Check if unknowns have been equated@>=
20104
20105   q=value(mp->cur_exp);
20106   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20107   if ( q==p ) mp_flush_cur_exp(mp, 0);
20108 }
20109
20110 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20111
20112   q=value(p); r=value(mp->cur_exp);
20113   rr=r+mp->big_node_size[mp->cur_type]-2;
20114   while (1) { mp_add_or_subtract(mp, q,r,minus);
20115     if ( type(r)!=mp_known ) break;
20116     if ( value(r)!=0 ) break;
20117     if ( r==rr ) break;
20118     q=q+2; r=r+2;
20119   }
20120   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20121 }
20122
20123 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20124
20125 @<Additional cases of binary operators@>=
20126 case and_op:
20127 case or_op: 
20128   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20129     mp_bad_binary(mp, p,c);
20130   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20131   break;
20132
20133 @ @<Additional cases of binary operators@>=
20134 case times: 
20135   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20136    mp_bad_binary(mp, p,times);
20137   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20138     @<Multiply when at least one operand is known@>;
20139   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20140       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20141           (type(p)>mp_pair_type)) ) {
20142     mp_hard_times(mp, p); return;
20143   } else {
20144     mp_bad_binary(mp, p,times);
20145   }
20146   break;
20147
20148 @ @<Multiply when at least one operand is known@>=
20149
20150   if ( type(p)==mp_known ) {
20151     v=value(p); mp_free_node(mp, p,value_node_size); 
20152   } else {
20153     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20154   }
20155   if ( mp->cur_type==mp_known ) {
20156     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20157   } else if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_color_type)||
20158               (mp->cur_type==mp_cmykcolor_type) ) {
20159     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20160     do {  
20161        p=p-2; mp_dep_mult(mp, p,v,true);
20162     } while (p!=value(mp->cur_exp));
20163   } else {
20164     mp_dep_mult(mp, null,v,true);
20165   }
20166   return;
20167 }
20168
20169 @ @<Declare binary action...@>=
20170 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20171   pointer q; /* the dependency list being multiplied by |v| */
20172   small_number s,t; /* its type, before and after */
20173   if ( p==null ) {
20174     q=mp->cur_exp;
20175   } else if ( type(p)!=mp_known ) {
20176     q=p;
20177   } else { 
20178     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20179     else value(p)=mp_take_fraction(mp, value(p),v);
20180     return;
20181   };
20182   t=type(q); q=dep_list(q); s=t;
20183   if ( t==mp_dependent ) if ( v_is_scaled )
20184     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20185       t=mp_proto_dependent;
20186   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20187   mp_dep_finish(mp, q,p,t);
20188 }
20189
20190 @ Here is a routine that is similar to |times|; but it is invoked only
20191 internally, when |v| is a |fraction| whose magnitude is at most~1,
20192 and when |cur_type>=mp_color_type|.
20193
20194 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20195   /* multiplies |cur_exp| by |n/d| */
20196   pointer p; /* a pair node */
20197   pointer old_exp; /* a capsule to recycle */
20198   fraction v; /* |n/d| */
20199   if ( mp->internal[mp_tracing_commands]>two ) {
20200     @<Trace the fraction multiplication@>;
20201   }
20202   switch (mp->cur_type) {
20203   case mp_transform_type:
20204   case mp_color_type:
20205   case mp_cmykcolor_type:
20206   case mp_pair_type:
20207    old_exp=mp_tarnished(mp, mp->cur_exp);
20208    break;
20209   case mp_independent: old_exp=mp_void; break;
20210   default: old_exp=null; break;
20211   }
20212   if ( old_exp!=null ) { 
20213      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20214   }
20215   v=mp_make_fraction(mp, n,d);
20216   if ( mp->cur_type==mp_known ) {
20217     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20218   } else if ( mp->cur_type<=mp_pair_type ) { 
20219     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20220     do {  
20221       p=p-2;
20222       mp_dep_mult(mp, p,v,false);
20223     } while (p!=value(mp->cur_exp));
20224   } else {
20225     mp_dep_mult(mp, null,v,false);
20226   }
20227   if ( old_exp!=null ) {
20228     mp_recycle_value(mp, old_exp); 
20229     mp_free_node(mp, old_exp,value_node_size);
20230   }
20231 }
20232
20233 @ @<Trace the fraction multiplication@>=
20234
20235   mp_begin_diagnostic(mp); 
20236   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20237   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20238   mp_print(mp,")}");
20239   mp_end_diagnostic(mp, false);
20240 }
20241
20242 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20243
20244 @<Declare binary action procedures@>=
20245 void mp_hard_times (MP mp,pointer p) {
20246   pointer q; /* a copy of the dependent variable |p| */
20247   pointer r; /* a component of the big node for the nice color or pair */
20248   scaled v; /* the known value for |r| */
20249   if ( type(p)<=mp_pair_type ) { 
20250      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20251   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20252   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20253   while (1) { 
20254     r=r-2;
20255     v=value(r);
20256     type(r)=type(p);
20257     if ( r==value(mp->cur_exp) ) 
20258       break;
20259     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20260     mp_dep_mult(mp, r,v,true);
20261   }
20262   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20263   link(prev_dep(p))=r;
20264   mp_free_node(mp, p,value_node_size);
20265   mp_dep_mult(mp, r,v,true);
20266 }
20267
20268 @ @<Additional cases of binary operators@>=
20269 case over: 
20270   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20271     mp_bad_binary(mp, p,over);
20272   } else { 
20273     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20274     if ( v==0 ) {
20275       @<Squeal about division by zero@>;
20276     } else { 
20277       if ( mp->cur_type==mp_known ) {
20278         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20279       } else if ( mp->cur_type<=mp_pair_type ) { 
20280         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20281         do {  
20282           p=p-2;  mp_dep_div(mp, p,v);
20283         } while (p!=value(mp->cur_exp));
20284       } else {
20285         mp_dep_div(mp, null,v);
20286       }
20287     }
20288     return;
20289   }
20290   break;
20291
20292 @ @<Declare binary action...@>=
20293 void mp_dep_div (MP mp,pointer p, scaled v) {
20294   pointer q; /* the dependency list being divided by |v| */
20295   small_number s,t; /* its type, before and after */
20296   if ( p==null ) q=mp->cur_exp;
20297   else if ( type(p)!=mp_known ) q=p;
20298   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20299   t=type(q); q=dep_list(q); s=t;
20300   if ( t==mp_dependent )
20301     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20302       t=mp_proto_dependent;
20303   q=mp_p_over_v(mp, q,v,s,t); 
20304   mp_dep_finish(mp, q,p,t);
20305 }
20306
20307 @ @<Squeal about division by zero@>=
20308
20309   exp_err("Division by zero");
20310 @.Division by zero@>
20311   help2("You're trying to divide the quantity shown above the error")
20312     ("message by zero. I'm going to divide it by one instead.");
20313   mp_put_get_error(mp);
20314 }
20315
20316 @ @<Additional cases of binary operators@>=
20317 case pythag_add:
20318 case pythag_sub: 
20319    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20320      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20321      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20322    } else mp_bad_binary(mp, p,c);
20323    break;
20324
20325 @ The next few sections of the program deal with affine transformations
20326 of coordinate data.
20327
20328 @<Additional cases of binary operators@>=
20329 case rotated_by: case slanted_by:
20330 case scaled_by: case shifted_by: case transformed_by:
20331 case x_scaled: case y_scaled: case z_scaled:
20332   if ( type(p)==mp_path_type ) { 
20333     path_trans(c,p); return;
20334   } else if ( type(p)==mp_pen_type ) { 
20335     pen_trans(c,p);
20336     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20337       /* rounding error could destroy convexity */
20338     return;
20339   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20340     mp_big_trans(mp, p,c);
20341   } else if ( type(p)==mp_picture_type ) {
20342     mp_do_edges_trans(mp, p,c); return;
20343   } else {
20344     mp_bad_binary(mp, p,c);
20345   }
20346   break;
20347
20348 @ Let |c| be one of the eight transform operators. The procedure call
20349 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20350 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20351 change at all if |c=transformed_by|.)
20352
20353 Then, if all components of the resulting transform are |known|, they are
20354 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20355 and |cur_exp| is changed to the known value zero.
20356
20357 @<Declare binary action...@>=
20358 void mp_set_up_trans (MP mp,quarterword c) {
20359   pointer p,q,r; /* list manipulation registers */
20360   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20361     @<Put the current transform into |cur_exp|@>;
20362   }
20363   @<If the current transform is entirely known, stash it in global variables;
20364     otherwise |return|@>;
20365 }
20366
20367 @ @<Glob...@>=
20368 scaled txx;
20369 scaled txy;
20370 scaled tyx;
20371 scaled tyy;
20372 scaled tx;
20373 scaled ty; /* current transform coefficients */
20374
20375 @ @<Put the current transform...@>=
20376
20377   p=mp_stash_cur_exp(mp); 
20378   mp->cur_exp=mp_id_transform(mp); 
20379   mp->cur_type=mp_transform_type;
20380   q=value(mp->cur_exp);
20381   switch (c) {
20382   @<For each of the eight cases, change the relevant fields of |cur_exp|
20383     and |goto done|;
20384     but do nothing if capsule |p| doesn't have the appropriate type@>;
20385   }; /* there are no other cases */
20386   mp_disp_err(mp, p,"Improper transformation argument");
20387 @.Improper transformation argument@>
20388   help3("The expression shown above has the wrong type,")
20389        ("so I can\'t transform anything using it.")
20390        ("Proceed, and I'll omit the transformation.");
20391   mp_put_get_error(mp);
20392 DONE: 
20393   mp_recycle_value(mp, p); 
20394   mp_free_node(mp, p,value_node_size);
20395 }
20396
20397 @ @<If the current transform is entirely known, ...@>=
20398 q=value(mp->cur_exp); r=q+transform_node_size;
20399 do {  
20400   r=r-2;
20401   if ( type(r)!=mp_known ) return;
20402 } while (r!=q);
20403 mp->txx=value(xx_part_loc(q));
20404 mp->txy=value(xy_part_loc(q));
20405 mp->tyx=value(yx_part_loc(q));
20406 mp->tyy=value(yy_part_loc(q));
20407 mp->tx=value(x_part_loc(q));
20408 mp->ty=value(y_part_loc(q));
20409 mp_flush_cur_exp(mp, 0)
20410
20411 @ @<For each of the eight cases...@>=
20412 case rotated_by:
20413   if ( type(p)==mp_known )
20414     @<Install sines and cosines, then |goto done|@>;
20415   break;
20416 case slanted_by:
20417   if ( type(p)>mp_pair_type ) { 
20418    mp_install(mp, xy_part_loc(q),p); goto DONE;
20419   };
20420   break;
20421 case scaled_by:
20422   if ( type(p)>mp_pair_type ) { 
20423     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20424     goto DONE;
20425   };
20426   break;
20427 case shifted_by:
20428   if ( type(p)==mp_pair_type ) {
20429     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20430     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20431   };
20432   break;
20433 case x_scaled:
20434   if ( type(p)>mp_pair_type ) {
20435     mp_install(mp, xx_part_loc(q),p); goto DONE;
20436   };
20437   break;
20438 case y_scaled:
20439   if ( type(p)>mp_pair_type ) {
20440     mp_install(mp, yy_part_loc(q),p); goto DONE;
20441   };
20442   break;
20443 case z_scaled:
20444   if ( type(p)==mp_pair_type )
20445     @<Install a complex multiplier, then |goto done|@>;
20446   break;
20447 case transformed_by:
20448   break;
20449   
20450
20451 @ @<Install sines and cosines, then |goto done|@>=
20452 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20453   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20454   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20455   value(xy_part_loc(q))=-value(yx_part_loc(q));
20456   value(yy_part_loc(q))=value(xx_part_loc(q));
20457   goto DONE;
20458 }
20459
20460 @ @<Install a complex multiplier, then |goto done|@>=
20461
20462   r=value(p);
20463   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20464   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20465   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20466   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20467   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20468   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20469   goto DONE;
20470 }
20471
20472 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20473 insists that the transformation be entirely known.
20474
20475 @<Declare binary action...@>=
20476 void mp_set_up_known_trans (MP mp,quarterword c) { 
20477   mp_set_up_trans(mp, c);
20478   if ( mp->cur_type!=mp_known ) {
20479     exp_err("Transform components aren't all known");
20480 @.Transform components...@>
20481     help3("I'm unable to apply a partially specified transformation")
20482       ("except to a fully known pair or transform.")
20483       ("Proceed, and I'll omit the transformation.");
20484     mp_put_get_flush_error(mp, 0);
20485     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20486     mp->tx=0; mp->ty=0;
20487   }
20488 }
20489
20490 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20491 coordinates in locations |p| and~|q|.
20492
20493 @<Declare binary action...@>= 
20494 void mp_trans (MP mp,pointer p, pointer q) {
20495   scaled v; /* the new |x| value */
20496   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20497   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20498   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20499   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20500   mp->mem[p].sc=v;
20501 }
20502
20503 @ The simplest transformation procedure applies a transform to all
20504 coordinates of a path.  The |path_trans(c)(p)| macro applies
20505 a transformation defined by |cur_exp| and the transform operator |c|
20506 to the path~|p|.
20507
20508 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20509                      mp_unstash_cur_exp(mp, (B)); 
20510                      mp_do_path_trans(mp, mp->cur_exp); }
20511
20512 @<Declare binary action...@>=
20513 void mp_do_path_trans (MP mp,pointer p) {
20514   pointer q; /* list traverser */
20515   q=p;
20516   do { 
20517     if ( left_type(q)!=mp_endpoint ) 
20518       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20519     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20520     if ( right_type(q)!=mp_endpoint ) 
20521       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20522 @^data structure assumptions@>
20523     q=link(q);
20524   } while (q!=p);
20525 }
20526
20527 @ Transforming a pen is very similar, except that there are no |left_type|
20528 and |right_type| fields.
20529
20530 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20531                     mp_unstash_cur_exp(mp, (B)); 
20532                     mp_do_pen_trans(mp, mp->cur_exp); }
20533
20534 @<Declare binary action...@>=
20535 void mp_do_pen_trans (MP mp,pointer p) {
20536   pointer q; /* list traverser */
20537   if ( pen_is_elliptical(p) ) {
20538     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20539     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20540   };
20541   q=p;
20542   do { 
20543     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20544 @^data structure assumptions@>
20545     q=link(q);
20546   } while (q!=p);
20547 }
20548
20549 @ The next transformation procedure applies to edge structures. It will do
20550 any transformation, but the results may be substandard if the picture contains
20551 text that uses downloaded bitmap fonts.  The binary action procedure is
20552 |do_edges_trans|, but we also need a function that just scales a picture.
20553 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20554 should be thought of as procedures that update an edge structure |h|, except
20555 that they have to return a (possibly new) structure because of the need to call
20556 |private_edges|.
20557
20558 @<Declare binary action...@>=
20559 pointer mp_edges_trans (MP mp, pointer h) {
20560   pointer q; /* the object being transformed */
20561   pointer r,s; /* for list manipulation */
20562   scaled sx,sy; /* saved transformation parameters */
20563   scaled sqdet; /* square root of determinant for |dash_scale| */
20564   integer sgndet; /* sign of the determinant */
20565   scaled v; /* a temporary value */
20566   h=mp_private_edges(mp, h);
20567   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20568   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20569   if ( dash_list(h)!=null_dash ) {
20570     @<Try to transform the dash list of |h|@>;
20571   }
20572   @<Make the bounding box of |h| unknown if it can't be updated properly
20573     without scanning the whole structure@>;  
20574   q=link(dummy_loc(h));
20575   while ( q!=null ) { 
20576     @<Transform graphical object |q|@>;
20577     q=link(q);
20578   }
20579   return h;
20580 }
20581 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20582   mp_set_up_known_trans(mp, c);
20583   value(p)=mp_edges_trans(mp, value(p));
20584   mp_unstash_cur_exp(mp, p);
20585 }
20586 void mp_scale_edges (MP mp) { 
20587   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20588   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20589   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20590 }
20591
20592 @ @<Try to transform the dash list of |h|@>=
20593 if ( (mp->txy!=0)||(mp->tyx!=0)||
20594      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20595   mp_flush_dash_list(mp, h);
20596 } else { 
20597   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20598   @<Scale the dash list by |txx| and shift it by |tx|@>;
20599   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20600 }
20601
20602 @ @<Reverse the dash list of |h|@>=
20603
20604   r=dash_list(h);
20605   dash_list(h)=null_dash;
20606   while ( r!=null_dash ) {
20607     s=r; r=link(r);
20608     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20609     link(s)=dash_list(h);
20610     dash_list(h)=s;
20611   }
20612 }
20613
20614 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20615 r=dash_list(h);
20616 while ( r!=null_dash ) {
20617   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20618   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20619   r=link(r);
20620 }
20621
20622 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20623 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20624   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20625 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20626   mp_init_bbox(mp, h);
20627   goto DONE1;
20628 }
20629 if ( minx_val(h)<=maxx_val(h) ) {
20630   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20631    |(tx,ty)|@>;
20632 }
20633 DONE1:
20634
20635
20636
20637 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20638
20639   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20640   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20641 }
20642
20643 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20644 sum is similar.
20645
20646 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20647
20648   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20649   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20650   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20651   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20652   if ( mp->txx+mp->txy<0 ) {
20653     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20654   }
20655   if ( mp->tyx+mp->tyy<0 ) {
20656     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20657   }
20658 }
20659
20660 @ Now we ready for the main task of transforming the graphical objects in edge
20661 structure~|h|.
20662
20663 @<Transform graphical object |q|@>=
20664 switch (type(q)) {
20665 case mp_fill_code: case mp_stroked_code: 
20666   mp_do_path_trans(mp, path_p(q));
20667   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20668   break;
20669 case mp_start_clip_code: case mp_start_bounds_code: 
20670   mp_do_path_trans(mp, path_p(q));
20671   break;
20672 case mp_text_code: 
20673   r=text_tx_loc(q);
20674   @<Transform the compact transformation starting at |r|@>;
20675   break;
20676 case mp_stop_clip_code: case mp_stop_bounds_code: 
20677   break;
20678 } /* there are no other cases */
20679
20680 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20681 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20682 since the \ps\ output procedures will try to compensate for the transformation
20683 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20684 root of the determinant, |sqdet| is the appropriate factor.
20685
20686 @<Transform |pen_p(q)|, making sure...@>=
20687 if ( pen_p(q)!=null ) {
20688   sx=mp->tx; sy=mp->ty;
20689   mp->tx=0; mp->ty=0;
20690   mp_do_pen_trans(mp, pen_p(q));
20691   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20692     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20693   if ( ! pen_is_elliptical(pen_p(q)) )
20694     if ( sgndet<0 )
20695       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20696          /* this unreverses the pen */
20697   mp->tx=sx; mp->ty=sy;
20698 }
20699
20700 @ This uses the fact that transformations are stored in the order
20701 |(tx,ty,txx,txy,tyx,tyy)|.
20702 @^data structure assumptions@>
20703
20704 @<Transform the compact transformation starting at |r|@>=
20705 mp_trans(mp, r,r+1);
20706 sx=mp->tx; sy=mp->ty;
20707 mp->tx=0; mp->ty=0;
20708 mp_trans(mp, r+2,r+4);
20709 mp_trans(mp, r+3,r+5);
20710 mp->tx=sx; mp->ty=sy
20711
20712 @ The hard cases of transformation occur when big nodes are involved,
20713 and when some of their components are unknown.
20714
20715 @<Declare binary action...@>=
20716 @<Declare subroutines needed by |big_trans|@>;
20717 void mp_big_trans (MP mp,pointer p, quarterword c) {
20718   pointer q,r,pp,qq; /* list manipulation registers */
20719   small_number s; /* size of a big node */
20720   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20721   do {  
20722     r=r-2;
20723     if ( type(r)!=mp_known ) {
20724       @<Transform an unknown big node and |return|@>;
20725     }
20726   } while (r!=q);
20727   @<Transform a known big node@>;
20728 }; /* node |p| will now be recycled by |do_binary| */
20729
20730 @ @<Transform an unknown big node and |return|@>=
20731
20732   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20733   r=value(mp->cur_exp);
20734   if ( mp->cur_type==mp_transform_type ) {
20735     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20736     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20737     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20738     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20739   }
20740   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20741   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20742   return;
20743 }
20744
20745 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20746 and let |q| point to a another value field. The |bilin1| procedure
20747 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20748
20749 @<Declare subroutines needed by |big_trans|@>=
20750 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20751                 scaled u, scaled delta) {
20752   pointer r; /* list traverser */
20753   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20754   if ( u!=0 ) {
20755     if ( type(q)==mp_known ) {
20756       delta+=mp_take_scaled(mp, value(q),u);
20757     } else { 
20758       @<Ensure that |type(p)=mp_proto_dependent|@>;
20759       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20760                                mp_proto_dependent,type(q));
20761     }
20762   }
20763   if ( type(p)==mp_known ) {
20764     value(p)+=delta;
20765   } else {
20766     r=dep_list(p);
20767     while ( info(r)!=null ) r=link(r);
20768     delta+=value(r);
20769     if ( r!=dep_list(p) ) value(r)=delta;
20770     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20771   }
20772   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20773 }
20774
20775 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20776 if ( type(p)!=mp_proto_dependent ) {
20777   if ( type(p)==mp_known ) 
20778     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20779   else 
20780     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20781                              mp_proto_dependent,true);
20782   type(p)=mp_proto_dependent;
20783 }
20784
20785 @ @<Transform a known big node@>=
20786 mp_set_up_trans(mp, c);
20787 if ( mp->cur_type==mp_known ) {
20788   @<Transform known by known@>;
20789 } else { 
20790   pp=mp_stash_cur_exp(mp); qq=value(pp);
20791   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20792   if ( mp->cur_type==mp_transform_type ) {
20793     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20794       value(xy_part_loc(q)),yx_part_loc(qq),null);
20795     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20796       value(xx_part_loc(q)),yx_part_loc(qq),null);
20797     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20798       value(yy_part_loc(q)),xy_part_loc(qq),null);
20799     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20800       value(yx_part_loc(q)),xy_part_loc(qq),null);
20801   };
20802   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20803     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20804   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20805     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20806   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20807 }
20808
20809 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20810 at |dep_final|. The following procedure adds |v| times another
20811 numeric quantity to~|p|.
20812
20813 @<Declare subroutines needed by |big_trans|@>=
20814 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20815   if ( type(r)==mp_known ) {
20816     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20817   } else  { 
20818     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20819                                                          mp_proto_dependent,type(r));
20820     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20821   }
20822 }
20823
20824 @ The |bilin2| procedure is something like |bilin1|, but with known
20825 and unknown quantities reversed. Parameter |p| points to a value field
20826 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20827 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20828 unless it is |null| (which stands for zero). Location~|p| will be
20829 replaced by $p\cdot t+v\cdot u+q$.
20830
20831 @<Declare subroutines needed by |big_trans|@>=
20832 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20833                 pointer u, pointer q) {
20834   scaled vv; /* temporary storage for |value(p)| */
20835   vv=value(p); type(p)=mp_proto_dependent;
20836   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20837   if ( vv!=0 ) 
20838     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20839   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20840   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20841   if ( dep_list(p)==mp->dep_final ) {
20842     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20843     type(p)=mp_known; value(p)=vv;
20844   }
20845 }
20846
20847 @ @<Transform known by known@>=
20848
20849   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20850   if ( mp->cur_type==mp_transform_type ) {
20851     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20852     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20853     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20854     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20855   }
20856   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20857   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20858 }
20859
20860 @ Finally, in |bilin3| everything is |known|.
20861
20862 @<Declare subroutines needed by |big_trans|@>=
20863 void mp_bilin3 (MP mp,pointer p, scaled t, 
20864                scaled v, scaled u, scaled delta) { 
20865   if ( t!=unity )
20866     delta+=mp_take_scaled(mp, value(p),t);
20867   else 
20868     delta+=value(p);
20869   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20870   else value(p)=delta;
20871 }
20872
20873 @ @<Additional cases of binary operators@>=
20874 case concatenate: 
20875   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20876   else mp_bad_binary(mp, p,concatenate);
20877   break;
20878 case substring_of: 
20879   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20880     mp_chop_string(mp, value(p));
20881   else mp_bad_binary(mp, p,substring_of);
20882   break;
20883 case subpath_of: 
20884   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20885   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20886     mp_chop_path(mp, value(p));
20887   else mp_bad_binary(mp, p,subpath_of);
20888   break;
20889
20890 @ @<Declare binary action...@>=
20891 void mp_cat (MP mp,pointer p) {
20892   str_number a,b; /* the strings being concatenated */
20893   pool_pointer k; /* index into |str_pool| */
20894   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20895   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20896     append_char(mp->str_pool[k]);
20897   }
20898   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20899     append_char(mp->str_pool[k]);
20900   }
20901   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20902 }
20903
20904 @ @<Declare binary action...@>=
20905 void mp_chop_string (MP mp,pointer p) {
20906   integer a, b; /* start and stop points */
20907   integer l; /* length of the original string */
20908   integer k; /* runs from |a| to |b| */
20909   str_number s; /* the original string */
20910   boolean reversed; /* was |a>b|? */
20911   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20912   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20913   if ( a<=b ) reversed=false;
20914   else  { reversed=true; k=a; a=b; b=k; };
20915   s=mp->cur_exp; l=length(s);
20916   if ( a<0 ) { 
20917     a=0;
20918     if ( b<0 ) b=0;
20919   }
20920   if ( b>l ) { 
20921     b=l;
20922     if ( a>l ) a=l;
20923   }
20924   str_room(b-a);
20925   if ( reversed ) {
20926     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20927       append_char(mp->str_pool[k]);
20928     }
20929   } else  {
20930     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20931       append_char(mp->str_pool[k]);
20932     }
20933   }
20934   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20935 }
20936
20937 @ @<Declare binary action...@>=
20938 void mp_chop_path (MP mp,pointer p) {
20939   pointer q; /* a knot in the original path */
20940   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
20941   scaled a,b,k,l; /* indices for chopping */
20942   boolean reversed; /* was |a>b|? */
20943   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
20944   if ( a<=b ) reversed=false;
20945   else  { reversed=true; k=a; a=b; b=k; };
20946   @<Dispense with the cases |a<0| and/or |b>l|@>;
20947   q=mp->cur_exp;
20948   while ( a>=unity ) {
20949     q=link(q); a=a-unity; b=b-unity;
20950   }
20951   if ( b==a ) {
20952     @<Construct a path from |pp| to |qq| of length zero@>; 
20953   } else { 
20954     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
20955   }
20956   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
20957   mp_toss_knot_list(mp, mp->cur_exp);
20958   if ( reversed ) {
20959     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
20960   } else {
20961     mp->cur_exp=pp;
20962   }
20963 }
20964
20965 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
20966 if ( a<0 ) {
20967   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20968     a=0; if ( b<0 ) b=0;
20969   } else  {
20970     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
20971   }
20972 }
20973 if ( b>l ) {
20974   if ( left_type(mp->cur_exp)==mp_endpoint ) {
20975     b=l; if ( a>l ) a=l;
20976   } else {
20977     while ( a>=l ) { 
20978       a=a-l; b=b-l;
20979     }
20980   }
20981 }
20982
20983 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
20984
20985   pp=mp_copy_knot(mp, q); qq=pp;
20986   do {  
20987     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
20988   } while (b>0);
20989   if ( a>0 ) {
20990     ss=pp; pp=link(pp);
20991     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
20992     mp_free_node(mp, ss,knot_node_size);
20993     if ( rr==ss ) {
20994       b=mp_make_scaled(mp, b,unity-a); rr=pp;
20995     }
20996   }
20997   if ( b<0 ) {
20998     mp_split_cubic(mp, rr,(b+unity)*010000);
20999     mp_free_node(mp, qq,knot_node_size);
21000     qq=link(rr);
21001   }
21002 }
21003
21004 @ @<Construct a path from |pp| to |qq| of length zero@>=
21005
21006   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
21007   pp=mp_copy_knot(mp, q); qq=pp;
21008 }
21009
21010 @ @<Additional cases of binary operators@>=
21011 case point_of: case precontrol_of: case postcontrol_of: 
21012   if ( mp->cur_type==mp_pair_type )
21013      mp_pair_to_path(mp);
21014   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21015     mp_find_point(mp, value(p),c);
21016   else 
21017     mp_bad_binary(mp, p,c);
21018   break;
21019 case pen_offset_of: 
21020   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21021     mp_set_up_offset(mp, value(p));
21022   else 
21023     mp_bad_binary(mp, p,pen_offset_of);
21024   break;
21025 case direction_time_of: 
21026   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21027   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21028     mp_set_up_direction_time(mp, value(p));
21029   else 
21030     mp_bad_binary(mp, p,direction_time_of);
21031   break;
21032 case envelope_of:
21033   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21034     mp_bad_binary(mp, p,envelope_of);
21035   else
21036     mp_set_up_envelope(mp, p);
21037   break;
21038
21039 @ @<Declare binary action...@>=
21040 void mp_set_up_offset (MP mp,pointer p) { 
21041   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21042   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21043 }
21044 void mp_set_up_direction_time (MP mp,pointer p) { 
21045   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21046   value(y_part_loc(p)),mp->cur_exp));
21047 }
21048 void mp_set_up_envelope (MP mp,pointer p) {
21049   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21050   /* TODO: accept elliptical pens for straight paths */
21051   if (pen_is_elliptical(value(p))) {
21052     mp_bad_envelope_pen(mp);
21053     mp->cur_exp = q;
21054     mp->cur_type = mp_path_type;
21055     return;
21056   }
21057   small_number ljoin, lcap;
21058   scaled miterlim;
21059   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21060   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21061   else ljoin=0;
21062   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21063   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21064   else lcap=0;
21065   if ( mp->internal[mp_miterlimit]<unity )
21066     miterlim=unity;
21067   else
21068     miterlim=mp->internal[mp_miterlimit];
21069   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21070   mp->cur_type = mp_path_type;
21071 }
21072
21073 @ @<Declare binary action...@>=
21074 void mp_find_point (MP mp,scaled v, quarterword c) {
21075   pointer p; /* the path */
21076   scaled n; /* its length */
21077   p=mp->cur_exp;
21078   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21079   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21080   if ( n==0 ) { 
21081     v=0; 
21082   } else if ( v<0 ) {
21083     if ( left_type(p)==mp_endpoint ) v=0;
21084     else v=n-1-((-v-1) % n);
21085   } else if ( v>n ) {
21086     if ( left_type(p)==mp_endpoint ) v=n;
21087     else v=v % n;
21088   }
21089   p=mp->cur_exp;
21090   while ( v>=unity ) { p=link(p); v=v-unity;  };
21091   if ( v!=0 ) {
21092      @<Insert a fractional node by splitting the cubic@>;
21093   }
21094   @<Set the current expression to the desired path coordinates@>;
21095 }
21096
21097 @ @<Insert a fractional node...@>=
21098 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21099
21100 @ @<Set the current expression to the desired path coordinates...@>=
21101 switch (c) {
21102 case point_of: 
21103   mp_pair_value(mp, x_coord(p),y_coord(p));
21104   break;
21105 case precontrol_of: 
21106   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21107   else mp_pair_value(mp, left_x(p),left_y(p));
21108   break;
21109 case postcontrol_of: 
21110   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21111   else mp_pair_value(mp, right_x(p),right_y(p));
21112   break;
21113 } /* there are no other cases */
21114
21115 @ @<Additional cases of binary operators@>=
21116 case arc_time_of: 
21117   if ( mp->cur_type==mp_pair_type )
21118      mp_pair_to_path(mp);
21119   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21120     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21121   else 
21122     mp_bad_binary(mp, p,c);
21123   break;
21124
21125 @ @<Additional cases of bin...@>=
21126 case intersect: 
21127   if ( type(p)==mp_pair_type ) {
21128     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21129     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21130   };
21131   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21132   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21133     mp_path_intersection(mp, value(p),mp->cur_exp);
21134     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21135   } else {
21136     mp_bad_binary(mp, p,intersect);
21137   }
21138   break;
21139
21140 @ @<Additional cases of bin...@>=
21141 case in_font:
21142   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21143     mp_bad_binary(mp, p,in_font);
21144   else { mp_do_infont(mp, p); return; }
21145   break;
21146
21147 @ Function |new_text_node| owns the reference count for its second argument
21148 (the text string) but not its first (the font name).
21149
21150 @<Declare binary action...@>=
21151 void mp_do_infont (MP mp,pointer p) {
21152   pointer q;
21153   q=mp_get_node(mp, edge_header_size);
21154   mp_init_edges(mp, q);
21155   link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21156   obj_tail(q)=link(obj_tail(q));
21157   mp_free_node(mp, p,value_node_size);
21158   mp_flush_cur_exp(mp, q);
21159   mp->cur_type=mp_picture_type;
21160 }
21161
21162 @* \[40] Statements and commands.
21163 The chief executive of \MP\ is the |do_statement| routine, which
21164 contains the master switch that causes all the various pieces of \MP\
21165 to do their things, in the right order.
21166
21167 In a sense, this is the grand climax of the program: It applies all the
21168 tools that we have worked so hard to construct. In another sense, this is
21169 the messiest part of the program: It necessarily refers to other pieces
21170 of code all over the place, so that a person can't fully understand what is
21171 going on without paging back and forth to be reminded of conventions that
21172 are defined elsewhere. We are now at the hub of the web.
21173
21174 The structure of |do_statement| itself is quite simple.  The first token
21175 of the statement is fetched using |get_x_next|.  If it can be the first
21176 token of an expression, we look for an equation, an assignment, or a
21177 title. Otherwise we use a \&{case} construction to branch at high speed to
21178 the appropriate routine for various and sundry other types of commands,
21179 each of which has an ``action procedure'' that does the necessary work.
21180
21181 The program uses the fact that
21182 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21183 to interpret a statement that starts with, e.g., `\&{string}',
21184 as a type declaration rather than a boolean expression.
21185
21186 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21187   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21188   if ( mp->cur_cmd>max_primary_command ) {
21189     @<Worry about bad statement@>;
21190   } else if ( mp->cur_cmd>max_statement_command ) {
21191     @<Do an equation, assignment, title, or
21192      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21193   } else {
21194     @<Do a statement that doesn't begin with an expression@>;
21195   }
21196   if ( mp->cur_cmd<semicolon )
21197     @<Flush unparsable junk that was found after the statement@>;
21198   mp->error_count=0;
21199 }
21200
21201 @ @<Declarations@>=
21202 @<Declare action procedures for use by |do_statement|@>;
21203
21204 @ The only command codes |>max_primary_command| that can be present
21205 at the beginning of a statement are |semicolon| and higher; these
21206 occur when the statement is null.
21207
21208 @<Worry about bad statement@>=
21209
21210   if ( mp->cur_cmd<semicolon ) {
21211     print_err("A statement can't begin with `");
21212 @.A statement can't begin with x@>
21213     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21214     help5("I was looking for the beginning of a new statement.")
21215       ("If you just proceed without changing anything, I'll ignore")
21216       ("everything up to the next `;'. Please insert a semicolon")
21217       ("now in front of anything that you don't want me to delete.")
21218       ("(See Chapter 27 of The METAFONTbook for an example.)");
21219 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21220     mp_back_error(mp); mp_get_x_next(mp);
21221   }
21222 }
21223
21224 @ The help message printed here says that everything is flushed up to
21225 a semicolon, but actually the commands |end_group| and |stop| will
21226 also terminate a statement.
21227
21228 @<Flush unparsable junk that was found after the statement@>=
21229
21230   print_err("Extra tokens will be flushed");
21231 @.Extra tokens will be flushed@>
21232   help6("I've just read as much of that statement as I could fathom,")
21233        ("so a semicolon should have been next. It's very puzzling...")
21234        ("but I'll try to get myself back together, by ignoring")
21235        ("everything up to the next `;'. Please insert a semicolon")
21236        ("now in front of anything that you don't want me to delete.")
21237        ("(See Chapter 27 of The METAFONTbook for an example.)");
21238 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21239   mp_back_error(mp); mp->scanner_status=flushing;
21240   do {  
21241     get_t_next;
21242     @<Decrease the string reference count...@>;
21243   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21244   mp->scanner_status=normal;
21245 }
21246
21247 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21248 |cur_type=mp_vacuous| unless the statement was simply an expression;
21249 in the latter case, |cur_type| and |cur_exp| should represent that
21250 expression.
21251
21252 @<Do a statement that doesn't...@>=
21253
21254   if ( mp->internal[mp_tracing_commands]>0 ) 
21255     show_cur_cmd_mod;
21256   switch (mp->cur_cmd ) {
21257   case type_name:mp_do_type_declaration(mp); break;
21258   case macro_def:
21259     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21260     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21261      break;
21262   @<Cases of |do_statement| that invoke particular commands@>;
21263   } /* there are no other cases */
21264   mp->cur_type=mp_vacuous;
21265 }
21266
21267 @ The most important statements begin with expressions.
21268
21269 @<Do an equation, assignment, title, or...@>=
21270
21271   mp->var_flag=assignment; mp_scan_expression(mp);
21272   if ( mp->cur_cmd<end_group ) {
21273     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21274     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21275     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21276     else if ( mp->cur_type!=mp_vacuous ){ 
21277       exp_err("Isolated expression");
21278 @.Isolated expression@>
21279       help3("I couldn't find an `=' or `:=' after the")
21280         ("expression that is shown above this error message,")
21281         ("so I guess I'll just ignore it and carry on.");
21282       mp_put_get_error(mp);
21283     }
21284     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21285   }
21286 }
21287
21288 @ @<Do a title@>=
21289
21290   if ( mp->internal[mp_tracing_titles]>0 ) {
21291     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21292   }
21293 }
21294
21295 @ Equations and assignments are performed by the pair of mutually recursive
21296 @^recursion@>
21297 routines |do_equation| and |do_assignment|. These routines are called when
21298 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21299 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21300 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21301 will be equal to the right-hand side (which will normally be equal
21302 to the left-hand side).
21303
21304 @<Declare action procedures for use by |do_statement|@>=
21305 @<Declare the procedure called |try_eq|@>;
21306 @<Declare the procedure called |make_eq|@>;
21307 void mp_do_equation (MP mp) ;
21308
21309 @ @c
21310 void mp_do_equation (MP mp) {
21311   pointer lhs; /* capsule for the left-hand side */
21312   pointer p; /* temporary register */
21313   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21314   mp->var_flag=assignment; mp_scan_expression(mp);
21315   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21316   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21317   if ( mp->internal[mp_tracing_commands]>two ) 
21318     @<Trace the current equation@>;
21319   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21320     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21321   }; /* in this case |make_eq| will change the pair to a path */
21322   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21323 }
21324
21325 @ And |do_assignment| is similar to |do_expression|:
21326
21327 @<Declarations@>=
21328 void mp_do_assignment (MP mp);
21329
21330 @ @<Declare action procedures for use by |do_statement|@>=
21331 void mp_do_assignment (MP mp) ;
21332
21333 @ @c
21334 void mp_do_assignment (MP mp) {
21335   pointer lhs; /* token list for the left-hand side */
21336   pointer p; /* where the left-hand value is stored */
21337   pointer q; /* temporary capsule for the right-hand value */
21338   if ( mp->cur_type!=mp_token_list ) { 
21339     exp_err("Improper `:=' will be changed to `='");
21340 @.Improper `:='@>
21341     help2("I didn't find a variable name at the left of the `:=',")
21342       ("so I'm going to pretend that you said `=' instead.");
21343     mp_error(mp); mp_do_equation(mp);
21344   } else { 
21345     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21346     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21347     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21348     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21349     if ( mp->internal[mp_tracing_commands]>two ) 
21350       @<Trace the current assignment@>;
21351     if ( info(lhs)>hash_end ) {
21352       @<Assign the current expression to an internal variable@>;
21353     } else  {
21354       @<Assign the current expression to the variable |lhs|@>;
21355     }
21356     mp_flush_node_list(mp, lhs);
21357   }
21358 }
21359
21360 @ @<Trace the current equation@>=
21361
21362   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21363   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21364   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21365 }
21366
21367 @ @<Trace the current assignment@>=
21368
21369   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21370   if ( info(lhs)>hash_end ) 
21371      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21372   else 
21373      mp_show_token_list(mp, lhs,null,1000,0);
21374   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21375   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21376 }
21377
21378 @ @<Assign the current expression to an internal variable@>=
21379 if ( mp->cur_type==mp_known )  {
21380   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21381 } else { 
21382   exp_err("Internal quantity `");
21383 @.Internal quantity...@>
21384   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21385   mp_print(mp, "' must receive a known value");
21386   help2("I can\'t set an internal quantity to anything but a known")
21387     ("numeric value, so I'll have to ignore this assignment.");
21388   mp_put_get_error(mp);
21389 }
21390
21391 @ @<Assign the current expression to the variable |lhs|@>=
21392
21393   p=mp_find_variable(mp, lhs);
21394   if ( p!=null ) {
21395     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21396     mp_recycle_value(mp, p);
21397     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21398     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21399   } else  { 
21400     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21401   }
21402 }
21403
21404
21405 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21406 a pointer to a capsule that is to be equated to the current expression.
21407
21408 @<Declare the procedure called |make_eq|@>=
21409 void mp_make_eq (MP mp,pointer lhs) ;
21410
21411
21412
21413 @c void mp_make_eq (MP mp,pointer lhs) {
21414   small_number t; /* type of the left-hand side */
21415   pointer p,q; /* pointers inside of big nodes */
21416   integer v=0; /* value of the left-hand side */
21417 RESTART: 
21418   t=type(lhs);
21419   if ( t<=mp_pair_type ) v=value(lhs);
21420   switch (t) {
21421   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21422     is incompatible with~|t|@>;
21423   } /* all cases have been listed */
21424   @<Announce that the equation cannot be performed@>;
21425 DONE:
21426   check_arith; mp_recycle_value(mp, lhs); 
21427   mp_free_node(mp, lhs,value_node_size);
21428 }
21429
21430 @ @<Announce that the equation cannot be performed@>=
21431 mp_disp_err(mp, lhs,""); 
21432 exp_err("Equation cannot be performed (");
21433 @.Equation cannot be performed@>
21434 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21435 else mp_print(mp, "numeric");
21436 mp_print_char(mp, '=');
21437 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21438 else mp_print(mp, "numeric");
21439 mp_print_char(mp, ')');
21440 help2("I'm sorry, but I don't know how to make such things equal.")
21441      ("(See the two expressions just above the error message.)");
21442 mp_put_get_error(mp)
21443
21444 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21445 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21446 case mp_path_type: case mp_picture_type:
21447   if ( mp->cur_type==t+unknown_tag ) { 
21448     mp_nonlinear_eq(mp, v,mp->cur_exp,false); goto DONE;
21449   } else if ( mp->cur_type==t ) {
21450     @<Report redundant or inconsistent equation and |goto done|@>;
21451   }
21452   break;
21453 case unknown_types:
21454   if ( mp->cur_type==t-unknown_tag ) { 
21455     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21456   } else if ( mp->cur_type==t ) { 
21457     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21458   } else if ( mp->cur_type==mp_pair_type ) {
21459     if ( t==mp_unknown_path ) { 
21460      mp_pair_to_path(mp); goto RESTART;
21461     };
21462   }
21463   break;
21464 case mp_transform_type: case mp_color_type:
21465 case mp_cmykcolor_type: case mp_pair_type:
21466   if ( mp->cur_type==t ) {
21467     @<Do multiple equations and |goto done|@>;
21468   }
21469   break;
21470 case mp_known: case mp_dependent:
21471 case mp_proto_dependent: case mp_independent:
21472   if ( mp->cur_type>=mp_known ) { 
21473     mp_try_eq(mp, lhs,null); goto DONE;
21474   };
21475   break;
21476 case mp_vacuous:
21477   break;
21478
21479 @ @<Report redundant or inconsistent equation and |goto done|@>=
21480
21481   if ( mp->cur_type<=mp_string_type ) {
21482     if ( mp->cur_type==mp_string_type ) {
21483       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21484         goto NOT_FOUND;
21485       }
21486     } else if ( v!=mp->cur_exp ) {
21487       goto NOT_FOUND;
21488     }
21489     @<Exclaim about a redundant equation@>; goto DONE;
21490   }
21491   print_err("Redundant or inconsistent equation");
21492 @.Redundant or inconsistent equation@>
21493   help2("An equation between already-known quantities can't help.")
21494        ("But don't worry; continue and I'll just ignore it.");
21495   mp_put_get_error(mp); goto DONE;
21496 NOT_FOUND: 
21497   print_err("Inconsistent equation");
21498 @.Inconsistent equation@>
21499   help2("The equation I just read contradicts what was said before.")
21500        ("But don't worry; continue and I'll just ignore it.");
21501   mp_put_get_error(mp); goto DONE;
21502 }
21503
21504 @ @<Do multiple equations and |goto done|@>=
21505
21506   p=v+mp->big_node_size[t]; 
21507   q=value(mp->cur_exp)+mp->big_node_size[t];
21508   do {  
21509     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21510   } while (p!=v);
21511   goto DONE;
21512 }
21513
21514 @ The first argument to |try_eq| is the location of a value node
21515 in a capsule that will soon be recycled. The second argument is
21516 either a location within a pair or transform node pointed to by
21517 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21518 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21519 but to equate the two operands.
21520
21521 @<Declare the procedure called |try_eq|@>=
21522 void mp_try_eq (MP mp,pointer l, pointer r) ;
21523
21524
21525 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21526   pointer p; /* dependency list for right operand minus left operand */
21527   int t; /* the type of list |p| */
21528   pointer q; /* the constant term of |p| is here */
21529   pointer pp; /* dependency list for right operand */
21530   int tt; /* the type of list |pp| */
21531   boolean copied; /* have we copied a list that ought to be recycled? */
21532   @<Remove the left operand from its container, negate it, and
21533     put it into dependency list~|p| with constant term~|q|@>;
21534   @<Add the right operand to list |p|@>;
21535   if ( info(p)==null ) {
21536     @<Deal with redundant or inconsistent equation@>;
21537   } else { 
21538     mp_linear_eq(mp, p,t);
21539     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21540       if ( type(mp->cur_exp)==mp_known ) {
21541         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21542         mp_free_node(mp, pp,value_node_size);
21543       }
21544     }
21545   }
21546 }
21547
21548 @ @<Remove the left operand from its container, negate it, and...@>=
21549 t=type(l);
21550 if ( t==mp_known ) { 
21551   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21552 } else if ( t==mp_independent ) {
21553   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21554   q=mp->dep_final;
21555 } else { 
21556   p=dep_list(l); q=p;
21557   while (1) { 
21558     negate(value(q));
21559     if ( info(q)==null ) break;
21560     q=link(q);
21561   }
21562   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21563   type(l)=mp_known;
21564 }
21565
21566 @ @<Deal with redundant or inconsistent equation@>=
21567
21568   if ( abs(value(p))>64 ) { /* off by .001 or more */
21569     print_err("Inconsistent equation");
21570 @.Inconsistent equation@>
21571     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21572     mp_print_char(mp, ')');
21573     help2("The equation I just read contradicts what was said before.")
21574       ("But don't worry; continue and I'll just ignore it.");
21575     mp_put_get_error(mp);
21576   } else if ( r==null ) {
21577     @<Exclaim about a redundant equation@>;
21578   }
21579   mp_free_node(mp, p,dep_node_size);
21580 }
21581
21582 @ @<Add the right operand to list |p|@>=
21583 if ( r==null ) {
21584   if ( mp->cur_type==mp_known ) {
21585     value(q)=value(q)+mp->cur_exp; goto DONE1;
21586   } else { 
21587     tt=mp->cur_type;
21588     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21589     else pp=dep_list(mp->cur_exp);
21590   } 
21591 } else {
21592   if ( type(r)==mp_known ) {
21593     value(q)=value(q)+value(r); goto DONE1;
21594   } else { 
21595     tt=type(r);
21596     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21597     else pp=dep_list(r);
21598   }
21599 }
21600 if ( tt!=mp_independent ) copied=false;
21601 else  { copied=true; tt=mp_dependent; };
21602 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21603 if ( copied ) mp_flush_node_list(mp, pp);
21604 DONE1:
21605
21606 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21607 mp->watch_coefs=false;
21608 if ( t==tt ) {
21609   p=mp_p_plus_q(mp, p,pp,t);
21610 } else if ( t==mp_proto_dependent ) {
21611   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21612 } else { 
21613   q=p;
21614   while ( info(q)!=null ) {
21615     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21616   }
21617   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21618 }
21619 mp->watch_coefs=true;
21620
21621 @ Our next goal is to process type declarations. For this purpose it's
21622 convenient to have a procedure that scans a $\langle\,$declared
21623 variable$\,\rangle$ and returns the corresponding token list. After the
21624 following procedure has acted, the token after the declared variable
21625 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21626 and~|cur_sym|.
21627
21628 @<Declare the function called |scan_declared_variable|@>=
21629 pointer mp_scan_declared_variable (MP mp) {
21630   pointer x; /* hash address of the variable's root */
21631   pointer h,t; /* head and tail of the token list to be returned */
21632   pointer l; /* hash address of left bracket */
21633   mp_get_symbol(mp); x=mp->cur_sym;
21634   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21635   h=mp_get_avail(mp); info(h)=x; t=h;
21636   while (1) { 
21637     mp_get_x_next(mp);
21638     if ( mp->cur_sym==0 ) break;
21639     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21640       if ( mp->cur_cmd==left_bracket ) {
21641         @<Descend past a collective subscript@>;
21642       } else {
21643         break;
21644       }
21645     }
21646     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21647   }
21648   if ( eq_type(x)!=tag_token ) mp_clear_symbol(mp, x,false);
21649   if ( equiv(x)==null ) mp_new_root(mp, x);
21650   return h;
21651 }
21652
21653 @ If the subscript isn't collective, we don't accept it as part of the
21654 declared variable.
21655
21656 @<Descend past a collective subscript@>=
21657
21658   l=mp->cur_sym; mp_get_x_next(mp);
21659   if ( mp->cur_cmd!=right_bracket ) {
21660     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21661   } else {
21662     mp->cur_sym=collective_subscript;
21663   }
21664 }
21665
21666 @ Type declarations are introduced by the following primitive operations.
21667
21668 @<Put each...@>=
21669 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21670 @:numeric_}{\&{numeric} primitive@>
21671 mp_primitive(mp, "string",type_name,mp_string_type);
21672 @:string_}{\&{string} primitive@>
21673 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21674 @:boolean_}{\&{boolean} primitive@>
21675 mp_primitive(mp, "path",type_name,mp_path_type);
21676 @:path_}{\&{path} primitive@>
21677 mp_primitive(mp, "pen",type_name,mp_pen_type);
21678 @:pen_}{\&{pen} primitive@>
21679 mp_primitive(mp, "picture",type_name,mp_picture_type);
21680 @:picture_}{\&{picture} primitive@>
21681 mp_primitive(mp, "transform",type_name,mp_transform_type);
21682 @:transform_}{\&{transform} primitive@>
21683 mp_primitive(mp, "color",type_name,mp_color_type);
21684 @:color_}{\&{color} primitive@>
21685 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21686 @:color_}{\&{rgbcolor} primitive@>
21687 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21688 @:color_}{\&{cmykcolor} primitive@>
21689 mp_primitive(mp, "pair",type_name,mp_pair_type);
21690 @:pair_}{\&{pair} primitive@>
21691
21692 @ @<Cases of |print_cmd...@>=
21693 case type_name: mp_print_type(mp, m); break;
21694
21695 @ Now we are ready to handle type declarations, assuming that a
21696 |type_name| has just been scanned.
21697
21698 @<Declare action procedures for use by |do_statement|@>=
21699 void mp_do_type_declaration (MP mp) ;
21700
21701 @ @c
21702 void mp_do_type_declaration (MP mp) {
21703   small_number t; /* the type being declared */
21704   pointer p; /* token list for a declared variable */
21705   pointer q; /* value node for the variable */
21706   if ( mp->cur_mod>=mp_transform_type ) 
21707     t=mp->cur_mod;
21708   else 
21709     t=mp->cur_mod+unknown_tag;
21710   do {  
21711     p=mp_scan_declared_variable(mp);
21712     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21713     q=mp_find_variable(mp, p);
21714     if ( q!=null ) { 
21715       type(q)=t; value(q)=null; 
21716     } else  { 
21717       print_err("Declared variable conflicts with previous vardef");
21718 @.Declared variable conflicts...@>
21719       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21720            ("Proceed, and I'll ignore the illegal redeclaration.");
21721       mp_put_get_error(mp);
21722     }
21723     mp_flush_list(mp, p);
21724     if ( mp->cur_cmd<comma ) {
21725       @<Flush spurious symbols after the declared variable@>;
21726     }
21727   } while (! end_of_statement);
21728 }
21729
21730 @ @<Flush spurious symbols after the declared variable@>=
21731
21732   print_err("Illegal suffix of declared variable will be flushed");
21733 @.Illegal suffix...flushed@>
21734   help5("Variables in declarations must consist entirely of")
21735     ("names and collective subscripts, e.g., `x[]a'.")
21736     ("Are you trying to use a reserved word in a variable name?")
21737     ("I'm going to discard the junk I found here,")
21738     ("up to the next comma or the end of the declaration.");
21739   if ( mp->cur_cmd==numeric_token )
21740     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21741   mp_put_get_error(mp); mp->scanner_status=flushing;
21742   do {  
21743     get_t_next;
21744     @<Decrease the string reference count...@>;
21745   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21746   mp->scanner_status=normal;
21747 }
21748
21749 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21750 until coming to the end of the user's program.
21751 Each execution of |do_statement| concludes with
21752 |cur_cmd=semicolon|, |end_group|, or |stop|.
21753
21754 @c void mp_main_control (MP mp) { 
21755   do {  
21756     mp_do_statement(mp);
21757     if ( mp->cur_cmd==end_group ) {
21758       print_err("Extra `endgroup'");
21759 @.Extra `endgroup'@>
21760       help2("I'm not currently working on a `begingroup',")
21761         ("so I had better not try to end anything.");
21762       mp_flush_error(mp, 0);
21763     }
21764   } while (mp->cur_cmd!=stop);
21765 }
21766 int __attribute__((noinline)) 
21767 mp_run (MP mp) {
21768   if (mp->history < mp_fatal_error_stop ) {
21769     @<Install and test the non-local jump buffer@>;
21770     mp_main_control(mp); /* come to life */
21771     mp_final_cleanup(mp); /* prepare for death */
21772     mp_close_files_and_terminate(mp);
21773   }
21774   return mp->history;
21775 }
21776 int __attribute__((noinline)) 
21777 mp_execute (MP mp) {
21778   if (mp->history < mp_fatal_error_stop ) {
21779     mp->history = mp_spotless;
21780     mp->file_offset = 0;
21781     mp->term_offset = 0;
21782     mp->tally = 0; 
21783     @<Install and test the non-local jump buffer@>;
21784     mp_input_ln(mp,mp->term_in);
21785     mp_firm_up_the_line(mp);
21786     mp->buffer[limit]='%';
21787     mp->first=limit+1; 
21788     loc=start;
21789     mp_main_control(mp); /* come to life */ 
21790   }
21791   return mp->history;
21792 }
21793 int __attribute__((noinline)) 
21794 mp_finish (MP mp) {
21795   if (mp->history < mp_fatal_error_stop ) {
21796     @<Install and test the non-local jump buffer@>;
21797     mp_final_cleanup(mp); /* prepare for death */
21798     mp_close_files_and_terminate(mp);
21799   }
21800   return mp->history;
21801 }
21802 char * mp_mplib_version (MP mp) {
21803   assert(mp);
21804   return mplib_version;
21805 }
21806 char * mp_metapost_version (MP mp) {
21807   assert(mp);
21808   return metapost_version;
21809 }
21810
21811 @ @<Exported function headers@>=
21812 int mp_run (MP mp);
21813 int mp_execute (MP mp);
21814 int mp_finish (MP mp);
21815 char * mp_mplib_version (MP mp);
21816 char * mp_metapost_version (MP mp);
21817
21818 @ @<Put each...@>=
21819 mp_primitive(mp, "end",stop,0);
21820 @:end_}{\&{end} primitive@>
21821 mp_primitive(mp, "dump",stop,1);
21822 @:dump_}{\&{dump} primitive@>
21823
21824 @ @<Cases of |print_cmd...@>=
21825 case stop:
21826   if ( m==0 ) mp_print(mp, "end");
21827   else mp_print(mp, "dump");
21828   break;
21829
21830 @* \[41] Commands.
21831 Let's turn now to statements that are classified as ``commands'' because
21832 of their imperative nature. We'll begin with simple ones, so that it
21833 will be clear how to hook command processing into the |do_statement| routine;
21834 then we'll tackle the tougher commands.
21835
21836 Here's one of the simplest:
21837
21838 @<Cases of |do_statement|...@>=
21839 case mp_random_seed: mp_do_random_seed(mp);  break;
21840
21841 @ @<Declare action procedures for use by |do_statement|@>=
21842 void mp_do_random_seed (MP mp) ;
21843
21844 @ @c void mp_do_random_seed (MP mp) { 
21845   mp_get_x_next(mp);
21846   if ( mp->cur_cmd!=assignment ) {
21847     mp_missing_err(mp, ":=");
21848 @.Missing `:='@>
21849     help1("Always say `randomseed:=<numeric expression>'.");
21850     mp_back_error(mp);
21851   };
21852   mp_get_x_next(mp); mp_scan_expression(mp);
21853   if ( mp->cur_type!=mp_known ) {
21854     exp_err("Unknown value will be ignored");
21855 @.Unknown value...ignored@>
21856     help2("Your expression was too random for me to handle,")
21857       ("so I won't change the random seed just now.");
21858     mp_put_get_flush_error(mp, 0);
21859   } else {
21860    @<Initialize the random seed to |cur_exp|@>;
21861   }
21862 }
21863
21864 @ @<Initialize the random seed to |cur_exp|@>=
21865
21866   mp_init_randoms(mp, mp->cur_exp);
21867   if ( mp->selector>=log_only && mp->selector<write_file) {
21868     mp->old_setting=mp->selector; mp->selector=log_only;
21869     mp_print_nl(mp, "{randomseed:="); 
21870     mp_print_scaled(mp, mp->cur_exp); 
21871     mp_print_char(mp, '}');
21872     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21873   }
21874 }
21875
21876 @ And here's another simple one (somewhat different in flavor):
21877
21878 @<Cases of |do_statement|...@>=
21879 case mode_command: 
21880   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21881   @<Initialize the print |selector| based on |interaction|@>;
21882   if ( mp->log_opened ) mp->selector=mp->selector+2;
21883   mp_get_x_next(mp);
21884   break;
21885
21886 @ @<Put each...@>=
21887 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21888 @:mp_batch_mode_}{\&{batchmode} primitive@>
21889 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21890 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21891 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21892 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21893 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21894 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21895
21896 @ @<Cases of |print_cmd_mod|...@>=
21897 case mode_command: 
21898   switch (m) {
21899   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21900   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21901   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21902   default: mp_print(mp, "errorstopmode"); break;
21903   }
21904   break;
21905
21906 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21907
21908 @<Cases of |do_statement|...@>=
21909 case protection_command: mp_do_protection(mp); break;
21910
21911 @ @<Put each...@>=
21912 mp_primitive(mp, "inner",protection_command,0);
21913 @:inner_}{\&{inner} primitive@>
21914 mp_primitive(mp, "outer",protection_command,1);
21915 @:outer_}{\&{outer} primitive@>
21916
21917 @ @<Cases of |print_cmd...@>=
21918 case protection_command: 
21919   if ( m==0 ) mp_print(mp, "inner");
21920   else mp_print(mp, "outer");
21921   break;
21922
21923 @ @<Declare action procedures for use by |do_statement|@>=
21924 void mp_do_protection (MP mp) ;
21925
21926 @ @c void mp_do_protection (MP mp) {
21927   int m; /* 0 to unprotect, 1 to protect */
21928   halfword t; /* the |eq_type| before we change it */
21929   m=mp->cur_mod;
21930   do {  
21931     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
21932     if ( m==0 ) { 
21933       if ( t>=outer_tag ) 
21934         eq_type(mp->cur_sym)=t-outer_tag;
21935     } else if ( t<outer_tag ) {
21936       eq_type(mp->cur_sym)=t+outer_tag;
21937     }
21938     mp_get_x_next(mp);
21939   } while (mp->cur_cmd==comma);
21940 }
21941
21942 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
21943 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
21944 declaration assigns the command code |left_delimiter| to `\.{(}' and
21945 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
21946 hash address of its mate.
21947
21948 @<Cases of |do_statement|...@>=
21949 case delimiters: mp_def_delims(mp); break;
21950
21951 @ @<Declare action procedures for use by |do_statement|@>=
21952 void mp_def_delims (MP mp) ;
21953
21954 @ @c void mp_def_delims (MP mp) {
21955   pointer l_delim,r_delim; /* the new delimiter pair */
21956   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
21957   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
21958   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
21959   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
21960   mp_get_x_next(mp);
21961 }
21962
21963 @ Here is a procedure that is called when \MP\ has reached a point
21964 where some right delimiter is mandatory.
21965
21966 @<Declare the procedure called |check_delimiter|@>=
21967 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
21968   if ( mp->cur_cmd==right_delimiter ) 
21969     if ( mp->cur_mod==l_delim ) 
21970       return;
21971   if ( mp->cur_sym!=r_delim ) {
21972      mp_missing_err(mp, str(text(r_delim)));
21973 @.Missing `)'@>
21974     help2("I found no right delimiter to match a left one. So I've")
21975       ("put one in, behind the scenes; this may fix the problem.");
21976     mp_back_error(mp);
21977   } else { 
21978     print_err("The token `"); mp_print_text(r_delim);
21979 @.The token...delimiter@>
21980     mp_print(mp, "' is no longer a right delimiter");
21981     help3("Strange: This token has lost its former meaning!")
21982       ("I'll read it as a right delimiter this time;")
21983       ("but watch out, I'll probably miss it later.");
21984     mp_error(mp);
21985   }
21986 }
21987
21988 @ The next four commands save or change the values associated with tokens.
21989
21990 @<Cases of |do_statement|...@>=
21991 case save_command: 
21992   do {  
21993     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
21994   } while (mp->cur_cmd==comma);
21995   break;
21996 case interim_command: mp_do_interim(mp); break;
21997 case let_command: mp_do_let(mp); break;
21998 case new_internal: mp_do_new_internal(mp); break;
21999
22000 @ @<Declare action procedures for use by |do_statement|@>=
22001 void mp_do_statement (MP mp);
22002 void mp_do_interim (MP mp);
22003
22004 @ @c void mp_do_interim (MP mp) { 
22005   mp_get_x_next(mp);
22006   if ( mp->cur_cmd!=internal_quantity ) {
22007      print_err("The token `");
22008 @.The token...quantity@>
22009     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22010     else mp_print_text(mp->cur_sym);
22011     mp_print(mp, "' isn't an internal quantity");
22012     help1("Something like `tracingonline' should follow `interim'.");
22013     mp_back_error(mp);
22014   } else { 
22015     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22016   }
22017   mp_do_statement(mp);
22018 }
22019
22020 @ The following procedure is careful not to undefine the left-hand symbol
22021 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22022
22023 @<Declare action procedures for use by |do_statement|@>=
22024 void mp_do_let (MP mp) ;
22025
22026 @ @c void mp_do_let (MP mp) {
22027   pointer l; /* hash location of the left-hand symbol */
22028   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22029   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22030      mp_missing_err(mp, "=");
22031 @.Missing `='@>
22032     help3("You should have said `let symbol = something'.")
22033       ("But don't worry; I'll pretend that an equals sign")
22034       ("was present. The next token I read will be `something'.");
22035     mp_back_error(mp);
22036   }
22037   mp_get_symbol(mp);
22038   switch (mp->cur_cmd) {
22039   case defined_macro: case secondary_primary_macro:
22040   case tertiary_secondary_macro: case expression_tertiary_macro: 
22041     add_mac_ref(mp->cur_mod);
22042     break;
22043   default: 
22044     break;
22045   }
22046   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22047   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22048   else equiv(l)=mp->cur_mod;
22049   mp_get_x_next(mp);
22050 }
22051
22052 @ @<Declarations@>=
22053 void mp_grow_internals (MP mp, int l);
22054 void mp_do_new_internal (MP mp) ;
22055
22056 @ @c
22057 void mp_grow_internals (MP mp, int l) {
22058   scaled *internal;
22059   char * *int_name; 
22060   int k;
22061   if ( hash_end+l>max_halfword ) {
22062     mp_confusion(mp, "out of memory space"); /* can't be reached */
22063   }
22064   int_name = xmalloc ((l+1),sizeof(char *));
22065   internal = xmalloc ((l+1),sizeof(scaled));
22066   for (k=0;k<=l; k++ ) { 
22067     if (k<=mp->max_internal) {
22068       internal[k]=mp->internal[k]; 
22069       int_name[k]=mp->int_name[k]; 
22070     } else {
22071       internal[k]=0; 
22072       int_name[k]=NULL; 
22073     }
22074   }
22075   xfree(mp->internal); xfree(mp->int_name);
22076   mp->int_name = int_name;
22077   mp->internal = internal;
22078   mp->max_internal = l;
22079 }
22080
22081
22082 void mp_do_new_internal (MP mp) { 
22083   do {  
22084     if ( mp->int_ptr==mp->max_internal ) {
22085       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22086     }
22087     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22088     eq_type(mp->cur_sym)=internal_quantity; 
22089     equiv(mp->cur_sym)=mp->int_ptr;
22090     if(mp->int_name[mp->int_ptr]!=NULL)
22091       xfree(mp->int_name[mp->int_ptr]);
22092     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22093     mp->internal[mp->int_ptr]=0;
22094     mp_get_x_next(mp);
22095   } while (mp->cur_cmd==comma);
22096 }
22097
22098 @ @<Dealloc variables@>=
22099 for (k=0;k<=mp->max_internal;k++) {
22100    xfree(mp->int_name[k]);
22101 }
22102 xfree(mp->internal); 
22103 xfree(mp->int_name); 
22104
22105
22106 @ The various `\&{show}' commands are distinguished by modifier fields
22107 in the usual way.
22108
22109 @d show_token_code 0 /* show the meaning of a single token */
22110 @d show_stats_code 1 /* show current memory and string usage */
22111 @d show_code 2 /* show a list of expressions */
22112 @d show_var_code 3 /* show a variable and its descendents */
22113 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22114
22115 @<Put each...@>=
22116 mp_primitive(mp, "showtoken",show_command,show_token_code);
22117 @:show_token_}{\&{showtoken} primitive@>
22118 mp_primitive(mp, "showstats",show_command,show_stats_code);
22119 @:show_stats_}{\&{showstats} primitive@>
22120 mp_primitive(mp, "show",show_command,show_code);
22121 @:show_}{\&{show} primitive@>
22122 mp_primitive(mp, "showvariable",show_command,show_var_code);
22123 @:show_var_}{\&{showvariable} primitive@>
22124 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22125 @:show_dependencies_}{\&{showdependencies} primitive@>
22126
22127 @ @<Cases of |print_cmd...@>=
22128 case show_command: 
22129   switch (m) {
22130   case show_token_code:mp_print(mp, "showtoken"); break;
22131   case show_stats_code:mp_print(mp, "showstats"); break;
22132   case show_code:mp_print(mp, "show"); break;
22133   case show_var_code:mp_print(mp, "showvariable"); break;
22134   default: mp_print(mp, "showdependencies"); break;
22135   }
22136   break;
22137
22138 @ @<Cases of |do_statement|...@>=
22139 case show_command:mp_do_show_whatever(mp); break;
22140
22141 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22142 if it's |show_code|, complicated structures are abbreviated, otherwise
22143 they aren't.
22144
22145 @<Declare action procedures for use by |do_statement|@>=
22146 void mp_do_show (MP mp) ;
22147
22148 @ @c void mp_do_show (MP mp) { 
22149   do {  
22150     mp_get_x_next(mp); mp_scan_expression(mp);
22151     mp_print_nl(mp, ">> ");
22152 @.>>@>
22153     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22154   } while (mp->cur_cmd==comma);
22155 }
22156
22157 @ @<Declare action procedures for use by |do_statement|@>=
22158 void mp_disp_token (MP mp) ;
22159
22160 @ @c void mp_disp_token (MP mp) { 
22161   mp_print_nl(mp, "> ");
22162 @.>\relax@>
22163   if ( mp->cur_sym==0 ) {
22164     @<Show a numeric or string or capsule token@>;
22165   } else { 
22166     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22167     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22168     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22169     if ( mp->cur_cmd==defined_macro ) {
22170       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22171     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22172 @^recursion@>
22173   }
22174 }
22175
22176 @ @<Show a numeric or string or capsule token@>=
22177
22178   if ( mp->cur_cmd==numeric_token ) {
22179     mp_print_scaled(mp, mp->cur_mod);
22180   } else if ( mp->cur_cmd==capsule_token ) {
22181     mp_print_capsule(mp,mp->cur_mod);
22182   } else  { 
22183     mp_print_char(mp, '"'); 
22184     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22185     delete_str_ref(mp->cur_mod);
22186   }
22187 }
22188
22189 @ The following cases of |print_cmd_mod| might arise in connection
22190 with |disp_token|, although they don't correspond to any
22191 primitive tokens.
22192
22193 @<Cases of |print_cmd_...@>=
22194 case left_delimiter:
22195 case right_delimiter: 
22196   if ( c==left_delimiter ) mp_print(mp, "left");
22197   else mp_print(mp, "right");
22198   mp_print(mp, " delimiter that matches "); 
22199   mp_print_text(m);
22200   break;
22201 case tag_token:
22202   if ( m==null ) mp_print(mp, "tag");
22203    else mp_print(mp, "variable");
22204    break;
22205 case defined_macro: 
22206    mp_print(mp, "macro:");
22207    break;
22208 case secondary_primary_macro:
22209 case tertiary_secondary_macro:
22210 case expression_tertiary_macro:
22211   mp_print_cmd_mod(mp, macro_def,c); 
22212   mp_print(mp, "'d macro:");
22213   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22214   break;
22215 case repeat_loop:
22216   mp_print(mp, "[repeat the loop]");
22217   break;
22218 case internal_quantity:
22219   mp_print(mp, mp->int_name[m]);
22220   break;
22221
22222 @ @<Declare action procedures for use by |do_statement|@>=
22223 void mp_do_show_token (MP mp) ;
22224
22225 @ @c void mp_do_show_token (MP mp) { 
22226   do {  
22227     get_t_next; mp_disp_token(mp);
22228     mp_get_x_next(mp);
22229   } while (mp->cur_cmd==comma);
22230 }
22231
22232 @ @<Declare action procedures for use by |do_statement|@>=
22233 void mp_do_show_stats (MP mp) ;
22234
22235 @ @c void mp_do_show_stats (MP mp) { 
22236   mp_print_nl(mp, "Memory usage ");
22237 @.Memory usage...@>
22238   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22239   if ( false )
22240     mp_print(mp, "unknown");
22241   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22242   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22243   mp_print_nl(mp, "String usage ");
22244   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22245   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22246   if ( false )
22247     mp_print(mp, "unknown");
22248   mp_print(mp, " (");
22249   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22250   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22251   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22252   mp_get_x_next(mp);
22253 }
22254
22255 @ Here's a recursive procedure that gives an abbreviated account
22256 of a variable, for use by |do_show_var|.
22257
22258 @<Declare action procedures for use by |do_statement|@>=
22259 void mp_disp_var (MP mp,pointer p) ;
22260
22261 @ @c void mp_disp_var (MP mp,pointer p) {
22262   pointer q; /* traverses attributes and subscripts */
22263   int n; /* amount of macro text to show */
22264   if ( type(p)==mp_structured )  {
22265     @<Descend the structure@>;
22266   } else if ( type(p)>=mp_unsuffixed_macro ) {
22267     @<Display a variable macro@>;
22268   } else if ( type(p)!=undefined ){ 
22269     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22270     mp_print_char(mp, '=');
22271     mp_print_exp(mp, p,0);
22272   }
22273 }
22274
22275 @ @<Descend the structure@>=
22276
22277   q=attr_head(p);
22278   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22279   q=subscr_head(p);
22280   while ( name_type(q)==mp_subscr ) { 
22281     mp_disp_var(mp, q); q=link(q);
22282   }
22283 }
22284
22285 @ @<Display a variable macro@>=
22286
22287   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22288   if ( type(p)>mp_unsuffixed_macro ) 
22289     mp_print(mp, "@@#"); /* |suffixed_macro| */
22290   mp_print(mp, "=macro:");
22291   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22292   else n=mp->max_print_line-mp->file_offset-15;
22293   mp_show_macro(mp, value(p),null,n);
22294 }
22295
22296 @ @<Declare action procedures for use by |do_statement|@>=
22297 void mp_do_show_var (MP mp) ;
22298
22299 @ @c void mp_do_show_var (MP mp) { 
22300   do {  
22301     get_t_next;
22302     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22303       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22304       mp_disp_var(mp, mp->cur_mod); goto DONE;
22305     }
22306    mp_disp_token(mp);
22307   DONE:
22308    mp_get_x_next(mp);
22309   } while (mp->cur_cmd==comma);
22310 }
22311
22312 @ @<Declare action procedures for use by |do_statement|@>=
22313 void mp_do_show_dependencies (MP mp) ;
22314
22315 @ @c void mp_do_show_dependencies (MP mp) {
22316   pointer p; /* link that runs through all dependencies */
22317   p=link(dep_head);
22318   while ( p!=dep_head ) {
22319     if ( mp_interesting(mp, p) ) {
22320       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22321       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22322       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22323       mp_print_dependency(mp, dep_list(p),type(p));
22324     }
22325     p=dep_list(p);
22326     while ( info(p)!=null ) p=link(p);
22327     p=link(p);
22328   }
22329   mp_get_x_next(mp);
22330 }
22331
22332 @ Finally we are ready for the procedure that governs all of the
22333 show commands.
22334
22335 @<Declare action procedures for use by |do_statement|@>=
22336 void mp_do_show_whatever (MP mp) ;
22337
22338 @ @c void mp_do_show_whatever (MP mp) { 
22339   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22340   switch (mp->cur_mod) {
22341   case show_token_code:mp_do_show_token(mp); break;
22342   case show_stats_code:mp_do_show_stats(mp); break;
22343   case show_code:mp_do_show(mp); break;
22344   case show_var_code:mp_do_show_var(mp); break;
22345   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22346   } /* there are no other cases */
22347   if ( mp->internal[mp_showstopping]>0 ){ 
22348     print_err("OK");
22349 @.OK@>
22350     if ( mp->interaction<mp_error_stop_mode ) { 
22351       help0; decr(mp->error_count);
22352     } else {
22353       help1("This isn't an error message; I'm just showing something.");
22354     }
22355     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22356      else mp_put_get_error(mp);
22357   }
22358 }
22359
22360 @ The `\&{addto}' command needs the following additional primitives:
22361
22362 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22363 @d contour_code 1 /* command modifier for `\&{contour}' */
22364 @d also_code 2 /* command modifier for `\&{also}' */
22365
22366 @ Pre and postscripts need two new identifiers:
22367
22368 @d with_pre_script 11
22369 @d with_post_script 13
22370
22371 @<Put each...@>=
22372 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22373 @:double_path_}{\&{doublepath} primitive@>
22374 mp_primitive(mp, "contour",thing_to_add,contour_code);
22375 @:contour_}{\&{contour} primitive@>
22376 mp_primitive(mp, "also",thing_to_add,also_code);
22377 @:also_}{\&{also} primitive@>
22378 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22379 @:with_pen_}{\&{withpen} primitive@>
22380 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22381 @:dashed_}{\&{dashed} primitive@>
22382 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22383 @:with_pre_script_}{\&{withprescript} primitive@>
22384 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22385 @:with_post_script_}{\&{withpostscript} primitive@>
22386 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22387 @:with_color_}{\&{withoutcolor} primitive@>
22388 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22389 @:with_color_}{\&{withgreyscale} primitive@>
22390 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22391 @:with_color_}{\&{withcolor} primitive@>
22392 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22393 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22394 @:with_color_}{\&{withrgbcolor} primitive@>
22395 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22396 @:with_color_}{\&{withcmykcolor} primitive@>
22397
22398 @ @<Cases of |print_cmd...@>=
22399 case thing_to_add:
22400   if ( m==contour_code ) mp_print(mp, "contour");
22401   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22402   else mp_print(mp, "also");
22403   break;
22404 case with_option:
22405   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22406   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22407   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22408   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22409   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22410   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22411   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22412   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22413   else mp_print(mp, "dashed");
22414   break;
22415
22416 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22417 updates the list of graphical objects starting at |p|.  Each $\langle$with
22418 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22419 Other objects are ignored.
22420
22421 @<Declare action procedures for use by |do_statement|@>=
22422 void mp_scan_with_list (MP mp,pointer p) ;
22423
22424 @ @c void mp_scan_with_list (MP mp,pointer p) {
22425   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22426   pointer q; /* for list manipulation */
22427   int old_setting; /* saved |selector| setting */
22428   pointer k; /* for finding the near-last item in a list  */
22429   str_number s; /* for string cleanup after combining  */
22430   pointer cp,pp,dp,ap,bp;
22431     /* objects being updated; |void| initially; |null| to suppress update */
22432   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22433   k=0;
22434   while ( mp->cur_cmd==with_option ){ 
22435     t=mp->cur_mod;
22436     mp_get_x_next(mp);
22437     if ( t!=mp_no_model ) mp_scan_expression(mp);
22438     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22439      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22440      ((t==mp_uninitialized_model)&&
22441         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22442           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22443      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22444      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22445      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22446      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22447      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22448       @<Complain about improper type@>;
22449     } else if ( t==mp_uninitialized_model ) {
22450       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22451       if ( cp!=null )
22452         @<Transfer a color from the current expression to object~|cp|@>;
22453       mp_flush_cur_exp(mp, 0);
22454     } else if ( t==mp_rgb_model ) {
22455       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22456       if ( cp!=null )
22457         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22458       mp_flush_cur_exp(mp, 0);
22459     } else if ( t==mp_cmyk_model ) {
22460       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22461       if ( cp!=null )
22462         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22463       mp_flush_cur_exp(mp, 0);
22464     } else if ( t==mp_grey_model ) {
22465       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22466       if ( cp!=null )
22467         @<Transfer a greyscale from the current expression to object~|cp|@>;
22468       mp_flush_cur_exp(mp, 0);
22469     } else if ( t==mp_no_model ) {
22470       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22471       if ( cp!=null )
22472         @<Transfer a noncolor from the current expression to object~|cp|@>;
22473     } else if ( t==mp_pen_type ) {
22474       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22475       if ( pp!=null ) {
22476         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22477         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22478       }
22479     } else if ( t==with_pre_script ) {
22480       if ( ap==mp_void )
22481         ap=p;
22482       while ( (ap!=null)&&(! has_color(ap)) )
22483          ap=link(ap);
22484       if ( ap!=null ) {
22485         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22486           s=pre_script(ap);
22487           old_setting=mp->selector;
22488               mp->selector=new_string;
22489           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22490               mp_print_str(mp, mp->cur_exp);
22491           append_char(13);  /* a forced \ps\ newline  */
22492           mp_print_str(mp, pre_script(ap));
22493           pre_script(ap)=mp_make_string(mp);
22494           delete_str_ref(s);
22495           mp->selector=old_setting;
22496         } else {
22497           pre_script(ap)=mp->cur_exp;
22498         }
22499         mp->cur_type=mp_vacuous;
22500       }
22501     } else if ( t==with_post_script ) {
22502       if ( bp==mp_void )
22503         k=p; 
22504       bp=k;
22505       while ( link(k)!=null ) {
22506         k=link(k);
22507         if ( has_color(k) ) bp=k;
22508       }
22509       if ( bp!=null ) {
22510          if ( post_script(bp)!=null ) {
22511            s=post_script(bp);
22512            old_setting=mp->selector;
22513                mp->selector=new_string;
22514            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22515            mp_print_str(mp, post_script(bp));
22516            append_char(13); /* a forced \ps\ newline  */
22517            mp_print_str(mp, mp->cur_exp);
22518            post_script(bp)=mp_make_string(mp);
22519            delete_str_ref(s);
22520            mp->selector=old_setting;
22521          } else {
22522            post_script(bp)=mp->cur_exp;
22523          }
22524          mp->cur_type=mp_vacuous;
22525        }
22526     } else { 
22527       if ( dp==mp_void ) {
22528         @<Make |dp| a stroked node in list~|p|@>;
22529       }
22530       if ( dp!=null ) {
22531         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22532         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22533         dash_scale(dp)=unity;
22534         mp->cur_type=mp_vacuous;
22535       }
22536     }
22537   }
22538   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22539     of the list@>;
22540 };
22541
22542 @ @<Complain about improper type@>=
22543 { exp_err("Improper type");
22544 @.Improper type@>
22545 help2("Next time say `withpen <known pen expression>';")
22546   ("I'll ignore the bad `with' clause and look for another.");
22547 if ( t==with_pre_script )
22548   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22549 else if ( t==with_post_script )
22550   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22551 else if ( t==mp_picture_type )
22552   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22553 else if ( t==mp_uninitialized_model )
22554   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22555 else if ( t==mp_rgb_model )
22556   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22557 else if ( t==mp_cmyk_model )
22558   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22559 else if ( t==mp_grey_model )
22560   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22561 mp_put_get_flush_error(mp, 0);
22562 }
22563
22564 @ Forcing the color to be between |0| and |unity| here guarantees that no
22565 picture will ever contain a color outside the legal range for \ps\ graphics.
22566
22567 @<Transfer a color from the current expression to object~|cp|@>=
22568 { if ( mp->cur_type==mp_color_type )
22569    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22570 else if ( mp->cur_type==mp_cmykcolor_type )
22571    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22572 else if ( mp->cur_type==mp_known )
22573    @<Transfer a greyscale from the current expression to object~|cp|@>
22574 else if ( mp->cur_exp==false_code )
22575    @<Transfer a noncolor from the current expression to object~|cp|@>;
22576 }
22577
22578 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22579 { q=value(mp->cur_exp);
22580 cyan_val(cp)=0;
22581 magenta_val(cp)=0;
22582 yellow_val(cp)=0;
22583 black_val(cp)=0;
22584 red_val(cp)=value(red_part_loc(q));
22585 green_val(cp)=value(green_part_loc(q));
22586 blue_val(cp)=value(blue_part_loc(q));
22587 color_model(cp)=mp_rgb_model;
22588 if ( red_val(cp)<0 ) red_val(cp)=0;
22589 if ( green_val(cp)<0 ) green_val(cp)=0;
22590 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22591 if ( red_val(cp)>unity ) red_val(cp)=unity;
22592 if ( green_val(cp)>unity ) green_val(cp)=unity;
22593 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22594 }
22595
22596 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22597 { q=value(mp->cur_exp);
22598 cyan_val(cp)=value(cyan_part_loc(q));
22599 magenta_val(cp)=value(magenta_part_loc(q));
22600 yellow_val(cp)=value(yellow_part_loc(q));
22601 black_val(cp)=value(black_part_loc(q));
22602 color_model(cp)=mp_cmyk_model;
22603 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22604 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22605 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22606 if ( black_val(cp)<0 ) black_val(cp)=0;
22607 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22608 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22609 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22610 if ( black_val(cp)>unity ) black_val(cp)=unity;
22611 }
22612
22613 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22614 { q=mp->cur_exp;
22615 cyan_val(cp)=0;
22616 magenta_val(cp)=0;
22617 yellow_val(cp)=0;
22618 black_val(cp)=0;
22619 grey_val(cp)=q;
22620 color_model(cp)=mp_grey_model;
22621 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22622 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22623 }
22624
22625 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22626 {
22627 cyan_val(cp)=0;
22628 magenta_val(cp)=0;
22629 yellow_val(cp)=0;
22630 black_val(cp)=0;
22631 grey_val(cp)=0;
22632 color_model(cp)=mp_no_model;
22633 }
22634
22635 @ @<Make |cp| a colored object in object list~|p|@>=
22636 { cp=p;
22637   while ( cp!=null ){ 
22638     if ( has_color(cp) ) break;
22639     cp=link(cp);
22640   }
22641 }
22642
22643 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22644 { pp=p;
22645   while ( pp!=null ) {
22646     if ( has_pen(pp) ) break;
22647     pp=link(pp);
22648   }
22649 }
22650
22651 @ @<Make |dp| a stroked node in list~|p|@>=
22652 { dp=p;
22653   while ( dp!=null ) {
22654     if ( type(dp)==mp_stroked_code ) break;
22655     dp=link(dp);
22656   }
22657 }
22658
22659 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22660 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22661 if ( pp>mp_void ) {
22662   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22663 }
22664 if ( dp>mp_void ) {
22665   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22666 }
22667
22668
22669 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22670 { q=link(cp);
22671   while ( q!=null ) { 
22672     if ( has_color(q) ) {
22673       red_val(q)=red_val(cp);
22674       green_val(q)=green_val(cp);
22675       blue_val(q)=blue_val(cp);
22676       black_val(q)=black_val(cp);
22677       color_model(q)=color_model(cp);
22678     }
22679     q=link(q);
22680   }
22681 }
22682
22683 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22684 { q=link(pp);
22685   while ( q!=null ) {
22686     if ( has_pen(q) ) {
22687       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22688       pen_p(q)=copy_pen(pen_p(pp));
22689     }
22690     q=link(q);
22691   }
22692 }
22693
22694 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22695 { q=link(dp);
22696   while ( q!=null ) {
22697     if ( type(q)==mp_stroked_code ) {
22698       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22699       dash_p(q)=dash_p(dp);
22700       dash_scale(q)=unity;
22701       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22702     }
22703     q=link(q);
22704   }
22705 }
22706
22707 @ One of the things we need to do when we've parsed an \&{addto} or
22708 similar command is find the header of a supposed \&{picture} variable, given
22709 a token list for that variable.  Since the edge structure is about to be
22710 updated, we use |private_edges| to make sure that this is possible.
22711
22712 @<Declare action procedures for use by |do_statement|@>=
22713 pointer mp_find_edges_var (MP mp, pointer t) ;
22714
22715 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22716   pointer p;
22717   pointer cur_edges; /* the return value */
22718   p=mp_find_variable(mp, t); cur_edges=null;
22719   if ( p==null ) { 
22720     mp_obliterated(mp, t); mp_put_get_error(mp);
22721   } else if ( type(p)!=mp_picture_type )  { 
22722     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22723 @.Variable x is the wrong type@>
22724     mp_print(mp, " is the wrong type ("); 
22725     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22726     help2("I was looking for a \"known\" picture variable.")
22727          ("So I'll not change anything just now."); 
22728     mp_put_get_error(mp);
22729   } else { 
22730     value(p)=mp_private_edges(mp, value(p));
22731     cur_edges=value(p);
22732   }
22733   mp_flush_node_list(mp, t);
22734   return cur_edges;
22735 };
22736
22737 @ @<Cases of |do_statement|...@>=
22738 case add_to_command: mp_do_add_to(mp); break;
22739 case bounds_command:mp_do_bounds(mp); break;
22740
22741 @ @<Put each...@>=
22742 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22743 @:clip_}{\&{clip} primitive@>
22744 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22745 @:set_bounds_}{\&{setbounds} primitive@>
22746
22747 @ @<Cases of |print_cmd...@>=
22748 case bounds_command: 
22749   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22750   else mp_print(mp, "setbounds");
22751   break;
22752
22753 @ The following function parses the beginning of an \&{addto} or \&{clip}
22754 command: it expects a variable name followed by a token with |cur_cmd=sep|
22755 and then an expression.  The function returns the token list for the variable
22756 and stores the command modifier for the separator token in the global variable
22757 |last_add_type|.  We must be careful because this variable might get overwritten
22758 any time we call |get_x_next|.
22759
22760 @<Glob...@>=
22761 quarterword last_add_type;
22762   /* command modifier that identifies the last \&{addto} command */
22763
22764 @ @<Declare action procedures for use by |do_statement|@>=
22765 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22766
22767 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22768   pointer lhv; /* variable to add to left */
22769   quarterword add_type=0; /* value to be returned in |last_add_type| */
22770   lhv=null;
22771   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22772   if ( mp->cur_type!=mp_token_list ) {
22773     @<Abandon edges command because there's no variable@>;
22774   } else  { 
22775     lhv=mp->cur_exp; add_type=mp->cur_mod;
22776     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22777   }
22778   mp->last_add_type=add_type;
22779   return lhv;
22780 }
22781
22782 @ @<Abandon edges command because there's no variable@>=
22783 { exp_err("Not a suitable variable");
22784 @.Not a suitable variable@>
22785   help4("At this point I needed to see the name of a picture variable.")
22786     ("(Or perhaps you have indeed presented me with one; I might")
22787     ("have missed it, if it wasn't followed by the proper token.)")
22788     ("So I'll not change anything just now.");
22789   mp_put_get_flush_error(mp, 0);
22790 }
22791
22792 @ Here is an example of how to use |start_draw_cmd|.
22793
22794 @<Declare action procedures for use by |do_statement|@>=
22795 void mp_do_bounds (MP mp) ;
22796
22797 @ @c void mp_do_bounds (MP mp) {
22798   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22799   pointer p; /* for list manipulation */
22800   integer m; /* initial value of |cur_mod| */
22801   m=mp->cur_mod;
22802   lhv=mp_start_draw_cmd(mp, to_token);
22803   if ( lhv!=null ) {
22804     lhe=mp_find_edges_var(mp, lhv);
22805     if ( lhe==null ) {
22806       mp_flush_cur_exp(mp, 0);
22807     } else if ( mp->cur_type!=mp_path_type ) {
22808       exp_err("Improper `clip'");
22809 @.Improper `addto'@>
22810       help2("This expression should have specified a known path.")
22811         ("So I'll not change anything just now."); 
22812       mp_put_get_flush_error(mp, 0);
22813     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22814       @<Complain about a non-cycle@>;
22815     } else {
22816       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22817     }
22818   }
22819 }
22820
22821 @ @<Complain about a non-cycle@>=
22822 { print_err("Not a cycle");
22823 @.Not a cycle@>
22824   help2("That contour should have ended with `..cycle' or `&cycle'.")
22825     ("So I'll not change anything just now."); mp_put_get_error(mp);
22826 }
22827
22828 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22829 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22830   link(p)=link(dummy_loc(lhe));
22831   link(dummy_loc(lhe))=p;
22832   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22833   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22834   type(p)=stop_type(m);
22835   link(obj_tail(lhe))=p;
22836   obj_tail(lhe)=p;
22837   mp_init_bbox(mp, lhe);
22838 }
22839
22840 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22841 cases to deal with.
22842
22843 @<Declare action procedures for use by |do_statement|@>=
22844 void mp_do_add_to (MP mp) ;
22845
22846 @ @c void mp_do_add_to (MP mp) {
22847   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22848   pointer p; /* the graphical object or list for |scan_with_list| to update */
22849   pointer e; /* an edge structure to be merged */
22850   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22851   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22852   if ( lhv!=null ) {
22853     if ( add_type==also_code ) {
22854       @<Make sure the current expression is a suitable picture and set |e| and |p|
22855        appropriately@>;
22856     } else {
22857       @<Create a graphical object |p| based on |add_type| and the current
22858         expression@>;
22859     }
22860     mp_scan_with_list(mp, p);
22861     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22862   }
22863 }
22864
22865 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22866 setting |e:=null| prevents anything from being added to |lhe|.
22867
22868 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22869
22870   p=null; e=null;
22871   if ( mp->cur_type!=mp_picture_type ) {
22872     exp_err("Improper `addto'");
22873 @.Improper `addto'@>
22874     help2("This expression should have specified a known picture.")
22875       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22876   } else { 
22877     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22878     p=link(dummy_loc(e));
22879   }
22880 }
22881
22882 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22883 attempts to add to the edge structure.
22884
22885 @<Create a graphical object |p| based on |add_type| and the current...@>=
22886 { e=null; p=null;
22887   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22888   if ( mp->cur_type!=mp_path_type ) {
22889     exp_err("Improper `addto'");
22890 @.Improper `addto'@>
22891     help2("This expression should have specified a known path.")
22892       ("So I'll not change anything just now."); 
22893     mp_put_get_flush_error(mp, 0);
22894   } else if ( add_type==contour_code ) {
22895     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22896       @<Complain about a non-cycle@>;
22897     } else { 
22898       p=mp_new_fill_node(mp, mp->cur_exp);
22899       mp->cur_type=mp_vacuous;
22900     }
22901   } else { 
22902     p=mp_new_stroked_node(mp, mp->cur_exp);
22903     mp->cur_type=mp_vacuous;
22904   }
22905 }
22906
22907 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22908 lhe=mp_find_edges_var(mp, lhv);
22909 if ( lhe==null ) {
22910   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22911   if ( e!=null ) delete_edge_ref(e);
22912 } else if ( add_type==also_code ) {
22913   if ( e!=null ) {
22914     @<Merge |e| into |lhe| and delete |e|@>;
22915   } else { 
22916     do_nothing;
22917   }
22918 } else if ( p!=null ) {
22919   link(obj_tail(lhe))=p;
22920   obj_tail(lhe)=p;
22921   if ( add_type==double_path_code )
22922     if ( pen_p(p)==null ) 
22923       pen_p(p)=mp_get_pen_circle(mp, 0);
22924 }
22925
22926 @ @<Merge |e| into |lhe| and delete |e|@>=
22927 { if ( link(dummy_loc(e))!=null ) {
22928     link(obj_tail(lhe))=link(dummy_loc(e));
22929     obj_tail(lhe)=obj_tail(e);
22930     obj_tail(e)=dummy_loc(e);
22931     link(dummy_loc(e))=null;
22932     mp_flush_dash_list(mp, lhe);
22933   }
22934   mp_toss_edges(mp, e);
22935 }
22936
22937 @ @<Cases of |do_statement|...@>=
22938 case ship_out_command: mp_do_ship_out(mp); break;
22939
22940 @ @<Declare action procedures for use by |do_statement|@>=
22941 @<Declare the function called |tfm_check|@>;
22942 @<Declare the \ps\ output procedures@>;
22943 void mp_do_ship_out (MP mp) ;
22944
22945 @ @c void mp_do_ship_out (MP mp) {
22946   integer c; /* the character code */
22947   mp_get_x_next(mp); mp_scan_expression(mp);
22948   if ( mp->cur_type!=mp_picture_type ) {
22949     @<Complain that it's not a known picture@>;
22950   } else { 
22951     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
22952     if ( c<0 ) c=c+256;
22953     @<Store the width information for character code~|c|@>;
22954     mp_ship_out(mp, mp->cur_exp);
22955     mp_flush_cur_exp(mp, 0);
22956   }
22957 }
22958
22959 @ @<Complain that it's not a known picture@>=
22960
22961   exp_err("Not a known picture");
22962   help1("I can only output known pictures.");
22963   mp_put_get_flush_error(mp, 0);
22964 }
22965
22966 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
22967 |start_sym|.
22968
22969 @<Cases of |do_statement|...@>=
22970 case every_job_command: 
22971   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
22972   break;
22973
22974 @ @<Glob...@>=
22975 halfword start_sym; /* a symbolic token to insert at beginning of job */
22976
22977 @ @<Set init...@>=
22978 mp->start_sym=0;
22979
22980 @ Finally, we have only the ``message'' commands remaining.
22981
22982 @d message_code 0
22983 @d err_message_code 1
22984 @d err_help_code 2
22985 @d filename_template_code 3
22986 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
22987               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
22988               if ( f>g ) {
22989                 mp->pool_ptr = mp->pool_ptr - g;
22990                 while ( f>g ) {
22991                   mp_print_char(mp, '0');
22992                   decr(f);
22993                   };
22994                 mp_print_int(mp, (A));
22995               };
22996               f = 0
22997
22998 @<Put each...@>=
22999 mp_primitive(mp, "message",message_command,message_code);
23000 @:message_}{\&{message} primitive@>
23001 mp_primitive(mp, "errmessage",message_command,err_message_code);
23002 @:err_message_}{\&{errmessage} primitive@>
23003 mp_primitive(mp, "errhelp",message_command,err_help_code);
23004 @:err_help_}{\&{errhelp} primitive@>
23005 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23006 @:filename_template_}{\&{filenametemplate} primitive@>
23007
23008 @ @<Cases of |print_cmd...@>=
23009 case message_command: 
23010   if ( m<err_message_code ) mp_print(mp, "message");
23011   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23012   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23013   else mp_print(mp, "errhelp");
23014   break;
23015
23016 @ @<Cases of |do_statement|...@>=
23017 case message_command: mp_do_message(mp); break;
23018
23019 @ @<Declare action procedures for use by |do_statement|@>=
23020 @<Declare a procedure called |no_string_err|@>;
23021 void mp_do_message (MP mp) ;
23022
23023
23024 @c void mp_do_message (MP mp) {
23025   int m; /* the type of message */
23026   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23027   if ( mp->cur_type!=mp_string_type )
23028     mp_no_string_err(mp, "A message should be a known string expression.");
23029   else {
23030     switch (m) {
23031     case message_code: 
23032       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23033       break;
23034     case err_message_code:
23035       @<Print string |cur_exp| as an error message@>;
23036       break;
23037     case err_help_code:
23038       @<Save string |cur_exp| as the |err_help|@>;
23039       break;
23040     case filename_template_code:
23041       @<Save the filename template@>;
23042       break;
23043     } /* there are no other cases */
23044   }
23045   mp_flush_cur_exp(mp, 0);
23046 }
23047
23048 @ @<Declare a procedure called |no_string_err|@>=
23049 void mp_no_string_err (MP mp,char *s) { 
23050    exp_err("Not a string");
23051 @.Not a string@>
23052   help1(s);
23053   mp_put_get_error(mp);
23054 }
23055
23056 @ The global variable |err_help| is zero when the user has most recently
23057 given an empty help string, or if none has ever been given.
23058
23059 @<Save string |cur_exp| as the |err_help|@>=
23060
23061   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23062   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23063   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23064 }
23065
23066 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23067 \&{errhelp}, we don't want to give a long help message each time. So we
23068 give a verbose explanation only once.
23069
23070 @<Glob...@>=
23071 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23072
23073 @ @<Set init...@>=mp->long_help_seen=false;
23074
23075 @ @<Print string |cur_exp| as an error message@>=
23076
23077   print_err(""); mp_print_str(mp, mp->cur_exp);
23078   if ( mp->err_help!=0 ) {
23079     mp->use_err_help=true;
23080   } else if ( mp->long_help_seen ) { 
23081     help1("(That was another `errmessage'.)") ; 
23082   } else  { 
23083    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23084     help4("This error message was generated by an `errmessage'")
23085      ("command, so I can\'t give any explicit help.")
23086      ("Pretend that you're Miss Marple: Examine all clues,")
23087 @^Marple, Jane@>
23088      ("and deduce the truth by inspired guesses.");
23089   }
23090   mp_put_get_error(mp); mp->use_err_help=false;
23091 }
23092
23093 @ @<Cases of |do_statement|...@>=
23094 case write_command: mp_do_write(mp); break;
23095
23096 @ @<Declare action procedures for use by |do_statement|@>=
23097 void mp_do_write (MP mp) ;
23098
23099 @ @c void mp_do_write (MP mp) {
23100   str_number t; /* the line of text to be written */
23101   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23102   int old_setting; /* for saving |selector| during output */
23103   mp_get_x_next(mp);
23104   mp_scan_expression(mp);
23105   if ( mp->cur_type!=mp_string_type ) {
23106     mp_no_string_err(mp, "The text to be written should be a known string expression");
23107   } else if ( mp->cur_cmd!=to_token ) { 
23108     print_err("Missing `to' clause");
23109     help1("A write command should end with `to <filename>'");
23110     mp_put_get_error(mp);
23111   } else { 
23112     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23113     mp_get_x_next(mp);
23114     mp_scan_expression(mp);
23115     if ( mp->cur_type!=mp_string_type )
23116       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23117     else {
23118       @<Write |t| to the file named by |cur_exp|@>;
23119     }
23120     delete_str_ref(t);
23121   }
23122   mp_flush_cur_exp(mp, 0);
23123 }
23124
23125 @ @<Write |t| to the file named by |cur_exp|@>=
23126
23127   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23128     |cur_exp| must be inserted@>;
23129   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23130     @<Record the end of file on |wr_file[n]|@>;
23131   } else { 
23132     old_setting=mp->selector;
23133     mp->selector=n+write_file;
23134     mp_print_str(mp, t); mp_print_ln(mp);
23135     mp->selector = old_setting;
23136   }
23137 }
23138
23139 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23140 {
23141   char *fn = str(mp->cur_exp);
23142   n=mp->write_files;
23143   n0=mp->write_files;
23144   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23145     if ( n==0 ) { /* bottom reached */
23146           if ( n0==mp->write_files ) {
23147         if ( mp->write_files<mp->max_write_files ) {
23148           incr(mp->write_files);
23149         } else {
23150           void **wr_file;
23151           char **wr_fname;
23152               write_index l,k;
23153           l = mp->max_write_files + (mp->max_write_files>>2);
23154           wr_file = xmalloc((l+1),sizeof(void *));
23155           wr_fname = xmalloc((l+1),sizeof(char *));
23156               for (k=0;k<=l;k++) {
23157             if (k<=mp->max_write_files) {
23158                   wr_file[k]=mp->wr_file[k]; 
23159               wr_fname[k]=mp->wr_fname[k];
23160             } else {
23161                   wr_file[k]=0; 
23162               wr_fname[k]=NULL;
23163             }
23164           }
23165               xfree(mp->wr_file); xfree(mp->wr_fname);
23166           mp->max_write_files = l;
23167           mp->wr_file = wr_file;
23168           mp->wr_fname = wr_fname;
23169         }
23170       }
23171       n=n0;
23172       mp_open_write_file(mp, fn ,n);
23173     } else { 
23174       decr(n);
23175           if ( mp->wr_fname[n]==NULL )  n0=n; 
23176     }
23177   }
23178 }
23179
23180 @ @<Record the end of file on |wr_file[n]|@>=
23181 { (mp->close_file)(mp->wr_file[n]);
23182   xfree(mp->wr_fname[n]);
23183   mp->wr_fname[n]=NULL;
23184   if ( n==mp->write_files-1 ) mp->write_files=n;
23185 }
23186
23187
23188 @* \[42] Writing font metric data.
23189 \TeX\ gets its knowledge about fonts from font metric files, also called
23190 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23191 but other programs know about them too. One of \MP's duties is to
23192 write \.{TFM} files so that the user's fonts can readily be
23193 applied to typesetting.
23194 @:TFM files}{\.{TFM} files@>
23195 @^font metric files@>
23196
23197 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23198 Since the number of bytes is always a multiple of~4, we could
23199 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23200 byte interpretation. The format of \.{TFM} files was designed by
23201 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23202 @^Ramshaw, Lyle Harold@>
23203 of information in a compact but useful form.
23204
23205 @<Glob...@>=
23206 void * tfm_file; /* the font metric output goes here */
23207 char * metric_file_name; /* full name of the font metric file */
23208
23209 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23210 integers that give the lengths of the various subsequent portions
23211 of the file. These twelve integers are, in order:
23212 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23213 |lf|&length of the entire file, in words;\cr
23214 |lh|&length of the header data, in words;\cr
23215 |bc|&smallest character code in the font;\cr
23216 |ec|&largest character code in the font;\cr
23217 |nw|&number of words in the width table;\cr
23218 |nh|&number of words in the height table;\cr
23219 |nd|&number of words in the depth table;\cr
23220 |ni|&number of words in the italic correction table;\cr
23221 |nl|&number of words in the lig/kern table;\cr
23222 |nk|&number of words in the kern table;\cr
23223 |ne|&number of words in the extensible character table;\cr
23224 |np|&number of font parameter words.\cr}}$$
23225 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23226 |ne<=256|, and
23227 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23228 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23229 and as few as 0 characters (if |bc=ec+1|).
23230
23231 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23232 16 or more bits, the most significant bytes appear first in the file.
23233 This is called BigEndian order.
23234 @^BigEndian order@>
23235
23236 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23237 arrays.
23238
23239 The most important data type used here is a |fix_word|, which is
23240 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23241 quantity, with the two's complement of the entire word used to represent
23242 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23243 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23244 the smallest is $-2048$. We will see below, however, that all but two of
23245 the |fix_word| values must lie between $-16$ and $+16$.
23246
23247 @ The first data array is a block of header information, which contains
23248 general facts about the font. The header must contain at least two words,
23249 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23250 header information of use to other software routines might also be
23251 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23252 For example, 16 more words of header information are in use at the Xerox
23253 Palo Alto Research Center; the first ten specify the character coding
23254 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23255 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23256 last gives the ``face byte.''
23257
23258 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23259 the \.{GF} output file. This helps ensure consistency between files,
23260 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23261 should match the check sums on actual fonts that are used.  The actual
23262 relation between this check sum and the rest of the \.{TFM} file is not
23263 important; the check sum is simply an identification number with the
23264 property that incompatible fonts almost always have distinct check sums.
23265 @^check sum@>
23266
23267 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23268 font, in units of \TeX\ points. This number must be at least 1.0; it is
23269 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23270 font, i.e., a font that was designed to look best at a 10-point size,
23271 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23272 $\delta$ \.{pt}', the effect is to override the design size and replace it
23273 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23274 the font image by a factor of $\delta$ divided by the design size.  {\sl
23275 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23276 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23277 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23278 since many fonts have a design size equal to one em.  The other dimensions
23279 must be less than 16 design-size units in absolute value; thus,
23280 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23281 \.{TFM} file whose first byte might be something besides 0 or 255.
23282
23283 @ Next comes the |char_info| array, which contains one |char_info_word|
23284 per character. Each word in this part of the file contains six fields
23285 packed into four bytes as follows.
23286
23287 \yskip\hang first byte: |width_index| (8 bits)\par
23288 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23289   (4~bits)\par
23290 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23291   (2~bits)\par
23292 \hang fourth byte: |remainder| (8 bits)\par
23293 \yskip\noindent
23294 The actual width of a character is \\{width}|[width_index]|, in design-size
23295 units; this is a device for compressing information, since many characters
23296 have the same width. Since it is quite common for many characters
23297 to have the same height, depth, or italic correction, the \.{TFM} format
23298 imposes a limit of 16 different heights, 16 different depths, and
23299 64 different italic corrections.
23300
23301 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23302 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23303 value of zero.  The |width_index| should never be zero unless the
23304 character does not exist in the font, since a character is valid if and
23305 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23306
23307 @ The |tag| field in a |char_info_word| has four values that explain how to
23308 interpret the |remainder| field.
23309
23310 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23311 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23312 program starting at location |remainder| in the |lig_kern| array.\par
23313 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23314 characters of ascending sizes, and not the largest in the chain.  The
23315 |remainder| field gives the character code of the next larger character.\par
23316 \hang|tag=3| (|ext_tag|) means that this character code represents an
23317 extensible character, i.e., a character that is built up of smaller pieces
23318 so that it can be made arbitrarily large. The pieces are specified in
23319 |exten[remainder]|.\par
23320 \yskip\noindent
23321 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23322 unless they are used in special circumstances in math formulas. For example,
23323 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23324 operation looks for both |list_tag| and |ext_tag|.
23325
23326 @d no_tag 0 /* vanilla character */
23327 @d lig_tag 1 /* character has a ligature/kerning program */
23328 @d list_tag 2 /* character has a successor in a charlist */
23329 @d ext_tag 3 /* character is extensible */
23330
23331 @ The |lig_kern| array contains instructions in a simple programming language
23332 that explains what to do for special letter pairs. Each word in this array is a
23333 |lig_kern_command| of four bytes.
23334
23335 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23336   step if the byte is 128 or more, otherwise the next step is obtained by
23337   skipping this number of intervening steps.\par
23338 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23339   then perform the operation and stop, otherwise continue.''\par
23340 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23341   a kern step otherwise.\par
23342 \hang fourth byte: |remainder|.\par
23343 \yskip\noindent
23344 In a kern step, an
23345 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23346 between the current character and |next_char|. This amount is
23347 often negative, so that the characters are brought closer together
23348 by kerning; but it might be positive.
23349
23350 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23351 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23352 |remainder| is inserted between the current character and |next_char|;
23353 then the current character is deleted if $b=0$, and |next_char| is
23354 deleted if $c=0$; then we pass over $a$~characters to reach the next
23355 current character (which may have a ligature/kerning program of its own).
23356
23357 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23358 the |next_char| byte is the so-called right boundary character of this font;
23359 the value of |next_char| need not lie between |bc| and~|ec|.
23360 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23361 there is a special ligature/kerning program for a left boundary character,
23362 beginning at location |256*op_byte+remainder|.
23363 The interpretation is that \TeX\ puts implicit boundary characters
23364 before and after each consecutive string of characters from the same font.
23365 These implicit characters do not appear in the output, but they can affect
23366 ligatures and kerning.
23367
23368 If the very first instruction of a character's |lig_kern| program has
23369 |skip_byte>128|, the program actually begins in location
23370 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23371 arrays, because the first instruction must otherwise
23372 appear in a location |<=255|.
23373
23374 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23375 the condition
23376 $$\hbox{|256*op_byte+remainder<nl|.}$$
23377 If such an instruction is encountered during
23378 normal program execution, it denotes an unconditional halt; no ligature
23379 command is performed.
23380
23381 @d stop_flag (128)
23382   /* value indicating `\.{STOP}' in a lig/kern program */
23383 @d kern_flag (128) /* op code for a kern step */
23384 @d skip_byte(A) mp->lig_kern[(A)].b0
23385 @d next_char(A) mp->lig_kern[(A)].b1
23386 @d op_byte(A) mp->lig_kern[(A)].b2
23387 @d rem_byte(A) mp->lig_kern[(A)].b3
23388
23389 @ Extensible characters are specified by an |extensible_recipe|, which
23390 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23391 order). These bytes are the character codes of individual pieces used to
23392 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23393 present in the built-up result. For example, an extensible vertical line is
23394 like an extensible bracket, except that the top and bottom pieces are missing.
23395
23396 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23397 if the piece isn't present. Then the extensible characters have the form
23398 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23399 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23400 The width of the extensible character is the width of $R$; and the
23401 height-plus-depth is the sum of the individual height-plus-depths of the
23402 components used, since the pieces are butted together in a vertical list.
23403
23404 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23405 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23406 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23407 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23408
23409 @ The final portion of a \.{TFM} file is the |param| array, which is another
23410 sequence of |fix_word| values.
23411
23412 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23413 to help position accents. For example, |slant=.25| means that when you go
23414 up one unit, you also go .25 units to the right. The |slant| is a pure
23415 number; it is the only |fix_word| other than the design size itself that is
23416 not scaled by the design size.
23417
23418 \hang|param[2]=space| is the normal spacing between words in text.
23419 Note that character 040 in the font need not have anything to do with
23420 blank spaces.
23421
23422 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23423
23424 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23425
23426 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23427 the height of letters for which accents don't have to be raised or lowered.
23428
23429 \hang|param[6]=quad| is the size of one em in the font.
23430
23431 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23432 ends of sentences.
23433
23434 \yskip\noindent
23435 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23436 to zero.
23437
23438 @d slant_code 1
23439 @d space_code 2
23440 @d space_stretch_code 3
23441 @d space_shrink_code 4
23442 @d x_height_code 5
23443 @d quad_code 6
23444 @d extra_space_code 7
23445
23446 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23447 information, and it does this all at once at the end of a job.
23448 In order to prepare for such frenetic activity, it squirrels away the
23449 necessary facts in various arrays as information becomes available.
23450
23451 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23452 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23453 |tfm_ital_corr|. Other information about a character (e.g., about
23454 its ligatures or successors) is accessible via the |char_tag| and
23455 |char_remainder| arrays. Other information about the font as a whole
23456 is kept in additional arrays called |header_byte|, |lig_kern|,
23457 |kern|, |exten|, and |param|.
23458
23459 @d max_tfm_int 32510
23460 @d undefined_label max_tfm_int /* an undefined local label */
23461
23462 @<Glob...@>=
23463 #define TFM_ITEMS 257
23464 eight_bits bc;
23465 eight_bits ec; /* smallest and largest character codes shipped out */
23466 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23467 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23468 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23469 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23470 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23471 int char_tag[TFM_ITEMS]; /* |remainder| category */
23472 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23473 char *header_byte; /* bytes of the \.{TFM} header */
23474 int header_last; /* last initialized \.{TFM} header byte */
23475 int header_size; /* size of the \.{TFM} header */
23476 four_quarters *lig_kern; /* the ligature/kern table */
23477 short nl; /* the number of ligature/kern steps so far */
23478 scaled *kern; /* distinct kerning amounts */
23479 short nk; /* the number of distinct kerns so far */
23480 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23481 short ne; /* the number of extensible characters so far */
23482 scaled *param; /* \&{fontinfo} parameters */
23483 short np; /* the largest \&{fontinfo} parameter specified so far */
23484 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23485 short skip_table[TFM_ITEMS]; /* local label status */
23486 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23487 integer bchar; /* right boundary character */
23488 short bch_label; /* left boundary starting location */
23489 short ll;short lll; /* registers used for lig/kern processing */
23490 short label_loc[257]; /* lig/kern starting addresses */
23491 eight_bits label_char[257]; /* characters for |label_loc| */
23492 short label_ptr; /* highest position occupied in |label_loc| */
23493
23494 @ @<Allocate or initialize ...@>=
23495 mp->header_last = 0; mp->header_size = 128; /* just for init */
23496 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23497 mp->lig_kern = NULL; /* allocated when needed */
23498 mp->kern = NULL; /* allocated when needed */ 
23499 mp->param = NULL; /* allocated when needed */
23500
23501 @ @<Dealloc variables@>=
23502 xfree(mp->header_byte);
23503 xfree(mp->lig_kern);
23504 xfree(mp->kern);
23505 xfree(mp->param);
23506
23507 @ @<Set init...@>=
23508 for (k=0;k<= 255;k++ ) {
23509   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23510   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23511   mp->skip_table[k]=undefined_label;
23512 };
23513 memset(mp->header_byte,0,mp->header_size);
23514 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23515 mp->internal[mp_boundary_char]=-unity;
23516 mp->bch_label=undefined_label;
23517 mp->label_loc[0]=-1; mp->label_ptr=0;
23518
23519 @ @<Declarations@>=
23520 scaled mp_tfm_check (MP mp,small_number m) ;
23521
23522 @ @<Declare the function called |tfm_check|@>=
23523 scaled mp_tfm_check (MP mp,small_number m) {
23524   if ( abs(mp->internal[m])>=fraction_half ) {
23525     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23526 @.Enormous charwd...@>
23527 @.Enormous chardp...@>
23528 @.Enormous charht...@>
23529 @.Enormous charic...@>
23530 @.Enormous designsize...@>
23531     mp_print(mp, " has been reduced");
23532     help1("Font metric dimensions must be less than 2048pt.");
23533     mp_put_get_error(mp);
23534     if ( mp->internal[m]>0 ) return (fraction_half-1);
23535     else return (1-fraction_half);
23536   } else {
23537     return mp->internal[m];
23538   }
23539 }
23540
23541 @ @<Store the width information for character code~|c|@>=
23542 if ( c<mp->bc ) mp->bc=c;
23543 if ( c>mp->ec ) mp->ec=c;
23544 mp->char_exists[c]=true;
23545 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23546 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23547 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23548 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23549
23550 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23551
23552 @<Cases of |do_statement|...@>=
23553 case tfm_command: mp_do_tfm_command(mp); break;
23554
23555 @ @d char_list_code 0
23556 @d lig_table_code 1
23557 @d extensible_code 2
23558 @d header_byte_code 3
23559 @d font_dimen_code 4
23560
23561 @<Put each...@>=
23562 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23563 @:char_list_}{\&{charlist} primitive@>
23564 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23565 @:lig_table_}{\&{ligtable} primitive@>
23566 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23567 @:extensible_}{\&{extensible} primitive@>
23568 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23569 @:header_byte_}{\&{headerbyte} primitive@>
23570 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23571 @:font_dimen_}{\&{fontdimen} primitive@>
23572
23573 @ @<Cases of |print_cmd...@>=
23574 case tfm_command: 
23575   switch (m) {
23576   case char_list_code:mp_print(mp, "charlist"); break;
23577   case lig_table_code:mp_print(mp, "ligtable"); break;
23578   case extensible_code:mp_print(mp, "extensible"); break;
23579   case header_byte_code:mp_print(mp, "headerbyte"); break;
23580   default: mp_print(mp, "fontdimen"); break;
23581   }
23582   break;
23583
23584 @ @<Declare action procedures for use by |do_statement|@>=
23585 eight_bits mp_get_code (MP mp) ;
23586
23587 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23588   integer c; /* the code value found */
23589   mp_get_x_next(mp); mp_scan_expression(mp);
23590   if ( mp->cur_type==mp_known ) { 
23591     c=mp_round_unscaled(mp, mp->cur_exp);
23592     if ( c>=0 ) if ( c<256 ) return c;
23593   } else if ( mp->cur_type==mp_string_type ) {
23594     if ( length(mp->cur_exp)==1 )  { 
23595       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23596       return c;
23597     }
23598   }
23599   exp_err("Invalid code has been replaced by 0");
23600 @.Invalid code...@>
23601   help2("I was looking for a number between 0 and 255, or for a")
23602        ("string of length 1. Didn't find it; will use 0 instead.");
23603   mp_put_get_flush_error(mp, 0); c=0;
23604   return c;
23605 };
23606
23607 @ @<Declare action procedures for use by |do_statement|@>=
23608 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23609
23610 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23611   if ( mp->char_tag[c]==no_tag ) {
23612     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23613     if ( t==lig_tag ){ 
23614       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23615       mp->label_char[mp->label_ptr]=c;
23616     }
23617   } else {
23618     @<Complain about a character tag conflict@>;
23619   }
23620 }
23621
23622 @ @<Complain about a character tag conflict@>=
23623
23624   print_err("Character ");
23625   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23626   else if ( c==256 ) mp_print(mp, "||");
23627   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23628   mp_print(mp, " is already ");
23629 @.Character c is already...@>
23630   switch (mp->char_tag[c]) {
23631   case lig_tag: mp_print(mp, "in a ligtable"); break;
23632   case list_tag: mp_print(mp, "in a charlist"); break;
23633   case ext_tag: mp_print(mp, "extensible"); break;
23634   } /* there are no other cases */
23635   help2("It's not legal to label a character more than once.")
23636     ("So I'll not change anything just now.");
23637   mp_put_get_error(mp); 
23638 }
23639
23640 @ @<Declare action procedures for use by |do_statement|@>=
23641 void mp_do_tfm_command (MP mp) ;
23642
23643 @ @c void mp_do_tfm_command (MP mp) {
23644   int c,cc; /* character codes */
23645   int k; /* index into the |kern| array */
23646   int j; /* index into |header_byte| or |param| */
23647   switch (mp->cur_mod) {
23648   case char_list_code: 
23649     c=mp_get_code(mp);
23650      /* we will store a list of character successors */
23651     while ( mp->cur_cmd==colon )   { 
23652       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23653     };
23654     break;
23655   case lig_table_code: 
23656     if (mp->lig_kern==NULL) 
23657        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23658     if (mp->kern==NULL) 
23659        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23660     @<Store a list of ligature/kern steps@>;
23661     break;
23662   case extensible_code: 
23663     @<Define an extensible recipe@>;
23664     break;
23665   case header_byte_code: 
23666   case font_dimen_code: 
23667     c=mp->cur_mod; mp_get_x_next(mp);
23668     mp_scan_expression(mp);
23669     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23670       exp_err("Improper location");
23671 @.Improper location@>
23672       help2("I was looking for a known, positive number.")
23673        ("For safety's sake I'll ignore the present command.");
23674       mp_put_get_error(mp);
23675     } else  { 
23676       j=mp_round_unscaled(mp, mp->cur_exp);
23677       if ( mp->cur_cmd!=colon ) {
23678         mp_missing_err(mp, ":");
23679 @.Missing `:'@>
23680         help1("A colon should follow a headerbyte or fontinfo location.");
23681         mp_back_error(mp);
23682       }
23683       if ( c==header_byte_code ) { 
23684         @<Store a list of header bytes@>;
23685       } else {     
23686         if (mp->param==NULL) 
23687           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23688         @<Store a list of font dimensions@>;
23689       }
23690     }
23691     break;
23692   } /* there are no other cases */
23693 };
23694
23695 @ @<Store a list of ligature/kern steps@>=
23696
23697   mp->lk_started=false;
23698 CONTINUE: 
23699   mp_get_x_next(mp);
23700   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23701     @<Process a |skip_to| command and |goto done|@>;
23702   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23703   else { mp_back_input(mp); c=mp_get_code(mp); };
23704   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23705     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23706   }
23707   if ( mp->cur_cmd==lig_kern_token ) { 
23708     @<Compile a ligature/kern command@>; 
23709   } else  { 
23710     print_err("Illegal ligtable step");
23711 @.Illegal ligtable step@>
23712     help1("I was looking for `=:' or `kern' here.");
23713     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23714     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23715     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23716   }
23717   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23718   incr(mp->nl);
23719   if ( mp->cur_cmd==comma ) goto CONTINUE;
23720   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23721 }
23722 DONE:
23723
23724 @ @<Put each...@>=
23725 mp_primitive(mp, "=:",lig_kern_token,0);
23726 @:=:_}{\.{=:} primitive@>
23727 mp_primitive(mp, "=:|",lig_kern_token,1);
23728 @:=:/_}{\.{=:\char'174} primitive@>
23729 mp_primitive(mp, "=:|>",lig_kern_token,5);
23730 @:=:/>_}{\.{=:\char'174>} primitive@>
23731 mp_primitive(mp, "|=:",lig_kern_token,2);
23732 @:=:/_}{\.{\char'174=:} primitive@>
23733 mp_primitive(mp, "|=:>",lig_kern_token,6);
23734 @:=:/>_}{\.{\char'174=:>} primitive@>
23735 mp_primitive(mp, "|=:|",lig_kern_token,3);
23736 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23737 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23738 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23739 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23740 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23741 mp_primitive(mp, "kern",lig_kern_token,128);
23742 @:kern_}{\&{kern} primitive@>
23743
23744 @ @<Cases of |print_cmd...@>=
23745 case lig_kern_token: 
23746   switch (m) {
23747   case 0:mp_print(mp, "=:"); break;
23748   case 1:mp_print(mp, "=:|"); break;
23749   case 2:mp_print(mp, "|=:"); break;
23750   case 3:mp_print(mp, "|=:|"); break;
23751   case 5:mp_print(mp, "=:|>"); break;
23752   case 6:mp_print(mp, "|=:>"); break;
23753   case 7:mp_print(mp, "|=:|>"); break;
23754   case 11:mp_print(mp, "|=:|>>"); break;
23755   default: mp_print(mp, "kern"); break;
23756   }
23757   break;
23758
23759 @ Local labels are implemented by maintaining the |skip_table| array,
23760 where |skip_table[c]| is either |undefined_label| or the address of the
23761 most recent lig/kern instruction that skips to local label~|c|. In the
23762 latter case, the |skip_byte| in that instruction will (temporarily)
23763 be zero if there were no prior skips to this label, or it will be the
23764 distance to the prior skip.
23765
23766 We may need to cancel skips that span more than 127 lig/kern steps.
23767
23768 @d cancel_skips(A) mp->ll=(A);
23769   do {  
23770     mp->lll=qo(skip_byte(mp->ll)); 
23771     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23772   } while (mp->lll!=0)
23773 @d skip_error(A) { print_err("Too far to skip");
23774 @.Too far to skip@>
23775   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23776   mp_error(mp); cancel_skips((A));
23777   }
23778
23779 @<Process a |skip_to| command and |goto done|@>=
23780
23781   c=mp_get_code(mp);
23782   if ( mp->nl-mp->skip_table[c]>128 ) { /* |skip_table[c]<<nl<=undefined_label| */
23783     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23784   }
23785   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23786   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23787   mp->skip_table[c]=mp->nl-1; goto DONE;
23788 }
23789
23790 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23791
23792   if ( mp->cur_cmd==colon ) {
23793     if ( c==256 ) mp->bch_label=mp->nl;
23794     else mp_set_tag(mp, c,lig_tag,mp->nl);
23795   } else if ( mp->skip_table[c]<undefined_label ) {
23796     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23797     do {  
23798       mp->lll=qo(skip_byte(mp->ll));
23799       if ( mp->nl-mp->ll>128 ) {
23800         skip_error(mp->ll); goto CONTINUE;
23801       }
23802       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23803     } while (mp->lll!=0);
23804   }
23805   goto CONTINUE;
23806 }
23807
23808 @ @<Compile a ligature/kern...@>=
23809
23810   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23811   if ( mp->cur_mod<128 ) { /* ligature op */
23812     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23813   } else { 
23814     mp_get_x_next(mp); mp_scan_expression(mp);
23815     if ( mp->cur_type!=mp_known ) {
23816       exp_err("Improper kern");
23817 @.Improper kern@>
23818       help2("The amount of kern should be a known numeric value.")
23819         ("I'm zeroing this one. Proceed, with fingers crossed.");
23820       mp_put_get_flush_error(mp, 0);
23821     }
23822     mp->kern[mp->nk]=mp->cur_exp;
23823     k=0; 
23824     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23825     if ( k==mp->nk ) {
23826       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23827       incr(mp->nk);
23828     }
23829     op_byte(mp->nl)=kern_flag+(k / 256);
23830     rem_byte(mp->nl)=qi((k % 256));
23831   }
23832   mp->lk_started=true;
23833 }
23834
23835 @ @d missing_extensible_punctuation(A) 
23836   { mp_missing_err(mp, (A));
23837 @.Missing `\char`\#'@>
23838   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23839   }
23840
23841 @<Define an extensible recipe@>=
23842
23843   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23844   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23845   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23846   ext_top(mp->ne)=qi(mp_get_code(mp));
23847   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23848   ext_mid(mp->ne)=qi(mp_get_code(mp));
23849   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23850   ext_bot(mp->ne)=qi(mp_get_code(mp));
23851   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23852   ext_rep(mp->ne)=qi(mp_get_code(mp));
23853   incr(mp->ne);
23854 }
23855
23856 @ The header could contain ASCII zeroes, so can't use |strdup|.
23857
23858 @<Store a list of header bytes@>=
23859 do {  
23860   if ( j>=mp->header_size ) {
23861     int l = mp->header_size + (mp->header_size >> 2);
23862     char *t = xmalloc(l,sizeof(char));
23863     memset(t,0,l); 
23864     memcpy(t,mp->header_byte,mp->header_size);
23865     xfree (mp->header_byte);
23866     mp->header_byte = t;
23867     mp->header_size = l;
23868   }
23869   mp->header_byte[j]=mp_get_code(mp); 
23870   incr(j); incr(mp->header_last);
23871 } while (mp->cur_cmd==comma)
23872
23873 @ @<Store a list of font dimensions@>=
23874 do {  
23875   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23876   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23877   mp_get_x_next(mp); mp_scan_expression(mp);
23878   if ( mp->cur_type!=mp_known ){ 
23879     exp_err("Improper font parameter");
23880 @.Improper font parameter@>
23881     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23882     mp_put_get_flush_error(mp, 0);
23883   }
23884   mp->param[j]=mp->cur_exp; incr(j);
23885 } while (mp->cur_cmd==comma)
23886
23887 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23888 All that remains is to output it in the correct format.
23889
23890 An interesting problem needs to be solved in this connection, because
23891 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23892 and 64~italic corrections. If the data has more distinct values than
23893 this, we want to meet the necessary restrictions by perturbing the
23894 given values as little as possible.
23895
23896 \MP\ solves this problem in two steps. First the values of a given
23897 kind (widths, heights, depths, or italic corrections) are sorted;
23898 then the list of sorted values is perturbed, if necessary.
23899
23900 The sorting operation is facilitated by having a special node of
23901 essentially infinite |value| at the end of the current list.
23902
23903 @<Initialize table entries...@>=
23904 value(inf_val)=fraction_four;
23905
23906 @ Straight linear insertion is good enough for sorting, since the lists
23907 are usually not terribly long. As we work on the data, the current list
23908 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23909 list will be in increasing order of their |value| fields.
23910
23911 Given such a list, the |sort_in| function takes a value and returns a pointer
23912 to where that value can be found in the list. The value is inserted in
23913 the proper place, if necessary.
23914
23915 At the time we need to do these operations, most of \MP's work has been
23916 completed, so we will have plenty of memory to play with. The value nodes
23917 that are allocated for sorting will never be returned to free storage.
23918
23919 @d clear_the_list link(temp_head)=inf_val
23920
23921 @c pointer mp_sort_in (MP mp,scaled v) {
23922   pointer p,q,r; /* list manipulation registers */
23923   p=temp_head;
23924   while (1) { 
23925     q=link(p);
23926     if ( v<=value(q) ) break;
23927     p=q;
23928   }
23929   if ( v<value(q) ) {
23930     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23931   }
23932   return link(p);
23933 }
23934
23935 @ Now we come to the interesting part, where we reduce the list if necessary
23936 until it has the required size. The |min_cover| routine is basic to this
23937 process; it computes the minimum number~|m| such that the values of the
23938 current sorted list can be covered by |m|~intervals of width~|d|. It
23939 also sets the global value |perturbation| to the smallest value $d'>d$
23940 such that the covering found by this algorithm would be different.
23941
23942 In particular, |min_cover(0)| returns the number of distinct values in the
23943 current list and sets |perturbation| to the minimum distance between
23944 adjacent values.
23945
23946 @c integer mp_min_cover (MP mp,scaled d) {
23947   pointer p; /* runs through the current list */
23948   scaled l; /* the least element covered by the current interval */
23949   integer m; /* lower bound on the size of the minimum cover */
23950   m=0; p=link(temp_head); mp->perturbation=el_gordo;
23951   while ( p!=inf_val ){ 
23952     incr(m); l=value(p);
23953     do {  p=link(p); } while (value(p)<=l+d);
23954     if ( value(p)-l<mp->perturbation ) 
23955       mp->perturbation=value(p)-l;
23956   }
23957   return m;
23958 }
23959
23960 @ @<Glob...@>=
23961 scaled perturbation; /* quantity related to \.{TFM} rounding */
23962 integer excess; /* the list is this much too long */
23963
23964 @ The smallest |d| such that a given list can be covered with |m| intervals
23965 is determined by the |threshold| routine, which is sort of an inverse
23966 to |min_cover|. The idea is to increase the interval size rapidly until
23967 finding the range, then to go sequentially until the exact borderline has
23968 been discovered.
23969
23970 @c scaled mp_threshold (MP mp,integer m) {
23971   scaled d; /* lower bound on the smallest interval size */
23972   mp->excess=mp_min_cover(mp, 0)-m;
23973   if ( mp->excess<=0 ) {
23974     return 0;
23975   } else  { 
23976     do {  
23977       d=mp->perturbation;
23978     } while (mp_min_cover(mp, d+d)>m);
23979     while ( mp_min_cover(mp, d)>m ) 
23980       d=mp->perturbation;
23981     return d;
23982   }
23983 }
23984
23985 @ The |skimp| procedure reduces the current list to at most |m| entries,
23986 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
23987 is the |k|th distinct value on the resulting list, and it sets
23988 |perturbation| to the maximum amount by which a |value| field has
23989 been changed. The size of the resulting list is returned as the
23990 value of |skimp|.
23991
23992 @c integer mp_skimp (MP mp,integer m) {
23993   scaled d; /* the size of intervals being coalesced */
23994   pointer p,q,r; /* list manipulation registers */
23995   scaled l; /* the least value in the current interval */
23996   scaled v; /* a compromise value */
23997   d=mp_threshold(mp, m); mp->perturbation=0;
23998   q=temp_head; m=0; p=link(temp_head);
23999   while ( p!=inf_val ) {
24000     incr(m); l=value(p); info(p)=m;
24001     if ( value(link(p))<=l+d ) {
24002       @<Replace an interval of values by its midpoint@>;
24003     }
24004     q=p; p=link(p);
24005   }
24006   return m;
24007 }
24008
24009 @ @<Replace an interval...@>=
24010
24011   do {  
24012     p=link(p); info(p)=m;
24013     decr(mp->excess); if ( mp->excess==0 ) d=0;
24014   } while (value(link(p))<=l+d);
24015   v=l+halfp(value(p)-l);
24016   if ( value(p)-v>mp->perturbation ) 
24017     mp->perturbation=value(p)-v;
24018   r=q;
24019   do {  
24020     r=link(r); value(r)=v;
24021   } while (r!=p);
24022   link(q)=p; /* remove duplicate values from the current list */
24023 }
24024
24025 @ A warning message is issued whenever something is perturbed by
24026 more than 1/16\thinspace pt.
24027
24028 @c void mp_tfm_warning (MP mp,small_number m) { 
24029   mp_print_nl(mp, "(some "); 
24030   mp_print(mp, mp->int_name[m]);
24031 @.some charwds...@>
24032 @.some chardps...@>
24033 @.some charhts...@>
24034 @.some charics...@>
24035   mp_print(mp, " values had to be adjusted by as much as ");
24036   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24037 }
24038
24039 @ Here's an example of how we use these routines.
24040 The width data needs to be perturbed only if there are 256 distinct
24041 widths, but \MP\ must check for this case even though it is
24042 highly unusual.
24043
24044 An integer variable |k| will be defined when we use this code.
24045 The |dimen_head| array will contain pointers to the sorted
24046 lists of dimensions.
24047
24048 @<Massage the \.{TFM} widths@>=
24049 clear_the_list;
24050 for (k=mp->bc;k<=mp->ec;k++)  {
24051   if ( mp->char_exists[k] )
24052     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24053 }
24054 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24055 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24056
24057 @ @<Glob...@>=
24058 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24059
24060 @ Heights, depths, and italic corrections are different from widths
24061 not only because their list length is more severely restricted, but
24062 also because zero values do not need to be put into the lists.
24063
24064 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24065 clear_the_list;
24066 for (k=mp->bc;k<=mp->ec;k++) {
24067   if ( mp->char_exists[k] ) {
24068     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24069     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24070   }
24071 }
24072 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24073 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24074 clear_the_list;
24075 for (k=mp->bc;k<=mp->ec;k++) {
24076   if ( mp->char_exists[k] ) {
24077     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24078     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24079   }
24080 }
24081 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24082 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24083 clear_the_list;
24084 for (k=mp->bc;k<=mp->ec;k++) {
24085   if ( mp->char_exists[k] ) {
24086     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24087     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24088   }
24089 }
24090 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24091 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24092
24093 @ @<Initialize table entries...@>=
24094 value(zero_val)=0; info(zero_val)=0;
24095
24096 @ Bytes 5--8 of the header are set to the design size, unless the user has
24097 some crazy reason for specifying them differently.
24098
24099 Error messages are not allowed at the time this procedure is called,
24100 so a warning is printed instead.
24101
24102 The value of |max_tfm_dimen| is calculated so that
24103 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24104  < \\{three\_bytes}.$$
24105
24106 @d three_bytes 0100000000 /* $2^{24}$ */
24107
24108 @c 
24109 void mp_fix_design_size (MP mp) {
24110   scaled d; /* the design size */
24111   d=mp->internal[mp_design_size];
24112   if ( (d<unity)||(d>=fraction_half) ) {
24113     if ( d!=0 )
24114       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24115 @.illegal design size...@>
24116     d=040000000; mp->internal[mp_design_size]=d;
24117   }
24118   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24119     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24120      mp->header_byte[4]=d / 04000000;
24121      mp->header_byte[5]=(d / 4096) % 256;
24122      mp->header_byte[6]=(d / 16) % 256;
24123      mp->header_byte[7]=(d % 16)*16;
24124   };
24125   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-mp->internal[mp_design_size] / 010000000;
24126   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24127 }
24128
24129 @ The |dimen_out| procedure computes a |fix_word| relative to the
24130 design size. If the data was out of range, it is corrected and the
24131 global variable |tfm_changed| is increased by~one.
24132
24133 @c integer mp_dimen_out (MP mp,scaled x) { 
24134   if ( abs(x)>mp->max_tfm_dimen ) {
24135     incr(mp->tfm_changed);
24136     if ( x>0 ) x=three_bytes-1; else x=1-three_bytes;
24137   } else {
24138     x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24139   }
24140   return x;
24141 }
24142
24143 @ @<Glob...@>=
24144 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24145 integer tfm_changed; /* the number of data entries that were out of bounds */
24146
24147 @ If the user has not specified any of the first four header bytes,
24148 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24149 from the |tfm_width| data relative to the design size.
24150 @^check sum@>
24151
24152 @c void mp_fix_check_sum (MP mp) {
24153   eight_bits k; /* runs through character codes */
24154   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24155   integer x;  /* hash value used in check sum computation */
24156   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24157        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24158     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24159     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24160     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24161     return;
24162   }
24163 }
24164
24165 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24166 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24167 for (k=mp->bc;k<=mp->ec;k++) { 
24168   if ( mp->char_exists[k] ) {
24169     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24170     B1=(B1+B1+x) % 255;
24171     B2=(B2+B2+x) % 253;
24172     B3=(B3+B3+x) % 251;
24173     B4=(B4+B4+x) % 247;
24174   }
24175 }
24176
24177 @ Finally we're ready to actually write the \.{TFM} information.
24178 Here are some utility routines for this purpose.
24179
24180 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24181   unsigned char s=(A); 
24182   (mp->write_binary_file)(mp->tfm_file,(void *)&s,1); 
24183   } while (0)
24184
24185 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24186   tfm_out(x / 256); tfm_out(x % 256);
24187 }
24188 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24189   if ( x>=0 ) tfm_out(x / three_bytes);
24190   else { 
24191     x=x+010000000000; /* use two's complement for negative values */
24192     x=x+010000000000;
24193     tfm_out((x / three_bytes) + 128);
24194   };
24195   x=x % three_bytes; tfm_out(x / unity);
24196   x=x % unity; tfm_out(x / 0400);
24197   tfm_out(x % 0400);
24198 }
24199 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24200   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24201   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24202 }
24203
24204 @ @<Finish the \.{TFM} file@>=
24205 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24206 mp_pack_job_name(mp, ".tfm");
24207 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24208   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24209 mp->metric_file_name=xstrdup(mp->name_of_file);
24210 @<Output the subfile sizes and header bytes@>;
24211 @<Output the character information bytes, then
24212   output the dimensions themselves@>;
24213 @<Output the ligature/kern program@>;
24214 @<Output the extensible character recipes and the font metric parameters@>;
24215   if ( mp->internal[mp_tracing_stats]>0 )
24216   @<Log the subfile sizes of the \.{TFM} file@>;
24217 mp_print_nl(mp, "Font metrics written on "); 
24218 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24219 @.Font metrics written...@>
24220 (mp->close_file)(mp->tfm_file)
24221
24222 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24223 this code.
24224
24225 @<Output the subfile sizes and header bytes@>=
24226 k=mp->header_last;
24227 LH=(k+3) / 4; /* this is the number of header words */
24228 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24229 @<Compute the ligature/kern program offset and implant the
24230   left boundary label@>;
24231 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24232      +lk_offset+mp->nk+mp->ne+mp->np);
24233   /* this is the total number of file words that will be output */
24234 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24235 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24236 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24237 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24238 mp_tfm_two(mp, mp->np);
24239 for (k=0;k< 4*LH;k++)   { 
24240   tfm_out(mp->header_byte[k]);
24241 }
24242
24243 @ @<Output the character information bytes...@>=
24244 for (k=mp->bc;k<=mp->ec;k++) {
24245   if ( ! mp->char_exists[k] ) {
24246     mp_tfm_four(mp, 0);
24247   } else { 
24248     tfm_out(info(mp->tfm_width[k])); /* the width index */
24249     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24250     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24251     tfm_out(mp->char_remainder[k]);
24252   };
24253 }
24254 mp->tfm_changed=0;
24255 for (k=1;k<=4;k++) { 
24256   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24257   while ( p!=inf_val ) {
24258     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24259   }
24260 }
24261
24262
24263 @ We need to output special instructions at the beginning of the
24264 |lig_kern| array in order to specify the right boundary character
24265 and/or to handle starting addresses that exceed 255. The |label_loc|
24266 and |label_char| arrays have been set up to record all the
24267 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24268 \le|label_loc|[|label_ptr]|$.
24269
24270 @<Compute the ligature/kern program offset...@>=
24271 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24272 if ((mp->bchar<0)||(mp->bchar>255))
24273   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24274 else { mp->lk_started=true; lk_offset=1; };
24275 @<Find the minimum |lk_offset| and adjust all remainders@>;
24276 if ( mp->bch_label<undefined_label )
24277   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24278   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24279   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24280   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24281   }
24282
24283 @ @<Find the minimum |lk_offset|...@>=
24284 k=mp->label_ptr; /* pointer to the largest unallocated label */
24285 if ( mp->label_loc[k]+lk_offset>255 ) {
24286   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24287   do {  
24288     mp->char_remainder[mp->label_char[k]]=lk_offset;
24289     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24290        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24291     }
24292     incr(lk_offset); decr(k);
24293   } while (! (lk_offset+mp->label_loc[k]<256));
24294     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24295 };
24296 if ( lk_offset>0 ) {
24297   while ( k>0 ) {
24298     mp->char_remainder[mp->label_char[k]]
24299      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24300     decr(k);
24301   }
24302 }
24303
24304 @ @<Output the ligature/kern program@>=
24305 for (k=0;k<= 255;k++ ) {
24306   if ( mp->skip_table[k]<undefined_label ) {
24307      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24308 @.local label l:: was missing@>
24309     cancel_skips(mp->skip_table[k]);
24310   }
24311 }
24312 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24313   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24314 } else {
24315   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24316     mp->ll=mp->label_loc[mp->label_ptr];
24317     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24318     else { tfm_out(255); tfm_out(mp->bchar);   };
24319     mp_tfm_two(mp, mp->ll+lk_offset);
24320     do {  
24321       decr(mp->label_ptr);
24322     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24323   }
24324 }
24325 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24326 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24327
24328 @ @<Output the extensible character recipes...@>=
24329 for (k=0;k<=mp->ne-1;k++) 
24330   mp_tfm_qqqq(mp, mp->exten[k]);
24331 for (k=1;k<=mp->np;k++) {
24332   if ( k==1 ) {
24333     if ( abs(mp->param[1])<fraction_half ) {
24334       mp_tfm_four(mp, mp->param[1]*16);
24335     } else  { 
24336       incr(mp->tfm_changed);
24337       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24338       else mp_tfm_four(mp, -el_gordo);
24339     }
24340   } else {
24341     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24342   }
24343 }
24344 if ( mp->tfm_changed>0 )  { 
24345   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24346 @.a font metric dimension...@>
24347   else  { 
24348     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24349 @.font metric dimensions...@>
24350     mp_print(mp, " font metric dimensions");
24351   }
24352   mp_print(mp, " had to be decreased)");
24353 }
24354
24355 @ @<Log the subfile sizes of the \.{TFM} file@>=
24356
24357   char s[200];
24358   wlog_ln(" ");
24359   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24360   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24361                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24362   wlog_ln(s);
24363 }
24364
24365 @* \[43] Reading font metric data.
24366
24367 \MP\ isn't a typesetting program but it does need to find the bounding box
24368 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24369 well as write them.
24370
24371 @<Glob...@>=
24372 void * tfm_infile;
24373
24374 @ All the width, height, and depth information is stored in an array called
24375 |font_info|.  This array is allocated sequentially and each font is stored
24376 as a series of |char_info| words followed by the width, height, and depth
24377 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24378 set to |max_str_ref|.
24379
24380 @<Types...@>=
24381 typedef unsigned int font_number; /* |0..font_max| */
24382
24383 @ The |font_info| array is indexed via a group directory arrays.
24384 For example, the |char_info| data for character~|c| in font~|f| will be
24385 in |font_info[char_base[f]+c].qqqq|.
24386
24387 @<Glob...@>=
24388 font_number font_max; /* maximum font number for included text fonts */
24389 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24390 memory_word *font_info; /* height, width, and depth data */
24391 char        **font_enc_name; /* encoding names, if any */
24392 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24393 int         next_fmem; /* next unused entry in |font_info| */
24394 font_number last_fnum; /* last font number used so far */
24395 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24396 char        **font_name;  /* name as specified in the \&{infont} command */
24397 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24398 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24399 eight_bits  *font_bc;
24400 eight_bits  *font_ec;  /* first and last character code */
24401 int         *char_base;  /* base address for |char_info| */
24402 int         *width_base; /* index for zeroth character width */
24403 int         *height_base; /* index for zeroth character height */
24404 int         *depth_base; /* index for zeroth character depth */
24405 pointer     *font_sizes;
24406
24407 @ @<Allocate or initialize ...@>=
24408 mp->font_mem_size = 10000; 
24409 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24410 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24411 mp->font_enc_name = NULL;
24412 mp->font_ps_name_fixed = NULL;
24413 mp->font_dsize = NULL;
24414 mp->font_name = NULL;
24415 mp->font_ps_name = NULL;
24416 mp->font_bc = NULL;
24417 mp->font_ec = NULL;
24418 mp->last_fnum = null_font;
24419 mp->char_base = NULL;
24420 mp->width_base = NULL;
24421 mp->height_base = NULL;
24422 mp->depth_base = NULL;
24423 mp->font_sizes = null;
24424
24425 @ @<Dealloc variables@>=
24426 for (k=1;k<=(int)mp->last_fnum;k++) {
24427   xfree(mp->font_enc_name[k]);
24428   xfree(mp->font_name[k]);
24429   xfree(mp->font_ps_name[k]);
24430 }
24431 xfree(mp->font_info);
24432 xfree(mp->font_enc_name);
24433 xfree(mp->font_ps_name_fixed);
24434 xfree(mp->font_dsize);
24435 xfree(mp->font_name);
24436 xfree(mp->font_ps_name);
24437 xfree(mp->font_bc);
24438 xfree(mp->font_ec);
24439 xfree(mp->char_base);
24440 xfree(mp->width_base);
24441 xfree(mp->height_base);
24442 xfree(mp->depth_base);
24443 xfree(mp->font_sizes);
24444
24445
24446 @c 
24447 void mp_reallocate_fonts (MP mp, font_number l) {
24448   font_number f;
24449   XREALLOC(mp->font_enc_name,      l, char *);
24450   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24451   XREALLOC(mp->font_dsize,         l, scaled);
24452   XREALLOC(mp->font_name,          l, char *);
24453   XREALLOC(mp->font_ps_name,       l, char *);
24454   XREALLOC(mp->font_bc,            l, eight_bits);
24455   XREALLOC(mp->font_ec,            l, eight_bits);
24456   XREALLOC(mp->char_base,          l, int);
24457   XREALLOC(mp->width_base,         l, int);
24458   XREALLOC(mp->height_base,        l, int);
24459   XREALLOC(mp->depth_base,         l, int);
24460   XREALLOC(mp->font_sizes,         l, pointer);
24461   for (f=(mp->last_fnum+1);f<=l;f++) {
24462     mp->font_enc_name[f]=NULL;
24463     mp->font_ps_name_fixed[f] = false;
24464     mp->font_name[f]=NULL;
24465     mp->font_ps_name[f]=NULL;
24466     mp->font_sizes[f]=null;
24467   }
24468   mp->font_max = l;
24469 }
24470
24471 @ @<Declare |mp_reallocate| functions@>=
24472 void mp_reallocate_fonts (MP mp, font_number l);
24473
24474
24475 @ A |null_font| containing no characters is useful for error recovery.  Its
24476 |font_name| entry starts out empty but is reset each time an erroneous font is
24477 found.  This helps to cut down on the number of duplicate error messages without
24478 wasting a lot of space.
24479
24480 @d null_font 0 /* the |font_number| for an empty font */
24481
24482 @<Set initial...@>=
24483 mp->font_dsize[null_font]=0;
24484 mp->font_bc[null_font]=1;
24485 mp->font_ec[null_font]=0;
24486 mp->char_base[null_font]=0;
24487 mp->width_base[null_font]=0;
24488 mp->height_base[null_font]=0;
24489 mp->depth_base[null_font]=0;
24490 mp->next_fmem=0;
24491 mp->last_fnum=null_font;
24492 mp->last_ps_fnum=null_font;
24493 mp->font_name[null_font]="nullfont";
24494 mp->font_ps_name[null_font]="";
24495 mp->font_ps_name_fixed[null_font] = false;
24496 mp->font_enc_name[null_font]=NULL;
24497 mp->font_sizes[null_font]=null;
24498
24499 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24500 the |width index|; the |b1| field contains the height
24501 index; the |b2| fields contains the depth index, and the |b3| field used only
24502 for temporary storage. (It is used to keep track of which characters occur in
24503 an edge structure that is being shipped out.)
24504 The corresponding words in the width, height, and depth tables are stored as
24505 |scaled| values in units of \ps\ points.
24506
24507 With the macros below, the |char_info| word for character~|c| in font~|f| is
24508 |char_info(f)(c)| and the width is
24509 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24510
24511 @d char_info_end(A) (A)].qqqq
24512 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24513 @d char_width_end(A) (A).b0].sc
24514 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24515 @d char_height_end(A) (A).b1].sc
24516 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24517 @d char_depth_end(A) (A).b2].sc
24518 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24519 @d ichar_exists(A) ((A).b0>0)
24520
24521 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24522 A preliminary name is obtained here from the \.{TFM} name as given in the
24523 |fname| argument.  This gets updated later from an external table if necessary.
24524
24525 @<Declare text measuring subroutines@>=
24526 @<Declare subroutines for parsing file names@>;
24527 font_number mp_read_font_info (MP mp, char *fname) {
24528   boolean file_opened; /* has |tfm_infile| been opened? */
24529   font_number n; /* the number to return */
24530   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24531   size_t whd_size; /* words needed for heights, widths, and depths */
24532   int i,ii; /* |font_info| indices */
24533   int jj; /* counts bytes to be ignored */
24534   scaled z; /* used to compute the design size */
24535   fraction d;
24536   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24537   eight_bits h_and_d; /* height and depth indices being unpacked */
24538   unsigned char tfbyte; /* a byte read from the file */
24539   n=null_font;
24540   @<Open |tfm_infile| for input@>;
24541   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24542     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24543 BAD_TFM:
24544   @<Complain that the \.{TFM} file is bad@>;
24545 DONE:
24546   if ( file_opened ) (mp->close_file)(mp->tfm_infile);
24547   if ( n!=null_font ) { 
24548     mp->font_ps_name[n]=mp_xstrdup(mp,fname);
24549     mp->font_name[n]=mp_xstrdup(mp,fname);
24550   }
24551   return n;
24552 }
24553
24554 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24555 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24556 @.TFtoPL@> @.PLtoTF@>
24557 and \.{PLtoTF} can be used to debug \.{TFM} files.
24558
24559 @<Complain that the \.{TFM} file is bad@>=
24560 print_err("Font ");
24561 mp_print(mp, fname);
24562 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24563 else mp_print(mp, " not usable: TFM file not found");
24564 help3("I wasn't able to read the size data for this font so this")
24565   ("`infont' operation won't produce anything. If the font name")
24566   ("is right, you might ask an expert to make a TFM file");
24567 if ( file_opened )
24568   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24569 mp_error(mp)
24570
24571 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24572 @<Read the \.{TFM} size fields@>;
24573 @<Use the size fields to allocate space in |font_info|@>;
24574 @<Read the \.{TFM} header@>;
24575 @<Read the character data and the width, height, and depth tables and
24576   |goto done|@>
24577
24578 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24579 might try to read past the end of the file if this happens.  Changes will be
24580 needed if it causes a system error to refer to |tfm_infile^| or call
24581 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24582 @^system dependencies@>
24583 of |tfget| could be changed to
24584 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24585
24586 @d tfget do { 
24587   size_t wanted=1; 
24588   void *tfbyte_ptr = &tfbyte;
24589   (mp->read_binary_file)(mp->tfm_infile,&tfbyte_ptr,&wanted); 
24590   if (wanted==0) goto BAD_TFM; 
24591 } while (0)
24592 @d read_two(A) { (A)=tfbyte;
24593   if ( (A)>127 ) goto BAD_TFM;
24594   tfget; (A)=(A)*0400+tfbyte;
24595 }
24596 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24597
24598 @<Read the \.{TFM} size fields@>=
24599 tfget; read_two(lf);
24600 tfget; read_two(tfm_lh);
24601 tfget; read_two(bc);
24602 tfget; read_two(ec);
24603 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24604 tfget; read_two(nw);
24605 tfget; read_two(nh);
24606 tfget; read_two(nd);
24607 whd_size=(ec+1-bc)+nw+nh+nd;
24608 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24609 tf_ignore(10)
24610
24611 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24612 necessary to apply the |so|  and |qo| macros when looking up the width of a
24613 character in the string pool.  In order to ensure nonnegative |char_base|
24614 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24615 elements.
24616
24617 @<Use the size fields to allocate space in |font_info|@>=
24618 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24619 if (mp->last_fnum==mp->font_max)
24620   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24621 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24622   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24623   memory_word *font_info;
24624   font_info = xmalloc ((l+1),sizeof(memory_word));
24625   memset (font_info,0,sizeof(memory_word)*(l+1));
24626   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24627   xfree(mp->font_info);
24628   mp->font_info = font_info;
24629   mp->font_mem_size = l;
24630 }
24631 incr(mp->last_fnum);
24632 n=mp->last_fnum;
24633 mp->font_bc[n]=bc;
24634 mp->font_ec[n]=ec;
24635 mp->char_base[n]=mp->next_fmem-bc;
24636 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24637 mp->height_base[n]=mp->width_base[n]+nw;
24638 mp->depth_base[n]=mp->height_base[n]+nh;
24639 mp->next_fmem=mp->next_fmem+whd_size;
24640
24641
24642 @ @<Read the \.{TFM} header@>=
24643 if ( tfm_lh<2 ) goto BAD_TFM;
24644 tf_ignore(4);
24645 tfget; read_two(z);
24646 tfget; z=z*0400+tfbyte;
24647 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24648 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24649   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24650 tf_ignore(4*(tfm_lh-2))
24651
24652 @ @<Read the character data and the width, height, and depth tables...@>=
24653 ii=mp->width_base[n];
24654 i=mp->char_base[n]+bc;
24655 while ( i<ii ) { 
24656   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24657   tfget; h_and_d=tfbyte;
24658   mp->font_info[i].qqqq.b1=h_and_d / 16;
24659   mp->font_info[i].qqqq.b2=h_and_d % 16;
24660   tfget; tfget;
24661   incr(i);
24662 }
24663 while ( i<mp->next_fmem ) {
24664   @<Read a four byte dimension, scale it by the design size, store it in
24665     |font_info[i]|, and increment |i|@>;
24666 }
24667 goto DONE
24668
24669 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24670 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24671 we can multiply it by sixteen and think of it as a |fraction| that has been
24672 divided by sixteen.  This cancels the extra scale factor contained in
24673 |font_dsize[n|.
24674
24675 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24676
24677 tfget; d=tfbyte;
24678 if ( d>=0200 ) d=d-0400;
24679 tfget; d=d*0400+tfbyte;
24680 tfget; d=d*0400+tfbyte;
24681 tfget; d=d*0400+tfbyte;
24682 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24683 incr(i);
24684 }
24685
24686 @ This function does no longer use the file name parser, because |fname| is
24687 a C string already.
24688 @<Open |tfm_infile| for input@>=
24689 file_opened=false;
24690 mp_ptr_scan_file(mp, fname);
24691 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); mp->cur_area=xstrdup(MP_font_area);}
24692 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24693 pack_cur_name;
24694 mp->tfm_infile = (mp->open_file)( mp->name_of_file, "rb",mp_filetype_metrics);
24695 if ( !mp->tfm_infile  ) goto BAD_TFM;
24696 file_opened=true
24697
24698 @ When we have a font name and we don't know whether it has been loaded yet,
24699 we scan the |font_name| array before calling |read_font_info|.
24700
24701 @<Declare text measuring subroutines@>=
24702 font_number mp_find_font (MP mp, char *f) {
24703   font_number n;
24704   for (n=0;n<=mp->last_fnum;n++) {
24705     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
24706       mp_xfree(f);
24707       return n;
24708     }
24709   }
24710   n = mp_read_font_info(mp, f);
24711   mp_xfree(f);
24712   return n;
24713 }
24714
24715 @ One simple application of |find_font| is the implementation of the |font_size|
24716 operator that gets the design size for a given font name.
24717
24718 @<Find the design size of the font whose name is |cur_exp|@>=
24719 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24720
24721 @ If we discover that the font doesn't have a requested character, we omit it
24722 from the bounding box computation and expect the \ps\ interpreter to drop it.
24723 This routine issues a warning message if the user has asked for it.
24724
24725 @<Declare text measuring subroutines@>=
24726 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24727   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24728     mp_begin_diagnostic(mp);
24729     if ( mp->selector==log_only ) incr(mp->selector);
24730     mp_print_nl(mp, "Missing character: There is no ");
24731 @.Missing character@>
24732     mp_print_str(mp, mp->str_pool[k]); 
24733     mp_print(mp, " in font ");
24734     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24735     mp_end_diagnostic(mp, false);
24736   }
24737 }
24738
24739 @ The whole purpose of saving the height, width, and depth information is to be
24740 able to find the bounding box of an item of text in an edge structure.  The
24741 |set_text_box| procedure takes a text node and adds this information.
24742
24743 @<Declare text measuring subroutines@>=
24744 void mp_set_text_box (MP mp,pointer p) {
24745   font_number f; /* |font_n(p)| */
24746   ASCII_code bc,ec; /* range of valid characters for font |f| */
24747   pool_pointer k,kk; /* current character and character to stop at */
24748   four_quarters cc; /* the |char_info| for the current character */
24749   scaled h,d; /* dimensions of the current character */
24750   width_val(p)=0;
24751   height_val(p)=-el_gordo;
24752   depth_val(p)=-el_gordo;
24753   f=font_n(p);
24754   bc=mp->font_bc[f];
24755   ec=mp->font_ec[f];
24756   kk=str_stop(text_p(p));
24757   k=mp->str_start[text_p(p)];
24758   while ( k<kk ) {
24759     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24760   }
24761   @<Set the height and depth to zero if the bounding box is empty@>;
24762 }
24763
24764 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24765
24766   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24767     mp_lost_warning(mp, f,k);
24768   } else { 
24769     cc=char_info(f)(mp->str_pool[k]);
24770     if ( ! ichar_exists(cc) ) {
24771       mp_lost_warning(mp, f,k);
24772     } else { 
24773       width_val(p)=width_val(p)+char_width(f)(cc);
24774       h=char_height(f)(cc);
24775       d=char_depth(f)(cc);
24776       if ( h>height_val(p) ) height_val(p)=h;
24777       if ( d>depth_val(p) ) depth_val(p)=d;
24778     }
24779   }
24780   incr(k);
24781 }
24782
24783 @ Let's hope modern compilers do comparisons correctly when the difference would
24784 overflow.
24785
24786 @<Set the height and depth to zero if the bounding box is empty@>=
24787 if ( height_val(p)<-depth_val(p) ) { 
24788   height_val(p)=0;
24789   depth_val(p)=0;
24790 }
24791
24792 @ The new primitives fontmapfile and fontmapline.
24793
24794 @<Declare action procedures for use by |do_statement|@>=
24795 void mp_do_mapfile (MP mp) ;
24796 void mp_do_mapline (MP mp) ;
24797
24798 @ @c void mp_do_mapfile (MP mp) { 
24799   mp_get_x_next(mp); mp_scan_expression(mp);
24800   if ( mp->cur_type!=mp_string_type ) {
24801     @<Complain about improper map operation@>;
24802   } else {
24803     mp_map_file(mp,mp->cur_exp);
24804   }
24805 }
24806 void mp_do_mapline (MP mp) { 
24807   mp_get_x_next(mp); mp_scan_expression(mp);
24808   if ( mp->cur_type!=mp_string_type ) {
24809      @<Complain about improper map operation@>;
24810   } else { 
24811      mp_map_line(mp,mp->cur_exp);
24812   }
24813 }
24814
24815 @ @<Complain about improper map operation@>=
24816
24817   exp_err("Unsuitable expression");
24818   help1("Only known strings can be map files or map lines.");
24819   mp_put_get_error(mp);
24820 }
24821
24822 @ To print |scaled| value to PDF output we need some subroutines to ensure
24823 accurary.
24824
24825 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24826
24827 @<Glob...@>=
24828 scaled one_bp; /* scaled value corresponds to 1bp */
24829 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24830 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24831 integer ten_pow[10]; /* $10^0..10^9$ */
24832 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24833
24834 @ @<Set init...@>=
24835 mp->one_bp = 65782; /* 65781.76 */
24836 mp->one_hundred_bp = 6578176;
24837 mp->one_hundred_inch = 473628672;
24838 mp->ten_pow[0] = 1;
24839 for (i = 1;i<= 9; i++ ) {
24840   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24841 }
24842
24843 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24844
24845 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24846   scaled q,r;
24847   integer sign,i;
24848   sign = 1;
24849   if ( s < 0 ) { sign = -sign; s = -s; }
24850   if ( m < 0 ) { sign = -sign; m = -m; }
24851   if ( m == 0 )
24852     mp_confusion(mp, "arithmetic: divided by zero");
24853   else if ( m >= (max_integer / 10) )
24854     mp_confusion(mp, "arithmetic: number too big");
24855   q = s / m;
24856   r = s % m;
24857   for (i = 1;i<=dd;i++) {
24858     q = 10*q + (10*r) / m;
24859     r = (10*r) % m;
24860   }
24861   if ( 2*r >= m ) { incr(q); r = r - m; }
24862   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24863   return (sign*q);
24864 }
24865
24866 @* \[44] Shipping pictures out.
24867 The |ship_out| procedure, to be described below, is given a pointer to
24868 an edge structure. Its mission is to output a file containing the \ps\
24869 description of an edge structure.
24870
24871 @ Each time an edge structure is shipped out we write a new \ps\ output
24872 file named according to the current \&{charcode}.
24873 @:char_code_}{\&{charcode} primitive@>
24874
24875 This is the only backend function that remains in the main |mpost.w| file. 
24876 There are just too many variable accesses needed for status reporting 
24877 etcetera to make it worthwile to move the code to |psout.w|.
24878
24879 @<Internal library declarations@>=
24880 void mp_open_output_file (MP mp) ;
24881
24882 @ @c void mp_open_output_file (MP mp) {
24883   integer c; /* \&{charcode} rounded to the nearest integer */
24884   int old_setting; /* previous |selector| setting */
24885   pool_pointer i; /*  indexes into |filename_template|  */
24886   integer cc; /* a temporary integer for template building  */
24887   integer f,g=0; /* field widths */
24888   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24889   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
24890   if ( mp->filename_template==0 ) {
24891     char *s; /* a file extension derived from |c| */
24892     if ( c<0 ) 
24893       s=xstrdup(".ps");
24894     else 
24895       @<Use |c| to compute the file extension |s|@>;
24896     mp_pack_job_name(mp, s);
24897     xfree(s);
24898     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24899       mp_prompt_file_name(mp, "file name for output",s);
24900   } else { /* initializations */
24901     str_number s, n; /* a file extension derived from |c| */
24902     old_setting=mp->selector; 
24903     mp->selector=new_string;
24904     f = 0;
24905     i = mp->str_start[mp->filename_template];
24906     n = rts(""); /* initialize */
24907     while ( i<str_stop(mp->filename_template) ) {
24908        if ( mp->str_pool[i]=='%' ) {
24909       CONTINUE:
24910         incr(i);
24911         if ( i<str_stop(mp->filename_template) ) {
24912           if ( mp->str_pool[i]=='j' ) {
24913             mp_print(mp, mp->job_name);
24914           } else if ( mp->str_pool[i]=='d' ) {
24915              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24916              print_with_leading_zeroes(cc);
24917           } else if ( mp->str_pool[i]=='m' ) {
24918              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24919              print_with_leading_zeroes(cc);
24920           } else if ( mp->str_pool[i]=='y' ) {
24921              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24922              print_with_leading_zeroes(cc);
24923           } else if ( mp->str_pool[i]=='H' ) {
24924              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24925              print_with_leading_zeroes(cc);
24926           }  else if ( mp->str_pool[i]=='M' ) {
24927              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24928              print_with_leading_zeroes(cc);
24929           } else if ( mp->str_pool[i]=='c' ) {
24930             if ( c<0 ) mp_print(mp, "ps");
24931             else print_with_leading_zeroes(c);
24932           } else if ( (mp->str_pool[i]>='0') && 
24933                       (mp->str_pool[i]<='9') ) {
24934             if ( (f<10)  )
24935               f = (f*10) + mp->str_pool[i]-'0';
24936             goto CONTINUE;
24937           } else {
24938             mp_print_str(mp, mp->str_pool[i]);
24939           }
24940         }
24941       } else {
24942         if ( mp->str_pool[i]=='.' )
24943           if (length(n)==0)
24944             n = mp_make_string(mp);
24945         mp_print_str(mp, mp->str_pool[i]);
24946       };
24947       incr(i);
24948     };
24949     s = mp_make_string(mp);
24950     mp->selector= old_setting;
24951     if (length(n)==0) {
24952        n=s;
24953        s=rts("");
24954     };
24955     mp_pack_file_name(mp, str(n),"",str(s));
24956     while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
24957       mp_prompt_file_name(mp, "file name for output",str(s));
24958     delete_str_ref(n);
24959     delete_str_ref(s);
24960   }
24961   @<Store the true output file name if appropriate@>;
24962 }
24963
24964 @ The file extension created here could be up to five characters long in
24965 extreme cases so it may have to be shortened on some systems.
24966 @^system dependencies@>
24967
24968 @<Use |c| to compute the file extension |s|@>=
24969
24970   s = xmalloc(7,1);
24971   snprintf(s,7,".%i",(int)c);
24972 }
24973
24974 @ The user won't want to see all the output file names so we only save the
24975 first and last ones and a count of how many there were.  For this purpose
24976 files are ordered primarily by \&{charcode} and secondarily by order of
24977 creation.
24978 @:char_code_}{\&{charcode} primitive@>
24979
24980 @<Store the true output file name if appropriate@>=
24981 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
24982   mp->first_output_code=c;
24983   xfree(mp->first_file_name);
24984   mp->first_file_name=xstrdup(mp->name_of_file);
24985 }
24986 if ( c>=mp->last_output_code ) {
24987   mp->last_output_code=c;
24988   xfree(mp->last_file_name);
24989   mp->last_file_name=xstrdup(mp->name_of_file);
24990 }
24991
24992 @ @<Glob...@>=
24993 char * first_file_name;
24994 char * last_file_name; /* full file names */
24995 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
24996 @:char_code_}{\&{charcode} primitive@>
24997 integer total_shipped; /* total number of |ship_out| operations completed */
24998
24999 @ @<Set init...@>=
25000 mp->first_file_name=xstrdup("");
25001 mp->last_file_name=xstrdup("");
25002 mp->first_output_code=32768;
25003 mp->last_output_code=-32768;
25004 mp->total_shipped=0;
25005
25006 @ @<Dealloc variables@>=
25007 xfree(mp->first_file_name);
25008 xfree(mp->last_file_name);
25009
25010 @ @<Begin the progress report for the output of picture~|c|@>=
25011 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25012 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25013 mp_print_char(mp, '[');
25014 if ( c>=0 ) mp_print_int(mp, c)
25015
25016 @ @<End progress report@>=
25017 mp_print_char(mp, ']');
25018 update_terminal;
25019 incr(mp->total_shipped)
25020
25021 @ @<Explain what output files were written@>=
25022 if ( mp->total_shipped>0 ) { 
25023   mp_print_nl(mp, "");
25024   mp_print_int(mp, mp->total_shipped);
25025   mp_print(mp, " output file");
25026   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25027   mp_print(mp, " written: ");
25028   mp_print(mp, mp->first_file_name);
25029   if ( mp->total_shipped>1 ) {
25030     if ( 31+strlen(mp->first_file_name)+
25031          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25032       mp_print_ln(mp);
25033     mp_print(mp, " .. ");
25034     mp_print(mp, mp->last_file_name);
25035   }
25036 }
25037
25038 @ @<Internal library declarations@>=
25039 boolean mp_has_font_size(MP mp, font_number f );
25040
25041 @ @c 
25042 boolean mp_has_font_size(MP mp, font_number f ) {
25043   return (mp->font_sizes[f]!=null);
25044 }
25045
25046 @ The \&{special} command saves up lines of text to be printed during the next
25047 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25048
25049 @<Glob...@>=
25050 pointer last_pending; /* the last token in a list of pending specials */
25051
25052 @ @<Set init...@>=
25053 mp->last_pending=spec_head;
25054
25055 @ @<Cases of |do_statement|...@>=
25056 case special_command: 
25057   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25058   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25059   mp_do_mapline(mp);
25060   break;
25061
25062 @ @<Declare action procedures for use by |do_statement|@>=
25063 void mp_do_special (MP mp) ;
25064
25065 @ @c void mp_do_special (MP mp) { 
25066   mp_get_x_next(mp); mp_scan_expression(mp);
25067   if ( mp->cur_type!=mp_string_type ) {
25068     @<Complain about improper special operation@>;
25069   } else { 
25070     link(mp->last_pending)=mp_stash_cur_exp(mp);
25071     mp->last_pending=link(mp->last_pending);
25072     link(mp->last_pending)=null;
25073   }
25074 }
25075
25076 @ @<Complain about improper special operation@>=
25077
25078   exp_err("Unsuitable expression");
25079   help1("Only known strings are allowed for output as specials.");
25080   mp_put_get_error(mp);
25081 }
25082
25083 @ On the export side, we need an extra object type for special strings.
25084
25085 @<Graphical object codes@>=
25086 mp_special_code=8, 
25087
25088 @ @<Export pending specials@>=
25089 p=link(spec_head);
25090 while ( p!=null ) {
25091   hq = mp_new_graphic_object(mp,mp_special_code);
25092   gr_pre_script(hq)  = str(value(p));
25093   if (hh->body==NULL) hh->body=hq; else gr_link(hp) = hq;
25094   hp = hq;
25095   p=link(p);
25096 }
25097 mp_flush_token_list(mp, link(spec_head));
25098 link(spec_head)=null;
25099 mp->last_pending=spec_head
25100
25101 @ We are now ready for the main output procedure.  Note that the |selector|
25102 setting is saved in a global variable so that |begin_diagnostic| can access it.
25103
25104 @<Declare the \ps\ output procedures@>=
25105 void mp_ship_out (MP mp, pointer h) ;
25106
25107 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25108
25109 @c
25110 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25111   pointer p; /* the current graphical object */
25112   integer t; /* a temporary value */
25113   struct mp_edge_object *hh; /* the first graphical object */
25114   struct mp_graphic_object *hp; /* the current graphical object */
25115   struct mp_graphic_object *hq; /* something |hp| points to  */
25116   mp_set_bbox(mp, h, true);
25117   hh = mp_xmalloc(mp,1,sizeof(struct mp_edge_object));
25118   hh->body = NULL;
25119   hh->_next = NULL;
25120   hh->_parent = mp;
25121   hh->_minx = minx_val(h);
25122   hh->_miny = miny_val(h);
25123   hh->_maxx = maxx_val(h);
25124   hh->_maxy = maxy_val(h);
25125   @<Export pending specials@>;
25126   p=link(dummy_loc(h));
25127   while ( p!=null ) { 
25128     hq = mp_new_graphic_object(mp,type(p));
25129     switch (type(p)) {
25130     case mp_fill_code:
25131       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25132       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25133           gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25134       } else {
25135         pointer pc, pp;
25136         pc = mp_copy_path(mp, path_p(p));
25137         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25138         gr_path_p(hq)       = mp_export_knot_list(mp,pp);
25139         mp_toss_knot_list(mp, pp);
25140         pc = mp_htap_ypoc(mp, path_p(p));
25141         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25142         gr_htap_p(hq)       = mp_export_knot_list(mp,pp);
25143         mp_toss_knot_list(mp, pp);
25144       }
25145       @<Export object color@>;
25146       @<Export object scripts@>;
25147       gr_ljoin_val(hq)    = ljoin_val(p);
25148       gr_miterlim_val(hq) = miterlim_val(p);
25149       break;
25150     case mp_stroked_code:
25151       gr_pen_p(hq)        = mp_export_knot_list(mp,pen_p(p));
25152       if (pen_is_elliptical(pen_p(p)))  {
25153               gr_path_p(hq)       = mp_export_knot_list(mp,path_p(p));
25154       } else {
25155         pointer pc;
25156         pc=mp_copy_path(mp, path_p(p));
25157         t=lcap_val(p);
25158         if ( left_type(pc)!=mp_endpoint ) { 
25159           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25160           right_type(pc)=mp_endpoint;
25161           pc=link(pc);
25162           t=1;
25163         }
25164         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25165         gr_path_p(hq)       = mp_export_knot_list(mp,pc);
25166         mp_toss_knot_list(mp, pc);
25167       }
25168       @<Export object color@>;
25169       @<Export object scripts@>;
25170       gr_ljoin_val(hq)    = ljoin_val(p);
25171       gr_miterlim_val(hq) = miterlim_val(p);
25172       gr_lcap_val(hq)     = lcap_val(p);
25173       gr_dash_scale(hq)   = dash_scale(p);
25174       gr_dash_p(hq)       = mp_export_dashes(mp,dash_p(p));
25175       break;
25176     case mp_text_code:
25177       gr_text_p(hq)       = str(text_p(p));
25178       gr_font_n(hq)       = font_n(p);
25179       @<Export object color@>;
25180       @<Export object scripts@>;
25181       gr_width_val(hq)    = width_val(p);
25182       gr_height_val(hq)   = height_val(p);
25183       gr_depth_val(hq)    = depth_val(p);
25184       gr_tx_val(hq)       = tx_val(p);
25185       gr_ty_val(hq)       = ty_val(p);
25186       gr_txx_val(hq)      = txx_val(p);
25187       gr_txy_val(hq)      = txy_val(p);
25188       gr_tyx_val(hq)      = tyx_val(p);
25189       gr_tyy_val(hq)      = tyy_val(p);
25190       break;
25191     case mp_start_clip_code: 
25192     case mp_start_bounds_code:
25193       gr_path_p(hq) = mp_export_knot_list(mp,path_p(p));
25194       break;
25195     case mp_stop_clip_code: 
25196     case mp_stop_bounds_code:
25197       /* nothing to do here */
25198       break;
25199     } 
25200     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25201     hp = hq;
25202     p=link(p);
25203   }
25204   return hh;
25205 }
25206
25207 @ @<Exported function ...@>=
25208 struct mp_edge_object *mp_gr_export(MP mp, int h);
25209
25210 @ This function is now nearly trivial.
25211
25212 @c
25213 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25214   integer c; /* \&{charcode} rounded to the nearest integer */
25215   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25216   @<Begin the progress report for the output of picture~|c|@>;
25217   (mp->shipout_backend) (mp, h);
25218   @<End progress report@>;
25219   if ( mp->internal[mp_tracing_output]>0 ) 
25220    mp_print_edges(mp, h," (just shipped out)",true);
25221 }
25222
25223 @ @<Declarations@>=
25224 void mp_shipout_backend (MP mp, pointer h);
25225
25226 @ @c
25227 void mp_shipout_backend (MP mp, pointer h) {
25228   struct mp_edge_object *hh; /* the first graphical object */
25229   hh = mp_gr_export(mp,h);
25230   mp_gr_ship_out (hh,
25231                  (mp->internal[mp_prologues]>>16),
25232                  (mp->internal[mp_procset]>>16));
25233   mp_gr_toss_objects(hh);
25234 }
25235
25236 @ @<Exported types@>=
25237 typedef void (*mp_backend_writer)(MP, int);
25238
25239 @ @<Option variables@>=
25240 mp_backend_writer shipout_backend;
25241
25242 @ @<Allocate or initialize ...@>=
25243 set_callback_option(shipout_backend);
25244
25245
25246
25247 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25248
25249 @<Export object color@>=
25250 gr_color_model(hq)  = color_model(p);
25251 gr_cyan_val(hq)     = cyan_val(p);
25252 gr_magenta_val(hq)  = magenta_val(p);
25253 gr_yellow_val(hq)   = yellow_val(p);
25254 gr_black_val(hq)    = black_val(p);
25255 gr_red_val(hq)      = red_val(p);
25256 gr_green_val(hq)    = green_val(p);
25257 gr_blue_val(hq)     = blue_val(p);
25258 gr_grey_val(hq)     = grey_val(p)
25259
25260
25261 @ @<Export object scripts@>=
25262 if (pre_script(p)!=null)
25263   gr_pre_script(hq)   = str(pre_script(p));
25264 if (post_script(p)!=null)
25265   gr_post_script(hq)  = str(post_script(p));
25266
25267 @ Now that we've finished |ship_out|, let's look at the other commands
25268 by which a user can send things to the \.{GF} file.
25269
25270 @ @<Determine if a character has been shipped out@>=
25271
25272   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25273   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25274   boolean_reset(mp->char_exists[mp->cur_exp]);
25275   mp->cur_type=mp_boolean_type;
25276 }
25277
25278 @ @<Glob...@>=
25279 psout_data ps;
25280
25281 @ @<Allocate or initialize ...@>=
25282 mp_backend_initialize(mp);
25283
25284 @ @<Dealloc...@>=
25285 mp_backend_free(mp);
25286
25287
25288 @* \[45] Dumping and undumping the tables.
25289 After \.{INIMP} has seen a collection of macros, it
25290 can write all the necessary information on an auxiliary file so
25291 that production versions of \MP\ are able to initialize their
25292 memory at high speed. The present section of the program takes
25293 care of such output and input. We shall consider simultaneously
25294 the processes of storing and restoring,
25295 so that the inverse relation between them is clear.
25296 @.INIMP@>
25297
25298 The global variable |mem_ident| is a string that is printed right
25299 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25300 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25301 for example, `\.{(mem=plain 90.4.14)}', showing the year,
25302 month, and day that the mem file was created. We have |mem_ident=0|
25303 before \MP's tables are loaded.
25304
25305 @<Glob...@>=
25306 char * mem_ident;
25307
25308 @ @<Set init...@>=
25309 mp->mem_ident=NULL;
25310
25311 @ @<Initialize table entries...@>=
25312 mp->mem_ident=xstrdup(" (INIMP)");
25313
25314 @ @<Declare act...@>=
25315 void mp_store_mem_file (MP mp) ;
25316
25317 @ @c void mp_store_mem_file (MP mp) {
25318   integer k;  /* all-purpose index */
25319   pointer p,q; /* all-purpose pointers */
25320   integer x; /* something to dump */
25321   four_quarters w; /* four ASCII codes */
25322   memory_word WW;
25323   @<Create the |mem_ident|, open the mem file,
25324     and inform the user that dumping has begun@>;
25325   @<Dump constants for consistency check@>;
25326   @<Dump the string pool@>;
25327   @<Dump the dynamic memory@>;
25328   @<Dump the table of equivalents and the hash table@>;
25329   @<Dump a few more things and the closing check word@>;
25330   @<Close the mem file@>;
25331 }
25332
25333 @ Corresponding to the procedure that dumps a mem file, we also have a function
25334 that reads~one~in. The function returns |false| if the dumped mem is
25335 incompatible with the present \MP\ table sizes, etc.
25336
25337 @d off_base 6666 /* go here if the mem file is unacceptable */
25338 @d too_small(A) { wake_up_terminal;
25339   wterm_ln("---! Must increase the "); wterm((A));
25340 @.Must increase the x@>
25341   goto OFF_BASE;
25342   }
25343
25344 @c 
25345 boolean mp_load_mem_file (MP mp) {
25346   integer k; /* all-purpose index */
25347   pointer p,q; /* all-purpose pointers */
25348   integer x; /* something undumped */
25349   str_number s; /* some temporary string */
25350   four_quarters w; /* four ASCII codes */
25351   memory_word WW;
25352   @<Undump constants for consistency check@>;
25353   @<Undump the string pool@>;
25354   @<Undump the dynamic memory@>;
25355   @<Undump the table of equivalents and the hash table@>;
25356   @<Undump a few more things and the closing check word@>;
25357   return true; /* it worked! */
25358 OFF_BASE: 
25359   wake_up_terminal;
25360   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25361 @.Fatal mem file error@>
25362    return false;
25363 }
25364
25365 @ @<Declarations@>=
25366 boolean mp_load_mem_file (MP mp) ;
25367
25368 @ Mem files consist of |memory_word| items, and we use the following
25369 macros to dump words of different types:
25370
25371 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25372 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp->mem_file,&cint,sizeof(cint)); }
25373 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25374 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp->mem_file,&WW,sizeof(WW)); }
25375 @d dump_string(A) { dump_int(strlen(A)+1);
25376                     (mp->write_binary_file)(mp->mem_file,A,strlen(A)+1); }
25377
25378 @<Glob...@>=
25379 void * mem_file; /* for input or output of mem information */
25380
25381 @ The inverse macros are slightly more complicated, since we need to check
25382 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25383 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25384
25385 @d mgeti(A) do {
25386   size_t wanted = sizeof(A);
25387   void *A_ptr = &A;
25388   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25389   if (wanted!=sizeof(A)) goto OFF_BASE;
25390 } while (0)
25391
25392 @d mgetw(A) do {
25393   size_t wanted = sizeof(A);
25394   void *A_ptr = &A;
25395   (mp->read_binary_file)(mp->mem_file,&A_ptr,&wanted);
25396   if (wanted!=sizeof(A)) goto OFF_BASE;
25397 } while (0)
25398
25399 @d undump_wd(A)   { mgetw(WW); A=WW; }
25400 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25401 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25402 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25403 @d undump_strings(A,B,C) { 
25404    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25405 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25406 @d undump_size(A,B,C,D) { undump_int(x);
25407                           if (x<(A)) goto OFF_BASE; 
25408                           if (x>(B)) { too_small((C)); } else { D=x;} }
25409 @d undump_string(A) do { 
25410   size_t wanted; 
25411   integer XX=0; 
25412   undump_int(XX);
25413   wanted = XX;
25414   A = xmalloc(XX,sizeof(char));
25415   (mp->read_binary_file)(mp->mem_file,(void **)&A,&wanted);
25416   if (wanted!=(size_t)XX) goto OFF_BASE;
25417 } while (0)
25418
25419 @ The next few sections of the program should make it clear how we use the
25420 dump/undump macros.
25421
25422 @<Dump constants for consistency check@>=
25423 dump_int(mp->mem_top);
25424 dump_int(mp->hash_size);
25425 dump_int(mp->hash_prime)
25426 dump_int(mp->param_size);
25427 dump_int(mp->max_in_open);
25428
25429 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25430 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25431 the same strings. (And it is, of course, a good thing that they do.)
25432 @.WEB@>
25433 @^string pool@>
25434
25435 @<Undump constants for consistency check@>=
25436 undump_int(x); mp->mem_top = x;
25437 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25438 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25439 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25440 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25441
25442 @ We do string pool compaction to avoid dumping unused strings.
25443
25444 @d dump_four_ASCII 
25445   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25446   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25447   dump_qqqq(w)
25448
25449 @<Dump the string pool@>=
25450 mp_do_compaction(mp, mp->pool_size);
25451 dump_int(mp->pool_ptr);
25452 dump_int(mp->max_str_ptr);
25453 dump_int(mp->str_ptr);
25454 k=0;
25455 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25456   incr(k);
25457 dump_int(k);
25458 while ( k<=mp->max_str_ptr ) { 
25459   dump_int(mp->next_str[k]); incr(k);
25460 }
25461 k=0;
25462 while (1)  { 
25463   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25464   if ( k==mp->str_ptr ) {
25465     break;
25466   } else { 
25467     k=mp->next_str[k]; 
25468   }
25469 };
25470 k=0;
25471 while (k+4<mp->pool_ptr ) { 
25472   dump_four_ASCII; k=k+4; 
25473 }
25474 k=mp->pool_ptr-4; dump_four_ASCII;
25475 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25476 mp_print(mp, " strings of total length ");
25477 mp_print_int(mp, mp->pool_ptr)
25478
25479 @ @d undump_four_ASCII 
25480   undump_qqqq(w);
25481   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25482   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25483
25484 @<Undump the string pool@>=
25485 undump_int(mp->pool_ptr);
25486 mp_reallocate_pool(mp, mp->pool_ptr) ;
25487 undump_int(mp->max_str_ptr);
25488 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25489 undump(0,mp->max_str_ptr,mp->str_ptr);
25490 undump(0,mp->max_str_ptr+1,s);
25491 for (k=0;k<=s-1;k++) 
25492   mp->next_str[k]=k+1;
25493 for (k=s;k<=mp->max_str_ptr;k++) 
25494   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25495 mp->fixed_str_use=0;
25496 k=0;
25497 while (1) { 
25498   undump(0,mp->pool_ptr,mp->str_start[k]);
25499   if ( k==mp->str_ptr ) break;
25500   mp->str_ref[k]=max_str_ref;
25501   incr(mp->fixed_str_use);
25502   mp->last_fixed_str=k; k=mp->next_str[k];
25503 }
25504 k=0;
25505 while ( k+4<mp->pool_ptr ) { 
25506   undump_four_ASCII; k=k+4;
25507 }
25508 k=mp->pool_ptr-4; undump_four_ASCII;
25509 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25510 mp->max_pool_ptr=mp->pool_ptr;
25511 mp->strs_used_up=mp->fixed_str_use;
25512 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25513 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25514 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25515
25516 @ By sorting the list of available spaces in the variable-size portion of
25517 |mem|, we are usually able to get by without having to dump very much
25518 of the dynamic memory.
25519
25520 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25521 information even when it has not been gathering statistics.
25522
25523 @<Dump the dynamic memory@>=
25524 mp_sort_avail(mp); mp->var_used=0;
25525 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25526 p=0; q=mp->rover; x=0;
25527 do {  
25528   for (k=p;k<= q+1;k++) 
25529     dump_wd(mp->mem[k]);
25530   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25531   p=q+node_size(q); q=rlink(q);
25532 } while (q!=mp->rover);
25533 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25534 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25535 for (k=p;k<= mp->lo_mem_max;k++ ) 
25536   dump_wd(mp->mem[k]);
25537 x=x+mp->lo_mem_max+1-p;
25538 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25539 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25540   dump_wd(mp->mem[k]);
25541 x=x+mp->mem_end+1-mp->hi_mem_min;
25542 p=mp->avail;
25543 while ( p!=null ) { 
25544   decr(mp->dyn_used); p=link(p);
25545 }
25546 dump_int(mp->var_used); dump_int(mp->dyn_used);
25547 mp_print_ln(mp); mp_print_int(mp, x);
25548 mp_print(mp, " memory locations dumped; current usage is ");
25549 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25550
25551 @ @<Undump the dynamic memory@>=
25552 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25553 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25554 p=0; q=mp->rover;
25555 do {  
25556   for (k=p;k<= q+1; k++) 
25557     undump_wd(mp->mem[k]);
25558   p=q+node_size(q);
25559   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25560     goto OFF_BASE;
25561   q=rlink(q);
25562 } while (q!=mp->rover);
25563 for (k=p;k<=mp->lo_mem_max;k++ ) 
25564   undump_wd(mp->mem[k]);
25565 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25566 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25567 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25568   undump_wd(mp->mem[k]);
25569 undump_int(mp->var_used); undump_int(mp->dyn_used)
25570
25571 @ A different scheme is used to compress the hash table, since its lower region
25572 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25573 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25574 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25575
25576 @<Dump the table of equivalents and the hash table@>=
25577 dump_int(mp->hash_used); 
25578 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25579 for (p=1;p<=mp->hash_used;p++) {
25580   if ( text(p)!=0 ) {
25581      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25582   }
25583 }
25584 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25585   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25586 }
25587 dump_int(mp->st_count);
25588 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25589
25590 @ @<Undump the table of equivalents and the hash table@>=
25591 undump(1,frozen_inaccessible,mp->hash_used); 
25592 p=0;
25593 do {  
25594   undump(p+1,mp->hash_used,p); 
25595   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25596 } while (p!=mp->hash_used);
25597 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25598   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25599 }
25600 undump_int(mp->st_count)
25601
25602 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25603 to prevent them appearing again.
25604
25605 @<Dump a few more things and the closing check word@>=
25606 dump_int(mp->max_internal);
25607 dump_int(mp->int_ptr);
25608 for (k=1;k<= mp->int_ptr;k++ ) { 
25609   dump_int(mp->internal[k]); 
25610   dump_string(mp->int_name[k]);
25611 }
25612 dump_int(mp->start_sym); 
25613 dump_int(mp->interaction); 
25614 dump_string(mp->mem_ident);
25615 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25616 mp->internal[mp_tracing_stats]=0
25617
25618 @ @<Undump a few more things and the closing check word@>=
25619 undump_int(x);
25620 if (x>mp->max_internal) mp_grow_internals(mp,x);
25621 undump_int(mp->int_ptr);
25622 for (k=1;k<= mp->int_ptr;k++) { 
25623   undump_int(mp->internal[k]);
25624   undump_string(mp->int_name[k]);
25625 }
25626 undump(0,frozen_inaccessible,mp->start_sym);
25627 if (mp->interaction==mp_unspecified_mode) {
25628   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25629 } else {
25630   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25631 }
25632 undump_string(mp->mem_ident);
25633 undump(1,hash_end,mp->bg_loc);
25634 undump(1,hash_end,mp->eg_loc);
25635 undump_int(mp->serial_no);
25636 undump_int(x); 
25637 if (x!=69073) goto OFF_BASE
25638
25639 @ @<Create the |mem_ident|...@>=
25640
25641   xfree(mp->mem_ident);
25642   mp->mem_ident = xmalloc(256,1);
25643   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25644            mp->job_name,
25645            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25646            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25647            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25648   mp_pack_job_name(mp, mem_extension);
25649   while (! mp_w_open_out(mp, &mp->mem_file) )
25650     mp_prompt_file_name(mp, "mem file name", mem_extension);
25651   mp_print_nl(mp, "Beginning to dump on file ");
25652 @.Beginning to dump...@>
25653   mp_print(mp, mp->name_of_file); 
25654   mp_print_nl(mp, mp->mem_ident);
25655 }
25656
25657 @ @<Dealloc variables@>=
25658 xfree(mp->mem_ident);
25659
25660 @ @<Close the mem file@>=
25661 (mp->close_file)(mp->mem_file)
25662
25663 @* \[46] The main program.
25664 This is it: the part of \MP\ that executes all those procedures we have
25665 written.
25666
25667 Well---almost. We haven't put the parsing subroutines into the
25668 program yet; and we'd better leave space for a few more routines that may
25669 have been forgotten.
25670
25671 @c @<Declare the basic parsing subroutines@>;
25672 @<Declare miscellaneous procedures that were declared |forward|@>;
25673 @<Last-minute procedures@>
25674
25675 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25676 @.INIMP@>
25677 has to be run first; it initializes everything from scratch, without
25678 reading a mem file, and it has the capability of dumping a mem file.
25679 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25680 @.VIRMP@>
25681 to input a mem file in order to get started. \.{VIRMP} typically has
25682 a bit more memory capacity than \.{INIMP}, because it does not need the
25683 space consumed by the dumping/undumping routines and the numerous calls on
25684 |primitive|, etc.
25685
25686 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25687 the best implementations therefore allow for production versions of \MP\ that
25688 not only avoid the loading routine for object code, they also have
25689 a mem file pre-loaded. 
25690
25691 @ @<Option variables@>=
25692 int ini_version; /* are we iniMP? */
25693
25694 @ @<Set |ini_version|@>=
25695 mp->ini_version = (opt->ini_version ? true : false);
25696
25697 @ Here we do whatever is needed to complete \MP's job gracefully on the
25698 local operating system. The code here might come into play after a fatal
25699 error; it must therefore consist entirely of ``safe'' operations that
25700 cannot produce error messages. For example, it would be a mistake to call
25701 |str_room| or |make_string| at this time, because a call on |overflow|
25702 might lead to an infinite loop.
25703 @^system dependencies@>
25704
25705 This program doesn't bother to close the input files that may still be open.
25706
25707 @<Last-minute...@>=
25708 void mp_close_files_and_terminate (MP mp) {
25709   integer k; /* all-purpose index */
25710   integer LH; /* the length of the \.{TFM} header, in words */
25711   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25712   pointer p; /* runs through a list of \.{TFM} dimensions */
25713   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25714   if ( mp->internal[mp_tracing_stats]>0 )
25715     @<Output statistics about this job@>;
25716   wake_up_terminal; 
25717   @<Do all the finishing work on the \.{TFM} file@>;
25718   @<Explain what output files were written@>;
25719   if ( mp->log_opened ){ 
25720     wlog_cr;
25721     (mp->close_file)(mp->log_file); 
25722     mp->selector=mp->selector-2;
25723     if ( mp->selector==term_only ) {
25724       mp_print_nl(mp, "Transcript written on ");
25725 @.Transcript written...@>
25726       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25727     }
25728   }
25729   mp_print_ln(mp);
25730   t_close_out;
25731   t_close_in;
25732 }
25733
25734 @ @<Declarations@>=
25735 void mp_close_files_and_terminate (MP mp) ;
25736
25737 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25738 if (mp->rd_fname!=NULL) {
25739   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25740     if ( mp->rd_fname[k]!=NULL ) {
25741       (mp->close_file)(mp->rd_file[k]);
25742    }
25743  }
25744 }
25745 if (mp->wr_fname!=NULL) {
25746   for (k=0;k<=(int)mp->write_files-1;k++) {
25747     if ( mp->wr_fname[k]!=NULL ) {
25748      (mp->close_file)(mp->wr_file[k]);
25749     }
25750   }
25751 }
25752
25753 @ @<Dealloc ...@>=
25754 for (k=0;k<(int)mp->max_read_files;k++ ) {
25755   if ( mp->rd_fname[k]!=NULL ) {
25756     (mp->close_file)(mp->rd_file[k]);
25757     mp_xfree(mp->rd_fname[k]); 
25758   }
25759 }
25760 mp_xfree(mp->rd_file);
25761 mp_xfree(mp->rd_fname);
25762 for (k=0;k<(int)mp->max_write_files;k++) {
25763   if ( mp->wr_fname[k]!=NULL ) {
25764     (mp->close_file)(mp->wr_file[k]);
25765     mp_xfree(mp->wr_fname[k]); 
25766   }
25767 }
25768 mp_xfree(mp->wr_file);
25769 mp_xfree(mp->wr_fname);
25770
25771
25772 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25773
25774 We reclaim all of the variable-size memory at this point, so that
25775 there is no chance of another memory overflow after the memory capacity
25776 has already been exceeded.
25777
25778 @<Do all the finishing work on the \.{TFM} file@>=
25779 if ( mp->internal[mp_fontmaking]>0 ) {
25780   @<Make the dynamic memory into one big available node@>;
25781   @<Massage the \.{TFM} widths@>;
25782   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25783   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25784   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25785   @<Finish the \.{TFM} file@>;
25786 }
25787
25788 @ @<Make the dynamic memory into one big available node@>=
25789 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25790 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25791 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25792 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25793 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25794
25795 @ The present section goes directly to the log file instead of using
25796 |print| commands, because there's no need for these strings to take
25797 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25798
25799 @<Output statistics...@>=
25800 if ( mp->log_opened ) { 
25801   char s[128];
25802   wlog_ln(" ");
25803   wlog_ln("Here is how much of MetaPost's memory you used:");
25804 @.Here is how much...@>
25805   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25806           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25807           (int)(mp->max_strings-1-mp->init_str_use));
25808   wlog_ln(s);
25809   snprintf(s,128," %i string characters out of %i",
25810            (int)mp->max_pl_used-mp->init_pool_ptr,
25811            (int)mp->pool_size-mp->init_pool_ptr);
25812   wlog_ln(s);
25813   snprintf(s,128," %i words of memory out of %i",
25814            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25815            (int)mp->mem_end+1);
25816   wlog_ln(s);
25817   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25818   wlog_ln(s);
25819   snprintf(s,128," %ii, %in, %ip, %ib stack positions out of %ii, %in, %ip, %ib",
25820            (int)mp->max_in_stack,(int)mp->int_ptr,
25821            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25822            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25823   wlog_ln(s);
25824   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25825           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25826   wlog_ln(s);
25827 }
25828
25829 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25830 been scanned.
25831
25832 @<Last-minute...@>=
25833 void mp_final_cleanup (MP mp) {
25834   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25835   c=mp->cur_mod;
25836   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25837   while ( mp->input_ptr>0 ) {
25838     if ( token_state ) mp_end_token_list(mp);
25839     else  mp_end_file_reading(mp);
25840   }
25841   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25842   while ( mp->open_parens>0 ) { 
25843     mp_print(mp, " )"); decr(mp->open_parens);
25844   };
25845   while ( mp->cond_ptr!=null ) {
25846     mp_print_nl(mp, "(end occurred when ");
25847 @.end occurred...@>
25848     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25849     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25850     if ( mp->if_line!=0 ) {
25851       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25852     }
25853     mp_print(mp, " was incomplete)");
25854     mp->if_line=if_line_field(mp->cond_ptr);
25855     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25856   }
25857   if ( mp->history!=mp_spotless )
25858     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25859       if ( mp->selector==term_and_log ) {
25860     mp->selector=term_only;
25861     mp_print_nl(mp, "(see the transcript file for additional information)");
25862 @.see the transcript file...@>
25863     mp->selector=term_and_log;
25864   }
25865   if ( c==1 ) {
25866     if (mp->ini_version) {
25867       mp_store_mem_file(mp); return;
25868     }
25869     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
25870 @.dump...only by INIMP@>
25871   }
25872 }
25873
25874 @ @<Declarations@>=
25875 void mp_final_cleanup (MP mp) ;
25876 void mp_init_prim (MP mp) ;
25877 void mp_init_tab (MP mp) ;
25878
25879 @ @<Last-minute...@>=
25880 void mp_init_prim (MP mp) { /* initialize all the primitives */
25881   @<Put each...@>;
25882 }
25883 @#
25884 void mp_init_tab (MP mp) { /* initialize other tables */
25885   integer k; /* all-purpose index */
25886   @<Initialize table entries (done by \.{INIMP} only)@>;
25887 }
25888
25889
25890 @ When we begin the following code, \MP's tables may still contain garbage;
25891 the strings might not even be present. Thus we must proceed cautiously to get
25892 bootstrapped in.
25893
25894 But when we finish this part of the program, \MP\ is ready to call on the
25895 |main_control| routine to do its work.
25896
25897 @<Get the first line...@>=
25898
25899   @<Initialize the input routines@>;
25900   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
25901     if ( mp->mem_ident!=NULL ) {
25902       mp_do_initialize(mp); /* erase preloaded mem */
25903     }
25904     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
25905     if ( ! mp_load_mem_file(mp) ) {
25906       (mp->close_file)(mp->mem_file); 
25907       return mp_fatal_error_stop;
25908     }
25909     (mp->close_file)( mp->mem_file);
25910     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
25911   }
25912   mp->buffer[limit]='%';
25913   mp_fix_date_and_time(mp);
25914   if (mp->random_seed==0)
25915     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
25916   mp_init_randoms(mp, mp->random_seed);
25917   @<Initialize the print |selector|...@>;
25918   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
25919     mp_start_input(mp); /* \&{input} assumed */
25920 }
25921
25922 @ @<Run inimpost commands@>=
25923 {
25924   mp_get_strings_started(mp);
25925   mp_init_tab(mp); /* initialize the tables */
25926   mp_init_prim(mp); /* call |primitive| for each primitive */
25927   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
25928   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
25929   mp_fix_date_and_time(mp);
25930 }
25931
25932
25933 @* \[47] Debugging.
25934 Once \MP\ is working, you should be able to diagnose most errors with
25935 the \.{show} commands and other diagnostic features. But for the initial
25936 stages of debugging, and for the revelation of really deep mysteries, you
25937 can compile \MP\ with a few more aids. An additional routine called |debug_help|
25938 will also come into play when you type `\.D' after an error message;
25939 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
25940 @^debugging@>
25941 @^system dependencies@>
25942
25943 The interface to |debug_help| is primitive, but it is good enough when used
25944 with a debugger that allows you to set breakpoints and to read
25945 variables and change their values. After getting the prompt `\.{debug \#}', you
25946 type either a negative number (this exits |debug_help|), or zero (this
25947 goes to a location where you can set a breakpoint, thereby entering into
25948 dialog with the debugger), or a positive number |m| followed by
25949 an argument |n|. The meaning of |m| and |n| will be clear from the
25950 program below. (If |m=13|, there is an additional argument, |l|.)
25951 @.debug \#@>
25952
25953 @<Last-minute...@>=
25954 void mp_debug_help (MP mp) { /* routine to display various things */
25955   integer k;
25956   int l,m,n;
25957   char *aline;
25958   size_t len;
25959   while (1) { 
25960     wake_up_terminal;
25961     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
25962 @.debug \#@>
25963     m = 0;
25964     aline = (mp->read_ascii_file)(mp->term_in, &len);
25965     if (len) { sscanf(aline,"%i",&m); xfree(aline); }
25966     if ( m<=0 )
25967       return;
25968     n = 0 ;
25969     aline = (mp->read_ascii_file)(mp->term_in, &len);
25970     if (len) { sscanf(aline,"%i",&n); xfree(aline); }
25971     switch (m) {
25972     @<Numbered cases for |debug_help|@>;
25973     default: mp_print(mp, "?"); break;
25974     }
25975   }
25976 }
25977
25978 @ @<Numbered cases...@>=
25979 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
25980   break;
25981 case 2: mp_print_int(mp, info(n));
25982   break;
25983 case 3: mp_print_int(mp, link(n));
25984   break;
25985 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
25986   break;
25987 case 5: mp_print_variable_name(mp, n);
25988   break;
25989 case 6: mp_print_int(mp, mp->internal[n]);
25990   break;
25991 case 7: mp_do_show_dependencies(mp);
25992   break;
25993 case 9: mp_show_token_list(mp, n,null,100000,0);
25994   break;
25995 case 10: mp_print_str(mp, n);
25996   break;
25997 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
25998   break;
25999 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26000   break;
26001 case 13: 
26002   l = 0;  
26003   aline = (mp->read_ascii_file)(mp->term_in, &len);
26004   if (len) { sscanf(aline,"%i",&l); xfree(aline); }
26005   mp_print_cmd_mod(mp, n,l); 
26006   break;
26007 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26008   break;
26009 case 15: mp->panicking=! mp->panicking;
26010   break;
26011
26012
26013 @ Saving the filename template
26014
26015 @<Save the filename template@>=
26016
26017   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26018   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26019   else { 
26020     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26021   }
26022 }
26023
26024 @* \[48] System-dependent changes.
26025 This section should be replaced, if necessary, by any special
26026 modification of the program
26027 that are necessary to make \MP\ work at a particular installation.
26028 It is usually best to design your change file so that all changes to
26029 previous sections preserve the section numbering; then everybody's version
26030 will be consistent with the published program. More extensive changes,
26031 which introduce new sections, can be inserted here; then only the index
26032 itself will get a new section number.
26033 @^system dependencies@>
26034
26035 @* \[49] Index.
26036 Here is where you can find all uses of each identifier in the program,
26037 with underlined entries pointing to where the identifier was defined.
26038 If the identifier is only one letter long, however, you get to see only
26039 the underlined entries. {\sl All references are to section numbers instead of
26040 page numbers.}
26041
26042 This index also lists error messages and other aspects of the program
26043 that you might want to look up some day. For example, the entry
26044 for ``system dependencies'' lists all sections that should receive
26045 special attention from people who are installing \MP\ in a new
26046 operating environment. A list of various things that can't happen appears
26047 under ``this can't happen''.
26048 Approximately 25 sections are listed under ``inner loop''; these account
26049 for more than 60\pct! of \MP's running time, exclusive of input and output.