support -Wwrite-strings and some other cleanup
[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.003" /* printed when \MP\ starts */
77 @d metapost_version "1.003"
78 @d mplib_version "0.30"
79 @d version_string " (Cweb version 0.30)"
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 = malloc(1*sizeof(MP_instance));
173   if (mp==NULL)
174         return mp;
175   @<Set |ini_version|@>;
176   @<Setup the non-local jump buffer in |mp_new|@>;
177   @<Allocate or initialize variables@>
178   if (opt->main_memory>mp->mem_max)
179     mp_reallocate_memory(mp,opt->main_memory);
180   mp_reallocate_paths(mp,1000);
181   mp_reallocate_fonts(mp,8);
182   return mp;
183 }
184
185 @ @c
186 void mp_free (MP mp) {
187   int k; /* loop variable */
188   @<Dealloc variables@>
189   xfree(mp);
190 }
191
192 @ @c
193 void  __attribute__((noinline))
194 mp_do_initialize ( MP mp) {
195   @<Local variables for initialization@>
196   @<Set initial values of key variables@>
197 }
198 int mp_initialize (MP mp) { /* this procedure gets things started properly */
199   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
200   @<Install and test the non-local jump buffer@>;
201   t_open_out; /* open the terminal for output */
202   @<Check the ``constant'' values...@>;
203   if ( mp->bad>0 ) {
204         char ss[256];
205     snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
206                    "---case %i",(int)mp->bad);
207     do_fprintf(mp->err_out,(char *)ss);
208 @.Ouch...clobbered@>
209     return mp->history;
210   }
211   mp_do_initialize(mp); /* erase preloaded mem */
212   if (mp->ini_version) {
213     @<Run inimpost commands@>;
214   }
215   @<Initialize the output routines@>;
216   @<Get the first line of input and prepare to start@>;
217   mp_set_job_id(mp);
218   mp_init_map_file(mp, mp->troff_mode);
219   mp->history=mp_spotless; /* ready to go! */
220   if (mp->troff_mode) {
221     mp->internal[mp_gtroffmode]=unity; 
222     mp->internal[mp_prologues]=unity; 
223   }
224   if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
225     mp->cur_sym=mp->start_sym; mp_back_input(mp);
226   }
227   return mp->history;
228 }
229
230
231 @<Exported function headers@>=
232 extern struct MP_options *mp_options (void);
233 extern MP mp_new (struct MP_options *opt) ;
234 extern void mp_free (MP mp);
235 extern int mp_initialize (MP mp);
236
237 @ The overall \MP\ program begins with the heading just shown, after which
238 comes a bunch of procedure declarations and function declarations.
239 Finally we will get to the main program, which begins with the
240 comment `|start_here|'. If you want to skip down to the
241 main program now, you can look up `|start_here|' in the index.
242 But the author suggests that the best way to understand this program
243 is to follow pretty much the order of \MP's components as they appear in the
244 \.{WEB} description you are now reading, since the present ordering is
245 intended to combine the advantages of the ``bottom up'' and ``top down''
246 approaches to the problem of understanding a somewhat complicated system.
247
248 @ Some of the code below is intended to be used only when diagnosing the
249 strange behavior that sometimes occurs when \MP\ is being installed or
250 when system wizards are fooling around with \MP\ without quite knowing
251 what they are doing. Such code will not normally be compiled; it is
252 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
253
254 @ This program has two important variations: (1) There is a long and slow
255 version called \.{INIMP}, which does the extra calculations needed to
256 @.INIMP@>
257 initialize \MP's internal tables; and (2)~there is a shorter and faster
258 production version, which cuts the initialization to a bare minimum.
259
260 Which is which is decided at runtime.
261
262 @ The following parameters can be changed at compile time to extend or
263 reduce \MP's capacity. They may have different values in \.{INIMP} and
264 in production versions of \MP.
265 @.INIMP@>
266 @^system dependencies@>
267
268 @<Constants...@>=
269 #define file_name_size 255 /* file names shouldn't be longer than this */
270 #define bistack_size 1500 /* size of stack for bisection algorithms;
271   should probably be left at this value */
272
273 @ Like the preceding parameters, the following quantities can be changed
274 at compile time to extend or reduce \MP's capacity. But if they are changed,
275 it is necessary to rerun the initialization program \.{INIMP}
276 @.INIMP@>
277 to generate new tables for the production \MP\ program.
278 One can't simply make helter-skelter changes to the following constants,
279 since certain rather complex initialization
280 numbers are computed from them. 
281
282 @ @<Glob...@>=
283 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
284 int pool_size; /* maximum number of characters in strings, including all
285   error messages and help texts, and the names of all identifiers */
286 int mem_max; /* greatest index in \MP's internal |mem| array;
287   must be strictly less than |max_halfword|;
288   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
289 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
290   must not be greater than |mem_max| */
291
292 @ @<Option variables@>=
293 int error_line; /* width of context lines on terminal error messages */
294 int half_error_line; /* width of first lines of contexts in terminal
295   error messages; should be between 30 and |error_line-15| */
296 int max_print_line; /* width of longest text lines output; should be at least 60 */
297 int hash_size; /* maximum number of symbolic tokens,
298   must be less than |max_halfword-3*param_size| */
299 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
300 int param_size; /* maximum number of simultaneous macro parameters */
301 int max_in_open; /* maximum number of input files and error insertions that
302   can be going on simultaneously */
303 int main_memory; /* only for options, to set up |mem_max| and |mem_top| */
304 void *userdata; /* this allows the calling application to setup local */
305
306
307 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
308
309 @<Allocate or ...@>=
310 mp->max_strings=500;
311 mp->pool_size=10000;
312 set_value(mp->error_line,opt->error_line,79);
313 set_value(mp->half_error_line,opt->half_error_line,50);
314 set_value(mp->max_print_line,opt->max_print_line,100);
315 mp->main_memory=5000;
316 mp->mem_max=5000;
317 mp->mem_top=5000;
318 set_value(mp->hash_size,opt->hash_size,9500);
319 set_value(mp->hash_prime,opt->hash_prime,7919);
320 set_value(mp->param_size,opt->param_size,150);
321 set_value(mp->max_in_open,opt->max_in_open,10);
322 mp->userdata=opt->userdata;
323
324 @ In case somebody has inadvertently made bad settings of the ``constants,''
325 \MP\ checks them using a global variable called |bad|.
326
327 This is the first of many sections of \MP\ where global variables are
328 defined.
329
330 @<Glob...@>=
331 integer bad; /* is some ``constant'' wrong? */
332
333 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
334 or something similar. (We can't do that until |max_halfword| has been defined.)
335
336 @<Check the ``constant'' values for consistency@>=
337 mp->bad=0;
338 if ( (mp->half_error_line<30)||(mp->half_error_line>mp->error_line-15) ) mp->bad=1;
339 if ( mp->max_print_line<60 ) mp->bad=2;
340 if ( mp->mem_top<=1100 ) mp->bad=4;
341 if (mp->hash_prime>mp->hash_size ) mp->bad=5;
342
343 @ Some |goto| labels are used by the following definitions. The label
344 `|restart|' is occasionally used at the very beginning of a procedure; and
345 the label `|reswitch|' is occasionally used just prior to a |case|
346 statement in which some cases change the conditions and we wish to branch
347 to the newly applicable case.  Loops that are set up with the |loop|
348 construction defined below are commonly exited by going to `|done|' or to
349 `|found|' or to `|not_found|', and they are sometimes repeated by going to
350 `|continue|'.  If two or more parts of a subroutine start differently but
351 end up the same, the shared code may be gathered together at
352 `|common_ending|'.
353
354 @ Here are some macros for common programming idioms.
355
356 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
357 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
358 @d negate(A) (A)=-(A) /* change the sign of a variable */
359 @d double(A) (A)=(A)+(A)
360 @d odd(A)   ((A)%2==1)
361 @d chr(A)   (A)
362 @d do_nothing   /* empty statement */
363 @d Return   goto exit /* terminate a procedure call */
364 @f return   nil /* \.{WEB} will henceforth say |return| instead of \\{return} */
365
366 @* \[2] The character set.
367 In order to make \MP\ readily portable to a wide variety of
368 computers, all of its input text is converted to an internal eight-bit
369 code that includes standard ASCII, the ``American Standard Code for
370 Information Interchange.''  This conversion is done immediately when each
371 character is read in. Conversely, characters are converted from ASCII to
372 the user's external representation just before they are output to a
373 text file.
374 @^ASCII code@>
375
376 Such an internal code is relevant to users of \MP\ only with respect to
377 the \&{char} and \&{ASCII} operations, and the comparison of strings.
378
379 @ Characters of text that have been converted to \MP's internal form
380 are said to be of type |ASCII_code|, which is a subrange of the integers.
381
382 @<Types...@>=
383 typedef unsigned char ASCII_code; /* eight-bit numbers */
384
385 @ The present specification of \MP\ has been written under the assumption
386 that the character set contains at least the letters and symbols associated
387 with ASCII codes 040 through 0176; all of these characters are now
388 available on most computer terminals.
389
390 We shall use the name |text_char| to stand for the data type of the characters 
391 that are converted to and from |ASCII_code| when they are input and output. 
392 We shall also assume that |text_char| consists of the elements 
393 |chr(first_text_char)| through |chr(last_text_char)|, inclusive. 
394 The following definitions should be adjusted if necessary.
395 @^system dependencies@>
396
397 @d first_text_char 0 /* ordinal number of the smallest element of |text_char| */
398 @d last_text_char 255 /* ordinal number of the largest element of |text_char| */
399
400 @<Types...@>=
401 typedef unsigned char text_char; /* the data type of characters in text files */
402
403 @ @<Local variables for init...@>=
404 integer i;
405
406 @ The \MP\ processor converts between ASCII code and
407 the user's external character set by means of arrays |xord| and |xchr|
408 that are analogous to Pascal's |ord| and |chr| functions.
409
410 @d xchr(A) mp->xchr[(A)]
411 @d xord(A) mp->xord[(A)]
412
413 @<Glob...@>=
414 ASCII_code xord[256];  /* specifies conversion of input characters */
415 text_char xchr[256];  /* specifies conversion of output characters */
416
417 @ The core system assumes all 8-bit is acceptable.  If it is not,
418 a change file has to alter the below section.
419 @^system dependencies@>
420
421 Additionally, people with extended character sets can
422 assign codes arbitrarily, giving an |xchr| equivalent to whatever
423 characters the users of \MP\ are allowed to have in their input files.
424 Appropriate changes to \MP's |char_class| table should then be made.
425 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
426 codes, called the |char_class|.) Such changes make portability of programs
427 more difficult, so they should be introduced cautiously if at all.
428 @^character set dependencies@>
429 @^system dependencies@>
430
431 @<Set initial ...@>=
432 for (i=0;i<=0377;i++) { xchr(i)=i; }
433
434 @ The following system-independent code makes the |xord| array contain a
435 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
436 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
437 |j| or more; hence, standard ASCII code numbers will be used instead of
438 codes below 040 in case there is a coincidence.
439
440 @<Set initial ...@>=
441 for (i=first_text_char;i<=last_text_char;i++) { 
442    xord(chr(i))=0177;
443 }
444 for (i=0200;i<=0377;i++) { xord(xchr(i))=i;}
445 for (i=0;i<=0176;i++) { xord(xchr(i))=i;}
446
447 @* \[3] Input and output.
448 The bane of portability is the fact that different operating systems treat
449 input and output quite differently, perhaps because computer scientists
450 have not given sufficient attention to this problem. People have felt somehow
451 that input and output are not part of ``real'' programming. Well, it is true
452 that some kinds of programming are more fun than others. With existing
453 input/output conventions being so diverse and so messy, the only sources of
454 joy in such parts of the code are the rare occasions when one can find a
455 way to make the program a little less bad than it might have been. We have
456 two choices, either to attack I/O now and get it over with, or to postpone
457 I/O until near the end. Neither prospect is very attractive, so let's
458 get it over with.
459
460 The basic operations we need to do are (1)~inputting and outputting of
461 text, to or from a file or the user's terminal; (2)~inputting and
462 outputting of eight-bit bytes, to or from a file; (3)~instructing the
463 operating system to initiate (``open'') or to terminate (``close'') input or
464 output from a specified file; (4)~testing whether the end of an input
465 file has been reached; (5)~display of bits on the user's screen.
466 The bit-display operation will be discussed in a later section; we shall
467 deal here only with more traditional kinds of I/O.
468
469 @ Finding files happens in a slightly roundabout fashion: the \MP\
470 instance object contains a field that holds a function pointer that finds a
471 file, and returns its name, or NULL. For this, it receives three
472 parameters: the non-qualified name |fname|, the intended |fopen|
473 operation type |fmode|, and the type of the file |ftype|.
474
475 The file types that are passed on in |ftype| can be  used to 
476 differentiate file searches if a library like kpathsea is used,
477 the fopen mode is passed along for the same reason.
478
479 @<Types...@>=
480 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
481
482 @ @<Exported types@>=
483 enum mp_filetype {
484   mp_filetype_terminal = 0, /* the terminal */
485   mp_filetype_error, /* the terminal */
486   mp_filetype_program , /* \MP\ language input */
487   mp_filetype_log,  /* the log file */
488   mp_filetype_postscript, /* the postscript output */
489   mp_filetype_memfile, /* memory dumps */
490   mp_filetype_metrics, /* TeX font metric files */
491   mp_filetype_fontmap, /* PostScript font mapping files */
492   mp_filetype_font, /*  PostScript type1 font programs */
493   mp_filetype_encoding, /*  PostScript font encoding files */
494   mp_filetype_text  /* first text file for readfrom and writeto primitives */
495 };
496 typedef char *(*mp_file_finder)(MP, const char *, const char *, int);
497 typedef void *(*mp_file_opener)(MP, const char *, const char *, int);
498 typedef char *(*mp_file_reader)(MP, void *, size_t *);
499 typedef void (*mp_binfile_reader)(MP, void *, void **, size_t *);
500 typedef void (*mp_file_closer)(MP, void *);
501 typedef int (*mp_file_eoftest)(MP, void *);
502 typedef void (*mp_file_flush)(MP, void *);
503 typedef void (*mp_file_writer)(MP, void *, const char *);
504 typedef void (*mp_binfile_writer)(MP, void *, void *, size_t);
505 #define NOTTESTING 1
506
507 @ @<Option variables@>=
508 mp_file_finder find_file;
509 mp_file_opener open_file;
510 mp_file_reader read_ascii_file;
511 mp_binfile_reader read_binary_file;
512 mp_file_closer close_file;
513 mp_file_eoftest eof_file;
514 mp_file_flush flush_file;
515 mp_file_writer write_ascii_file;
516 mp_binfile_writer write_binary_file;
517
518 @ The default function for finding files is |mp_find_file|. It is 
519 pretty stupid: it will only find files in the current directory.
520
521 This function may disappear altogether, it is currently only
522 used for the default font map file.
523
524 @c
525 char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype)  {
526   (void) mp;
527   if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {  
528      return strdup(fname);
529   }
530   return NULL;
531 }
532
533 @ This has to be done very early on, so it is best to put it in with
534 the |mp_new| allocations
535
536 @d set_callback_option(A) do { mp->A = mp_##A;
537   if (opt->A!=NULL) mp->A = opt->A;
538 } while (0)
539
540 @<Allocate or initialize ...@>=
541 set_callback_option(find_file);
542 set_callback_option(open_file);
543 set_callback_option(read_ascii_file);
544 set_callback_option(read_binary_file);
545 set_callback_option(close_file);
546 set_callback_option(eof_file);
547 set_callback_option(flush_file);
548 set_callback_option(write_ascii_file);
549 set_callback_option(write_binary_file);
550
551 @ Because |mp_find_file| is used so early, it has to be in the helpers
552 section.
553
554 @<Internal ...@>=
555 char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype) ;
556 void *mp_open_file (MP mp , const char *fname, const char *fmode, int ftype) ;
557 char *mp_read_ascii_file (MP mp, void *f, size_t *size) ;
558 void mp_read_binary_file (MP mp, void *f, void **d, size_t *size) ;
559 void mp_close_file (MP mp, void *f) ;
560 int mp_eof_file (MP mp, void *f) ;
561 void mp_flush_file (MP mp, void *f) ;
562 void mp_write_ascii_file (MP mp, void *f, const char *s) ;
563 void mp_write_binary_file (MP mp, void *f, void *s, size_t t) ;
564
565 @ The function to open files can now be very short.
566
567 @c
568 void *mp_open_file(MP mp, const char *fname, const char *fmode, int ftype)  {
569   char realmode[3];
570   (void) mp;
571   realmode[0] = *fmode;
572   realmode[1] = 'b';
573   realmode[2] = 0;
574 #if NOTTESTING
575   if (ftype==mp_filetype_terminal) {
576     return (fmode[0] == 'r' ? stdin : stdout);
577   } else if (ftype==mp_filetype_error) {
578     return stderr;
579   } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
580     return (void *)fopen(fname, realmode);
581   }
582 #endif
583   return NULL;
584 }
585
586 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
587
588 @<Glob...@>=
589 char name_of_file[file_name_size+1]; /* the name of a system file */
590 int name_length;/* this many characters are actually
591   relevant in |name_of_file| (the rest are blank) */
592
593 @ @<Option variables@>=
594 int print_found_names; /* configuration parameter */
595
596 @ If this parameter is true, the terminal and log will report the found
597 file names for input files instead of the requested ones. 
598 It is off by default because it creates an extra filename lookup.
599
600 @<Allocate or initialize ...@>=
601 mp->print_found_names = (opt->print_found_names>0 ? true : false);
602
603 @ \MP's file-opening procedures return |false| if no file identified by
604 |name_of_file| could be opened.
605
606 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
607 It is not used for opening a mem file for read, because that file name 
608 is never printed.
609
610 @d OPEN_FILE(A) do {
611   if (mp->print_found_names) {
612     char *s = (mp->find_file)(mp,mp->name_of_file,A,ftype);
613     if (s!=NULL) {
614       *f = (mp->open_file)(mp,mp->name_of_file,A, ftype); 
615       strncpy(mp->name_of_file,s,file_name_size);
616       xfree(s);
617     } else {
618       *f = NULL;
619     }
620   } else {
621     *f = (mp->open_file)(mp,mp->name_of_file,A, ftype); 
622   }
623 } while (0);
624 return (*f ? true : false)
625
626 @c 
627 boolean mp_a_open_in (MP mp, void **f, int ftype) {
628   /* open a text file for input */
629   OPEN_FILE("r");
630 }
631 @#
632 boolean mp_w_open_in (MP mp, void **f) {
633   /* open a word file for input */
634   *f = (mp->open_file)(mp,mp->name_of_file,"r",mp_filetype_memfile); 
635   return (*f ? true : false);
636 }
637 @#
638 boolean mp_a_open_out (MP mp, void **f, int ftype) {
639   /* open a text file for output */
640   OPEN_FILE("w");
641 }
642 @#
643 boolean mp_b_open_out (MP mp, void **f, int ftype) {
644   /* open a binary file for output */
645   OPEN_FILE("w");
646 }
647 @#
648 boolean mp_w_open_out (MP mp, void **f) {
649   /* open a word file for output */
650   int ftype = mp_filetype_memfile;
651   OPEN_FILE("w");
652 }
653
654 @ @c
655 char *mp_read_ascii_file (MP mp, void *ff, size_t *size) {
656   int c;
657   size_t len = 0, lim = 128;
658   char *s = NULL;
659   FILE *f = (FILE *)ff;
660   *size = 0;
661   (void) mp; /* for -Wunused */
662 #if NOTTESTING
663   c = fgetc(f);
664   if (c==EOF)
665     return NULL;
666   s = malloc(lim); 
667   if (s==NULL) return NULL;
668   while (c!=EOF && c!='\n' && c!='\r') { 
669     if (len==lim) {
670       s =realloc(s, (lim+(lim>>2)));
671       if (s==NULL) return NULL;
672       lim+=(lim>>2);
673     }
674         s[len++] = c;
675     c =fgetc(f);
676   }
677   if (c=='\r') {
678     c = fgetc(f);
679     if (c!=EOF && c!='\n')
680        ungetc(c,f);
681   }
682   s[len] = 0;
683   *size = len;
684 #endif
685   return s;
686 }
687
688 @ @c
689 void mp_write_ascii_file (MP mp, void *f, const char *s) {
690   (void) mp;
691 #if NOTTESTING
692   if (f!=NULL) {
693     fputs(s,(FILE *)f);
694   }
695 #endif
696 }
697
698 @ @c
699 void mp_read_binary_file (MP mp, void *f, void **data, size_t *size) {
700   size_t len = 0;
701   (void) mp;
702 #if NOTTESTING
703   len = fread(*data,1,*size,(FILE *)f);
704 #endif
705   *size = len;
706 }
707
708 @ @c
709 void mp_write_binary_file (MP mp, void *f, void *s, size_t size) {
710   (void) mp;
711 #if NOTTESTING
712   if (f!=NULL)
713     fwrite(s,size,1,(FILE *)f);
714 #endif
715 }
716
717
718 @ @c
719 void mp_close_file (MP mp, void *f) {
720   (void) mp;
721 #if NOTTESTING
722   fclose((FILE *)f);
723 #endif
724 }
725
726 @ @c
727 int mp_eof_file (MP mp, void *f) {
728   (void) mp;
729 #if NOTTESTING
730   return feof((FILE *)f);
731 #else
732   return 0;
733 #endif
734 }
735
736 @ @c
737 void mp_flush_file (MP mp, void *f) {
738   (void) mp;
739 #if NOTTESTING
740   fflush((FILE *)f);
741 #endif
742 }
743
744 @ Input from text files is read one line at a time, using a routine called
745 |input_ln|. This function is defined in terms of global variables called
746 |buffer|, |first|, and |last| that will be described in detail later; for
747 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
748 values, and that |first| and |last| are indices into this array
749 representing the beginning and ending of a line of text.
750
751 @<Glob...@>=
752 size_t buf_size; /* maximum number of characters simultaneously present in
753                     current lines of open files */
754 ASCII_code *buffer; /* lines of characters being read */
755 size_t first; /* the first unused position in |buffer| */
756 size_t last; /* end of the line just input to |buffer| */
757 size_t max_buf_stack; /* largest index used in |buffer| */
758
759 @ @<Allocate or initialize ...@>=
760 mp->buf_size = 200;
761 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
762
763 @ @<Dealloc variables@>=
764 xfree(mp->buffer);
765
766 @ @c
767 void mp_reallocate_buffer(MP mp, size_t l) {
768   ASCII_code *buffer;
769   if (l>max_halfword) {
770     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
771   }
772   buffer = xmalloc((l+1),sizeof(ASCII_code));
773   memcpy(buffer,mp->buffer,(mp->buf_size+1));
774   xfree(mp->buffer);
775   mp->buffer = buffer ;
776   mp->buf_size = l;
777 }
778
779 @ The |input_ln| function brings the next line of input from the specified
780 field into available positions of the buffer array and returns the value
781 |true|, unless the file has already been entirely read, in which case it
782 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
783 numbers that represent the next line of the file are input into
784 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
785 global variable |last| is set equal to |first| plus the length of the
786 line. Trailing blanks are removed from the line; thus, either |last=first|
787 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
788 @^inner loop@>
789
790 The variable |max_buf_stack|, which is used to keep track of how large
791 the |buf_size| parameter must be to accommodate the present job, is
792 also kept up to date by |input_ln|.
793
794 @c 
795 boolean mp_input_ln (MP mp, void *f ) {
796   /* inputs the next line or returns |false| */
797   char *s;
798   size_t size = 0; 
799   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
800   s = (mp->read_ascii_file)(mp,f, &size);
801   if (s==NULL)
802         return false;
803   if (size>0) {
804     mp->last = mp->first+size;
805     if ( mp->last>=mp->max_buf_stack ) { 
806       mp->max_buf_stack=mp->last+1;
807       while ( mp->max_buf_stack>=mp->buf_size ) {
808         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
809       }
810     }
811     memcpy((mp->buffer+mp->first),s,size);
812     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
813   } 
814   free(s);
815   return true;
816 }
817
818 @ The user's terminal acts essentially like other files of text, except
819 that it is used both for input and for output. When the terminal is
820 considered an input file, the file variable is called |term_in|, and when it
821 is considered an output file the file variable is |term_out|.
822 @^system dependencies@>
823
824 @<Glob...@>=
825 void * term_in; /* the terminal as an input file */
826 void * term_out; /* the terminal as an output file */
827 void * err_out; /* the terminal as an output file */
828
829 @ Here is how to open the terminal files. In the default configuration,
830 nothing happens except that the command line (if there is one) is copied
831 to the input buffer.  The variable |command_line| will be filled by the 
832 |main| procedure. The copying can not be done earlier in the program 
833 logic because in the |INI| version, the |buffer| is also used for primitive 
834 initialization.
835
836 @^system dependencies@>
837
838 @d t_open_out  do {/* open the terminal for text output */
839     mp->term_out = (mp->open_file)(mp,"terminal", "w", mp_filetype_terminal);
840     mp->err_out = (mp->open_file)(mp,"error", "w", mp_filetype_error);
841 } while (0)
842 @d t_open_in  do { /* open the terminal for text input */
843     mp->term_in = (mp->open_file)(mp,"terminal", "r", mp_filetype_terminal);
844     if (mp->command_line!=NULL) {
845       mp->last = strlen(mp->command_line);
846       strncpy((char *)mp->buffer,mp->command_line,mp->last);
847       xfree(mp->command_line);
848     } else {
849           mp->last = 0;
850     }
851 } while (0)
852
853 @d t_close_out do { /* close the terminal */
854   (mp->close_file)(mp,mp->term_out);
855   (mp->close_file)(mp,mp->err_out);
856 } while (0)
857
858 @d t_close_in do { /* close the terminal */
859   (mp->close_file)(mp,mp->term_in);
860 } while (0)
861
862 @<Option variables@>=
863 char *command_line;
864
865 @ @<Allocate or initialize ...@>=
866 mp->command_line = xstrdup(opt->command_line);
867
868 @ Sometimes it is necessary to synchronize the input/output mixture that
869 happens on the user's terminal, and three system-dependent
870 procedures are used for this
871 purpose. The first of these, |update_terminal|, is called when we want
872 to make sure that everything we have output to the terminal so far has
873 actually left the computer's internal buffers and been sent.
874 The second, |clear_terminal|, is called when we wish to cancel any
875 input that the user may have typed ahead (since we are about to
876 issue an unexpected error message). The third, |wake_up_terminal|,
877 is supposed to revive the terminal if the user has disabled it by
878 some instruction to the operating system.  The following macros show how
879 these operations can be specified:
880 @^system dependencies@>
881
882 @d update_terminal  (mp->flush_file)(mp,mp->term_out) /* empty the terminal output buffer */
883 @d clear_terminal   do_nothing /* clear the terminal input buffer */
884 @d wake_up_terminal (mp->flush_file)(mp,mp->term_out) 
885                     /* cancel the user's cancellation of output */
886
887 @ We need a special routine to read the first line of \MP\ input from
888 the user's terminal. This line is different because it is read before we
889 have opened the transcript file; there is sort of a ``chicken and
890 egg'' problem here. If the user types `\.{input cmr10}' on the first
891 line, or if some macro invoked by that line does such an \.{input},
892 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
893 commands are performed during the first line of terminal input, the transcript
894 file will acquire its default name `\.{mpout.log}'. (The transcript file
895 will not contain error messages generated by the first line before the
896 first \.{input} command.)
897
898 The first line is even more special. It's nice to let the user start
899 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
900 such a case, \MP\ will operate as if the first line of input were
901 `\.{cmr10}', i.e., the first line will consist of the remainder of the
902 command line, after the part that invoked \MP.
903
904 @ Different systems have different ways to get started. But regardless of
905 what conventions are adopted, the routine that initializes the terminal
906 should satisfy the following specifications:
907
908 \yskip\textindent{1)}It should open file |term_in| for input from the
909   terminal. (The file |term_out| will already be open for output to the
910   terminal.)
911
912 \textindent{2)}If the user has given a command line, this line should be
913   considered the first line of terminal input. Otherwise the
914   user should be prompted with `\.{**}', and the first line of input
915   should be whatever is typed in response.
916
917 \textindent{3)}The first line of input, which might or might not be a
918   command line, should appear in locations |first| to |last-1| of the
919   |buffer| array.
920
921 \textindent{4)}The global variable |loc| should be set so that the
922   character to be read next by \MP\ is in |buffer[loc]|. This
923   character should not be blank, and we should have |loc<last|.
924
925 \yskip\noindent(It may be necessary to prompt the user several times
926 before a non-blank line comes in. The prompt is `\.{**}' instead of the
927 later `\.*' because the meaning is slightly different: `\.{input}' need
928 not be typed immediately after~`\.{**}'.)
929
930 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
931
932 @ The following program does the required initialization
933 without retrieving a possible command line.
934 It should be clear how to modify this routine to deal with command lines,
935 if the system permits them.
936 @^system dependencies@>
937
938 @c 
939 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
940   t_open_in; 
941   if (mp->last!=0) {
942     loc = mp->first = 0;
943         return true;
944   }
945   while (1) { 
946     if (!mp->noninteractive) {
947           wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
948 @.**@>
949     }
950     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
951       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
952 @.End of file on the terminal@>
953       return false;
954     }
955     loc=mp->first;
956     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
957       incr(loc);
958     if ( loc<(int)mp->last ) { 
959       return true; /* return unless the line was all blank */
960     }
961     if (!mp->noninteractive) {
962           do_fprintf(mp->term_out,"Please type the name of your input file.\n");
963     }
964   }
965 }
966
967 @ @<Declarations@>=
968 boolean mp_init_terminal (MP mp) ;
969
970
971 @* \[4] String handling.
972 Symbolic token names and diagnostic messages are variable-length strings
973 of eight-bit characters. Many strings \MP\ uses are simply literals
974 in the compiled source, like the error messages and the names of the
975 internal parameters. Other strings are used or defined from the \MP\ input 
976 language, and these have to be interned.
977
978 \MP\ uses strings more extensively than \MF\ does, but the necessary
979 operations can still be handled with a fairly simple data structure.
980 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
981 of the strings, and the array |str_start| contains indices of the starting
982 points of each string. Strings are referred to by integer numbers, so that
983 string number |s| comprises the characters |str_pool[j]| for
984 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
985 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
986 location.  The first string number not currently in use is |str_ptr|
987 and |next_str[str_ptr]| begins a list of free string numbers.  String
988 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
989 string currently being constructed.
990
991 String numbers 0 to 255 are reserved for strings that correspond to single
992 ASCII characters. This is in accordance with the conventions of \.{WEB},
993 @.WEB@>
994 which converts single-character strings into the ASCII code number of the
995 single character involved, while it converts other strings into integers
996 and builds a string pool file. Thus, when the string constant \.{"."} appears
997 in the program below, \.{WEB} converts it into the integer 46, which is the
998 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
999 into some integer greater than~255. String number 46 will presumably be the
1000 single character `\..'\thinspace; but some ASCII codes have no standard visible
1001 representation, and \MP\ may need to be able to print an arbitrary
1002 ASCII character, so the first 256 strings are used to specify exactly what
1003 should be printed for each of the 256 possibilities.
1004
1005 @<Types...@>=
1006 typedef int pool_pointer; /* for variables that point into |str_pool| */
1007 typedef int str_number; /* for variables that point into |str_start| */
1008
1009 @ @<Glob...@>=
1010 ASCII_code *str_pool; /* the characters */
1011 pool_pointer *str_start; /* the starting pointers */
1012 str_number *next_str; /* for linking strings in order */
1013 pool_pointer pool_ptr; /* first unused position in |str_pool| */
1014 str_number str_ptr; /* number of the current string being created */
1015 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
1016 str_number init_str_use; /* the initial number of strings in use */
1017 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
1018 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
1019
1020 @ @<Allocate or initialize ...@>=
1021 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
1022 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1023 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1024
1025 @ @<Dealloc variables@>=
1026 xfree(mp->str_pool);
1027 xfree(mp->str_start);
1028 xfree(mp->next_str);
1029
1030 @ Most printing is done from |char *|s, but sometimes not. Here are
1031 functions that convert an internal string into a |char *| for use
1032 by the printing routines, and vice versa.
1033
1034 @d str(A) mp_str(mp,A)
1035 @d rts(A) mp_rts(mp,A)
1036
1037 @<Internal ...@>=
1038 int mp_xstrcmp (const char *a, const char *b);
1039 char * mp_str (MP mp, str_number s);
1040
1041 @ @<Declarations@>=
1042 str_number mp_rts (MP mp, const char *s);
1043 str_number mp_make_string (MP mp);
1044
1045 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1046 very good: it does not handle nesting over more than one level.
1047
1048 @c 
1049 int mp_xstrcmp (const char *a, const char *b) {
1050         if (a==NULL && b==NULL) 
1051           return 0;
1052     if (a==NULL)
1053       return -1;
1054     if (b==NULL)
1055       return 1;
1056     return strcmp(a,b);
1057 }
1058
1059 @ @c
1060 char * mp_str (MP mp, str_number ss) {
1061   char *s;
1062   int len;
1063   if (ss==mp->str_ptr) {
1064     return NULL;
1065   } else {
1066     len = length(ss);
1067     s = xmalloc(len+1,sizeof(char));
1068     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1069     s[len] = 0;
1070     return (char *)s;
1071   }
1072 }
1073 str_number mp_rts (MP mp, const char *s) {
1074   int r; /* the new string */ 
1075   int old; /* a possible string in progress */
1076   int i=0;
1077   if (strlen(s)==0) {
1078     return 256;
1079   } else if (strlen(s)==1) {
1080     return s[0];
1081   } else {
1082    old=0;
1083    str_room((integer)strlen(s));
1084    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1085      old = mp_make_string(mp);
1086    while (*s) {
1087      append_char(*s);
1088      s++;
1089    }
1090    r = mp_make_string(mp);
1091    if (old!=0) {
1092       str_room(length(old));
1093       while (i<length(old)) {
1094         append_char((mp->str_start[old]+i));
1095       } 
1096       mp_flush_string(mp,old);
1097     }
1098     return r;
1099   }
1100 }
1101
1102 @ Except for |strs_used_up|, the following string statistics are only
1103 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1104 commented out:
1105
1106 @<Glob...@>=
1107 integer strs_used_up; /* strings in use or unused but not reclaimed */
1108 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1109 integer strs_in_use; /* total number of strings actually in use */
1110 integer max_pl_used; /* maximum |pool_in_use| so far */
1111 integer max_strs_used; /* maximum |strs_in_use| so far */
1112
1113 @ Several of the elementary string operations are performed using \.{WEB}
1114 macros instead of functions, because many of the
1115 operations are done quite frequently and we want to avoid the
1116 overhead of procedure calls. For example, here is
1117 a simple macro that computes the length of a string.
1118 @.WEB@>
1119
1120 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string
1121   number \# */
1122 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1123
1124 @ The length of the current string is called |cur_length|.  If we decide that
1125 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1126 |cur_length| becomes zero.
1127
1128 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1129 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1130
1131 @ Strings are created by appending character codes to |str_pool|.
1132 The |append_char| macro, defined here, does not check to see if the
1133 value of |pool_ptr| has gotten too high; this test is supposed to be
1134 made before |append_char| is used.
1135
1136 To test if there is room to append |l| more characters to |str_pool|,
1137 we shall write |str_room(l)|, which tries to make sure there is enough room
1138 by compacting the string pool if necessary.  If this does not work,
1139 |do_compaction| aborts \MP\ and gives an apologetic error message.
1140
1141 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1142 { mp->str_pool[mp->pool_ptr]=(A); incr(mp->pool_ptr);
1143 }
1144 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1145   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1146     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1147     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1148   }
1149
1150 @ The following routine is similar to |str_room(1)| but it uses the
1151 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1152 string space is exhausted.
1153
1154 @<Declare the procedure called |unit_str_room|@>=
1155 void mp_unit_str_room (MP mp);
1156
1157 @ @c
1158 void mp_unit_str_room (MP mp) { 
1159   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1160   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1161 }
1162
1163 @ \MP's string expressions are implemented in a brute-force way: Every
1164 new string or substring that is needed is simply copied into the string pool.
1165 Space is eventually reclaimed by a procedure called |do_compaction| with
1166 the aid of a simple system system of reference counts.
1167 @^reference counts@>
1168
1169 The number of references to string number |s| will be |str_ref[s]|. The
1170 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1171 positive number of references; such strings will never be recycled. If
1172 a string is ever referred to more than 126 times, simultaneously, we
1173 put it in this category. Hence a single byte suffices to store each |str_ref|.
1174
1175 @d max_str_ref 127 /* ``infinite'' number of references */
1176 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]);
1177   }
1178
1179 @<Glob...@>=
1180 int *str_ref;
1181
1182 @ @<Allocate or initialize ...@>=
1183 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1184
1185 @ @<Dealloc variables@>=
1186 xfree(mp->str_ref);
1187
1188 @ Here's what we do when a string reference disappears:
1189
1190 @d delete_str_ref(A)  { 
1191     if ( mp->str_ref[(A)]<max_str_ref ) {
1192        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1193        else mp_flush_string(mp, (A));
1194     }
1195   }
1196
1197 @<Declare the procedure called |flush_string|@>=
1198 void mp_flush_string (MP mp,str_number s) ;
1199
1200
1201 @ We can't flush the first set of static strings at all, so there 
1202 is no point in trying
1203
1204 @c
1205 void mp_flush_string (MP mp,str_number s) { 
1206   if (length(s)>1) {
1207     mp->pool_in_use=mp->pool_in_use-length(s);
1208     decr(mp->strs_in_use);
1209     if ( mp->next_str[s]!=mp->str_ptr ) {
1210       mp->str_ref[s]=0;
1211     } else { 
1212       mp->str_ptr=s;
1213       decr(mp->strs_used_up);
1214     }
1215     mp->pool_ptr=mp->str_start[mp->str_ptr];
1216   }
1217 }
1218
1219 @ C literals cannot be simply added, they need to be set so they can't
1220 be flushed.
1221
1222 @d intern(A) mp_intern(mp,(A))
1223
1224 @c
1225 str_number mp_intern (MP mp, const char *s) {
1226   str_number r ;
1227   r = rts(s);
1228   mp->str_ref[r] = max_str_ref;
1229   return r;
1230 }
1231
1232 @ @<Declarations@>=
1233 str_number mp_intern (MP mp, const char *s);
1234
1235
1236 @ Once a sequence of characters has been appended to |str_pool|, it
1237 officially becomes a string when the function |make_string| is called.
1238 This function returns the identification number of the new string as its
1239 value.
1240
1241 When getting the next unused string number from the linked list, we pretend
1242 that
1243 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1244 are linked sequentially even though the |next_str| entries have not been
1245 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1246 |do_compaction| is responsible for making sure of this.
1247
1248 @<Declarations@>=
1249 @<Declare the procedure called |do_compaction|@>
1250 @<Declare the procedure called |unit_str_room|@>
1251 str_number mp_make_string (MP mp);
1252
1253 @ @c 
1254 str_number mp_make_string (MP mp) { /* current string enters the pool */
1255   str_number s; /* the new string */
1256 RESTART: 
1257   s=mp->str_ptr;
1258   mp->str_ptr=mp->next_str[s];
1259   if ( mp->str_ptr>mp->max_str_ptr ) {
1260     if ( mp->str_ptr==mp->max_strings ) { 
1261       mp->str_ptr=s;
1262       mp_do_compaction(mp, 0);
1263       goto RESTART;
1264     } else {
1265 #ifdef DEBUG 
1266       if ( mp->strs_used_up!=mp->max_str_ptr ) mp_confusion(mp, "s");
1267 @:this can't happen s}{\quad \.s@>
1268 #endif
1269       mp->max_str_ptr=mp->str_ptr;
1270       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1271     }
1272   }
1273   mp->str_ref[s]=1;
1274   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1275   incr(mp->strs_used_up);
1276   incr(mp->strs_in_use);
1277   mp->pool_in_use=mp->pool_in_use+length(s);
1278   if ( mp->pool_in_use>mp->max_pl_used ) 
1279     mp->max_pl_used=mp->pool_in_use;
1280   if ( mp->strs_in_use>mp->max_strs_used ) 
1281     mp->max_strs_used=mp->strs_in_use;
1282   return s;
1283 }
1284
1285 @ The most interesting string operation is string pool compaction.  The idea
1286 is to recover unused space in the |str_pool| array by recopying the strings
1287 to close the gaps created when some strings become unused.  All string
1288 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1289 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1290 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1291 with |needed=mp->pool_size| supresses all overflow tests.
1292
1293 The compaction process starts with |last_fixed_str| because all lower numbered
1294 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1295
1296 @<Glob...@>=
1297 str_number last_fixed_str; /* last permanently allocated string */
1298 str_number fixed_str_use; /* number of permanently allocated strings */
1299
1300 @ @<Declare the procedure called |do_compaction|@>=
1301 void mp_do_compaction (MP mp, pool_pointer needed) ;
1302
1303 @ @c
1304 void mp_do_compaction (MP mp, pool_pointer needed) {
1305   str_number str_use; /* a count of strings in use */
1306   str_number r,s,t; /* strings being manipulated */
1307   pool_pointer p,q; /* destination and source for copying string characters */
1308   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1309   r=mp->last_fixed_str;
1310   s=mp->next_str[r];
1311   p=mp->str_start[s];
1312   while ( s!=mp->str_ptr ) { 
1313     while ( mp->str_ref[s]==0 ) {
1314       @<Advance |s| and add the old |s| to the list of free string numbers;
1315         then |break| if |s=str_ptr|@>;
1316     }
1317     r=s; s=mp->next_str[s];
1318     incr(str_use);
1319     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1320      after the end of the string@>;
1321   }
1322   @<Move the current string back so that it starts at |p|@>;
1323   if ( needed<mp->pool_size ) {
1324     @<Make sure that there is room for another string with |needed| characters@>;
1325   }
1326   @<Account for the compaction and make sure the statistics agree with the
1327      global versions@>;
1328   mp->strs_used_up=str_use;
1329 }
1330
1331 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1332 t=mp->next_str[mp->last_fixed_str];
1333 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1334   incr(mp->fixed_str_use);
1335   mp->last_fixed_str=t;
1336   t=mp->next_str[t];
1337 }
1338 str_use=mp->fixed_str_use
1339
1340 @ Because of the way |flush_string| has been written, it should never be
1341 necessary to |break| here.  The extra line of code seems worthwhile to
1342 preserve the generality of |do_compaction|.
1343
1344 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1345 {
1346 t=s;
1347 s=mp->next_str[s];
1348 mp->next_str[r]=s;
1349 mp->next_str[t]=mp->next_str[mp->str_ptr];
1350 mp->next_str[mp->str_ptr]=t;
1351 if ( s==mp->str_ptr ) break;
1352 }
1353
1354 @ The string currently starts at |str_start[r]| and ends just before
1355 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1356 to locate the next string.
1357
1358 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1359 q=mp->str_start[r];
1360 mp->str_start[r]=p;
1361 while ( q<mp->str_start[s] ) { 
1362   mp->str_pool[p]=mp->str_pool[q];
1363   incr(p); incr(q);
1364 }
1365
1366 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1367 we do this, anything between them should be moved.
1368
1369 @ @<Move the current string back so that it starts at |p|@>=
1370 q=mp->str_start[mp->str_ptr];
1371 mp->str_start[mp->str_ptr]=p;
1372 while ( q<mp->pool_ptr ) { 
1373   mp->str_pool[p]=mp->str_pool[q];
1374   incr(p); incr(q);
1375 }
1376 mp->pool_ptr=p
1377
1378 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1379
1380 @<Make sure that there is room for another string with |needed| char...@>=
1381 if ( str_use>=mp->max_strings-1 )
1382   mp_reallocate_strings (mp,str_use);
1383 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1384   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1385   mp->max_pool_ptr=mp->pool_ptr+needed;
1386 }
1387
1388 @ @<Declarations@>=
1389 void mp_reallocate_strings (MP mp, str_number str_use) ;
1390 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1391
1392 @ @c 
1393 void mp_reallocate_strings (MP mp, str_number str_use) { 
1394   while ( str_use>=mp->max_strings-1 ) {
1395     int l = mp->max_strings + (mp->max_strings>>2);
1396     XREALLOC (mp->str_ref,   l, int);
1397     XREALLOC (mp->str_start, l, pool_pointer);
1398     XREALLOC (mp->next_str,  l, str_number);
1399     mp->max_strings = l;
1400   }
1401 }
1402 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1403   while ( needed>mp->pool_size ) {
1404     int l = mp->pool_size + (mp->pool_size>>2);
1405         XREALLOC (mp->str_pool, l, ASCII_code);
1406     mp->pool_size = l;
1407   }
1408 }
1409
1410 @ @<Account for the compaction and make sure the statistics agree with...@>=
1411 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1412   mp_confusion(mp, "string");
1413 @:this can't happen string}{\quad string@>
1414 incr(mp->pact_count);
1415 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1416 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1417 #ifdef DEBUG
1418 s=mp->str_ptr; t=str_use;
1419 while ( s<=mp->max_str_ptr ){
1420   if ( t>mp->max_str_ptr ) mp_confusion(mp, "\"");
1421   incr(t); s=mp->next_str[s];
1422 };
1423 if ( t<=mp->max_str_ptr ) mp_confusion(mp, "\"");
1424 #endif
1425
1426 @ A few more global variables are needed to keep track of statistics when
1427 |stat| $\ldots$ |tats| blocks are not commented out.
1428
1429 @<Glob...@>=
1430 integer pact_count; /* number of string pool compactions so far */
1431 integer pact_chars; /* total number of characters moved during compactions */
1432 integer pact_strs; /* total number of strings moved during compactions */
1433
1434 @ @<Initialize compaction statistics@>=
1435 mp->pact_count=0;
1436 mp->pact_chars=0;
1437 mp->pact_strs=0;
1438
1439 @ The following subroutine compares string |s| with another string of the
1440 same length that appears in |buffer| starting at position |k|;
1441 the result is |true| if and only if the strings are equal.
1442
1443 @c 
1444 boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1445   /* test equality of strings */
1446   pool_pointer j; /* running index */
1447   j=mp->str_start[s];
1448   while ( j<str_stop(s) ) { 
1449     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1450       return false;
1451   }
1452   return true;
1453 }
1454
1455 @ Here is a similar routine, but it compares two strings in the string pool,
1456 and it does not assume that they have the same length. If the first string
1457 is lexicographically greater than, less than, or equal to the second,
1458 the result is respectively positive, negative, or zero.
1459
1460 @c 
1461 integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1462   /* test equality of strings */
1463   pool_pointer j,k; /* running indices */
1464   integer ls,lt; /* lengths */
1465   integer l; /* length remaining to test */
1466   ls=length(s); lt=length(t);
1467   if ( ls<=lt ) l=ls; else l=lt;
1468   j=mp->str_start[s]; k=mp->str_start[t];
1469   while ( l-->0 ) { 
1470     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1471        return (mp->str_pool[j]-mp->str_pool[k]); 
1472     }
1473     incr(j); incr(k);
1474   }
1475   return (ls-lt);
1476 }
1477
1478 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1479 and |str_ptr| are computed by the \.{INIMP} program, based in part
1480 on the information that \.{WEB} has output while processing \MP.
1481 @.INIMP@>
1482 @^string pool@>
1483
1484 @c 
1485 void mp_get_strings_started (MP mp) { 
1486   /* initializes the string pool,
1487     but returns |false| if something goes wrong */
1488   int k; /* small indices or counters */
1489   str_number g; /* a new string */
1490   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1491   mp->str_start[0]=0;
1492   mp->next_str[0]=1;
1493   mp->pool_in_use=0; mp->strs_in_use=0;
1494   mp->max_pl_used=0; mp->max_strs_used=0;
1495   @<Initialize compaction statistics@>;
1496   mp->strs_used_up=0;
1497   @<Make the first 256 strings@>;
1498   g=mp_make_string(mp); /* string 256 == "" */
1499   mp->str_ref[g]=max_str_ref;
1500   mp->last_fixed_str=mp->str_ptr-1;
1501   mp->fixed_str_use=mp->str_ptr;
1502   return;
1503 }
1504
1505 @ @<Declarations@>=
1506 void mp_get_strings_started (MP mp);
1507
1508 @ The first 256 strings will consist of a single character only.
1509
1510 @<Make the first 256...@>=
1511 for (k=0;k<=255;k++) { 
1512   append_char(k);
1513   g=mp_make_string(mp); 
1514   mp->str_ref[g]=max_str_ref;
1515 }
1516
1517 @ The first 128 strings will contain 95 standard ASCII characters, and the
1518 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1519 unless a system-dependent change is made here. Installations that have
1520 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1521 would like string 032 to be printed as the single character 032 instead
1522 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1523 even people with an extended character set will want to represent string
1524 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1525 to produce visible strings instead of tabs or line-feeds or carriage-returns
1526 or bell-rings or characters that are treated anomalously in text files.
1527
1528 Unprintable characters of codes 128--255 are, similarly, rendered
1529 \.{\^\^80}--\.{\^\^ff}.
1530
1531 The boolean expression defined here should be |true| unless \MP\ internal
1532 code number~|k| corresponds to a non-troublesome visible symbol in the
1533 local character set.
1534 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1535 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1536 must be printable.
1537 @^character set dependencies@>
1538 @^system dependencies@>
1539
1540 @<Character |k| cannot be printed@>=
1541   (k<' ')||(k>'~')
1542
1543 @* \[5] On-line and off-line printing.
1544 Messages that are sent to a user's terminal and to the transcript-log file
1545 are produced by several `|print|' procedures. These procedures will
1546 direct their output to a variety of places, based on the setting of
1547 the global variable |selector|, which has the following possible
1548 values:
1549
1550 \yskip
1551 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1552   transcript file.
1553
1554 \hang |log_only|, prints only on the transcript file.
1555
1556 \hang |term_only|, prints only on the terminal.
1557
1558 \hang |no_print|, doesn't print at all. This is used only in rare cases
1559   before the transcript file is open.
1560
1561 \hang |pseudo|, puts output into a cyclic buffer that is used
1562   by the |show_context| routine; when we get to that routine we shall discuss
1563   the reasoning behind this curious mode.
1564
1565 \hang |new_string|, appends the output to the current string in the
1566   string pool.
1567
1568 \hang |>=write_file| prints on one of the files used for the \&{write}
1569 @:write_}{\&{write} primitive@>
1570   command.
1571
1572 \yskip
1573 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1574 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1575 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1576 relations are not used when |selector| could be |pseudo|, or |new_string|.
1577 We need not check for unprintable characters when |selector<pseudo|.
1578
1579 Three additional global variables, |tally|, |term_offset| and |file_offset|
1580 record the number of characters that have been printed
1581 since they were most recently cleared to zero. We use |tally| to record
1582 the length of (possibly very long) stretches of printing; |term_offset|,
1583 and |file_offset|, on the other hand, keep track of how many
1584 characters have appeared so far on the current line that has been output
1585 to the terminal, the transcript file, or the \ps\ output file, respectively.
1586
1587 @d new_string 0 /* printing is deflected to the string pool */
1588 @d pseudo 2 /* special |selector| setting for |show_context| */
1589 @d no_print 3 /* |selector| setting that makes data disappear */
1590 @d term_only 4 /* printing is destined for the terminal only */
1591 @d log_only 5 /* printing is destined for the transcript file only */
1592 @d term_and_log 6 /* normal |selector| setting */
1593 @d write_file 7 /* first write file selector */
1594
1595 @<Glob...@>=
1596 void * log_file; /* transcript of \MP\ session */
1597 void * ps_file; /* the generic font output goes here */
1598 unsigned int selector; /* where to print a message */
1599 unsigned char dig[23]; /* digits in a number being output */
1600 integer tally; /* the number of characters recently printed */
1601 unsigned int term_offset;
1602   /* the number of characters on the current terminal line */
1603 unsigned int file_offset;
1604   /* the number of characters on the current file line */
1605 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1606 integer trick_count; /* threshold for pseudoprinting, explained later */
1607 integer first_count; /* another variable for pseudoprinting */
1608
1609 @ @<Allocate or initialize ...@>=
1610 memset(mp->dig,0,23);
1611 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1612
1613 @ @<Dealloc variables@>=
1614 xfree(mp->trick_buf);
1615
1616 @ @<Initialize the output routines@>=
1617 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1618
1619 @ Macro abbreviations for output to the terminal and to the log file are
1620 defined here for convenience. Some systems need special conventions
1621 for terminal output, and it is possible to adhere to those conventions
1622 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1623 @^system dependencies@>
1624
1625 @d do_fprintf(f,b) (mp->write_ascii_file)(mp,f,b)
1626 @d wterm(A)     do_fprintf(mp->term_out,(A))
1627 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->term_out,(char *)ss); }
1628 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1629 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1630 @d wlog(A)      do_fprintf(mp->log_file,(A))
1631 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]=0; do_fprintf(mp->log_file,(char *)ss); }
1632 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1633 @d wlog_ln(A)   { wlog_cr; do_fprintf(mp->log_file,(A)); }
1634
1635
1636 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1637 use an array |wr_file| that will be declared later.
1638
1639 @d mp_print_text(A) mp_print_str(mp,text((A)))
1640
1641 @<Internal ...@>=
1642 void mp_print_ln (MP mp);
1643 void mp_print_visible_char (MP mp, ASCII_code s); 
1644 void mp_print_char (MP mp, ASCII_code k);
1645 void mp_print (MP mp, const char *s);
1646 void mp_print_str (MP mp, str_number s);
1647 void mp_print_nl (MP mp, const char *s);
1648 void mp_print_two (MP mp,scaled x, scaled y) ;
1649 void mp_print_scaled (MP mp,scaled s);
1650
1651 @ @<Basic print...@>=
1652 void mp_print_ln (MP mp) { /* prints an end-of-line */
1653  switch (mp->selector) {
1654   case term_and_log: 
1655     wterm_cr; wlog_cr;
1656     mp->term_offset=0;  mp->file_offset=0;
1657     break;
1658   case log_only: 
1659     wlog_cr; mp->file_offset=0;
1660     break;
1661   case term_only: 
1662     wterm_cr; mp->term_offset=0;
1663     break;
1664   case no_print:
1665   case pseudo: 
1666   case new_string: 
1667     break;
1668   default: 
1669     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1670   }
1671 } /* note that |tally| is not affected */
1672
1673 @ The |print_visible_char| procedure sends one character to the desired
1674 destination, using the |xchr| array to map it into an external character
1675 compatible with |input_ln|.  (It assumes that it is always called with
1676 a visible ASCII character.)  All printing comes through |print_ln| or
1677 |print_char|, which ultimately calls |print_visible_char|, hence these
1678 routines are the ones that limit lines to at most |max_print_line| characters.
1679 But we must make an exception for the \ps\ output file since it is not safe
1680 to cut up lines arbitrarily in \ps.
1681
1682 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1683 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1684 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1685
1686 @<Basic printing...@>=
1687 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1688   switch (mp->selector) {
1689   case term_and_log: 
1690     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1691     incr(mp->term_offset); incr(mp->file_offset);
1692     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1693        wterm_cr; mp->term_offset=0;
1694     };
1695     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1696        wlog_cr; mp->file_offset=0;
1697     };
1698     break;
1699   case log_only: 
1700     wlog_chr(xchr(s)); incr(mp->file_offset);
1701     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1702     break;
1703   case term_only: 
1704     wterm_chr(xchr(s)); incr(mp->term_offset);
1705     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1706     break;
1707   case no_print: 
1708     break;
1709   case pseudo: 
1710     if ( mp->tally<mp->trick_count ) 
1711       mp->trick_buf[mp->tally % mp->error_line]=s;
1712     break;
1713   case new_string: 
1714     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1715       mp_unit_str_room(mp);
1716       if ( mp->pool_ptr>=mp->pool_size ) 
1717         goto DONE; /* drop characters if string space is full */
1718     };
1719     append_char(s);
1720     break;
1721   default:
1722     { char ss[2]; ss[0] = xchr(s); ss[1]=0;
1723       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1724     }
1725   }
1726 DONE:
1727   incr(mp->tally);
1728 }
1729
1730 @ The |print_char| procedure sends one character to the desired destination.
1731 File names and string expressions might contain |ASCII_code| values that
1732 can't be printed using |print_visible_char|.  These characters will be
1733 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1734 (This procedure assumes that it is safe to bypass all checks for unprintable
1735 characters when |selector| is in the range |0..max_write_files-1|.
1736 The user might want to write unprintable characters.
1737
1738 @d print_lc_hex(A) do { l=(A);
1739     mp_print_visible_char(mp, (l<10 ? l+'0' : l-10+'a'));
1740   } while (0)
1741
1742 @<Basic printing...@>=
1743 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1744   int l; /* small index or counter */
1745   if ( mp->selector<pseudo || mp->selector>=write_file) {
1746     mp_print_visible_char(mp, k);
1747   } else if ( @<Character |k| cannot be printed@> ) { 
1748     mp_print(mp, "^^"); 
1749     if ( k<0100 ) { 
1750       mp_print_visible_char(mp, k+0100); 
1751     } else if ( k<0200 ) { 
1752       mp_print_visible_char(mp, k-0100); 
1753     } else { 
1754       print_lc_hex(k / 16);  
1755       print_lc_hex(k % 16); 
1756     }
1757   } else {
1758     mp_print_visible_char(mp, k);
1759   }
1760 }
1761
1762 @ An entire string is output by calling |print|. Note that if we are outputting
1763 the single standard ASCII character \.c, we could call |print("c")|, since
1764 |"c"=99| is the number of a single-character string, as explained above. But
1765 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1766 routine when it knows that this is safe. (The present implementation
1767 assumes that it is always safe to print a visible ASCII character.)
1768 @^system dependencies@>
1769
1770 @<Basic print...@>=
1771 void mp_do_print (MP mp, const char *ss, unsigned int len) { /* prints string |s| */
1772   unsigned int j = 0;
1773   while ( j<len ){ 
1774     mp_print_char(mp, ss[j]); incr(j);
1775   }
1776 }
1777
1778
1779 @<Basic print...@>=
1780 void mp_print (MP mp, const char *ss) {
1781   mp_do_print(mp, ss, strlen(ss));
1782 }
1783 void mp_print_str (MP mp, str_number s) {
1784   pool_pointer j; /* current character code position */
1785   if ( (s<0)||(s>mp->max_str_ptr) ) {
1786      mp_do_print(mp,"???",3); /* this can't happen */
1787 @.???@>
1788   }
1789   j=mp->str_start[s];
1790   mp_do_print(mp, (char *)(mp->str_pool+j), (str_stop(s)-j));
1791 }
1792
1793
1794 @ Here is the very first thing that \MP\ prints: a headline that identifies
1795 the version number and base name. The |term_offset| variable is temporarily
1796 incorrect, but the discrepancy is not serious since we assume that the banner
1797 and mem identifier together will occupy at most |max_print_line|
1798 character positions.
1799
1800 @<Initialize the output...@>=
1801 wterm (banner);
1802 wterm (version_string);
1803 if (mp->mem_ident!=NULL) 
1804   mp_print(mp,mp->mem_ident); 
1805 mp_print_ln(mp);
1806 update_terminal;
1807
1808 @ The procedure |print_nl| is like |print|, but it makes sure that the
1809 string appears at the beginning of a new line.
1810
1811 @<Basic print...@>=
1812 void mp_print_nl (MP mp, const char *s) { /* prints string |s| at beginning of line */
1813   switch(mp->selector) {
1814   case term_and_log: 
1815     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1816     break;
1817   case log_only: 
1818     if ( mp->file_offset>0 ) mp_print_ln(mp);
1819     break;
1820   case term_only: 
1821     if ( mp->term_offset>0 ) mp_print_ln(mp);
1822     break;
1823   case no_print:
1824   case pseudo:
1825   case new_string: 
1826         break;
1827   } /* there are no other cases */
1828   mp_print(mp, s);
1829 }
1830
1831 @ An array of digits in the range |0..9| is printed by |print_the_digs|.
1832
1833 @<Basic print...@>=
1834 void mp_print_the_digs (MP mp, eight_bits k) {
1835   /* prints |dig[k-1]|$\,\ldots\,$|dig[0]| */
1836   while ( k>0 ){ 
1837     decr(k); mp_print_char(mp, '0'+mp->dig[k]);
1838   }
1839 }
1840
1841 @ The following procedure, which prints out the decimal representation of a
1842 given integer |n|, has been written carefully so that it works properly
1843 if |n=0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1844 to negative arguments, since such operations are not implemented consistently
1845 on all platforms.
1846
1847 @<Basic print...@>=
1848 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1849   integer m; /* used to negate |n| in possibly dangerous cases */
1850   int k = 0; /* index to current digit; we assume that $|n|<10^{23}$ */
1851   if ( n<0 ) { 
1852     mp_print_char(mp, '-');
1853     if ( n>-100000000 ) {
1854           negate(n);
1855     } else  { 
1856           m=-1-n; n=m / 10; m=(m % 10)+1; k=1;
1857       if ( m<10 ) {
1858         mp->dig[0]=m;
1859       } else { 
1860         mp->dig[0]=0; incr(n);
1861       }
1862     }
1863   }
1864   do {  
1865     mp->dig[k]=n % 10; n=n / 10; incr(k);
1866   } while (n!=0);
1867   mp_print_the_digs(mp, k);
1868 }
1869
1870 @ @<Internal ...@>=
1871 void mp_print_int (MP mp,integer n);
1872
1873 @ \MP\ also makes use of a trivial procedure to print two digits. The
1874 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1875
1876 @c 
1877 void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1878   n=abs(n) % 100; 
1879   mp_print_char(mp, '0'+(n / 10));
1880   mp_print_char(mp, '0'+(n % 10));
1881 }
1882
1883
1884 @ @<Internal ...@>=
1885 void mp_print_dd (MP mp,integer n);
1886
1887 @ Here is a procedure that asks the user to type a line of input,
1888 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1889 The input is placed into locations |first| through |last-1| of the
1890 |buffer| array, and echoed on the transcript file if appropriate.
1891
1892 This procedure is never called when |interaction<mp_scroll_mode|.
1893
1894 @d prompt_input(A) do { 
1895     if (!mp->noninteractive) {
1896       wake_up_terminal; mp_print(mp, (A)); 
1897     }
1898     mp_term_input(mp);
1899   } while (0) /* prints a string and gets a line of input */
1900
1901 @c 
1902 void mp_term_input (MP mp) { /* gets a line from the terminal */
1903   size_t k; /* index into |buffer| */
1904   update_terminal; /* Now the user sees the prompt for sure */
1905   if (!mp_input_ln(mp, mp->term_in )) {
1906     if (!mp->noninteractive) {
1907           mp_fatal_error(mp, "End of file on the terminal!");
1908 @.End of file on the terminal@>
1909     } else { /* we are done with this input chunk */
1910           longjmp(mp->jump_buf,1);      
1911     }
1912   }
1913   if (!mp->noninteractive) {
1914     mp->term_offset=0; /* the user's line ended with \<\rm return> */
1915     decr(mp->selector); /* prepare to echo the input */
1916     if ( mp->last!=mp->first ) {
1917       for (k=mp->first;k<=mp->last-1;k++) {
1918         mp_print_char(mp, mp->buffer[k]);
1919       }
1920     }
1921     mp_print_ln(mp); 
1922     mp->buffer[mp->last]='%'; 
1923     incr(mp->selector); /* restore previous status */
1924   }
1925 }
1926
1927 @* \[6] Reporting errors.
1928 When something anomalous is detected, \MP\ typically does something like this:
1929 $$\vbox{\halign{#\hfil\cr
1930 |print_err("Something anomalous has been detected");|\cr
1931 |help3("This is the first line of my offer to help.")|\cr
1932 |("This is the second line. I'm trying to")|\cr
1933 |("explain the best way for you to proceed.");|\cr
1934 |error;|\cr}}$$
1935 A two-line help message would be given using |help2|, etc.; these informal
1936 helps should use simple vocabulary that complements the words used in the
1937 official error message that was printed. (Outside the U.S.A., the help
1938 messages should preferably be translated into the local vernacular. Each
1939 line of help is at most 60 characters long, in the present implementation,
1940 so that |max_print_line| will not be exceeded.)
1941
1942 The |print_err| procedure supplies a `\.!' before the official message,
1943 and makes sure that the terminal is awake if a stop is going to occur.
1944 The |error| procedure supplies a `\..' after the official message, then it
1945 shows the location of the error; and if |interaction=error_stop_mode|,
1946 it also enters into a dialog with the user, during which time the help
1947 message may be printed.
1948 @^system dependencies@>
1949
1950 @ The global variable |interaction| has four settings, representing increasing
1951 amounts of user interaction:
1952
1953 @<Exported types@>=
1954 enum mp_interaction_mode { 
1955  mp_unspecified_mode=0, /* extra value for command-line switch */
1956  mp_batch_mode, /* omits all stops and omits terminal output */
1957  mp_nonstop_mode, /* omits all stops */
1958  mp_scroll_mode, /* omits error stops */
1959  mp_error_stop_mode /* stops at every opportunity to interact */
1960 };
1961
1962 @ @<Option variables@>=
1963 int interaction; /* current level of interaction */
1964 int noninteractive; /* do we have a terminal? */
1965
1966 @ Set it here so it can be overwritten by the commandline
1967
1968 @<Allocate or initialize ...@>=
1969 mp->interaction=opt->interaction;
1970 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1971   mp->interaction=mp_error_stop_mode;
1972 if (mp->interaction<mp_unspecified_mode) 
1973   mp->interaction=mp_batch_mode;
1974 mp->noninteractive=opt->noninteractive;
1975
1976
1977
1978 @d print_err(A) mp_print_err(mp,(A))
1979
1980 @<Internal ...@>=
1981 void mp_print_err(MP mp, const char * A);
1982
1983 @ @c
1984 void mp_print_err(MP mp, const char * A) { 
1985   if ( mp->interaction==mp_error_stop_mode ) 
1986     wake_up_terminal;
1987   mp_print_nl(mp, "! "); 
1988   mp_print(mp, A);
1989 @.!\relax@>
1990 }
1991
1992
1993 @ \MP\ is careful not to call |error| when the print |selector| setting
1994 might be unusual. The only possible values of |selector| at the time of
1995 error messages are
1996
1997 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1998   and |log_file| not yet open);
1999
2000 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
2001
2002 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
2003
2004 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
2005
2006 @<Initialize the print |selector| based on |interaction|@>=
2007 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
2008
2009 @ A global variable |deletions_allowed| is set |false| if the |get_next|
2010 routine is active when |error| is called; this ensures that |get_next|
2011 will never be called recursively.
2012 @^recursion@>
2013
2014 The global variable |history| records the worst level of error that
2015 has been detected. It has four possible values: |spotless|, |warning_issued|,
2016 |error_message_issued|, and |fatal_error_stop|.
2017
2018 Another global variable, |error_count|, is increased by one when an
2019 |error| occurs without an interactive dialog, and it is reset to zero at
2020 the end of every statement.  If |error_count| reaches 100, \MP\ decides
2021 that there is no point in continuing further.
2022
2023 @<Types...@>=
2024 enum mp_history_states {
2025   mp_spotless=0, /* |history| value when nothing has been amiss yet */
2026   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
2027   mp_error_message_issued, /* |history| value when |error| has been called */
2028   mp_fatal_error_stop /* |history| value when termination was premature */
2029 };
2030
2031 @ @<Glob...@>=
2032 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2033 int history; /* has the source input been clean so far? */
2034 int error_count; /* the number of scrolled errors since the last statement ended */
2035
2036 @ The value of |history| is initially |fatal_error_stop|, but it will
2037 be changed to |spotless| if \MP\ survives the initialization process.
2038
2039 @<Allocate or ...@>=
2040 mp->deletions_allowed=true; mp->error_count=0; /* |history| is initialized elsewhere */
2041
2042 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2043 error procedures near the beginning of the program. But the error procedures
2044 in turn use some other procedures, which need to be declared |forward|
2045 before we get to |error| itself.
2046
2047 It is possible for |error| to be called recursively if some error arises
2048 when |get_next| is being used to delete a token, and/or if some fatal error
2049 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2050 @^recursion@>
2051 is never more than two levels deep.
2052
2053 @<Declarations@>=
2054 void mp_get_next (MP mp);
2055 void mp_term_input (MP mp);
2056 void mp_show_context (MP mp);
2057 void mp_begin_file_reading (MP mp);
2058 void mp_open_log_file (MP mp);
2059 void mp_clear_for_error_prompt (MP mp);
2060 void mp_debug_help (MP mp);
2061 @<Declare the procedure called |flush_string|@>
2062
2063 @ @<Internal ...@>=
2064 void mp_normalize_selector (MP mp);
2065
2066 @ Individual lines of help are recorded in the array |help_line|, which
2067 contains entries in positions |0..(help_ptr-1)|. They should be printed
2068 in reverse order, i.e., with |help_line[0]| appearing last.
2069
2070 @d hlp1(A) mp->help_line[0]=(A); }
2071 @d hlp2(A) mp->help_line[1]=(A); hlp1
2072 @d hlp3(A) mp->help_line[2]=(A); hlp2
2073 @d hlp4(A) mp->help_line[3]=(A); hlp3
2074 @d hlp5(A) mp->help_line[4]=(A); hlp4
2075 @d hlp6(A) mp->help_line[5]=(A); hlp5
2076 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2077 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2078 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2079 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2080 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2081 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2082 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2083
2084 @<Glob...@>=
2085 const char * help_line[6]; /* helps for the next |error| */
2086 unsigned int help_ptr; /* the number of help lines present */
2087 boolean use_err_help; /* should the |err_help| string be shown? */
2088 str_number err_help; /* a string set up by \&{errhelp} */
2089 str_number filename_template; /* a string set up by \&{filenametemplate} */
2090
2091 @ @<Allocate or ...@>=
2092 mp->help_ptr=0; mp->use_err_help=false; mp->err_help=0; mp->filename_template=0;
2093
2094 @ The |jump_out| procedure just cuts across all active procedure levels and
2095 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2096 whole program. It is used when there is no recovery from a particular error.
2097
2098 The program uses a |jump_buf| to handle this, this is initialized at three
2099 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2100 of |mp_run|. Those are the only library enty points.
2101
2102 @^system dependencies@>
2103
2104 @<Glob...@>=
2105 jmp_buf jump_buf;
2106
2107 @ @<Install and test the non-local jump buffer@>=
2108 if (setjmp(mp->jump_buf) != 0) { return mp->history; }
2109
2110 @ @<Setup the non-local jump buffer in |mp_new|@>=
2111 if (setjmp(mp->jump_buf) != 0) return NULL;
2112
2113
2114 @ If the array of internals is still |NULL| when |jump_out| is called, a
2115 crash occured during initialization, and it is not safe to run the normal
2116 cleanup routine.
2117
2118 @<Error hand...@>=
2119 void mp_jump_out (MP mp) { 
2120   if(mp->internal!=NULL)
2121     mp_close_files_and_terminate(mp);
2122   longjmp(mp->jump_buf,1);
2123 }
2124
2125 @ Here now is the general |error| routine.
2126
2127 @<Error hand...@>=
2128 void mp_error (MP mp) { /* completes the job of error reporting */
2129   ASCII_code c; /* what the user types */
2130   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2131   pool_pointer j; /* character position being printed */
2132   if ( mp->history<mp_error_message_issued ) 
2133         mp->history=mp_error_message_issued;
2134   mp_print_char(mp, '.'); mp_show_context(mp);
2135   if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2136     @<Get user's advice and |return|@>;
2137   }
2138   incr(mp->error_count);
2139   if ( mp->error_count==100 ) { 
2140     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2141 @.That makes 100 errors...@>
2142     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2143   }
2144   @<Put help message on the transcript file@>;
2145 }
2146 void mp_warn (MP mp, const char *msg) {
2147   int saved_selector = mp->selector;
2148   mp_normalize_selector(mp);
2149   mp_print_nl(mp,"Warning: ");
2150   mp_print(mp,msg);
2151   mp_print_ln(mp);
2152   mp->selector = saved_selector;
2153 }
2154
2155 @ @<Exported function ...@>=
2156 void mp_error (MP mp);
2157 void mp_warn (MP mp, const char *msg);
2158
2159
2160 @ @<Get user's advice...@>=
2161 while (1) { 
2162 CONTINUE:
2163   mp_clear_for_error_prompt(mp); prompt_input("? ");
2164 @.?\relax@>
2165   if ( mp->last==mp->first ) return;
2166   c=mp->buffer[mp->first];
2167   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2168   @<Interpret code |c| and |return| if done@>;
2169 }
2170
2171 @ It is desirable to provide an `\.E' option here that gives the user
2172 an easy way to return from \MP\ to the system editor, with the offending
2173 line ready to be edited. But such an extension requires some system
2174 wizardry, so the present implementation simply types out the name of the
2175 file that should be
2176 edited and the relevant line number.
2177 @^system dependencies@>
2178
2179 @<Exported types@>=
2180 typedef void (*mp_run_editor_command)(MP, char *, int);
2181
2182 @ @<Option variables@>=
2183 mp_run_editor_command run_editor;
2184
2185 @ @<Allocate or initialize ...@>=
2186 set_callback_option(run_editor);
2187
2188 @ @<Declarations@>=
2189 void mp_run_editor (MP mp, char *fname, int fline);
2190
2191 @ @c void mp_run_editor (MP mp, char *fname, int fline) {
2192     mp_print_nl(mp, "You want to edit file ");
2193 @.You want to edit file x@>
2194     mp_print(mp, fname);
2195     mp_print(mp, " at line "); 
2196     mp_print_int(mp, fline);
2197     mp->interaction=mp_scroll_mode; 
2198     mp_jump_out(mp);
2199 }
2200
2201
2202 There is a secret `\.D' option available when the debugging routines haven't
2203 been commented~out.
2204 @^debugging@>
2205
2206 @<Interpret code |c| and |return| if done@>=
2207 switch (c) {
2208 case '0': case '1': case '2': case '3': case '4':
2209 case '5': case '6': case '7': case '8': case '9': 
2210   if ( mp->deletions_allowed ) {
2211     @<Delete |c-"0"| tokens and |continue|@>;
2212   }
2213   break;
2214 #ifdef DEBUG
2215 case 'D': 
2216   mp_debug_help(mp); continue; 
2217   break;
2218 #endif
2219 case 'E': 
2220   if ( mp->file_ptr>0 ){ 
2221     (mp->run_editor)(mp, 
2222                      str(mp->input_stack[mp->file_ptr].name_field), 
2223                      mp_true_line(mp));
2224   }
2225   break;
2226 case 'H': 
2227   @<Print the help information and |continue|@>;
2228   break;
2229 case 'I':
2230   @<Introduce new material from the terminal and |return|@>;
2231   break;
2232 case 'Q': case 'R': case 'S':
2233   @<Change the interaction level and |return|@>;
2234   break;
2235 case 'X':
2236   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2237   break;
2238 default:
2239   break;
2240 }
2241 @<Print the menu of available options@>
2242
2243 @ @<Print the menu...@>=
2244
2245   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2246 @.Type <return> to proceed...@>
2247   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2248   mp_print_nl(mp, "I to insert something, ");
2249   if ( mp->file_ptr>0 ) 
2250     mp_print(mp, "E to edit your file,");
2251   if ( mp->deletions_allowed )
2252     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2253   mp_print_nl(mp, "H for help, X to quit.");
2254 }
2255
2256 @ Here the author of \MP\ apologizes for making use of the numerical
2257 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2258 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2259 @^Knuth, Donald Ervin@>
2260
2261 @<Change the interaction...@>=
2262
2263   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2264   mp_print(mp, "OK, entering ");
2265   switch (c) {
2266   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2267   case 'R': mp_print(mp, "nonstopmode"); break;
2268   case 'S': mp_print(mp, "scrollmode"); break;
2269   } /* there are no other cases */
2270   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2271 }
2272
2273 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2274 contain the material inserted by the user; otherwise another prompt will
2275 be given. In order to understand this part of the program fully, you need
2276 to be familiar with \MP's input stacks.
2277
2278 @<Introduce new material...@>=
2279
2280   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2281   if ( mp->last>mp->first+1 ) { 
2282     loc=mp->first+1; mp->buffer[mp->first]=' ';
2283   } else { 
2284    prompt_input("insert>"); loc=mp->first;
2285 @.insert>@>
2286   };
2287   mp->first=mp->last+1; mp->cur_input.limit_field=mp->last; return;
2288 }
2289
2290 @ We allow deletion of up to 99 tokens at a time.
2291
2292 @<Delete |c-"0"| tokens...@>=
2293
2294   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2295   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2296     c=c*10+mp->buffer[mp->first+1]-'0'*11;
2297   else 
2298     c=c-'0';
2299   while ( c>0 ) { 
2300     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2301     @<Decrease the string reference count, if the current token is a string@>;
2302     decr(c);
2303   };
2304   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2305   help2("I have just deleted some text, as you asked.")
2306        ("You can now delete more, or insert, or whatever.");
2307   mp_show_context(mp); 
2308   goto CONTINUE;
2309 }
2310
2311 @ @<Print the help info...@>=
2312
2313   if ( mp->use_err_help ) { 
2314     @<Print the string |err_help|, possibly on several lines@>;
2315     mp->use_err_help=false;
2316   } else { 
2317     if ( mp->help_ptr==0 ) {
2318       help2("Sorry, I don't know how to help in this situation.")
2319            ("Maybe you should try asking a human?");
2320      }
2321     do { 
2322       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2323     } while (mp->help_ptr!=0);
2324   };
2325   help4("Sorry, I already gave what help I could...")
2326        ("Maybe you should try asking a human?")
2327        ("An error might have occurred before I noticed any problems.")
2328        ("``If all else fails, read the instructions.''");
2329   goto CONTINUE;
2330 }
2331
2332 @ @<Print the string |err_help|, possibly on several lines@>=
2333 j=mp->str_start[mp->err_help];
2334 while ( j<str_stop(mp->err_help) ) { 
2335   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2336   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2337   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2338   else  { incr(j); mp_print_char(mp, '%'); };
2339   incr(j);
2340 }
2341
2342 @ @<Put help message on the transcript file@>=
2343 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2344 if ( mp->use_err_help ) { 
2345   mp_print_nl(mp, "");
2346   @<Print the string |err_help|, possibly on several lines@>;
2347 } else { 
2348   while ( mp->help_ptr>0 ){ 
2349     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2350   };
2351 }
2352 mp_print_ln(mp);
2353 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2354 mp_print_ln(mp)
2355
2356 @ In anomalous cases, the print selector might be in an unknown state;
2357 the following subroutine is called to fix things just enough to keep
2358 running a bit longer.
2359
2360 @c 
2361 void mp_normalize_selector (MP mp) { 
2362   if ( mp->log_opened ) mp->selector=term_and_log;
2363   else mp->selector=term_only;
2364   if ( mp->job_name==NULL ) mp_open_log_file(mp);
2365   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2366 }
2367
2368 @ The following procedure prints \MP's last words before dying.
2369
2370 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2371     mp->interaction=mp_scroll_mode; /* no more interaction */
2372   if ( mp->log_opened ) mp_error(mp);
2373   /*| if ( mp->interaction>mp_batch_mode ) mp_debug_help(mp); |*/
2374   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2375   }
2376
2377 @<Error hand...@>=
2378 void mp_fatal_error (MP mp, const char *s) { /* prints |s|, and that's it */
2379   mp_normalize_selector(mp);
2380   print_err("Emergency stop"); help1(s); succumb;
2381 @.Emergency stop@>
2382 }
2383
2384 @ @<Exported function ...@>=
2385 void mp_fatal_error (MP mp, const char *s);
2386
2387
2388 @ Here is the most dreaded error message.
2389
2390 @<Error hand...@>=
2391 void mp_overflow (MP mp, const char *s, integer n) { /* stop due to finiteness */
2392   mp_normalize_selector(mp);
2393   print_err("MetaPost capacity exceeded, sorry [");
2394 @.MetaPost capacity exceeded ...@>
2395   mp_print(mp, s); mp_print_char(mp, '='); mp_print_int(mp, n); mp_print_char(mp, ']');
2396   help2("If you really absolutely need more capacity,")
2397        ("you can ask a wizard to enlarge me.");
2398   succumb;
2399 }
2400
2401 @ @<Internal library declarations@>=
2402 void mp_overflow (MP mp, const char *s, integer n);
2403
2404 @ The program might sometime run completely amok, at which point there is
2405 no choice but to stop. If no previous error has been detected, that's bad
2406 news; a message is printed that is really intended for the \MP\
2407 maintenance person instead of the user (unless the user has been
2408 particularly diabolical).  The index entries for `this can't happen' may
2409 help to pinpoint the problem.
2410 @^dry rot@>
2411
2412 @<Internal library ...@>=
2413 void mp_confusion (MP mp, const char *s);
2414
2415 @ @<Error hand...@>=
2416 void mp_confusion (MP mp, const char *s) {
2417   /* consistency check violated; |s| tells where */
2418   mp_normalize_selector(mp);
2419   if ( mp->history<mp_error_message_issued ) { 
2420     print_err("This can't happen ("); mp_print(mp, s); mp_print_char(mp, ')');
2421 @.This can't happen@>
2422     help1("I'm broken. Please show this to someone who can fix can fix");
2423   } else { 
2424     print_err("I can\'t go on meeting you like this");
2425 @.I can't go on...@>
2426     help2("One of your faux pas seems to have wounded me deeply...")
2427          ("in fact, I'm barely conscious. Please fix it and try again.");
2428   }
2429   succumb;
2430 }
2431
2432 @ Users occasionally want to interrupt \MP\ while it's running.
2433 If the runtime system allows this, one can implement
2434 a routine that sets the global variable |interrupt| to some nonzero value
2435 when such an interrupt is signaled. Otherwise there is probably at least
2436 a way to make |interrupt| nonzero using the C debugger.
2437 @^system dependencies@>
2438 @^debugging@>
2439
2440 @d check_interrupt { if ( mp->interrupt!=0 )
2441    mp_pause_for_instructions(mp); }
2442
2443 @<Global...@>=
2444 integer interrupt; /* should \MP\ pause for instructions? */
2445 boolean OK_to_interrupt; /* should interrupts be observed? */
2446 integer run_state; /* are we processing input ?*/
2447
2448 @ @<Allocate or ...@>=
2449 mp->interrupt=0; mp->OK_to_interrupt=true; mp->run_state=0; 
2450
2451 @ When an interrupt has been detected, the program goes into its
2452 highest interaction level and lets the user have the full flexibility of
2453 the |error| routine.  \MP\ checks for interrupts only at times when it is
2454 safe to do this.
2455
2456 @c 
2457 void mp_pause_for_instructions (MP mp) { 
2458   if ( mp->OK_to_interrupt ) { 
2459     mp->interaction=mp_error_stop_mode;
2460     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2461       incr(mp->selector);
2462     print_err("Interruption");
2463 @.Interruption@>
2464     help3("You rang?")
2465          ("Try to insert some instructions for me (e.g.,`I show x'),")
2466          ("unless you just want to quit by typing `X'.");
2467     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2468     mp->interrupt=0;
2469   }
2470 }
2471
2472 @ Many of \MP's error messages state that a missing token has been
2473 inserted behind the scenes. We can save string space and program space
2474 by putting this common code into a subroutine.
2475
2476 @c 
2477 void mp_missing_err (MP mp, const char *s) { 
2478   print_err("Missing `"); mp_print(mp, s); mp_print(mp, "' has been inserted");
2479 @.Missing...inserted@>
2480 }
2481
2482 @* \[7] Arithmetic with scaled numbers.
2483 The principal computations performed by \MP\ are done entirely in terms of
2484 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2485 program can be carried out in exactly the same way on a wide variety of
2486 computers, including some small ones.
2487 @^small computers@>
2488
2489 But C does not rigidly define the |/| operation in the case of negative
2490 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2491 computers and |-n| on others (is this true ?).  There are two principal
2492 types of arithmetic: ``translation-preserving,'' in which the identity
2493 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2494 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2495 different results, although the differences should be negligible when the
2496 language is being used properly.  The \TeX\ processor has been defined
2497 carefully so that both varieties of arithmetic will produce identical
2498 output, but it would be too inefficient to constrain \MP\ in a similar way.
2499
2500 @d el_gordo   017777777777 /* $2^{31}-1$, the largest value that \MP\ likes */
2501
2502 @ One of \MP's most common operations is the calculation of
2503 $\lfloor{a+b\over2}\rfloor$,
2504 the midpoint of two given integers |a| and~|b|. The most decent way to do
2505 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2506 to calculate `|(a+b)>>1|'.
2507
2508 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2509 in this program. If \MP\ is being implemented with languages that permit
2510 binary shifting, the |half| macro should be changed to make this operation
2511 as efficient as possible.  Since some systems have shift operators that can
2512 only be trusted to work on positive numbers, there is also a macro |halfp|
2513 that is used only when the quantity being halved is known to be positive
2514 or zero.
2515
2516 @d half(A) ((A) / 2)
2517 @d halfp(A) ((A) >> 1)
2518
2519 @ A single computation might use several subroutine calls, and it is
2520 desirable to avoid producing multiple error messages in case of arithmetic
2521 overflow. So the routines below set the global variable |arith_error| to |true|
2522 instead of reporting errors directly to the user.
2523 @^overflow in arithmetic@>
2524
2525 @<Glob...@>=
2526 boolean arith_error; /* has arithmetic overflow occurred recently? */
2527
2528 @ @<Allocate or ...@>=
2529 mp->arith_error=false;
2530
2531 @ At crucial points the program will say |check_arith|, to test if
2532 an arithmetic error has been detected.
2533
2534 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2535
2536 @c 
2537 void mp_clear_arith (MP mp) { 
2538   print_err("Arithmetic overflow");
2539 @.Arithmetic overflow@>
2540   help4("Uh, oh. A little while ago one of the quantities that I was")
2541        ("computing got too large, so I'm afraid your answers will be")
2542        ("somewhat askew. You'll probably have to adopt different")
2543        ("tactics next time. But I shall try to carry on anyway.");
2544   mp_error(mp); 
2545   mp->arith_error=false;
2546 }
2547
2548 @ Addition is not always checked to make sure that it doesn't overflow,
2549 but in places where overflow isn't too unlikely the |slow_add| routine
2550 is used.
2551
2552 @c integer mp_slow_add (MP mp,integer x, integer y) { 
2553   if ( x>=0 )  {
2554     if ( y<=el_gordo-x ) { 
2555       return x+y;
2556     } else  { 
2557       mp->arith_error=true; 
2558           return el_gordo;
2559     }
2560   } else  if ( -y<=el_gordo+x ) {
2561     return x+y;
2562   } else { 
2563     mp->arith_error=true; 
2564         return -el_gordo;
2565   }
2566 }
2567
2568 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2569 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2570 positions from the right end of a binary computer word.
2571
2572 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2573 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2574 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2575 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2576 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2577 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2578
2579 @<Types...@>=
2580 typedef integer scaled; /* this type is used for scaled integers */
2581 typedef unsigned char small_number; /* this type is self-explanatory */
2582
2583 @ The following function is used to create a scaled integer from a given decimal
2584 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2585 given in |dig[i]|, and the calculation produces a correctly rounded result.
2586
2587 @c 
2588 scaled mp_round_decimals (MP mp,small_number k) {
2589   /* converts a decimal fraction */
2590  integer a = 0; /* the accumulator */
2591  while ( k-->0 ) { 
2592     a=(a+mp->dig[k]*two) / 10;
2593   }
2594   return halfp(a+1);
2595 }
2596
2597 @ Conversely, here is a procedure analogous to |print_int|. If the output
2598 of this procedure is subsequently read by \MP\ and converted by the
2599 |round_decimals| routine above, it turns out that the original value will
2600 be reproduced exactly. A decimal point is printed only if the value is
2601 not an integer. If there is more than one way to print the result with
2602 the optimum number of digits following the decimal point, the closest
2603 possible value is given.
2604
2605 The invariant relation in the \&{repeat} loop is that a sequence of
2606 decimal digits yet to be printed will yield the original number if and only if
2607 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2608 We can stop if and only if $f=0$ satisfies this condition; the loop will
2609 terminate before $s$ can possibly become zero.
2610
2611 @<Basic printing...@>=
2612 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2613   scaled delta; /* amount of allowable inaccuracy */
2614   if ( s<0 ) { 
2615         mp_print_char(mp, '-'); 
2616     negate(s); /* print the sign, if negative */
2617   }
2618   mp_print_int(mp, s / unity); /* print the integer part */
2619   s=10*(s % unity)+5;
2620   if ( s!=5 ) { 
2621     delta=10; 
2622     mp_print_char(mp, '.');
2623     do {  
2624       if ( delta>unity )
2625         s=s+0100000-(delta / 2); /* round the final digit */
2626       mp_print_char(mp, '0'+(s / unity)); 
2627       s=10*(s % unity); 
2628       delta=delta*10;
2629     } while (s>delta);
2630   }
2631 }
2632
2633 @ We often want to print two scaled quantities in parentheses,
2634 separated by a comma.
2635
2636 @<Basic printing...@>=
2637 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2638   mp_print_char(mp, '('); 
2639   mp_print_scaled(mp, x); 
2640   mp_print_char(mp, ','); 
2641   mp_print_scaled(mp, y);
2642   mp_print_char(mp, ')');
2643 }
2644
2645 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2646 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2647 arithmetic with 28~significant bits of precision. A |fraction| denotes
2648 a scaled integer whose binary point is assumed to be 28 bit positions
2649 from the right.
2650
2651 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2652 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2653 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2654 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2655 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2656
2657 @<Types...@>=
2658 typedef integer fraction; /* this type is used for scaled fractions */
2659
2660 @ In fact, the two sorts of scaling discussed above aren't quite
2661 sufficient; \MP\ has yet another, used internally to keep track of angles
2662 in units of $2^{-20}$ degrees.
2663
2664 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2665 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2666 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2667 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2668
2669 @<Types...@>=
2670 typedef integer angle; /* this type is used for scaled angles */
2671
2672 @ The |make_fraction| routine produces the |fraction| equivalent of
2673 |p/q|, given integers |p| and~|q|; it computes the integer
2674 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2675 positive. If |p| and |q| are both of the same scaled type |t|,
2676 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2677 and it's also possible to use the subroutine ``backwards,'' using
2678 the relation |make_fraction(t,fraction)=t| between scaled types.
2679
2680 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2681 sets |arith_error:=true|. Most of \MP's internal computations have
2682 been designed to avoid this sort of error.
2683
2684 If this subroutine were programmed in assembly language on a typical
2685 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2686 double-precision product can often be input to a fixed-point division
2687 instruction. But when we are restricted to int-eger arithmetic it
2688 is necessary either to resort to multiple-precision maneuvering
2689 or to use a simple but slow iteration. The multiple-precision technique
2690 would be about three times faster than the code adopted here, but it
2691 would be comparatively long and tricky, involving about sixteen
2692 additional multiplications and divisions.
2693
2694 This operation is part of \MP's ``inner loop''; indeed, it will
2695 consume nearly 10\pct! of the running time (exclusive of input and output)
2696 if the code below is left unchanged. A machine-dependent recoding
2697 will therefore make \MP\ run faster. The present implementation
2698 is highly portable, but slow; it avoids multiplication and division
2699 except in the initial stage. System wizards should be careful to
2700 replace it with a routine that is guaranteed to produce identical
2701 results in all cases.
2702 @^system dependencies@>
2703
2704 As noted below, a few more routines should also be replaced by machine-dependent
2705 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2706 such changes aren't advisable; simplicity and robustness are
2707 preferable to trickery, unless the cost is too high.
2708 @^inner loop@>
2709
2710 @<Internal ...@>=
2711 fraction mp_make_fraction (MP mp,integer p, integer q);
2712 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2713
2714 @ If FIXPT is not defined, we need these preprocessor values
2715
2716 @d ELGORDO  0x7fffffff
2717 @d TWEXP31  2147483648.0
2718 @d TWEXP28  268435456.0
2719 @d TWEXP16 65536.0
2720 @d TWEXP_16 (1.0/65536.0)
2721 @d TWEXP_28 (1.0/268435456.0)
2722
2723
2724 @c 
2725 fraction mp_make_fraction (MP mp,integer p, integer q) {
2726 #ifdef FIXPT
2727   integer f; /* the fraction bits, with a leading 1 bit */
2728   integer n; /* the integer part of $\vert p/q\vert$ */
2729   integer be_careful; /* disables certain compiler optimizations */
2730   boolean negative = false; /* should the result be negated? */
2731   if ( p<0 ) {
2732     negate(p); negative=true;
2733   }
2734   if ( q<=0 ) { 
2735 #ifdef DEBUG
2736     if ( q==0 ) mp_confusion(mp, '/');
2737 #endif
2738 @:this can't happen /}{\quad \./@>
2739     negate(q); negative = ! negative;
2740   };
2741   n=p / q; p=p % q;
2742   if ( n>=8 ){ 
2743     mp->arith_error=true;
2744     return ( negative ? -el_gordo : el_gordo);
2745   } else { 
2746     n=(n-1)*fraction_one;
2747     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2748     return (negative ? (-(f+n)) : (f+n));
2749   }
2750 #else /* FIXPT */
2751     register double d;
2752         register integer i;
2753 #ifdef DEBUG
2754         if (q==0) mp_confusion(mp,'/'); 
2755 #endif /* DEBUG */
2756         d = TWEXP28 * (double)p /(double)q;
2757         if ((p^q) >= 0) {
2758                 d += 0.5;
2759                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
2760                 i = (integer) d;
2761                 if (d==i && ( ((q>0 ? -q : q)&077777)
2762                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2763         } else {
2764                 d -= 0.5;
2765                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
2766                 i = (integer) d;
2767                 if (d==i && ( ((q>0 ? q : -q)&077777)
2768                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2769         }
2770         return i;
2771 #endif /* FIXPT */
2772 }
2773
2774 @ The |repeat| loop here preserves the following invariant relations
2775 between |f|, |p|, and~|q|:
2776 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2777 $p_0$ is the original value of~$p$.
2778
2779 Notice that the computation specifies
2780 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2781 Let us hope that optimizing compilers do not miss this point; a
2782 special variable |be_careful| is used to emphasize the necessary
2783 order of computation. Optimizing compilers should keep |be_careful|
2784 in a register, not store it in memory.
2785 @^inner loop@>
2786
2787 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2788 {
2789   f=1;
2790   do {  
2791     be_careful=p-q; p=be_careful+p;
2792     if ( p>=0 ) { 
2793       f=f+f+1;
2794     } else  { 
2795       f+=f; p=p+q;
2796     }
2797   } while (f<fraction_one);
2798   be_careful=p-q;
2799   if ( be_careful+p>=0 ) incr(f);
2800 }
2801
2802 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2803 given integer~|q| by a fraction~|f|. When the operands are positive, it
2804 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2805 of |q| and~|f|.
2806
2807 This routine is even more ``inner loopy'' than |make_fraction|;
2808 the present implementation consumes almost 20\pct! of \MP's computation
2809 time during typical jobs, so a machine-language substitute is advisable.
2810 @^inner loop@> @^system dependencies@>
2811
2812 @<Declarations@>=
2813 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2814
2815 @ @c 
2816 #ifdef FIXPT
2817 integer mp_take_fraction (MP mp,integer q, fraction f) {
2818   integer p; /* the fraction so far */
2819   boolean negative; /* should the result be negated? */
2820   integer n; /* additional multiple of $q$ */
2821   integer be_careful; /* disables certain compiler optimizations */
2822   @<Reduce to the case that |f>=0| and |q>=0|@>;
2823   if ( f<fraction_one ) { 
2824     n=0;
2825   } else { 
2826     n=f / fraction_one; f=f % fraction_one;
2827     if ( q<=el_gordo / n ) { 
2828       n=n*q ; 
2829     } else { 
2830       mp->arith_error=true; n=el_gordo;
2831     }
2832   }
2833   f=f+fraction_one;
2834   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2835   be_careful=n-el_gordo;
2836   if ( be_careful+p>0 ){ 
2837     mp->arith_error=true; n=el_gordo-p;
2838   }
2839   if ( negative ) 
2840         return (-(n+p));
2841   else 
2842     return (n+p);
2843 #else /* FIXPT */
2844 integer mp_take_fraction (MP mp,integer p, fraction q) {
2845     register double d;
2846         register integer i;
2847         d = (double)p * (double)q * TWEXP_28;
2848         if ((p^q) >= 0) {
2849                 d += 0.5;
2850                 if (d>=TWEXP31) {
2851                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2852                                 mp->arith_error = true;
2853                         return ELGORDO;
2854                 }
2855                 i = (integer) d;
2856                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2857         } else {
2858                 d -= 0.5;
2859                 if (d<= -TWEXP31) {
2860                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2861                                 mp->arith_error = true;
2862                         return -ELGORDO;
2863                 }
2864                 i = (integer) d;
2865                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2866         }
2867         return i;
2868 #endif /* FIXPT */
2869 }
2870
2871 @ @<Reduce to the case that |f>=0| and |q>=0|@>=
2872 if ( f>=0 ) {
2873   negative=false;
2874 } else { 
2875   negate( f); negative=true;
2876 }
2877 if ( q<0 ) { 
2878   negate(q); negative=! negative;
2879 }
2880
2881 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2882 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2883 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2884 @^inner loop@>
2885
2886 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2887 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2888 if ( q<fraction_four ) {
2889   do {  
2890     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2891     f=halfp(f);
2892   } while (f!=1);
2893 } else  {
2894   do {  
2895     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2896     f=halfp(f);
2897   } while (f!=1);
2898 }
2899
2900
2901 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2902 analogous to |take_fraction| but with a different scaling.
2903 Given positive operands, |take_scaled|
2904 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2905
2906 Once again it is a good idea to use a machine-language replacement if
2907 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2908 when the Computer Modern fonts are being generated.
2909 @^inner loop@>
2910
2911 @c 
2912 #ifdef FIXPT
2913 integer mp_take_scaled (MP mp,integer q, scaled f) {
2914   integer p; /* the fraction so far */
2915   boolean negative; /* should the result be negated? */
2916   integer n; /* additional multiple of $q$ */
2917   integer be_careful; /* disables certain compiler optimizations */
2918   @<Reduce to the case that |f>=0| and |q>=0|@>;
2919   if ( f<unity ) { 
2920     n=0;
2921   } else  { 
2922     n=f / unity; f=f % unity;
2923     if ( q<=el_gordo / n ) {
2924       n=n*q;
2925     } else  { 
2926       mp->arith_error=true; n=el_gordo;
2927     }
2928   }
2929   f=f+unity;
2930   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2931   be_careful=n-el_gordo;
2932   if ( be_careful+p>0 ) { 
2933     mp->arith_error=true; n=el_gordo-p;
2934   }
2935   return ( negative ?(-(n+p)) :(n+p));
2936 #else /* FIXPT */
2937 integer mp_take_scaled (MP mp,integer p, scaled q) {
2938     register double d;
2939         register integer i;
2940         d = (double)p * (double)q * TWEXP_16;
2941         if ((p^q) >= 0) {
2942                 d += 0.5;
2943                 if (d>=TWEXP31) {
2944                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2945                                 mp->arith_error = true;
2946                         return ELGORDO;
2947                 }
2948                 i = (integer) d;
2949                 if (d==i && (((p&077777)*(q&077777))&040000)!=0) --i;
2950         } else {
2951                 d -= 0.5;
2952                 if (d<= -TWEXP31) {
2953                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2954                                 mp->arith_error = true;
2955                         return -ELGORDO;
2956                 }
2957                 i = (integer) d;
2958                 if (d==i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2959         }
2960         return i;
2961 #endif /* FIXPT */
2962 }
2963
2964 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2965 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2966 @^inner loop@>
2967 if ( q<fraction_four ) {
2968   do {  
2969     p = (odd(f) ? halfp(p+q) : halfp(p));
2970     f=halfp(f);
2971   } while (f!=1);
2972 } else {
2973   do {  
2974     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2975     f=halfp(f);
2976   } while (f!=1);
2977 }
2978
2979 @ For completeness, there's also |make_scaled|, which computes a
2980 quotient as a |scaled| number instead of as a |fraction|.
2981 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2982 operands are positive. \ (This procedure is not used especially often,
2983 so it is not part of \MP's inner loop.)
2984
2985 @<Internal library ...@>=
2986 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2987
2988 @ @c 
2989 scaled mp_make_scaled (MP mp,integer p, integer q) {
2990 #ifdef FIXPT 
2991   integer f; /* the fraction bits, with a leading 1 bit */
2992   integer n; /* the integer part of $\vert p/q\vert$ */
2993   boolean negative; /* should the result be negated? */
2994   integer be_careful; /* disables certain compiler optimizations */
2995   if ( p>=0 ) negative=false;
2996   else  { negate(p); negative=true; };
2997   if ( q<=0 ) { 
2998 #ifdef DEBUG 
2999     if ( q==0 ) mp_confusion(mp, "/");
3000 @:this can't happen /}{\quad \./@>
3001 #endif
3002     negate(q); negative=! negative;
3003   }
3004   n=p / q; p=p % q;
3005   if ( n>=0100000 ) { 
3006     mp->arith_error=true;
3007     return (negative ? (-el_gordo) : el_gordo);
3008   } else  { 
3009     n=(n-1)*unity;
3010     @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
3011     return ( negative ? (-(f+n)) :(f+n));
3012   }
3013 #else /* FIXPT */
3014     register double d;
3015         register integer i;
3016 #ifdef DEBUG
3017         if (q==0) mp_confusion(mp,"/"); 
3018 #endif /* DEBUG */
3019         d = TWEXP16 * (double)p /(double)q;
3020         if ((p^q) >= 0) {
3021                 d += 0.5;
3022                 if (d>=TWEXP31) {mp->arith_error=true; return ELGORDO;}
3023                 i = (integer) d;
3024                 if (d==i && ( ((q>0 ? -q : q)&077777)
3025                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
3026         } else {
3027                 d -= 0.5;
3028                 if (d<= -TWEXP31) {mp->arith_error=true; return -ELGORDO;}
3029                 i = (integer) d;
3030                 if (d==i && ( ((q>0 ? q : -q)&077777)
3031                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
3032         }
3033         return i;
3034 #endif /* FIXPT */
3035 }
3036
3037 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3038 f=1;
3039 do {  
3040   be_careful=p-q; p=be_careful+p;
3041   if ( p>=0 ) f=f+f+1;
3042   else  { f+=f; p=p+q; };
3043 } while (f<unity);
3044 be_careful=p-q;
3045 if ( be_careful+p>=0 ) incr(f)
3046
3047 @ Here is a typical example of how the routines above can be used.
3048 It computes the function
3049 $${1\over3\tau}f(\theta,\phi)=
3050 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3051  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3052 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3053 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3054 fudge factor for placing the first control point of a curve that starts
3055 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3056 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3057
3058 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3059 (It's a sum of eight terms whose absolute values can be bounded using
3060 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3061 is positive; and since the tension $\tau$ is constrained to be at least
3062 $3\over4$, the numerator is less than $16\over3$. The denominator is
3063 nonnegative and at most~6.  Hence the fixed-point calculations below
3064 are guaranteed to stay within the bounds of a 32-bit computer word.
3065
3066 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3067 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3068 $\sin\phi$, and $\cos\phi$, respectively.
3069
3070 @c 
3071 fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3072                       fraction cf, scaled t) {
3073   integer acc,num,denom; /* registers for intermediate calculations */
3074   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3075   acc=mp_take_fraction(mp, acc,ct-cf);
3076   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3077                    /* $2^{28}\sqrt2\approx379625062.497$ */
3078   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3079                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3080                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3081   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3082   /* |make_scaled(fraction,scaled)=fraction| */
3083   if ( num / 4>=denom ) 
3084     return fraction_four;
3085   else 
3086     return mp_make_fraction(mp, num, denom);
3087 }
3088
3089 @ The following somewhat different subroutine tests rigorously if $ab$ is
3090 greater than, equal to, or less than~$cd$,
3091 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3092 The result is $+1$, 0, or~$-1$ in the three respective cases.
3093
3094 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3095
3096 @c 
3097 integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3098   integer q,r; /* temporary registers */
3099   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3100   while (1) { 
3101     q = a / d; r = c / b;
3102     if ( q!=r )
3103       return ( q>r ? 1 : -1);
3104     q = a % d; r = c % b;
3105     if ( r==0 )
3106       return (q ? 1 : 0);
3107     if ( q==0 ) return -1;
3108     a=b; b=q; c=d; d=r;
3109   } /* now |a>d>0| and |c>b>0| */
3110 }
3111
3112 @ @<Reduce to the case that |a...@>=
3113 if ( a<0 ) { negate(a); negate(b);  };
3114 if ( c<0 ) { negate(c); negate(d);  };
3115 if ( d<=0 ) { 
3116   if ( b>=0 ) {
3117     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3118     else return 1;
3119   }
3120   if ( d==0 )
3121     return ( a==0 ? 0 : -1);
3122   q=a; a=c; c=q; q=-b; b=-d; d=q;
3123 } else if ( b<=0 ) { 
3124   if ( b<0 ) if ( a>0 ) return -1;
3125   return (c==0 ? 0 : -1);
3126 }
3127
3128 @ We conclude this set of elementary routines with some simple rounding
3129 and truncation operations.
3130
3131 @<Internal library declarations@>=
3132 #define mp_floor_scaled(M,i) ((i)&(-65536))
3133 #define mp_round_unscaled(M,i) (((i>>15)+1)>>1)
3134 #define mp_round_fraction(M,i) (((i>>11)+1)>>1)
3135
3136
3137 @* \[8] Algebraic and transcendental functions.
3138 \MP\ computes all of the necessary special functions from scratch, without
3139 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3140
3141 @ To get the square root of a |scaled| number |x|, we want to calculate
3142 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3143 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3144 determines $s$ by an iterative method that maintains the invariant
3145 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3146 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3147 might, however, be zero at the start of the first iteration.
3148
3149 @<Declarations@>=
3150 scaled mp_square_rt (MP mp,scaled x) ;
3151
3152 @ @c 
3153 scaled mp_square_rt (MP mp,scaled x) {
3154   small_number k; /* iteration control counter */
3155   integer y,q; /* registers for intermediate calculations */
3156   if ( x<=0 ) { 
3157     @<Handle square root of zero or negative argument@>;
3158   } else { 
3159     k=23; q=2;
3160     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3161       decr(k); x=x+x+x+x;
3162     }
3163     if ( x<fraction_four ) y=0;
3164     else  { x=x-fraction_four; y=1; };
3165     do {  
3166       @<Decrease |k| by 1, maintaining the invariant
3167       relations between |x|, |y|, and~|q|@>;
3168     } while (k!=0);
3169     return (halfp(q));
3170   }
3171 }
3172
3173 @ @<Handle square root of zero...@>=
3174
3175   if ( x<0 ) { 
3176     print_err("Square root of ");
3177 @.Square root...replaced by 0@>
3178     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3179     help2("Since I don't take square roots of negative numbers,")
3180          ("I'm zeroing this one. Proceed, with fingers crossed.");
3181     mp_error(mp);
3182   };
3183   return 0;
3184 }
3185
3186 @ @<Decrease |k| by 1, maintaining...@>=
3187 x+=x; y+=y;
3188 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3189   x=x-fraction_four; incr(y);
3190 };
3191 x+=x; y=y+y-q; q+=q;
3192 if ( x>=fraction_four ) { x=x-fraction_four; incr(y); };
3193 if ( y>q ){ y=y-q; q=q+2; }
3194 else if ( y<=0 )  { q=q-2; y=y+q;  };
3195 decr(k)
3196
3197 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3198 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3199 @^Moler, Cleve Barry@>
3200 @^Morrison, Donald Ross@>
3201 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3202 in such a way that their Pythagorean sum remains invariant, while the
3203 smaller argument decreases.
3204
3205 @<Internal library ...@>=
3206 integer mp_pyth_add (MP mp,integer a, integer b);
3207
3208
3209 @ @c 
3210 integer mp_pyth_add (MP mp,integer a, integer b) {
3211   fraction r; /* register used to transform |a| and |b| */
3212   boolean big; /* is the result dangerously near $2^{31}$? */
3213   a=abs(a); b=abs(b);
3214   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3215   if ( b>0 ) {
3216     if ( a<fraction_two ) {
3217       big=false;
3218     } else { 
3219       a=a / 4; b=b / 4; big=true;
3220     }; /* we reduced the precision to avoid arithmetic overflow */
3221     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3222     if ( big ) {
3223       if ( a<fraction_two ) {
3224         a=a+a+a+a;
3225       } else  { 
3226         mp->arith_error=true; a=el_gordo;
3227       };
3228     }
3229   }
3230   return a;
3231 }
3232
3233 @ The key idea here is to reflect the vector $(a,b)$ about the
3234 line through $(a,b/2)$.
3235
3236 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3237 while (1) {  
3238   r=mp_make_fraction(mp, b,a);
3239   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3240   if ( r==0 ) break;
3241   r=mp_make_fraction(mp, r,fraction_four+r);
3242   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3243 }
3244
3245
3246 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3247 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3248
3249 @c 
3250 integer mp_pyth_sub (MP mp,integer a, integer b) {
3251   fraction r; /* register used to transform |a| and |b| */
3252   boolean big; /* is the input dangerously near $2^{31}$? */
3253   a=abs(a); b=abs(b);
3254   if ( a<=b ) {
3255     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3256   } else { 
3257     if ( a<fraction_four ) {
3258       big=false;
3259     } else  { 
3260       a=halfp(a); b=halfp(b); big=true;
3261     }
3262     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3263     if ( big ) double(a);
3264   }
3265   return a;
3266 }
3267
3268 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3269 while (1) { 
3270   r=mp_make_fraction(mp, b,a);
3271   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3272   if ( r==0 ) break;
3273   r=mp_make_fraction(mp, r,fraction_four-r);
3274   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3275 }
3276
3277 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3278
3279   if ( a<b ){ 
3280     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3281     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3282     mp_print(mp, " has been replaced by 0");
3283 @.Pythagorean...@>
3284     help2("Since I don't take square roots of negative numbers,")
3285          ("I'm zeroing this one. Proceed, with fingers crossed.");
3286     mp_error(mp);
3287   }
3288   a=0;
3289 }
3290
3291 @ The subroutines for logarithm and exponential involve two tables.
3292 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3293 a bit more calculation, which the author claims to have done correctly:
3294 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3295 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3296 nearest integer.
3297
3298 @d two_to_the(A) (1<<(A))
3299
3300 @<Constants ...@>=
3301 static const integer spec_log[29] = { 0, /* special logarithms */
3302 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3303 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3304 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3305
3306 @ @<Local variables for initialization@>=
3307 integer k; /* all-purpose loop index */
3308
3309
3310 @ Here is the routine that calculates $2^8$ times the natural logarithm
3311 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3312 when |x| is a given positive integer.
3313
3314 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3315 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3316 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3317 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3318 during the calculation, and sixteen auxiliary bits to extend |y| are
3319 kept in~|z| during the initial argument reduction. (We add
3320 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3321 not become negative; also, the actual amount subtracted from~|y| is~96,
3322 not~100, because we want to add~4 for rounding before the final division by~8.)
3323
3324 @c 
3325 scaled mp_m_log (MP mp,scaled x) {
3326   integer y,z; /* auxiliary registers */
3327   integer k; /* iteration counter */
3328   if ( x<=0 ) {
3329      @<Handle non-positive logarithm@>;
3330   } else  { 
3331     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3332     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3333     while ( x<fraction_four ) {
3334        double(x); y-=93032639; z-=48782;
3335     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3336     y=y+(z / unity); k=2;
3337     while ( x>fraction_four+4 ) {
3338       @<Increase |k| until |x| can be multiplied by a
3339         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3340     }
3341     return (y / 8);
3342   }
3343 }
3344
3345 @ @<Increase |k| until |x| can...@>=
3346
3347   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3348   while ( x<fraction_four+z ) { z=halfp(z+1); incr(k); };
3349   y+=spec_log[k]; x-=z;
3350 }
3351
3352 @ @<Handle non-positive logarithm@>=
3353
3354   print_err("Logarithm of ");
3355 @.Logarithm...replaced by 0@>
3356   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3357   help2("Since I don't take logs of non-positive numbers,")
3358        ("I'm zeroing this one. Proceed, with fingers crossed.");
3359   mp_error(mp); 
3360   return 0;
3361 }
3362
3363 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3364 when |x| is |scaled|. The result is an integer approximation to
3365 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3366
3367 @c 
3368 scaled mp_m_exp (MP mp,scaled x) {
3369   small_number k; /* loop control index */
3370   integer y,z; /* auxiliary registers */
3371   if ( x>174436200 ) {
3372     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3373     mp->arith_error=true; 
3374     return el_gordo;
3375   } else if ( x<-197694359 ) {
3376         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3377     return 0;
3378   } else { 
3379     if ( x<=0 ) { 
3380        z=-8*x; y=04000000; /* $y=2^{20}$ */
3381     } else { 
3382       if ( x<=127919879 ) { 
3383         z=1023359037-8*x;
3384         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3385       } else {
3386        z=8*(174436200-x); /* |z| is always nonnegative */
3387       }
3388       y=el_gordo;
3389     };
3390     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3391     if ( x<=127919879 ) 
3392        return ((y+8) / 16);
3393      else 
3394        return y;
3395   }
3396 }
3397
3398 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3399 to multiplying |y| by $1-2^{-k}$.
3400
3401 A subtle point (which had to be checked) was that if $x=127919879$, the
3402 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3403 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3404 and by~16 when |k=27|.
3405
3406 @<Multiply |y| by...@>=
3407 k=1;
3408 while ( z>0 ) { 
3409   while ( z>=spec_log[k] ) { 
3410     z-=spec_log[k];
3411     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3412   }
3413   incr(k);
3414 }
3415
3416 @ The trigonometric subroutines use an auxiliary table such that
3417 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3418 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3419
3420 @<Constants ...@>=
3421 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3422 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3423 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3424
3425 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3426 returns the |angle| whose tangent points in the direction $(x,y)$.
3427 This subroutine first determines the correct octant, then solves the
3428 problem for |0<=y<=x|, then converts the result appropriately to
3429 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3430 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3431 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3432
3433 The octants are represented in a ``Gray code,'' since that turns out
3434 to be computationally simplest.
3435
3436 @d negate_x 1
3437 @d negate_y 2
3438 @d switch_x_and_y 4
3439 @d first_octant 1
3440 @d second_octant (first_octant+switch_x_and_y)
3441 @d third_octant (first_octant+switch_x_and_y+negate_x)
3442 @d fourth_octant (first_octant+negate_x)
3443 @d fifth_octant (first_octant+negate_x+negate_y)
3444 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3445 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3446 @d eighth_octant (first_octant+negate_y)
3447
3448 @c 
3449 angle mp_n_arg (MP mp,integer x, integer y) {
3450   angle z; /* auxiliary register */
3451   integer t; /* temporary storage */
3452   small_number k; /* loop counter */
3453   int octant; /* octant code */
3454   if ( x>=0 ) {
3455     octant=first_octant;
3456   } else { 
3457     negate(x); octant=first_octant+negate_x;
3458   }
3459   if ( y<0 ) { 
3460     negate(y); octant=octant+negate_y;
3461   }
3462   if ( x<y ) { 
3463     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3464   }
3465   if ( x==0 ) { 
3466     @<Handle undefined arg@>; 
3467   } else { 
3468     @<Set variable |z| to the arg of $(x,y)$@>;
3469     @<Return an appropriate answer based on |z| and |octant|@>;
3470   }
3471 }
3472
3473 @ @<Handle undefined arg@>=
3474
3475   print_err("angle(0,0) is taken as zero");
3476 @.angle(0,0)...zero@>
3477   help2("The `angle' between two identical points is undefined.")
3478        ("I'm zeroing this one. Proceed, with fingers crossed.");
3479   mp_error(mp); 
3480   return 0;
3481 }
3482
3483 @ @<Return an appropriate answer...@>=
3484 switch (octant) {
3485 case first_octant: return z;
3486 case second_octant: return (ninety_deg-z);
3487 case third_octant: return (ninety_deg+z);
3488 case fourth_octant: return (one_eighty_deg-z);
3489 case fifth_octant: return (z-one_eighty_deg);
3490 case sixth_octant: return (-z-ninety_deg);
3491 case seventh_octant: return (z-ninety_deg);
3492 case eighth_octant: return (-z);
3493 }; /* there are no other cases */
3494 return 0
3495
3496 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3497 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3498 will be made.
3499
3500 @<Set variable |z| to the arg...@>=
3501 while ( x>=fraction_two ) { 
3502   x=halfp(x); y=halfp(y);
3503 }
3504 z=0;
3505 if ( y>0 ) { 
3506  while ( x<fraction_one ) { 
3507     x+=x; y+=y; 
3508  };
3509  @<Increase |z| to the arg of $(x,y)$@>;
3510 }
3511
3512 @ During the calculations of this section, variables |x| and~|y|
3513 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3514 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3515 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3516 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3517 coordinates whose angle has decreased by~$\phi$; in the special case
3518 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3519 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3520 @^Meggitt, John E.@>
3521 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3522
3523 The initial value of |x| will be multiplied by at most
3524 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3525 there is no chance of integer overflow.
3526
3527 @<Increase |z|...@>=
3528 k=0;
3529 do {  
3530   y+=y; incr(k);
3531   if ( y>x ){ 
3532     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3533   };
3534 } while (k!=15);
3535 do {  
3536   y+=y; incr(k);
3537   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3538 } while (k!=26)
3539
3540 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3541 and cosine of that angle. The results of this routine are
3542 stored in global integer variables |n_sin| and |n_cos|.
3543
3544 @<Glob...@>=
3545 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3546
3547 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3548 the purpose of |n_sin_cos(z)| is to set
3549 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3550 for some rather large number~|r|. The maximum of |x| and |y|
3551 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3552 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3553
3554 @c 
3555 void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3556                                        and cosine */ 
3557   small_number k; /* loop control variable */
3558   int q; /* specifies the quadrant */
3559   fraction r; /* magnitude of |(x,y)| */
3560   integer x,y,t; /* temporary registers */
3561   while ( z<0 ) z=z+three_sixty_deg;
3562   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3563   q=z / forty_five_deg; z=z % forty_five_deg;
3564   x=fraction_one; y=x;
3565   if ( ! odd(q) ) z=forty_five_deg-z;
3566   @<Subtract angle |z| from |(x,y)|@>;
3567   @<Convert |(x,y)| to the octant determined by~|q|@>;
3568   r=mp_pyth_add(mp, x,y); 
3569   mp->n_cos=mp_make_fraction(mp, x,r); 
3570   mp->n_sin=mp_make_fraction(mp, y,r);
3571 }
3572
3573 @ In this case the octants are numbered sequentially.
3574
3575 @<Convert |(x,...@>=
3576 switch (q) {
3577 case 0: break;
3578 case 1: t=x; x=y; y=t; break;
3579 case 2: t=x; x=-y; y=t; break;
3580 case 3: negate(x); break;
3581 case 4: negate(x); negate(y); break;
3582 case 5: t=x; x=-y; y=-t; break;
3583 case 6: t=x; x=y; y=-t; break;
3584 case 7: negate(y); break;
3585 } /* there are no other cases */
3586
3587 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3588 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3589 that this loop is guaranteed to terminate before the (nonexistent) value
3590 |spec_atan[27]| would be required.
3591
3592 @<Subtract angle |z|...@>=
3593 k=1;
3594 while ( z>0 ){ 
3595   if ( z>=spec_atan[k] ) { 
3596     z=z-spec_atan[k]; t=x;
3597     x=t+y / two_to_the(k);
3598     y=y-t / two_to_the(k);
3599   }
3600   incr(k);
3601 }
3602 if ( y<0 ) y=0 /* this precaution may never be needed */
3603
3604 @ And now let's complete our collection of numeric utility routines
3605 by considering random number generation.
3606 \MP\ generates pseudo-random numbers with the additive scheme recommended
3607 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3608 results are random fractions between 0 and |fraction_one-1|, inclusive.
3609
3610 There's an auxiliary array |randoms| that contains 55 pseudo-random
3611 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3612 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3613 The global variable |j_random| tells which element has most recently
3614 been consumed.
3615 The global variable |random_seed| was introduced in version 0.9,
3616 for the sole reason of stressing the fact that the initial value of the
3617 random seed is system-dependant. The initialization code below will initialize
3618 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3619 is not good enough on modern fast machines that are capable of running
3620 multiple MetaPost processes within the same second.
3621 @^system dependencies@>
3622
3623 @<Glob...@>=
3624 fraction randoms[55]; /* the last 55 random values generated */
3625 int j_random; /* the number of unused |randoms| */
3626
3627 @ @<Option variables@>=
3628 int random_seed; /* the default random seed */
3629
3630 @ @<Allocate or initialize ...@>=
3631 mp->random_seed = (scaled)opt->random_seed;
3632
3633 @ To consume a random fraction, the program below will say `|next_random|'
3634 and then it will fetch |randoms[j_random]|.
3635
3636 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3637   else decr(mp->j_random); }
3638
3639 @c 
3640 void mp_new_randoms (MP mp) {
3641   int k; /* index into |randoms| */
3642   fraction x; /* accumulator */
3643   for (k=0;k<=23;k++) { 
3644    x=mp->randoms[k]-mp->randoms[k+31];
3645     if ( x<0 ) x=x+fraction_one;
3646     mp->randoms[k]=x;
3647   }
3648   for (k=24;k<= 54;k++){ 
3649     x=mp->randoms[k]-mp->randoms[k-24];
3650     if ( x<0 ) x=x+fraction_one;
3651     mp->randoms[k]=x;
3652   }
3653   mp->j_random=54;
3654 }
3655
3656 @ @<Declarations@>=
3657 void mp_init_randoms (MP mp,scaled seed);
3658
3659 @ To initialize the |randoms| table, we call the following routine.
3660
3661 @c 
3662 void mp_init_randoms (MP mp,scaled seed) {
3663   fraction j,jj,k; /* more or less random integers */
3664   int i; /* index into |randoms| */
3665   j=abs(seed);
3666   while ( j>=fraction_one ) j=halfp(j);
3667   k=1;
3668   for (i=0;i<=54;i++ ){ 
3669     jj=k; k=j-k; j=jj;
3670     if ( k<0 ) k=k+fraction_one;
3671     mp->randoms[(i*21)% 55]=j;
3672   }
3673   mp_new_randoms(mp); 
3674   mp_new_randoms(mp); 
3675   mp_new_randoms(mp); /* ``warm up'' the array */
3676 }
3677
3678 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3679 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3680
3681 Note that the call of |take_fraction| will produce the values 0 and~|x|
3682 with about half the probability that it will produce any other particular
3683 values between 0 and~|x|, because it rounds its answers.
3684
3685 @c 
3686 scaled mp_unif_rand (MP mp,scaled x) {
3687   scaled y; /* trial value */
3688   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3689   if ( y==abs(x) ) return 0;
3690   else if ( x>0 ) return y;
3691   else return (-y);
3692 }
3693
3694 @ Finally, a normal deviate with mean zero and unit standard deviation
3695 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3696 {\sl The Art of Computer Programming\/}).
3697
3698 @c 
3699 scaled mp_norm_rand (MP mp) {
3700   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3701   do { 
3702     do {  
3703       next_random;
3704       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3705       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3706       next_random; u=mp->randoms[mp->j_random];
3707     } while (abs(x)>=u);
3708     x=mp_make_fraction(mp, x,u);
3709     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3710   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3711   return x;
3712 }
3713
3714 @* \[9] Packed data.
3715 In order to make efficient use of storage space, \MP\ bases its major data
3716 structures on a |memory_word|, which contains either a (signed) integer,
3717 possibly scaled, or a small number of fields that are one half or one
3718 quarter of the size used for storing integers.
3719
3720 If |x| is a variable of type |memory_word|, it contains up to four
3721 fields that can be referred to as follows:
3722 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3723 |x|&.|int|&(an |integer|)\cr
3724 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3725 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3726 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3727   field)\cr
3728 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3729   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3730 This is somewhat cumbersome to write, and not very readable either, but
3731 macros will be used to make the notation shorter and more transparent.
3732 The code below gives a formal definition of |memory_word| and
3733 its subsidiary types, using packed variant records. \MP\ makes no
3734 assumptions about the relative positions of the fields within a word.
3735
3736 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3737 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3738
3739 @ Here are the inequalities that the quarterword and halfword values
3740 must satisfy (or rather, the inequalities that they mustn't satisfy):
3741
3742 @<Check the ``constant''...@>=
3743 if (mp->ini_version) {
3744   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3745 } else {
3746   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3747 }
3748 if ( max_quarterword<255 ) mp->bad=9;
3749 if ( max_halfword<65535 ) mp->bad=10;
3750 if ( max_quarterword>max_halfword ) mp->bad=11;
3751 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3752 if ( mp->max_strings>max_halfword ) mp->bad=13;
3753
3754 @ The macros |qi| and |qo| are used for input to and output 
3755 from quarterwords. These are legacy macros.
3756 @^system dependencies@>
3757
3758 @d qo(A) (A) /* to read eight bits from a quarterword */
3759 @d qi(A) (A) /* to store eight bits in a quarterword */
3760
3761 @ The reader should study the following definitions closely:
3762 @^system dependencies@>
3763
3764 @d sc cint /* |scaled| data is equivalent to |integer| */
3765
3766 @<Types...@>=
3767 typedef short quarterword; /* 1/4 of a word */
3768 typedef int halfword; /* 1/2 of a word */
3769 typedef union {
3770   struct {
3771     halfword RH, LH;
3772   } v;
3773   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3774     halfword junk;
3775     quarterword B0, B1;
3776   } u;
3777 } two_halves;
3778 typedef struct {
3779   struct {
3780     quarterword B2, B3, B0, B1;
3781   } u;
3782 } four_quarters;
3783 typedef union {
3784   two_halves hh;
3785   integer cint;
3786   four_quarters qqqq;
3787 } memory_word;
3788 #define b0 u.B0
3789 #define b1 u.B1
3790 #define b2 u.B2
3791 #define b3 u.B3
3792 #define rh v.RH
3793 #define lh v.LH
3794
3795 @ When debugging, we may want to print a |memory_word| without knowing
3796 what type it is; so we print it in all modes.
3797 @^debugging@>
3798
3799 @c 
3800 void mp_print_word (MP mp,memory_word w) {
3801   /* prints |w| in all ways */
3802   mp_print_int(mp, w.cint); mp_print_char(mp, ' ');
3803   mp_print_scaled(mp, w.sc); mp_print_char(mp, ' '); 
3804   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3805   mp_print_int(mp, w.hh.lh); mp_print_char(mp, '='); 
3806   mp_print_int(mp, w.hh.b0); mp_print_char(mp, ':');
3807   mp_print_int(mp, w.hh.b1); mp_print_char(mp, ';'); 
3808   mp_print_int(mp, w.hh.rh); mp_print_char(mp, ' ');
3809   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, ':'); 
3810   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, ':');
3811   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, ':'); 
3812   mp_print_int(mp, w.qqqq.b3);
3813 }
3814
3815
3816 @* \[10] Dynamic memory allocation.
3817
3818 The \MP\ system does nearly all of its own memory allocation, so that it
3819 can readily be transported into environments that do not have automatic
3820 facilities for strings, garbage collection, etc., and so that it can be in
3821 control of what error messages the user receives. The dynamic storage
3822 requirements of \MP\ are handled by providing a large array |mem| in
3823 which consecutive blocks of words are used as nodes by the \MP\ routines.
3824
3825 Pointer variables are indices into this array, or into another array
3826 called |eqtb| that will be explained later. A pointer variable might
3827 also be a special flag that lies outside the bounds of |mem|, so we
3828 allow pointers to assume any |halfword| value. The minimum memory
3829 index represents a null pointer.
3830
3831 @d null 0 /* the null pointer */
3832 @d mp_void (null+1) /* a null pointer different from |null| */
3833
3834
3835 @<Types...@>=
3836 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3837
3838 @ The |mem| array is divided into two regions that are allocated separately,
3839 but the dividing line between these two regions is not fixed; they grow
3840 together until finding their ``natural'' size in a particular job.
3841 Locations less than or equal to |lo_mem_max| are used for storing
3842 variable-length records consisting of two or more words each. This region
3843 is maintained using an algorithm similar to the one described in exercise
3844 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3845 appears in the allocated nodes; the program is responsible for knowing the
3846 relevant size when a node is freed. Locations greater than or equal to
3847 |hi_mem_min| are used for storing one-word records; a conventional
3848 \.{AVAIL} stack is used for allocation in this region.
3849
3850 Locations of |mem| between |0| and |mem_top| may be dumped as part
3851 of preloaded mem files, by the \.{INIMP} preprocessor.
3852 @.INIMP@>
3853 Production versions of \MP\ may extend the memory at the top end in order to
3854 provide more space; these locations, between |mem_top| and |mem_max|,
3855 are always used for single-word nodes.
3856
3857 The key pointers that govern |mem| allocation have a prescribed order:
3858 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3859
3860 @<Glob...@>=
3861 memory_word *mem; /* the big dynamic storage area */
3862 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3863 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3864
3865
3866
3867 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3868 @d xrealloc(P,A,B) mp_xrealloc(mp,P,A,B)
3869 @d xmalloc(A,B)  mp_xmalloc(mp,A,B)
3870 @d xstrdup(A)  mp_xstrdup(mp,A)
3871 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3872
3873 @<Declare helpers@>=
3874 void mp_xfree (void *x);
3875 void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3876 void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3877 char *mp_xstrdup(MP mp, const char *s);
3878
3879 @ The |max_size_test| guards against overflow, on the assumption that
3880 |size_t| is at least 31bits wide.
3881
3882 @d max_size_test 0x7FFFFFFF
3883
3884 @c
3885 void mp_xfree (void *x) {
3886   if (x!=NULL) free(x);
3887 }
3888 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3889   void *w ; 
3890   if ((max_size_test/size)<nmem) {
3891     do_fprintf(mp->err_out,"Memory size overflow!\n");
3892     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3893   }
3894   w = realloc (p,(nmem*size));
3895   if (w==NULL) {
3896     do_fprintf(mp->err_out,"Out of memory!\n");
3897     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3898   }
3899   return w;
3900 }
3901 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3902   void *w;
3903   if ((max_size_test/size)<nmem) {
3904     do_fprintf(mp->err_out,"Memory size overflow!\n");
3905     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3906   }
3907   w = malloc (nmem*size);
3908   if (w==NULL) {
3909     do_fprintf(mp->err_out,"Out of memory!\n");
3910     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3911   }
3912   return w;
3913 }
3914 char *mp_xstrdup(MP mp, const char *s) {
3915   char *w; 
3916   if (s==NULL)
3917     return NULL;
3918   w = strdup(s);
3919   if (w==NULL) {
3920     do_fprintf(mp->err_out,"Out of memory!\n");
3921     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3922   }
3923   return w;
3924 }
3925
3926
3927
3928 @<Allocate or initialize ...@>=
3929 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3930 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3931
3932 @ @<Dealloc variables@>=
3933 xfree(mp->mem);
3934
3935 @ Users who wish to study the memory requirements of particular applications can
3936 can use optional special features that keep track of current and
3937 maximum memory usage. When code between the delimiters |stat| $\ldots$
3938 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
3939 report these statistics when |mp_tracing_stats| is positive.
3940
3941 @<Glob...@>=
3942 integer var_used; integer dyn_used; /* how much memory is in use */
3943
3944 @ Let's consider the one-word memory region first, since it's the
3945 simplest. The pointer variable |mem_end| holds the highest-numbered location
3946 of |mem| that has ever been used. The free locations of |mem| that
3947 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3948 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3949 and |rh| fields of |mem[p]| when it is of this type. The single-word
3950 free locations form a linked list
3951 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3952 terminated by |null|.
3953
3954 @d link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
3955 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
3956
3957 @<Glob...@>=
3958 pointer avail; /* head of the list of available one-word nodes */
3959 pointer mem_end; /* the last one-word node used in |mem| */
3960
3961 @ If one-word memory is exhausted, it might mean that the user has forgotten
3962 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
3963 later that try to help pinpoint the trouble.
3964
3965 @c 
3966 @<Declare the procedure called |show_token_list|@>
3967 @<Declare the procedure called |runaway|@>
3968
3969 @ The function |get_avail| returns a pointer to a new one-word node whose
3970 |link| field is null. However, \MP\ will halt if there is no more room left.
3971 @^inner loop@>
3972
3973 @c 
3974 pointer mp_get_avail (MP mp) { /* single-word node allocation */
3975   pointer p; /* the new node being got */
3976   p=mp->avail; /* get top location in the |avail| stack */
3977   if ( p!=null ) {
3978     mp->avail=link(mp->avail); /* and pop it off */
3979   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
3980     incr(mp->mem_end); p=mp->mem_end;
3981   } else { 
3982     decr(mp->hi_mem_min); p=mp->hi_mem_min;
3983     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
3984       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
3985       mp_overflow(mp, "main memory size",mp->mem_max);
3986       /* quit; all one-word nodes are busy */
3987 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
3988     }
3989   }
3990   link(p)=null; /* provide an oft-desired initialization of the new node */
3991   incr(mp->dyn_used);/* maintain statistics */
3992   return p;
3993 }
3994
3995 @ Conversely, a one-word node is recycled by calling |free_avail|.
3996
3997 @d free_avail(A)  /* single-word node liberation */
3998   { link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
3999
4000 @ There's also a |fast_get_avail| routine, which saves the procedure-call
4001 overhead at the expense of extra programming. This macro is used in
4002 the places that would otherwise account for the most calls of |get_avail|.
4003 @^inner loop@>
4004
4005 @d fast_get_avail(A) { 
4006   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
4007   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
4008   else { mp->avail=link((A)); link((A))=null;  incr(mp->dyn_used); }
4009   }
4010
4011 @ The available-space list that keeps track of the variable-size portion
4012 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4013 pointed to by the roving pointer |rover|.
4014
4015 Each empty node has size 2 or more; the first word contains the special
4016 value |max_halfword| in its |link| field and the size in its |info| field;
4017 the second word contains the two pointers for double linking.
4018
4019 Each nonempty node also has size 2 or more. Its first word is of type
4020 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4021 Otherwise there is complete flexibility with respect to the contents
4022 of its other fields and its other words.
4023
4024 (We require |mem_max<max_halfword| because terrible things can happen
4025 when |max_halfword| appears in the |link| field of a nonempty node.)
4026
4027 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4028 @d is_empty(A)   (link((A))==empty_flag) /* tests for empty node */
4029 @d node_size   info /* the size field in empty variable-size nodes */
4030 @d llink(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4031 @d rlink(A)   link((A)+1) /* right link in doubly-linked list of empty nodes */
4032
4033 @<Glob...@>=
4034 pointer rover; /* points to some node in the list of empties */
4035
4036 @ A call to |get_node| with argument |s| returns a pointer to a new node
4037 of size~|s|, which must be 2~or more. The |link| field of the first word
4038 of this new node is set to null. An overflow stop occurs if no suitable
4039 space exists.
4040
4041 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4042 areas and returns the value |max_halfword|.
4043
4044 @<Internal library declarations@>=
4045 pointer mp_get_node (MP mp,integer s) ;
4046
4047 @ @c 
4048 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4049   pointer p; /* the node currently under inspection */
4050   pointer q;  /* the node physically after node |p| */
4051   integer r; /* the newly allocated node, or a candidate for this honor */
4052   integer t,tt; /* temporary registers */
4053 @^inner loop@>
4054  RESTART: 
4055   p=mp->rover; /* start at some free node in the ring */
4056   do {  
4057     @<Try to allocate within node |p| and its physical successors,
4058      and |goto found| if allocation was possible@>;
4059     if (rlink(p)==null || (rlink(p)==p && p!=mp->rover)) {
4060       print_err("Free list garbled");
4061       help3("I found an entry in the list of free nodes that links")
4062        ("badly. I will try to ignore the broken link, but something")
4063        ("is seriously amiss. It is wise to warn the maintainers.")
4064           mp_error(mp);
4065       rlink(p)=mp->rover;
4066     }
4067         p=rlink(p); /* move to the next node in the ring */
4068   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4069   if ( s==010000000000 ) { 
4070     return max_halfword;
4071   };
4072   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4073     if ( mp->lo_mem_max+2<=max_halfword ) {
4074       @<Grow more variable-size memory and |goto restart|@>;
4075     }
4076   }
4077   mp_overflow(mp, "main memory size",mp->mem_max);
4078   /* sorry, nothing satisfactory is left */
4079 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4080 FOUND: 
4081   link(r)=null; /* this node is now nonempty */
4082   mp->var_used+=s; /* maintain usage statistics */
4083   return r;
4084 }
4085
4086 @ The lower part of |mem| grows by 1000 words at a time, unless
4087 we are very close to going under. When it grows, we simply link
4088 a new node into the available-space list. This method of controlled
4089 growth helps to keep the |mem| usage consecutive when \MP\ is
4090 implemented on ``virtual memory'' systems.
4091 @^virtual memory@>
4092
4093 @<Grow more variable-size memory and |goto restart|@>=
4094
4095   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4096     t=mp->lo_mem_max+1000;
4097   } else {
4098     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4099     /* |lo_mem_max+2<=t<hi_mem_min| */
4100   }
4101   if ( t>max_halfword ) t=max_halfword;
4102   p=llink(mp->rover); q=mp->lo_mem_max; rlink(p)=q; llink(mp->rover)=q;
4103   rlink(q)=mp->rover; llink(q)=p; link(q)=empty_flag; 
4104   node_size(q)=t-mp->lo_mem_max;
4105   mp->lo_mem_max=t; link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4106   mp->rover=q; 
4107   goto RESTART;
4108 }
4109
4110 @ @<Try to allocate...@>=
4111 q=p+node_size(p); /* find the physical successor */
4112 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4113   t=rlink(q); tt=llink(q);
4114 @^inner loop@>
4115   if ( q==mp->rover ) mp->rover=t;
4116   llink(t)=tt; rlink(tt)=t;
4117   q=q+node_size(q);
4118 }
4119 r=q-s;
4120 if ( r>p+1 ) {
4121   @<Allocate from the top of node |p| and |goto found|@>;
4122 }
4123 if ( r==p ) { 
4124   if ( rlink(p)!=p ) {
4125     @<Allocate entire node |p| and |goto found|@>;
4126   }
4127 }
4128 node_size(p)=q-p /* reset the size in case it grew */
4129
4130 @ @<Allocate from the top...@>=
4131
4132   node_size(p)=r-p; /* store the remaining size */
4133   mp->rover=p; /* start searching here next time */
4134   goto FOUND;
4135 }
4136
4137 @ Here we delete node |p| from the ring, and let |rover| rove around.
4138
4139 @<Allocate entire...@>=
4140
4141   mp->rover=rlink(p); t=llink(p);
4142   llink(mp->rover)=t; rlink(t)=mp->rover;
4143   goto FOUND;
4144 }
4145
4146 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4147 the operation |free_node(p,s)| will make its words available, by inserting
4148 |p| as a new empty node just before where |rover| now points.
4149
4150 @<Internal library declarations@>=
4151 void mp_free_node (MP mp, pointer p, halfword s) ;
4152
4153 @ @c 
4154 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4155   liberation */
4156   pointer q; /* |llink(rover)| */
4157   node_size(p)=s; link(p)=empty_flag;
4158 @^inner loop@>
4159   q=llink(mp->rover); llink(p)=q; rlink(p)=mp->rover; /* set both links */
4160   llink(mp->rover)=p; rlink(q)=p; /* insert |p| into the ring */
4161   mp->var_used-=s; /* maintain statistics */
4162 }
4163
4164 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4165 available space list. The list is probably very short at such times, so a
4166 simple insertion sort is used. The smallest available location will be
4167 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
4168
4169 @c 
4170 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4171   by location */
4172   pointer p,q,r; /* indices into |mem| */
4173   pointer old_rover; /* initial |rover| setting */
4174   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4175   p=rlink(mp->rover); rlink(mp->rover)=max_halfword; old_rover=mp->rover;
4176   while ( p!=old_rover ) {
4177     @<Sort |p| into the list starting at |rover|
4178      and advance |p| to |rlink(p)|@>;
4179   }
4180   p=mp->rover;
4181   while ( rlink(p)!=max_halfword ) { 
4182     llink(rlink(p))=p; p=rlink(p);
4183   };
4184   rlink(p)=mp->rover; llink(mp->rover)=p;
4185 }
4186
4187 @ The following |while| loop is guaranteed to
4188 terminate, since the list that starts at
4189 |rover| ends with |max_halfword| during the sorting procedure.
4190
4191 @<Sort |p|...@>=
4192 if ( p<mp->rover ) { 
4193   q=p; p=rlink(q); rlink(q)=mp->rover; mp->rover=q;
4194 } else  { 
4195   q=mp->rover;
4196   while ( rlink(q)<p ) q=rlink(q);
4197   r=rlink(p); rlink(p)=rlink(q); rlink(q)=p; p=r;
4198 }
4199
4200 @* \[11] Memory layout.
4201 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4202 more efficient than dynamic allocation when we can get away with it. For
4203 example, locations |0| to |1| are always used to store a
4204 two-word dummy token whose second word is zero.
4205 The following macro definitions accomplish the static allocation by giving
4206 symbolic names to the fixed positions. Static variable-size nodes appear
4207 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4208 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4209
4210 @d null_dash (2) /* the first two words are reserved for a null value */
4211 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4212 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4213 @d temp_val (zero_val+2) /* two words for a temporary value node */
4214 @d end_attr temp_val /* we use |end_attr+2| only */
4215 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4216 @d test_pen (inf_val+2)
4217   /* nine words for a pen used when testing the turning number */
4218 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4219 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4220   allocated word in the variable-size |mem| */
4221 @#
4222 @d sentinel mp->mem_top /* end of sorted lists */
4223 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4224 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4225 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4226 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4227   the one-word |mem| */
4228
4229 @ The following code gets the dynamic part of |mem| off to a good start,
4230 when \MP\ is initializing itself the slow way.
4231
4232 @<Initialize table entries (done by \.{INIMP} only)@>=
4233 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4234 link(mp->rover)=empty_flag;
4235 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4236 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
4237 mp->lo_mem_max=mp->rover+1000; 
4238 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4239 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4240   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4241 }
4242 mp->avail=null; mp->mem_end=mp->mem_top;
4243 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4244 mp->var_used=lo_mem_stat_max+1; 
4245 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4246 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4247
4248 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4249 nodes that starts at a given position, until coming to |sentinel| or a
4250 pointer that is not in the one-word region. Another procedure,
4251 |flush_node_list|, frees an entire linked list of one-word and two-word
4252 nodes, until coming to a |null| pointer.
4253 @^inner loop@>
4254
4255 @c 
4256 void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4257   pointer q,r; /* list traversers */
4258   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4259     r=p;
4260     do {  
4261       q=r; r=link(r); 
4262       decr(mp->dyn_used);
4263       if ( r<mp->hi_mem_min ) break;
4264     } while (r!=sentinel);
4265   /* now |q| is the last node on the list */
4266     link(q)=mp->avail; mp->avail=p;
4267   }
4268 }
4269 @#
4270 void mp_flush_node_list (MP mp,pointer p) {
4271   pointer q; /* the node being recycled */
4272   while ( p!=null ){ 
4273     q=p; p=link(p);
4274     if ( q<mp->hi_mem_min ) 
4275       mp_free_node(mp, q,2);
4276     else 
4277       free_avail(q);
4278   }
4279 }
4280
4281 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4282 For example, some pointers might be wrong, or some ``dead'' nodes might not
4283 have been freed when the last reference to them disappeared. Procedures
4284 |check_mem| and |search_mem| are available to help diagnose such
4285 problems. These procedures make use of two arrays called |free| and
4286 |was_free| that are present only if \MP's debugging routines have
4287 been included. (You may want to decrease the size of |mem| while you
4288 @^debugging@>
4289 are debugging.)
4290
4291 Because |boolean|s are typedef-d as ints, it is better to use
4292 unsigned chars here.
4293
4294 @<Glob...@>=
4295 unsigned char *free; /* free cells */
4296 unsigned char *was_free; /* previously free cells */
4297 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4298   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4299 boolean panicking; /* do we want to check memory constantly? */
4300
4301 @ @<Allocate or initialize ...@>=
4302 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4303 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4304
4305 @ @<Dealloc variables@>=
4306 xfree(mp->free);
4307 xfree(mp->was_free);
4308
4309 @ @<Allocate or ...@>=
4310 mp->was_mem_end=0; /* indicate that everything was previously free */
4311 mp->was_lo_max=0; mp->was_hi_min=mp->mem_max;
4312 mp->panicking=false;
4313
4314 @ @<Declare |mp_reallocate| functions@>=
4315 void mp_reallocate_memory(MP mp, int l) ;
4316
4317 @ @c
4318 void mp_reallocate_memory(MP mp, int l) {
4319    XREALLOC(mp->free,     l, unsigned char);
4320    XREALLOC(mp->was_free, l, unsigned char);
4321    if (mp->mem) {
4322          int newarea = l-mp->mem_max;
4323      XREALLOC(mp->mem,      l, memory_word);
4324      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4325    } else {
4326      XREALLOC(mp->mem,      l, memory_word);
4327      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4328    }
4329    mp->mem_max = l;
4330    if (mp->ini_version) 
4331      mp->mem_top = l;
4332 }
4333
4334
4335
4336 @ Procedure |check_mem| makes sure that the available space lists of
4337 |mem| are well formed, and it optionally prints out all locations
4338 that are reserved now but were free the last time this procedure was called.
4339
4340 @c 
4341 void mp_check_mem (MP mp,boolean print_locs ) {
4342   pointer p,q,r; /* current locations of interest in |mem| */
4343   boolean clobbered; /* is something amiss? */
4344   for (p=0;p<=mp->lo_mem_max;p++) {
4345     mp->free[p]=false; /* you can probably do this faster */
4346   }
4347   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4348     mp->free[p]=false; /* ditto */
4349   }
4350   @<Check single-word |avail| list@>;
4351   @<Check variable-size |avail| list@>;
4352   @<Check flags of unavailable nodes@>;
4353   @<Check the list of linear dependencies@>;
4354   if ( print_locs ) {
4355     @<Print newly busy locations@>;
4356   }
4357   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4358   mp->was_mem_end=mp->mem_end; 
4359   mp->was_lo_max=mp->lo_mem_max; 
4360   mp->was_hi_min=mp->hi_mem_min;
4361 }
4362
4363 @ @<Check single-word...@>=
4364 p=mp->avail; q=null; clobbered=false;
4365 while ( p!=null ) { 
4366   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4367   else if ( mp->free[p] ) clobbered=true;
4368   if ( clobbered ) { 
4369     mp_print_nl(mp, "AVAIL list clobbered at ");
4370 @.AVAIL list clobbered...@>
4371     mp_print_int(mp, q); break;
4372   }
4373   mp->free[p]=true; q=p; p=link(q);
4374 }
4375
4376 @ @<Check variable-size...@>=
4377 p=mp->rover; q=null; clobbered=false;
4378 do {  
4379   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4380   else if ( (rlink(p)>=mp->lo_mem_max)||(rlink(p)<0) ) clobbered=true;
4381   else if (  !(is_empty(p))||(node_size(p)<2)||
4382    (p+node_size(p)>mp->lo_mem_max)|| (llink(rlink(p))!=p) ) clobbered=true;
4383   if ( clobbered ) { 
4384     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4385 @.Double-AVAIL list clobbered...@>
4386     mp_print_int(mp, q); break;
4387   }
4388   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4389     if ( mp->free[q] ) { 
4390       mp_print_nl(mp, "Doubly free location at ");
4391 @.Doubly free location...@>
4392       mp_print_int(mp, q); break;
4393     }
4394     mp->free[q]=true;
4395   }
4396   q=p; p=rlink(p);
4397 } while (p!=mp->rover)
4398
4399
4400 @ @<Check flags...@>=
4401 p=0;
4402 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4403   if ( is_empty(p) ) {
4404     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4405 @.Bad flag...@>
4406   }
4407   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) incr(p);
4408   while ( (p<=mp->lo_mem_max) && mp->free[p] ) incr(p);
4409 }
4410
4411 @ @<Print newly busy...@>=
4412
4413   @<Do intialization required before printing new busy locations@>;
4414   mp_print_nl(mp, "New busy locs:");
4415 @.New busy locs@>
4416   for (p=0;p<= mp->lo_mem_max;p++ ) {
4417     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4418       @<Indicate that |p| is a new busy location@>;
4419     }
4420   }
4421   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4422     if ( ! mp->free[p] &&
4423         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4424       @<Indicate that |p| is a new busy location@>;
4425     }
4426   }
4427   @<Finish printing new busy locations@>;
4428 }
4429
4430 @ There might be many new busy locations so we are careful to print contiguous
4431 blocks compactly.  During this operation |q| is the last new busy location and
4432 |r| is the start of the block containing |q|.
4433
4434 @<Indicate that |p| is a new busy location@>=
4435
4436   if ( p>q+1 ) { 
4437     if ( q>r ) { 
4438       mp_print(mp, ".."); mp_print_int(mp, q);
4439     }
4440     mp_print_char(mp, ' '); mp_print_int(mp, p);
4441     r=p;
4442   }
4443   q=p;
4444 }
4445
4446 @ @<Do intialization required before printing new busy locations@>=
4447 q=mp->mem_max; r=mp->mem_max
4448
4449 @ @<Finish printing new busy locations@>=
4450 if ( q>r ) { 
4451   mp_print(mp, ".."); mp_print_int(mp, q);
4452 }
4453
4454 @ The |search_mem| procedure attempts to answer the question ``Who points
4455 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4456 that might not be of type |two_halves|. Strictly speaking, this is
4457 undefined, and it can lead to ``false drops'' (words that seem to
4458 point to |p| purely by coincidence). But for debugging purposes, we want
4459 to rule out the places that do {\sl not\/} point to |p|, so a few false
4460 drops are tolerable.
4461
4462 @c
4463 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4464   integer q; /* current position being searched */
4465   for (q=0;q<=mp->lo_mem_max;q++) { 
4466     if ( link(q)==p ){ 
4467       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4468     }
4469     if ( info(q)==p ) { 
4470       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4471     }
4472   }
4473   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4474     if ( link(q)==p ) {
4475       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, ')');
4476     }
4477     if ( info(q)==p ) {
4478       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, ')');
4479     }
4480   }
4481   @<Search |eqtb| for equivalents equal to |p|@>;
4482 }
4483
4484 @* \[12] The command codes.
4485 Before we can go much further, we need to define symbolic names for the internal
4486 code numbers that represent the various commands obeyed by \MP. These codes
4487 are somewhat arbitrary, but not completely so. For example,
4488 some codes have been made adjacent so that |case| statements in the
4489 program need not consider cases that are widely spaced, or so that |case|
4490 statements can be replaced by |if| statements. A command can begin an
4491 expression if and only if its code lies between |min_primary_command| and
4492 |max_primary_command|, inclusive. The first token of a statement that doesn't
4493 begin with an expression has a command code between |min_command| and
4494 |max_statement_command|, inclusive. Anything less than |min_command| is
4495 eliminated during macro expansions, and anything no more than |max_pre_command|
4496 is eliminated when expanding \TeX\ material.  Ranges such as
4497 |min_secondary_command..max_secondary_command| are used when parsing
4498 expressions, but the relative ordering within such a range is generally not
4499 critical.
4500
4501 The ordering of the highest-numbered commands
4502 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4503 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4504 for the smallest two commands.  The ordering is also important in the ranges
4505 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4506
4507 At any rate, here is the list, for future reference.
4508
4509 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4510 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4511 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4512 @d max_pre_command mpx_break
4513 @d if_test 4 /* conditional text (\&{if}) */
4514 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi}) */
4515 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4516 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4517 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4518 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4519 @d relax 10 /* do nothing (\.{\char`\\}) */
4520 @d scan_tokens 11 /* put a string into the input buffer */
4521 @d expand_after 12 /* look ahead one token */
4522 @d defined_macro 13 /* a macro defined by the user */
4523 @d min_command (defined_macro+1)
4524 @d save_command 14 /* save a list of tokens (\&{save}) */
4525 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4526 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4527 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4528 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4529 @d ship_out_command 19 /* output a character (\&{shipout}) */
4530 @d add_to_command 20 /* add to edges (\&{addto}) */
4531 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4532 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4533 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4534 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4535 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4536 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4537 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4538 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4539 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4540 @d special_command 30 /* output special info (\&{special})
4541                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4542 @d write_command 31 /* write text to a file (\&{write}) */
4543 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc.) */
4544 @d max_statement_command type_name
4545 @d min_primary_command type_name
4546 @d left_delimiter 33 /* the left delimiter of a matching pair */
4547 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4548 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4549 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4550 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4551 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4552 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4553 @d capsule_token 40 /* a value that has been put into a token list */
4554 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4555 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4556 @d min_suffix_token internal_quantity
4557 @d tag_token 43 /* a symbolic token without a primitive meaning */
4558 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4559 @d max_suffix_token numeric_token
4560 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4561 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4562 @d min_tertiary_command plus_or_minus
4563 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4564 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4565 @d max_tertiary_command tertiary_binary
4566 @d left_brace 48 /* the operator `\.{\char`\{}' */
4567 @d min_expression_command left_brace
4568 @d path_join 49 /* the operator `\.{..}' */
4569 @d ampersand 50 /* the operator `\.\&' */
4570 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4571 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4572 @d equals 53 /* the operator `\.=' */
4573 @d max_expression_command equals
4574 @d and_command 54 /* the operator `\&{and}' */
4575 @d min_secondary_command and_command
4576 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4577 @d slash 56 /* the operator `\./' */
4578 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4579 @d max_secondary_command secondary_binary
4580 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4581 @d controls 59 /* specify control points explicitly (\&{controls}) */
4582 @d tension 60 /* specify tension between knots (\&{tension}) */
4583 @d at_least 61 /* bounded tension value (\&{atleast}) */
4584 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4585 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4586 @d right_delimiter 64 /* the right delimiter of a matching pair */
4587 @d left_bracket 65 /* the operator `\.[' */
4588 @d right_bracket 66 /* the operator `\.]' */
4589 @d right_brace 67 /* the operator `\.{\char`\}}' */
4590 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4591 @d thing_to_add 69
4592   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4593 @d of_token 70 /* the operator `\&{of}' */
4594 @d to_token 71 /* the operator `\&{to}' */
4595 @d step_token 72 /* the operator `\&{step}' */
4596 @d until_token 73 /* the operator `\&{until}' */
4597 @d within_token 74 /* the operator `\&{within}' */
4598 @d lig_kern_token 75
4599   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}', etc. */
4600 @d assignment 76 /* the operator `\.{:=}' */
4601 @d skip_to 77 /* the operation `\&{skipto}' */
4602 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4603 @d double_colon 79 /* the operator `\.{::}' */
4604 @d colon 80 /* the operator `\.:' */
4605 @#
4606 @d comma 81 /* the operator `\.,', must be |colon+1| */
4607 @d end_of_statement (mp->cur_cmd>comma)
4608 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4609 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4610 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4611 @d max_command_code stop
4612 @d outer_tag (max_command_code+1) /* protection code added to command code */
4613
4614 @<Types...@>=
4615 typedef int command_code;
4616
4617 @ Variables and capsules in \MP\ have a variety of ``types,''
4618 distinguished by the code numbers defined here. These numbers are also
4619 not completely arbitrary.  Things that get expanded must have types
4620 |>mp_independent|; a type remaining after expansion is numeric if and only if
4621 its code number is at least |numeric_type|; objects containing numeric
4622 parts must have types between |transform_type| and |pair_type|;
4623 all other types must be smaller than |transform_type|; and among the types
4624 that are not unknown or vacuous, the smallest two must be |boolean_type|
4625 and |string_type| in that order.
4626  
4627 @d undefined 0 /* no type has been declared */
4628 @d unknown_tag 1 /* this constant is added to certain type codes below */
4629 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4630   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4631
4632 @<Types...@>=
4633 enum mp_variable_type {
4634 mp_vacuous=1, /* no expression was present */
4635 mp_boolean_type, /* \&{boolean} with a known value */
4636 mp_unknown_boolean,
4637 mp_string_type, /* \&{string} with a known value */
4638 mp_unknown_string,
4639 mp_pen_type, /* \&{pen} with a known value */
4640 mp_unknown_pen,
4641 mp_path_type, /* \&{path} with a known value */
4642 mp_unknown_path,
4643 mp_picture_type, /* \&{picture} with a known value */
4644 mp_unknown_picture,
4645 mp_transform_type, /* \&{transform} variable or capsule */
4646 mp_color_type, /* \&{color} variable or capsule */
4647 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4648 mp_pair_type, /* \&{pair} variable or capsule */
4649 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4650 mp_known, /* \&{numeric} with a known value */
4651 mp_dependent, /* a linear combination with |fraction| coefficients */
4652 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4653 mp_independent, /* \&{numeric} with unknown value */
4654 mp_token_list, /* variable name or suffix argument or text argument */
4655 mp_structured, /* variable with subscripts and attributes */
4656 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4657 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4658 } ;
4659
4660 @ @<Declarations@>=
4661 void mp_print_type (MP mp,small_number t) ;
4662
4663 @ @<Basic printing procedures@>=
4664 void mp_print_type (MP mp,small_number t) { 
4665   switch (t) {
4666   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4667   case mp_boolean_type:mp_print(mp, "boolean"); break;
4668   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4669   case mp_string_type:mp_print(mp, "string"); break;
4670   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4671   case mp_pen_type:mp_print(mp, "pen"); break;
4672   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4673   case mp_path_type:mp_print(mp, "path"); break;
4674   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4675   case mp_picture_type:mp_print(mp, "picture"); break;
4676   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4677   case mp_transform_type:mp_print(mp, "transform"); break;
4678   case mp_color_type:mp_print(mp, "color"); break;
4679   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4680   case mp_pair_type:mp_print(mp, "pair"); break;
4681   case mp_known:mp_print(mp, "known numeric"); break;
4682   case mp_dependent:mp_print(mp, "dependent"); break;
4683   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4684   case mp_numeric_type:mp_print(mp, "numeric"); break;
4685   case mp_independent:mp_print(mp, "independent"); break;
4686   case mp_token_list:mp_print(mp, "token list"); break;
4687   case mp_structured:mp_print(mp, "mp_structured"); break;
4688   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4689   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4690   default: mp_print(mp, "undefined"); break;
4691   }
4692 }
4693
4694 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4695 as well as a |type|. The possibilities for |name_type| are defined
4696 here; they will be explained in more detail later.
4697
4698 @<Types...@>=
4699 enum mp_name_type {
4700  mp_root=0, /* |name_type| at the top level of a variable */
4701  mp_saved_root, /* same, when the variable has been saved */
4702  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4703  mp_subscr, /* |name_type| in a subscript node */
4704  mp_attr, /* |name_type| in an attribute node */
4705  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4706  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4707  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4708  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4709  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4710  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4711  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4712  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4713  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4714  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4715  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4716  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4717  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4718  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4719  mp_capsule, /* |name_type| in stashed-away subexpressions */
4720  mp_token  /* |name_type| in a numeric token or string token */
4721 };
4722
4723 @ Primitive operations that produce values have a secondary identification
4724 code in addition to their command code; it's something like genera and species.
4725 For example, `\.*' has the command code |primary_binary|, and its
4726 secondary identification is |times|. The secondary codes start at 30 so that
4727 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4728 are used as operators as well as type identifications.  The relative values
4729 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4730 and |filled_op..bounded_op|.  The restrictions are that
4731 |and_op-false_code=or_op-true_code|, that the ordering of
4732 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4733 and the ordering of |filled_op..bounded_op| must match that of the code
4734 values they test for.
4735
4736 @d true_code 30 /* operation code for \.{true} */
4737 @d false_code 31 /* operation code for \.{false} */
4738 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4739 @d null_pen_code 33 /* operation code for \.{nullpen} */
4740 @d job_name_op 34 /* operation code for \.{jobname} */
4741 @d read_string_op 35 /* operation code for \.{readstring} */
4742 @d pen_circle 36 /* operation code for \.{pencircle} */
4743 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4744 @d read_from_op 38 /* operation code for \.{readfrom} */
4745 @d close_from_op 39 /* operation code for \.{closefrom} */
4746 @d odd_op 40 /* operation code for \.{odd} */
4747 @d known_op 41 /* operation code for \.{known} */
4748 @d unknown_op 42 /* operation code for \.{unknown} */
4749 @d not_op 43 /* operation code for \.{not} */
4750 @d decimal 44 /* operation code for \.{decimal} */
4751 @d reverse 45 /* operation code for \.{reverse} */
4752 @d make_path_op 46 /* operation code for \.{makepath} */
4753 @d make_pen_op 47 /* operation code for \.{makepen} */
4754 @d oct_op 48 /* operation code for \.{oct} */
4755 @d hex_op 49 /* operation code for \.{hex} */
4756 @d ASCII_op 50 /* operation code for \.{ASCII} */
4757 @d char_op 51 /* operation code for \.{char} */
4758 @d length_op 52 /* operation code for \.{length} */
4759 @d turning_op 53 /* operation code for \.{turningnumber} */
4760 @d color_model_part 54 /* operation code for \.{colormodel} */
4761 @d x_part 55 /* operation code for \.{xpart} */
4762 @d y_part 56 /* operation code for \.{ypart} */
4763 @d xx_part 57 /* operation code for \.{xxpart} */
4764 @d xy_part 58 /* operation code for \.{xypart} */
4765 @d yx_part 59 /* operation code for \.{yxpart} */
4766 @d yy_part 60 /* operation code for \.{yypart} */
4767 @d red_part 61 /* operation code for \.{redpart} */
4768 @d green_part 62 /* operation code for \.{greenpart} */
4769 @d blue_part 63 /* operation code for \.{bluepart} */
4770 @d cyan_part 64 /* operation code for \.{cyanpart} */
4771 @d magenta_part 65 /* operation code for \.{magentapart} */
4772 @d yellow_part 66 /* operation code for \.{yellowpart} */
4773 @d black_part 67 /* operation code for \.{blackpart} */
4774 @d grey_part 68 /* operation code for \.{greypart} */
4775 @d font_part 69 /* operation code for \.{fontpart} */
4776 @d text_part 70 /* operation code for \.{textpart} */
4777 @d path_part 71 /* operation code for \.{pathpart} */
4778 @d pen_part 72 /* operation code for \.{penpart} */
4779 @d dash_part 73 /* operation code for \.{dashpart} */
4780 @d sqrt_op 74 /* operation code for \.{sqrt} */
4781 @d m_exp_op 75 /* operation code for \.{mexp} */
4782 @d m_log_op 76 /* operation code for \.{mlog} */
4783 @d sin_d_op 77 /* operation code for \.{sind} */
4784 @d cos_d_op 78 /* operation code for \.{cosd} */
4785 @d floor_op 79 /* operation code for \.{floor} */
4786 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4787 @d char_exists_op 81 /* operation code for \.{charexists} */
4788 @d font_size 82 /* operation code for \.{fontsize} */
4789 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4790 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4791 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4792 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4793 @d arc_length 87 /* operation code for \.{arclength} */
4794 @d angle_op 88 /* operation code for \.{angle} */
4795 @d cycle_op 89 /* operation code for \.{cycle} */
4796 @d filled_op 90 /* operation code for \.{filled} */
4797 @d stroked_op 91 /* operation code for \.{stroked} */
4798 @d textual_op 92 /* operation code for \.{textual} */
4799 @d clipped_op 93 /* operation code for \.{clipped} */
4800 @d bounded_op 94 /* operation code for \.{bounded} */
4801 @d plus 95 /* operation code for \.+ */
4802 @d minus 96 /* operation code for \.- */
4803 @d times 97 /* operation code for \.* */
4804 @d over 98 /* operation code for \./ */
4805 @d pythag_add 99 /* operation code for \.{++} */
4806 @d pythag_sub 100 /* operation code for \.{+-+} */
4807 @d or_op 101 /* operation code for \.{or} */
4808 @d and_op 102 /* operation code for \.{and} */
4809 @d less_than 103 /* operation code for \.< */
4810 @d less_or_equal 104 /* operation code for \.{<=} */
4811 @d greater_than 105 /* operation code for \.> */
4812 @d greater_or_equal 106 /* operation code for \.{>=} */
4813 @d equal_to 107 /* operation code for \.= */
4814 @d unequal_to 108 /* operation code for \.{<>} */
4815 @d concatenate 109 /* operation code for \.\& */
4816 @d rotated_by 110 /* operation code for \.{rotated} */
4817 @d slanted_by 111 /* operation code for \.{slanted} */
4818 @d scaled_by 112 /* operation code for \.{scaled} */
4819 @d shifted_by 113 /* operation code for \.{shifted} */
4820 @d transformed_by 114 /* operation code for \.{transformed} */
4821 @d x_scaled 115 /* operation code for \.{xscaled} */
4822 @d y_scaled 116 /* operation code for \.{yscaled} */
4823 @d z_scaled 117 /* operation code for \.{zscaled} */
4824 @d in_font 118 /* operation code for \.{infont} */
4825 @d intersect 119 /* operation code for \.{intersectiontimes} */
4826 @d double_dot 120 /* operation code for improper \.{..} */
4827 @d substring_of 121 /* operation code for \.{substring} */
4828 @d min_of substring_of
4829 @d subpath_of 122 /* operation code for \.{subpath} */
4830 @d direction_time_of 123 /* operation code for \.{directiontime} */
4831 @d point_of 124 /* operation code for \.{point} */
4832 @d precontrol_of 125 /* operation code for \.{precontrol} */
4833 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4834 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4835 @d arc_time_of 128 /* operation code for \.{arctime} */
4836 @d mp_version 129 /* operation code for \.{mpversion} */
4837 @d envelope_of 130 /* operation code for \.{envelope} */
4838
4839 @c void mp_print_op (MP mp,quarterword c) { 
4840   if (c<=mp_numeric_type ) {
4841     mp_print_type(mp, c);
4842   } else {
4843     switch (c) {
4844     case true_code:mp_print(mp, "true"); break;
4845     case false_code:mp_print(mp, "false"); break;
4846     case null_picture_code:mp_print(mp, "nullpicture"); break;
4847     case null_pen_code:mp_print(mp, "nullpen"); break;
4848     case job_name_op:mp_print(mp, "jobname"); break;
4849     case read_string_op:mp_print(mp, "readstring"); break;
4850     case pen_circle:mp_print(mp, "pencircle"); break;
4851     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4852     case read_from_op:mp_print(mp, "readfrom"); break;
4853     case close_from_op:mp_print(mp, "closefrom"); break;
4854     case odd_op:mp_print(mp, "odd"); break;
4855     case known_op:mp_print(mp, "known"); break;
4856     case unknown_op:mp_print(mp, "unknown"); break;
4857     case not_op:mp_print(mp, "not"); break;
4858     case decimal:mp_print(mp, "decimal"); break;
4859     case reverse:mp_print(mp, "reverse"); break;
4860     case make_path_op:mp_print(mp, "makepath"); break;
4861     case make_pen_op:mp_print(mp, "makepen"); break;
4862     case oct_op:mp_print(mp, "oct"); break;
4863     case hex_op:mp_print(mp, "hex"); break;
4864     case ASCII_op:mp_print(mp, "ASCII"); break;
4865     case char_op:mp_print(mp, "char"); break;
4866     case length_op:mp_print(mp, "length"); break;
4867     case turning_op:mp_print(mp, "turningnumber"); break;
4868     case x_part:mp_print(mp, "xpart"); break;
4869     case y_part:mp_print(mp, "ypart"); break;
4870     case xx_part:mp_print(mp, "xxpart"); break;
4871     case xy_part:mp_print(mp, "xypart"); break;
4872     case yx_part:mp_print(mp, "yxpart"); break;
4873     case yy_part:mp_print(mp, "yypart"); break;
4874     case red_part:mp_print(mp, "redpart"); break;
4875     case green_part:mp_print(mp, "greenpart"); break;
4876     case blue_part:mp_print(mp, "bluepart"); break;
4877     case cyan_part:mp_print(mp, "cyanpart"); break;
4878     case magenta_part:mp_print(mp, "magentapart"); break;
4879     case yellow_part:mp_print(mp, "yellowpart"); break;
4880     case black_part:mp_print(mp, "blackpart"); break;
4881     case grey_part:mp_print(mp, "greypart"); break;
4882     case color_model_part:mp_print(mp, "colormodel"); break;
4883     case font_part:mp_print(mp, "fontpart"); break;
4884     case text_part:mp_print(mp, "textpart"); break;
4885     case path_part:mp_print(mp, "pathpart"); break;
4886     case pen_part:mp_print(mp, "penpart"); break;
4887     case dash_part:mp_print(mp, "dashpart"); break;
4888     case sqrt_op:mp_print(mp, "sqrt"); break;
4889     case m_exp_op:mp_print(mp, "mexp"); break;
4890     case m_log_op:mp_print(mp, "mlog"); break;
4891     case sin_d_op:mp_print(mp, "sind"); break;
4892     case cos_d_op:mp_print(mp, "cosd"); break;
4893     case floor_op:mp_print(mp, "floor"); break;
4894     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4895     case char_exists_op:mp_print(mp, "charexists"); break;
4896     case font_size:mp_print(mp, "fontsize"); break;
4897     case ll_corner_op:mp_print(mp, "llcorner"); break;
4898     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4899     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4900     case ur_corner_op:mp_print(mp, "urcorner"); break;
4901     case arc_length:mp_print(mp, "arclength"); break;
4902     case angle_op:mp_print(mp, "angle"); break;
4903     case cycle_op:mp_print(mp, "cycle"); break;
4904     case filled_op:mp_print(mp, "filled"); break;
4905     case stroked_op:mp_print(mp, "stroked"); break;
4906     case textual_op:mp_print(mp, "textual"); break;
4907     case clipped_op:mp_print(mp, "clipped"); break;
4908     case bounded_op:mp_print(mp, "bounded"); break;
4909     case plus:mp_print_char(mp, '+'); break;
4910     case minus:mp_print_char(mp, '-'); break;
4911     case times:mp_print_char(mp, '*'); break;
4912     case over:mp_print_char(mp, '/'); break;
4913     case pythag_add:mp_print(mp, "++"); break;
4914     case pythag_sub:mp_print(mp, "+-+"); break;
4915     case or_op:mp_print(mp, "or"); break;
4916     case and_op:mp_print(mp, "and"); break;
4917     case less_than:mp_print_char(mp, '<'); break;
4918     case less_or_equal:mp_print(mp, "<="); break;
4919     case greater_than:mp_print_char(mp, '>'); break;
4920     case greater_or_equal:mp_print(mp, ">="); break;
4921     case equal_to:mp_print_char(mp, '='); break;
4922     case unequal_to:mp_print(mp, "<>"); break;
4923     case concatenate:mp_print(mp, "&"); break;
4924     case rotated_by:mp_print(mp, "rotated"); break;
4925     case slanted_by:mp_print(mp, "slanted"); break;
4926     case scaled_by:mp_print(mp, "scaled"); break;
4927     case shifted_by:mp_print(mp, "shifted"); break;
4928     case transformed_by:mp_print(mp, "transformed"); break;
4929     case x_scaled:mp_print(mp, "xscaled"); break;
4930     case y_scaled:mp_print(mp, "yscaled"); break;
4931     case z_scaled:mp_print(mp, "zscaled"); break;
4932     case in_font:mp_print(mp, "infont"); break;
4933     case intersect:mp_print(mp, "intersectiontimes"); break;
4934     case substring_of:mp_print(mp, "substring"); break;
4935     case subpath_of:mp_print(mp, "subpath"); break;
4936     case direction_time_of:mp_print(mp, "directiontime"); break;
4937     case point_of:mp_print(mp, "point"); break;
4938     case precontrol_of:mp_print(mp, "precontrol"); break;
4939     case postcontrol_of:mp_print(mp, "postcontrol"); break;
4940     case pen_offset_of:mp_print(mp, "penoffset"); break;
4941     case arc_time_of:mp_print(mp, "arctime"); break;
4942     case mp_version:mp_print(mp, "mpversion"); break;
4943     case envelope_of:mp_print(mp, "envelope"); break;
4944     default: mp_print(mp, ".."); break;
4945     }
4946   }
4947 }
4948
4949 @ \MP\ also has a bunch of internal parameters that a user might want to
4950 fuss with. Every such parameter has an identifying code number, defined here.
4951
4952 @<Types...@>=
4953 enum mp_given_internal {
4954   mp_tracing_titles=1, /* show titles online when they appear */
4955   mp_tracing_equations, /* show each variable when it becomes known */
4956   mp_tracing_capsules, /* show capsules too */
4957   mp_tracing_choices, /* show the control points chosen for paths */
4958   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
4959   mp_tracing_commands, /* show commands and operations before they are performed */
4960   mp_tracing_restores, /* show when a variable or internal is restored */
4961   mp_tracing_macros, /* show macros before they are expanded */
4962   mp_tracing_output, /* show digitized edges as they are output */
4963   mp_tracing_stats, /* show memory usage at end of job */
4964   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
4965   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
4966   mp_year, /* the current year (e.g., 1984) */
4967   mp_month, /* the current month (e.g., 3 $\equiv$ March) */
4968   mp_day, /* the current day of the month */
4969   mp_time, /* the number of minutes past midnight when this job started */
4970   mp_char_code, /* the number of the next character to be output */
4971   mp_char_ext, /* the extension code of the next character to be output */
4972   mp_char_wd, /* the width of the next character to be output */
4973   mp_char_ht, /* the height of the next character to be output */
4974   mp_char_dp, /* the depth of the next character to be output */
4975   mp_char_ic, /* the italic correction of the next character to be output */
4976   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
4977   mp_pausing, /* positive to display lines on the terminal before they are read */
4978   mp_showstopping, /* positive to stop after each \&{show} command */
4979   mp_fontmaking, /* positive if font metric output is to be produced */
4980   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
4981   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
4982   mp_miterlimit, /* controls miter length as in \ps */
4983   mp_warning_check, /* controls error message when variable value is large */
4984   mp_boundary_char, /* the right boundary character for ligatures */
4985   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
4986   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
4987   mp_default_color_model, /* the default color model for unspecified items */
4988   mp_restore_clip_color,
4989   mp_procset, /* wether or not create PostScript command shortcuts */
4990   mp_gtroffmode  /* whether the user specified |-troff| on the command line */
4991 };
4992
4993 @
4994
4995 @d max_given_internal mp_gtroffmode
4996
4997 @<Glob...@>=
4998 scaled *internal;  /* the values of internal quantities */
4999 char **int_name;  /* their names */
5000 int int_ptr;  /* the maximum internal quantity defined so far */
5001 int max_internal; /* current maximum number of internal quantities */
5002
5003 @ @<Option variables@>=
5004 int troff_mode; 
5005
5006 @ @<Allocate or initialize ...@>=
5007 mp->max_internal=2*max_given_internal;
5008 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5009 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5010 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5011
5012 @ @<Exported function ...@>=
5013 int mp_troff_mode(MP mp);
5014
5015 @ @c
5016 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5017
5018 @ @<Set initial ...@>=
5019 for (k=0;k<= mp->max_internal; k++ ) { 
5020    mp->internal[k]=0; 
5021    mp->int_name[k]=NULL; 
5022 }
5023 mp->int_ptr=max_given_internal;
5024
5025 @ The symbolic names for internal quantities are put into \MP's hash table
5026 by using a routine called |primitive|, which will be defined later. Let us
5027 enter them now, so that we don't have to list all those names again
5028 anywhere else.
5029
5030 @<Put each of \MP's primitives into the hash table@>=
5031 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5032 @:tracingtitles_}{\&{tracingtitles} primitive@>
5033 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5034 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5035 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5036 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5037 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5038 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5039 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5040 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5041 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5042 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5043 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5044 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5045 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5046 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5047 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5048 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5049 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5050 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5051 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5052 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5053 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5054 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5055 mp_primitive(mp, "year",internal_quantity,mp_year);
5056 @:mp_year_}{\&{year} primitive@>
5057 mp_primitive(mp, "month",internal_quantity,mp_month);
5058 @:mp_month_}{\&{month} primitive@>
5059 mp_primitive(mp, "day",internal_quantity,mp_day);
5060 @:mp_day_}{\&{day} primitive@>
5061 mp_primitive(mp, "time",internal_quantity,mp_time);
5062 @:time_}{\&{time} primitive@>
5063 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5064 @:mp_char_code_}{\&{charcode} primitive@>
5065 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5066 @:mp_char_ext_}{\&{charext} primitive@>
5067 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5068 @:mp_char_wd_}{\&{charwd} primitive@>
5069 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5070 @:mp_char_ht_}{\&{charht} primitive@>
5071 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5072 @:mp_char_dp_}{\&{chardp} primitive@>
5073 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5074 @:mp_char_ic_}{\&{charic} primitive@>
5075 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5076 @:mp_design_size_}{\&{designsize} primitive@>
5077 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5078 @:mp_pausing_}{\&{pausing} primitive@>
5079 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5080 @:mp_showstopping_}{\&{showstopping} primitive@>
5081 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5082 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5083 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5084 @:mp_linejoin_}{\&{linejoin} primitive@>
5085 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5086 @:mp_linecap_}{\&{linecap} primitive@>
5087 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5088 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5089 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5090 @:mp_warning_check_}{\&{warningcheck} primitive@>
5091 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5092 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5093 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5094 @:mp_prologues_}{\&{prologues} primitive@>
5095 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5096 @:mp_true_corners_}{\&{truecorners} primitive@>
5097 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5098 @:mp_procset_}{\&{mpprocset} primitive@>
5099 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5100 @:troffmode_}{\&{troffmode} primitive@>
5101 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5102 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5103 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5104 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5105
5106 @ Colors can be specified in four color models. In the special
5107 case of |no_model|, MetaPost does not output any color operator to
5108 the postscript output.
5109
5110 Note: these values are passed directly on to |with_option|. This only
5111 works because the other possible values passed to |with_option| are
5112 8 and 10 respectively (from |with_pen| and |with_picture|).
5113
5114 There is a first state, that is only used for |gs_colormodel|. It flags
5115 the fact that there has not been any kind of color specification by
5116 the user so far in the game.
5117
5118 @<Types...@>=
5119 enum mp_color_model {
5120   mp_no_model=1,
5121   mp_grey_model=3,
5122   mp_rgb_model=5,
5123   mp_cmyk_model=7,
5124   mp_uninitialized_model=9
5125 };
5126
5127
5128 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5129 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5130 mp->internal[mp_restore_clip_color]=unity;
5131
5132 @ Well, we do have to list the names one more time, for use in symbolic
5133 printouts.
5134
5135 @<Initialize table...@>=
5136 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5137 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5138 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5139 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5140 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5141 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5142 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5143 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5144 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5145 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5146 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5147 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5148 mp->int_name[mp_year]=xstrdup("year");
5149 mp->int_name[mp_month]=xstrdup("month");
5150 mp->int_name[mp_day]=xstrdup("day");
5151 mp->int_name[mp_time]=xstrdup("time");
5152 mp->int_name[mp_char_code]=xstrdup("charcode");
5153 mp->int_name[mp_char_ext]=xstrdup("charext");
5154 mp->int_name[mp_char_wd]=xstrdup("charwd");
5155 mp->int_name[mp_char_ht]=xstrdup("charht");
5156 mp->int_name[mp_char_dp]=xstrdup("chardp");
5157 mp->int_name[mp_char_ic]=xstrdup("charic");
5158 mp->int_name[mp_design_size]=xstrdup("designsize");
5159 mp->int_name[mp_pausing]=xstrdup("pausing");
5160 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5161 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5162 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5163 mp->int_name[mp_linecap]=xstrdup("linecap");
5164 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5165 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5166 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5167 mp->int_name[mp_prologues]=xstrdup("prologues");
5168 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5169 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5170 mp->int_name[mp_procset]=xstrdup("mpprocset");
5171 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5172 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5173
5174 @ The following procedure, which is called just before \MP\ initializes its
5175 input and output, establishes the initial values of the date and time.
5176 @^system dependencies@>
5177
5178 Note that the values are |scaled| integers. Hence \MP\ can no longer
5179 be used after the year 32767.
5180
5181 @c 
5182 void mp_fix_date_and_time (MP mp) { 
5183   time_t aclock = time ((time_t *) 0);
5184   struct tm *tmptr = localtime (&aclock);
5185   mp->internal[mp_time]=
5186       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5187   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5188   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5189   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5190 }
5191
5192 @ @<Declarations@>=
5193 void mp_fix_date_and_time (MP mp) ;
5194
5195 @ \MP\ is occasionally supposed to print diagnostic information that
5196 goes only into the transcript file, unless |mp_tracing_online| is positive.
5197 Now that we have defined |mp_tracing_online| we can define
5198 two routines that adjust the destination of print commands:
5199
5200 @<Declarations@>=
5201 void mp_begin_diagnostic (MP mp) ;
5202 void mp_end_diagnostic (MP mp,boolean blank_line);
5203 void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) ;
5204
5205 @ @<Basic printing...@>=
5206 @<Declare a function called |true_line|@>
5207 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5208   mp->old_setting=mp->selector;
5209   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5210     decr(mp->selector);
5211     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5212   }
5213 }
5214 @#
5215 void mp_end_diagnostic (MP mp,boolean blank_line) {
5216   /* restore proper conditions after tracing */
5217   mp_print_nl(mp, "");
5218   if ( blank_line ) mp_print_ln(mp);
5219   mp->selector=mp->old_setting;
5220 }
5221
5222
5223
5224 @<Glob...@>=
5225 unsigned int old_setting;
5226
5227 @ We will occasionally use |begin_diagnostic| in connection with line-number
5228 printing, as follows. (The parameter |s| is typically |"Path"| or
5229 |"Cycle spec"|, etc.)
5230
5231 @<Basic printing...@>=
5232 void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) { 
5233   mp_begin_diagnostic(mp);
5234   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5235   mp_print(mp, " at line "); 
5236   mp_print_int(mp, mp_true_line(mp));
5237   mp_print(mp, t); mp_print_char(mp, ':');
5238 }
5239
5240 @ The 256 |ASCII_code| characters are grouped into classes by means of
5241 the |char_class| table. Individual class numbers have no semantic
5242 or syntactic significance, except in a few instances defined here.
5243 There's also |max_class|, which can be used as a basis for additional
5244 class numbers in nonstandard extensions of \MP.
5245
5246 @d digit_class 0 /* the class number of \.{0123456789} */
5247 @d period_class 1 /* the class number of `\..' */
5248 @d space_class 2 /* the class number of spaces and nonstandard characters */
5249 @d percent_class 3 /* the class number of `\.\%' */
5250 @d string_class 4 /* the class number of `\."' */
5251 @d right_paren_class 8 /* the class number of `\.)' */
5252 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5253 @d letter_class 9 /* letters and the underline character */
5254 @d left_bracket_class 17 /* `\.[' */
5255 @d right_bracket_class 18 /* `\.]' */
5256 @d invalid_class 20 /* bad character in the input */
5257 @d max_class 20 /* the largest class number */
5258
5259 @<Glob...@>=
5260 int char_class[256]; /* the class numbers */
5261
5262 @ If changes are made to accommodate non-ASCII character sets, they should
5263 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5264 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5265 @^system dependencies@>
5266
5267 @<Set initial ...@>=
5268 for (k='0';k<='9';k++) 
5269   mp->char_class[k]=digit_class;
5270 mp->char_class['.']=period_class;
5271 mp->char_class[' ']=space_class;
5272 mp->char_class['%']=percent_class;
5273 mp->char_class['"']=string_class;
5274 mp->char_class[',']=5;
5275 mp->char_class[';']=6;
5276 mp->char_class['(']=7;
5277 mp->char_class[')']=right_paren_class;
5278 for (k='A';k<= 'Z';k++ )
5279   mp->char_class[k]=letter_class;
5280 for (k='a';k<='z';k++) 
5281   mp->char_class[k]=letter_class;
5282 mp->char_class['_']=letter_class;
5283 mp->char_class['<']=10;
5284 mp->char_class['=']=10;
5285 mp->char_class['>']=10;
5286 mp->char_class[':']=10;
5287 mp->char_class['|']=10;
5288 mp->char_class['`']=11;
5289 mp->char_class['\'']=11;
5290 mp->char_class['+']=12;
5291 mp->char_class['-']=12;
5292 mp->char_class['/']=13;
5293 mp->char_class['*']=13;
5294 mp->char_class['\\']=13;
5295 mp->char_class['!']=14;
5296 mp->char_class['?']=14;
5297 mp->char_class['#']=15;
5298 mp->char_class['&']=15;
5299 mp->char_class['@@']=15;
5300 mp->char_class['$']=15;
5301 mp->char_class['^']=16;
5302 mp->char_class['~']=16;
5303 mp->char_class['[']=left_bracket_class;
5304 mp->char_class[']']=right_bracket_class;
5305 mp->char_class['{']=19;
5306 mp->char_class['}']=19;
5307 for (k=0;k<' ';k++)
5308   mp->char_class[k]=invalid_class;
5309 mp->char_class['\t']=space_class;
5310 mp->char_class['\f']=space_class;
5311 for (k=127;k<=255;k++)
5312   mp->char_class[k]=invalid_class;
5313
5314 @* \[13] The hash table.
5315 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5316 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5317 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5318 table, it is never removed.
5319
5320 The actual sequence of characters forming a symbolic token is
5321 stored in the |str_pool| array together with all the other strings. An
5322 auxiliary array |hash| consists of items with two halfword fields per
5323 word. The first of these, called |next(p)|, points to the next identifier
5324 belonging to the same coalesced list as the identifier corresponding to~|p|;
5325 and the other, called |text(p)|, points to the |str_start| entry for
5326 |p|'s identifier. If position~|p| of the hash table is empty, we have
5327 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5328 hash list, we have |next(p)=0|.
5329
5330 An auxiliary pointer variable called |hash_used| is maintained in such a
5331 way that all locations |p>=hash_used| are nonempty. The global variable
5332 |st_count| tells how many symbolic tokens have been defined, if statistics
5333 are being kept.
5334
5335 The first 256 locations of |hash| are reserved for symbols of length one.
5336
5337 There's a parallel array called |eqtb| that contains the current equivalent
5338 values of each symbolic token. The entries of this array consist of
5339 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5340 piece of information that qualifies the |eq_type|).
5341
5342 @d next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5343 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5344 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5345 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5346 @d hash_base 257 /* hashing actually starts here */
5347 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5348
5349 @<Glob...@>=
5350 pointer hash_used; /* allocation pointer for |hash| */
5351 integer st_count; /* total number of known identifiers */
5352
5353 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5354 since they are used in error recovery.
5355
5356 @d hash_top (hash_base+mp->hash_size) /* the first location of the frozen area */
5357 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5358 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5359 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5360 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5361 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5362 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5363 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5364 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5365 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5366 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5367 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5368 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5369 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5370 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5371 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5372 @d hash_end (hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5373
5374 @<Glob...@>=
5375 two_halves *hash; /* the hash table */
5376 two_halves *eqtb; /* the equivalents */
5377
5378 @ @<Allocate or initialize ...@>=
5379 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5380 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5381
5382 @ @<Dealloc variables@>=
5383 xfree(mp->hash);
5384 xfree(mp->eqtb);
5385
5386 @ @<Set init...@>=
5387 next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5388 for (k=2;k<=hash_end;k++)  { 
5389   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5390 }
5391
5392 @ @<Initialize table entries...@>=
5393 mp->hash_used=frozen_inaccessible; /* nothing is used */
5394 mp->st_count=0;
5395 text(frozen_bad_vardef)=intern("a bad variable");
5396 text(frozen_etex)=intern("etex");
5397 text(frozen_mpx_break)=intern("mpxbreak");
5398 text(frozen_fi)=intern("fi");
5399 text(frozen_end_group)=intern("endgroup");
5400 text(frozen_end_def)=intern("enddef");
5401 text(frozen_end_for)=intern("endfor");
5402 text(frozen_semicolon)=intern(";");
5403 text(frozen_colon)=intern(":");
5404 text(frozen_slash)=intern("/");
5405 text(frozen_left_bracket)=intern("[");
5406 text(frozen_right_delimiter)=intern(")");
5407 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5408 eq_type(frozen_right_delimiter)=right_delimiter;
5409
5410 @ @<Check the ``constant'' values...@>=
5411 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5412
5413 @ Here is the subroutine that searches the hash table for an identifier
5414 that matches a given string of length~|l| appearing in |buffer[j..
5415 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5416 will always be found, and the corresponding hash table address
5417 will be returned.
5418
5419 @c 
5420 pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5421   integer h; /* hash code */
5422   pointer p; /* index in |hash| array */
5423   pointer k; /* index in |buffer| array */
5424   if (l==1) {
5425     @<Treat special case of length 1 and |break|@>;
5426   }
5427   @<Compute the hash code |h|@>;
5428   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5429   while (true)  { 
5430         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5431       break;
5432     if ( next(p)==0 ) {
5433       @<Insert a new symbolic token after |p|, then
5434         make |p| point to it and |break|@>;
5435     }
5436     p=next(p);
5437   }
5438   return p;
5439 }
5440
5441 @ @<Treat special case of length 1...@>=
5442  p=mp->buffer[j]+1; text(p)=p-1; return p;
5443
5444
5445 @ @<Insert a new symbolic...@>=
5446 {
5447 if ( text(p)>0 ) { 
5448   do {  
5449     if ( hash_is_full )
5450       mp_overflow(mp, "hash size",mp->hash_size);
5451 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5452     decr(mp->hash_used);
5453   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5454   next(p)=mp->hash_used; 
5455   p=mp->hash_used;
5456 }
5457 str_room(l);
5458 for (k=j;k<=j+l-1;k++) {
5459   append_char(mp->buffer[k]);
5460 }
5461 text(p)=mp_make_string(mp); 
5462 mp->str_ref[text(p)]=max_str_ref;
5463 incr(mp->st_count);
5464 break;
5465 }
5466
5467
5468 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5469 should be a prime number.  The theory of hashing tells us to expect fewer
5470 than two table probes, on the average, when the search is successful.
5471 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5472 @^Vitter, Jeffrey Scott@>
5473
5474 @<Compute the hash code |h|@>=
5475 h=mp->buffer[j];
5476 for (k=j+1;k<=j+l-1;k++){ 
5477   h=h+h+mp->buffer[k];
5478   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5479 }
5480
5481 @ @<Search |eqtb| for equivalents equal to |p|@>=
5482 for (q=1;q<=hash_end;q++) { 
5483   if ( equiv(q)==p ) { 
5484     mp_print_nl(mp, "EQUIV("); 
5485     mp_print_int(mp, q); 
5486     mp_print_char(mp, ')');
5487   }
5488 }
5489
5490 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5491 table, together with their command code (which will be the |eq_type|)
5492 and an operand (which will be the |equiv|). The |primitive| procedure
5493 does this, in a way that no \MP\ user can. The global value |cur_sym|
5494 contains the new |eqtb| pointer after |primitive| has acted.
5495
5496 @c 
5497 void mp_primitive (MP mp, const char *ss, halfword c, halfword o) {
5498   pool_pointer k; /* index into |str_pool| */
5499   small_number j; /* index into |buffer| */
5500   small_number l; /* length of the string */
5501   str_number s;
5502   s = intern(ss);
5503   k=mp->str_start[s]; l=str_stop(s)-k;
5504   /* we will move |s| into the (empty) |buffer| */
5505   for (j=0;j<=l-1;j++) {
5506     mp->buffer[j]=mp->str_pool[k+j];
5507   }
5508   mp->cur_sym=mp_id_lookup(mp, 0,l);
5509   if ( s>=256 ) { /* we don't want to have the string twice */
5510     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5511   };
5512   eq_type(mp->cur_sym)=c; 
5513   equiv(mp->cur_sym)=o;
5514 }
5515
5516
5517 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5518 by their |eq_type| alone. These primitives are loaded into the hash table
5519 as follows:
5520
5521 @<Put each of \MP's primitives into the hash table@>=
5522 mp_primitive(mp, "..",path_join,0);
5523 @:.._}{\.{..} primitive@>
5524 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5525 @:[ }{\.{[} primitive@>
5526 mp_primitive(mp, "]",right_bracket,0);
5527 @:] }{\.{]} primitive@>
5528 mp_primitive(mp, "}",right_brace,0);
5529 @:]]}{\.{\char`\}} primitive@>
5530 mp_primitive(mp, "{",left_brace,0);
5531 @:][}{\.{\char`\{} primitive@>
5532 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5533 @:: }{\.{:} primitive@>
5534 mp_primitive(mp, "::",double_colon,0);
5535 @::: }{\.{::} primitive@>
5536 mp_primitive(mp, "||:",bchar_label,0);
5537 @:::: }{\.{\char'174\char'174:} primitive@>
5538 mp_primitive(mp, ":=",assignment,0);
5539 @::=_}{\.{:=} primitive@>
5540 mp_primitive(mp, ",",comma,0);
5541 @:, }{\., primitive@>
5542 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5543 @:; }{\.; primitive@>
5544 mp_primitive(mp, "\\",relax,0);
5545 @:]]\\}{\.{\char`\\} primitive@>
5546 @#
5547 mp_primitive(mp, "addto",add_to_command,0);
5548 @:add_to_}{\&{addto} primitive@>
5549 mp_primitive(mp, "atleast",at_least,0);
5550 @:at_least_}{\&{atleast} primitive@>
5551 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5552 @:begin_group_}{\&{begingroup} primitive@>
5553 mp_primitive(mp, "controls",controls,0);
5554 @:controls_}{\&{controls} primitive@>
5555 mp_primitive(mp, "curl",curl_command,0);
5556 @:curl_}{\&{curl} primitive@>
5557 mp_primitive(mp, "delimiters",delimiters,0);
5558 @:delimiters_}{\&{delimiters} primitive@>
5559 mp_primitive(mp, "endgroup",end_group,0);
5560  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5561 @:endgroup_}{\&{endgroup} primitive@>
5562 mp_primitive(mp, "everyjob",every_job_command,0);
5563 @:every_job_}{\&{everyjob} primitive@>
5564 mp_primitive(mp, "exitif",exit_test,0);
5565 @:exit_if_}{\&{exitif} primitive@>
5566 mp_primitive(mp, "expandafter",expand_after,0);
5567 @:expand_after_}{\&{expandafter} primitive@>
5568 mp_primitive(mp, "interim",interim_command,0);
5569 @:interim_}{\&{interim} primitive@>
5570 mp_primitive(mp, "let",let_command,0);
5571 @:let_}{\&{let} primitive@>
5572 mp_primitive(mp, "newinternal",new_internal,0);
5573 @:new_internal_}{\&{newinternal} primitive@>
5574 mp_primitive(mp, "of",of_token,0);
5575 @:of_}{\&{of} primitive@>
5576 mp_primitive(mp, "randomseed",mp_random_seed,0);
5577 @:mp_random_seed_}{\&{randomseed} primitive@>
5578 mp_primitive(mp, "save",save_command,0);
5579 @:save_}{\&{save} primitive@>
5580 mp_primitive(mp, "scantokens",scan_tokens,0);
5581 @:scan_tokens_}{\&{scantokens} primitive@>
5582 mp_primitive(mp, "shipout",ship_out_command,0);
5583 @:ship_out_}{\&{shipout} primitive@>
5584 mp_primitive(mp, "skipto",skip_to,0);
5585 @:skip_to_}{\&{skipto} primitive@>
5586 mp_primitive(mp, "special",special_command,0);
5587 @:special}{\&{special} primitive@>
5588 mp_primitive(mp, "fontmapfile",special_command,1);
5589 @:fontmapfile}{\&{fontmapfile} primitive@>
5590 mp_primitive(mp, "fontmapline",special_command,2);
5591 @:fontmapline}{\&{fontmapline} primitive@>
5592 mp_primitive(mp, "step",step_token,0);
5593 @:step_}{\&{step} primitive@>
5594 mp_primitive(mp, "str",str_op,0);
5595 @:str_}{\&{str} primitive@>
5596 mp_primitive(mp, "tension",tension,0);
5597 @:tension_}{\&{tension} primitive@>
5598 mp_primitive(mp, "to",to_token,0);
5599 @:to_}{\&{to} primitive@>
5600 mp_primitive(mp, "until",until_token,0);
5601 @:until_}{\&{until} primitive@>
5602 mp_primitive(mp, "within",within_token,0);
5603 @:within_}{\&{within} primitive@>
5604 mp_primitive(mp, "write",write_command,0);
5605 @:write_}{\&{write} primitive@>
5606
5607 @ Each primitive has a corresponding inverse, so that it is possible to
5608 display the cryptic numeric contents of |eqtb| in symbolic form.
5609 Every call of |primitive| in this program is therefore accompanied by some
5610 straightforward code that forms part of the |print_cmd_mod| routine
5611 explained below.
5612
5613 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5614 case add_to_command:mp_print(mp, "addto"); break;
5615 case assignment:mp_print(mp, ":="); break;
5616 case at_least:mp_print(mp, "atleast"); break;
5617 case bchar_label:mp_print(mp, "||:"); break;
5618 case begin_group:mp_print(mp, "begingroup"); break;
5619 case colon:mp_print(mp, ":"); break;
5620 case comma:mp_print(mp, ","); break;
5621 case controls:mp_print(mp, "controls"); break;
5622 case curl_command:mp_print(mp, "curl"); break;
5623 case delimiters:mp_print(mp, "delimiters"); break;
5624 case double_colon:mp_print(mp, "::"); break;
5625 case end_group:mp_print(mp, "endgroup"); break;
5626 case every_job_command:mp_print(mp, "everyjob"); break;
5627 case exit_test:mp_print(mp, "exitif"); break;
5628 case expand_after:mp_print(mp, "expandafter"); break;
5629 case interim_command:mp_print(mp, "interim"); break;
5630 case left_brace:mp_print(mp, "{"); break;
5631 case left_bracket:mp_print(mp, "["); break;
5632 case let_command:mp_print(mp, "let"); break;
5633 case new_internal:mp_print(mp, "newinternal"); break;
5634 case of_token:mp_print(mp, "of"); break;
5635 case path_join:mp_print(mp, ".."); break;
5636 case mp_random_seed:mp_print(mp, "randomseed"); break;
5637 case relax:mp_print_char(mp, '\\'); break;
5638 case right_brace:mp_print(mp, "}"); break;
5639 case right_bracket:mp_print(mp, "]"); break;
5640 case save_command:mp_print(mp, "save"); break;
5641 case scan_tokens:mp_print(mp, "scantokens"); break;
5642 case semicolon:mp_print(mp, ";"); break;
5643 case ship_out_command:mp_print(mp, "shipout"); break;
5644 case skip_to:mp_print(mp, "skipto"); break;
5645 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5646                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5647                  mp_print(mp, "special"); break;
5648 case step_token:mp_print(mp, "step"); break;
5649 case str_op:mp_print(mp, "str"); break;
5650 case tension:mp_print(mp, "tension"); break;
5651 case to_token:mp_print(mp, "to"); break;
5652 case until_token:mp_print(mp, "until"); break;
5653 case within_token:mp_print(mp, "within"); break;
5654 case write_command:mp_print(mp, "write"); break;
5655
5656 @ We will deal with the other primitives later, at some point in the program
5657 where their |eq_type| and |equiv| values are more meaningful.  For example,
5658 the primitives for macro definitions will be loaded when we consider the
5659 routines that define macros.
5660 It is easy to find where each particular
5661 primitive was treated by looking in the index at the end; for example, the
5662 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5663
5664 @* \[14] Token lists.
5665 A \MP\ token is either symbolic or numeric or a string, or it denotes
5666 a macro parameter or capsule; so there are five corresponding ways to encode it
5667 @^token@>
5668 internally: (1)~A symbolic token whose hash code is~|p|
5669 is represented by the number |p|, in the |info| field of a single-word
5670 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5671 represented in a two-word node of~|mem|; the |type| field is |known|,
5672 the |name_type| field is |token|, and the |value| field holds~|v|.
5673 The fact that this token appears in a two-word node rather than a
5674 one-word node is, of course, clear from the node address.
5675 (3)~A string token is also represented in a two-word node; the |type|
5676 field is |mp_string_type|, the |name_type| field is |token|, and the
5677 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5678 |name_type=capsule|, and their |type| and |value| fields represent
5679 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5680 are like symbolic tokens in that they appear in |info| fields of
5681 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5682 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5683 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5684 Actual values of these parameters are kept in a separate stack, as we will
5685 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5686 of course, chosen so that there will be no confusion between symbolic
5687 tokens and parameters of various types.
5688
5689 Note that
5690 the `\\{type}' field of a node has nothing to do with ``type'' in a
5691 printer's sense. It's curious that the same word is used in such different ways.
5692
5693 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5694 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5695 @d token_node_size 2 /* the number of words in a large token node */
5696 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5697 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5698 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5699 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5700 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5701
5702 @<Check the ``constant''...@>=
5703 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5704
5705 @ We have set aside a two word node beginning at |null| so that we can have
5706 |value(null)=0|.  We will make use of this coincidence later.
5707
5708 @<Initialize table entries...@>=
5709 link(null)=null; value(null)=0;
5710
5711 @ A numeric token is created by the following trivial routine.
5712
5713 @c 
5714 pointer mp_new_num_tok (MP mp,scaled v) {
5715   pointer p; /* the new node */
5716   p=mp_get_node(mp, token_node_size); value(p)=v;
5717   type(p)=mp_known; name_type(p)=mp_token; 
5718   return p;
5719 }
5720
5721 @ A token list is a singly linked list of nodes in |mem|, where
5722 each node contains a token and a link.  Here's a subroutine that gets rid
5723 of a token list when it is no longer needed.
5724
5725 @c void mp_flush_token_list (MP mp,pointer p) {
5726   pointer q; /* the node being recycled */
5727   while ( p!=null ) { 
5728     q=p; p=link(p);
5729     if ( q>=mp->hi_mem_min ) {
5730      free_avail(q);
5731     } else { 
5732       switch (type(q)) {
5733       case mp_vacuous: case mp_boolean_type: case mp_known:
5734         break;
5735       case mp_string_type:
5736         delete_str_ref(value(q));
5737         break;
5738       case unknown_types: case mp_pen_type: case mp_path_type: 
5739       case mp_picture_type: case mp_pair_type: case mp_color_type:
5740       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5741       case mp_proto_dependent: case mp_independent:
5742         mp_recycle_value(mp,q);
5743         break;
5744       default: mp_confusion(mp, "token");
5745 @:this can't happen token}{\quad token@>
5746       }
5747       mp_free_node(mp, q,token_node_size);
5748     }
5749   }
5750 }
5751
5752 @ The procedure |show_token_list|, which prints a symbolic form of
5753 the token list that starts at a given node |p|, illustrates these
5754 conventions. The token list being displayed should not begin with a reference
5755 count. However, the procedure is intended to be fairly robust, so that if the
5756 memory links are awry or if |p| is not really a pointer to a token list,
5757 almost nothing catastrophic can happen.
5758
5759 An additional parameter |q| is also given; this parameter is either null
5760 or it points to a node in the token list where a certain magic computation
5761 takes place that will be explained later. (Basically, |q| is non-null when
5762 we are printing the two-line context information at the time of an error
5763 message; |q| marks the place corresponding to where the second line
5764 should begin.)
5765
5766 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5767 of printing exceeds a given limit~|l|; the length of printing upon entry is
5768 assumed to be a given amount called |null_tally|. (Note that
5769 |show_token_list| sometimes uses itself recursively to print
5770 variable names within a capsule.)
5771 @^recursion@>
5772
5773 Unusual entries are printed in the form of all-caps tokens
5774 preceded by a space, e.g., `\.{\char`\ BAD}'.
5775
5776 @<Declare the procedure called |show_token_list|@>=
5777 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5778                          integer null_tally) ;
5779
5780 @ @c
5781 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5782                          integer null_tally) {
5783   small_number class,c; /* the |char_class| of previous and new tokens */
5784   integer r,v; /* temporary registers */
5785   class=percent_class;
5786   mp->tally=null_tally;
5787   while ( (p!=null) && (mp->tally<l) ) { 
5788     if ( p==q ) 
5789       @<Do magic computation@>;
5790     @<Display token |p| and set |c| to its class;
5791       but |return| if there are problems@>;
5792     class=c; p=link(p);
5793   }
5794   if ( p!=null ) 
5795      mp_print(mp, " ETC.");
5796 @.ETC@>
5797   return;
5798 }
5799
5800 @ @<Display token |p| and set |c| to its class...@>=
5801 c=letter_class; /* the default */
5802 if ( (p<0)||(p>mp->mem_end) ) { 
5803   mp_print(mp, " CLOBBERED"); return;
5804 @.CLOBBERED@>
5805 }
5806 if ( p<mp->hi_mem_min ) { 
5807   @<Display two-word token@>;
5808 } else { 
5809   r=info(p);
5810   if ( r>=expr_base ) {
5811      @<Display a parameter token@>;
5812   } else {
5813     if ( r<1 ) {
5814       if ( r==0 ) { 
5815         @<Display a collective subscript@>
5816       } else {
5817         mp_print(mp, " IMPOSSIBLE");
5818 @.IMPOSSIBLE@>
5819       }
5820     } else { 
5821       r=text(r);
5822       if ( (r<0)||(r>mp->max_str_ptr) ) {
5823         mp_print(mp, " NONEXISTENT");
5824 @.NONEXISTENT@>
5825       } else {
5826        @<Print string |r| as a symbolic token
5827         and set |c| to its class@>;
5828       }
5829     }
5830   }
5831 }
5832
5833 @ @<Display two-word token@>=
5834 if ( name_type(p)==mp_token ) {
5835   if ( type(p)==mp_known ) {
5836     @<Display a numeric token@>;
5837   } else if ( type(p)!=mp_string_type ) {
5838     mp_print(mp, " BAD");
5839 @.BAD@>
5840   } else { 
5841     mp_print_char(mp, '"'); mp_print_str(mp, value(p)); mp_print_char(mp, '"');
5842     c=string_class;
5843   }
5844 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5845   mp_print(mp, " BAD");
5846 } else { 
5847   mp_print_capsule(mp,p); c=right_paren_class;
5848 }
5849
5850 @ @<Display a numeric token@>=
5851 if ( class==digit_class ) 
5852   mp_print_char(mp, ' ');
5853 v=value(p);
5854 if ( v<0 ){ 
5855   if ( class==left_bracket_class ) 
5856     mp_print_char(mp, ' ');
5857   mp_print_char(mp, '['); mp_print_scaled(mp, v); mp_print_char(mp, ']');
5858   c=right_bracket_class;
5859 } else { 
5860   mp_print_scaled(mp, v); c=digit_class;
5861 }
5862
5863
5864 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5865 But we will see later (in the |print_variable_name| routine) that
5866 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5867
5868 @<Display a collective subscript@>=
5869 {
5870 if ( class==left_bracket_class ) 
5871   mp_print_char(mp, ' ');
5872 mp_print(mp, "[]"); c=right_bracket_class;
5873 }
5874
5875 @ @<Display a parameter token@>=
5876 {
5877 if ( r<suffix_base ) { 
5878   mp_print(mp, "(EXPR"); r=r-(expr_base);
5879 @.EXPR@>
5880 } else if ( r<text_base ) { 
5881   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5882 @.SUFFIX@>
5883 } else { 
5884   mp_print(mp, "(TEXT"); r=r-(text_base);
5885 @.TEXT@>
5886 }
5887 mp_print_int(mp, r); mp_print_char(mp, ')'); c=right_paren_class;
5888 }
5889
5890
5891 @ @<Print string |r| as a symbolic token...@>=
5892
5893 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5894 if ( c==class ) {
5895   switch (c) {
5896   case letter_class:mp_print_char(mp, '.'); break;
5897   case isolated_classes: break;
5898   default: mp_print_char(mp, ' '); break;
5899   }
5900 }
5901 mp_print_str(mp, r);
5902 }
5903
5904 @ @<Declarations@>=
5905 void mp_print_capsule (MP mp, pointer p);
5906
5907 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5908 void mp_print_capsule (MP mp, pointer p) { 
5909   mp_print_char(mp, '('); mp_print_exp(mp,p,0); mp_print_char(mp, ')');
5910 }
5911
5912 @ Macro definitions are kept in \MP's memory in the form of token lists
5913 that have a few extra one-word nodes at the beginning.
5914
5915 The first node contains a reference count that is used to tell when the
5916 list is no longer needed. To emphasize the fact that a reference count is
5917 present, we shall refer to the |info| field of this special node as the
5918 |ref_count| field.
5919 @^reference counts@>
5920
5921 The next node or nodes after the reference count serve to describe the
5922 formal parameters. They consist of zero or more parameter tokens followed
5923 by a code for the type of macro.
5924
5925 @d ref_count info
5926   /* reference count preceding a macro definition or picture header */
5927 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5928 @d general_macro 0 /* preface to a macro defined with a parameter list */
5929 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5930 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5931 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5932 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5933 @d of_macro 5 /* preface to a macro with
5934   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5935 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5936 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5937
5938 @c 
5939 void mp_delete_mac_ref (MP mp,pointer p) {
5940   /* |p| points to the reference count of a macro list that is
5941     losing one reference */
5942   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
5943   else decr(ref_count(p));
5944 }
5945
5946 @ The following subroutine displays a macro, given a pointer to its
5947 reference count.
5948
5949 @c 
5950 @<Declare the procedure called |print_cmd_mod|@>
5951 void mp_show_macro (MP mp, pointer p, integer q, integer l) {
5952   pointer r; /* temporary storage */
5953   p=link(p); /* bypass the reference count */
5954   while ( info(p)>text_macro ){ 
5955     r=link(p); link(p)=null;
5956     mp_show_token_list(mp, p,null,l,0); link(p)=r; p=r;
5957     if ( l>0 ) l=l-mp->tally; else return;
5958   } /* control printing of `\.{ETC.}' */
5959 @.ETC@>
5960   mp->tally=0;
5961   switch(info(p)) {
5962   case general_macro:mp_print(mp, "->"); break;
5963 @.->@>
5964   case primary_macro: case secondary_macro: case tertiary_macro:
5965     mp_print_char(mp, '<');
5966     mp_print_cmd_mod(mp, param_type,info(p)); 
5967     mp_print(mp, ">->");
5968     break;
5969   case expr_macro:mp_print(mp, "<expr>->"); break;
5970   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
5971   case suffix_macro:mp_print(mp, "<suffix>->"); break;
5972   case text_macro:mp_print(mp, "<text>->"); break;
5973   } /* there are no other cases */
5974   mp_show_token_list(mp, link(p),q,l-mp->tally,0);
5975 }
5976
5977 @* \[15] Data structures for variables.
5978 The variables of \MP\ programs can be simple, like `\.x', or they can
5979 combine the structural properties of arrays and records, like `\.{x20a.b}'.
5980 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
5981 example, `\.{boolean} \.{x[]a.b}'. It's time for us to study how such
5982 things are represented inside of the computer.
5983
5984 Each variable value occupies two consecutive words, either in a two-word
5985 node called a value node, or as a two-word subfield of a larger node.  One
5986 of those two words is called the |value| field; it is an integer,
5987 containing either a |scaled| numeric value or the representation of some
5988 other type of quantity. (It might also be subdivided into halfwords, in
5989 which case it is referred to by other names instead of |value|.) The other
5990 word is broken into subfields called |type|, |name_type|, and |link|.  The
5991 |type| field is a quarterword that specifies the variable's type, and
5992 |name_type| is a quarterword from which \MP\ can reconstruct the
5993 variable's name (sometimes by using the |link| field as well).  Thus, only
5994 1.25 words are actually devoted to the value itself; the other
5995 three-quarters of a word are overhead, but they aren't wasted because they
5996 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
5997
5998 In this section we shall be concerned only with the structural aspects of
5999 variables, not their values. Later parts of the program will change the
6000 |type| and |value| fields, but we shall treat those fields as black boxes
6001 whose contents should not be touched.
6002
6003 However, if the |type| field is |mp_structured|, there is no |value| field,
6004 and the second word is broken into two pointer fields called |attr_head|
6005 and |subscr_head|. Those fields point to additional nodes that
6006 contain structural information, as we shall see.
6007
6008 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6009 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
6010 @d subscr_head(A)   link(subscr_head_loc((A))) /* pointer to subscript info */
6011 @d value_node_size 2 /* the number of words in a value node */
6012
6013 @ An attribute node is three words long. Two of these words contain |type|
6014 and |value| fields as described above, and the third word contains
6015 additional information:  There is an |attr_loc| field, which contains the
6016 hash address of the token that names this attribute; and there's also a
6017 |parent| field, which points to the value node of |mp_structured| type at the
6018 next higher level (i.e., at the level to which this attribute is
6019 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6020 |link| field points to the next attribute with the same parent; these are
6021 arranged in increasing order, so that |attr_loc(link(p))>attr_loc(p)|. The
6022 final attribute node links to the constant |end_attr|, whose |attr_loc|
6023 field is greater than any legal hash address. The |attr_head| in the
6024 parent points to a node whose |name_type| is |mp_structured_root|; this
6025 node represents the null attribute, i.e., the variable that is relevant
6026 when no attributes are attached to the parent. The |attr_head| node
6027 has the fields of either
6028 a value node, a subscript node, or an attribute node, depending on what
6029 the parent would be if it were not structured; but the subscript and
6030 attribute fields are ignored, so it effectively contains only the data of
6031 a value node. The |link| field in this special node points to an attribute
6032 node whose |attr_loc| field is zero; the latter node represents a collective
6033 subscript `\.{[]}' attached to the parent, and its |link| field points to
6034 the first non-special attribute node (or to |end_attr| if there are none).
6035
6036 A subscript node likewise occupies three words, with |type| and |value| fields
6037 plus extra information; its |name_type| is |subscr|. In this case the
6038 third word is called the |subscript| field, which is a |scaled| integer.
6039 The |link| field points to the subscript node with the next larger
6040 subscript, if any; otherwise the |link| points to the attribute node
6041 for collective subscripts at this level. We have seen that the latter node
6042 contains an upward pointer, so that the parent can be deduced.
6043
6044 The |name_type| in a parent-less value node is |root|, and the |link|
6045 is the hash address of the token that names this value.
6046
6047 In other words, variables have a hierarchical structure that includes
6048 enough threads running around so that the program is able to move easily
6049 between siblings, parents, and children. An example should be helpful:
6050 (The reader is advised to draw a picture while reading the following
6051 description, since that will help to firm up the ideas.)
6052 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6053 and `\.{x20b}' have been mentioned in a user's program, where
6054 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6055 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6056 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6057 node with |name_type(p)=root| and |link(p)=h(x)|. We have |type(p)=mp_structured|,
6058 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6059 node and |r| to a subscript node. (Are you still following this? Use
6060 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6061 |type(q)| and |value(q)|; furthermore
6062 |name_type(q)=mp_structured_root| and |link(q)=q1|, where |q1| points
6063 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6064 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6065 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6066 |qq| is a  three-word ``attribute-as-value'' node with |type(qq)=numeric_type|
6067 (assuming that \.{x5} is numeric, because |qq| represents `\.{x[]}' 
6068 with no further attributes), |name_type(qq)=structured_root|, 
6069 |attr_loc(qq)=0|, |parent(qq)=p|, and
6070 |link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6071 an attribute node representing `\.{x[][]}', which has never yet
6072 occurred; its |type| field is |undefined|, and its |value| field is
6073 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6074 |parent(qq1)=q1|, and |link(qq1)=qq2|. Since |qq2| represents
6075 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6076 |parent(qq2)=q1|, |name_type(qq2)=attr|, |link(qq2)=end_attr|.
6077 (Maybe colored lines will help untangle your picture.)
6078  Node |r| is a subscript node with |type| and |value|
6079 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6080 and |link(r)=r1| is another subscript node. To complete the picture,
6081 see if you can guess what |link(r1)| is; give up? It's~|q1|.
6082 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6083 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6084 and we finish things off with three more nodes
6085 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6086 with a larger sheet of paper.) The value of variable \.{x20b}
6087 appears in node~|qqq2|, as you can well imagine.
6088
6089 If the example in the previous paragraph doesn't make things crystal
6090 clear, a glance at some of the simpler subroutines below will reveal how
6091 things work out in practice.
6092
6093 The only really unusual thing about these conventions is the use of
6094 collective subscript attributes. The idea is to avoid repeating a lot of
6095 type information when many elements of an array are identical macros
6096 (for which distinct values need not be stored) or when they don't have
6097 all of the possible attributes. Branches of the structure below collective
6098 subscript attributes do not carry actual values except for macro identifiers;
6099 branches of the structure below subscript nodes do not carry significant
6100 information in their collective subscript attributes.
6101
6102 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6103 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6104 @d parent(A) link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6105 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6106 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6107 @d attr_node_size 3 /* the number of words in an attribute node */
6108 @d subscr_node_size 3 /* the number of words in a subscript node */
6109 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6110
6111 @<Initialize table...@>=
6112 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6113
6114 @ Variables of type \&{pair} will have values that point to four-word
6115 nodes containing two numeric values. The first of these values has
6116 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6117 the |link| in the first points back to the node whose |value| points
6118 to this four-word node.
6119
6120 Variables of type \&{transform} are similar, but in this case their
6121 |value| points to a 12-word node containing six values, identified by
6122 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6123 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6124 Finally, variables of type \&{color} have 3~values in 6~words
6125 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6126
6127 When an entire structured variable is saved, the |root| indication
6128 is temporarily replaced by |saved_root|.
6129
6130 Some variables have no name; they just are used for temporary storage
6131 while expressions are being evaluated. We call them {\sl capsules}.
6132
6133 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6134 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6135 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6136 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6137 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6138 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6139 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6140 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6141 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6142 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6143 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6144 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6145 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6146 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6147 @#
6148 @d pair_node_size 4 /* the number of words in a pair node */
6149 @d transform_node_size 12 /* the number of words in a transform node */
6150 @d color_node_size 6 /* the number of words in a color node */
6151 @d cmykcolor_node_size 8 /* the number of words in a color node */
6152
6153 @<Glob...@>=
6154 small_number big_node_size[mp_pair_type+1];
6155 small_number sector0[mp_pair_type+1];
6156 small_number sector_offset[mp_black_part_sector+1];
6157
6158 @ The |sector0| array gives for each big node type, |name_type| values
6159 for its first subfield; the |sector_offset| array gives for each
6160 |name_type| value, the offset from the first subfield in words;
6161 and the |big_node_size| array gives the size in words for each type of
6162 big node.
6163
6164 @<Set init...@>=
6165 mp->big_node_size[mp_transform_type]=transform_node_size;
6166 mp->big_node_size[mp_pair_type]=pair_node_size;
6167 mp->big_node_size[mp_color_type]=color_node_size;
6168 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6169 mp->sector0[mp_transform_type]=mp_x_part_sector;
6170 mp->sector0[mp_pair_type]=mp_x_part_sector;
6171 mp->sector0[mp_color_type]=mp_red_part_sector;
6172 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6173 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6174   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6175 }
6176 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6177   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6178 }
6179 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6180   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6181 }
6182
6183 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6184 procedure call |init_big_node(p)| will allocate a pair or transform node
6185 for~|p|.  The individual parts of such nodes are initially of type
6186 |mp_independent|.
6187
6188 @c 
6189 void mp_init_big_node (MP mp,pointer p) {
6190   pointer q; /* the new node */
6191   small_number s; /* its size */
6192   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6193   do {  
6194     s=s-2; 
6195     @<Make variable |q+s| newly independent@>;
6196     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6197     link(q+s)=null;
6198   } while (s!=0);
6199   link(q)=p; value(p)=q;
6200 }
6201
6202 @ The |id_transform| function creates a capsule for the
6203 identity transformation.
6204
6205 @c 
6206 pointer mp_id_transform (MP mp) {
6207   pointer p,q,r; /* list manipulation registers */
6208   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6209   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6210   r=q+transform_node_size;
6211   do {  
6212     r=r-2;
6213     type(r)=mp_known; value(r)=0;
6214   } while (r!=q);
6215   value(xx_part_loc(q))=unity; 
6216   value(yy_part_loc(q))=unity;
6217   return p;
6218 }
6219
6220 @ Tokens are of type |tag_token| when they first appear, but they point
6221 to |null| until they are first used as the root of a variable.
6222 The following subroutine establishes the root node on such grand occasions.
6223
6224 @c 
6225 void mp_new_root (MP mp,pointer x) {
6226   pointer p; /* the new node */
6227   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6228   link(p)=x; equiv(x)=p;
6229 }
6230
6231 @ These conventions for variable representation are illustrated by the
6232 |print_variable_name| routine, which displays the full name of a
6233 variable given only a pointer to its two-word value packet.
6234
6235 @<Declarations@>=
6236 void mp_print_variable_name (MP mp, pointer p);
6237
6238 @ @c 
6239 void mp_print_variable_name (MP mp, pointer p) {
6240   pointer q; /* a token list that will name the variable's suffix */
6241   pointer r; /* temporary for token list creation */
6242   while ( name_type(p)>=mp_x_part_sector ) {
6243     @<Preface the output with a part specifier; |return| in the
6244       case of a capsule@>;
6245   }
6246   q=null;
6247   while ( name_type(p)>mp_saved_root ) {
6248     @<Ascend one level, pushing a token onto list |q|
6249      and replacing |p| by its parent@>;
6250   }
6251   r=mp_get_avail(mp); info(r)=link(p); link(r)=q;
6252   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6253 @.SAVED@>
6254   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6255   mp_flush_token_list(mp, r);
6256 }
6257
6258 @ @<Ascend one level, pushing a token onto list |q|...@>=
6259
6260   if ( name_type(p)==mp_subscr ) { 
6261     r=mp_new_num_tok(mp, subscript(p));
6262     do {  
6263       p=link(p);
6264     } while (name_type(p)!=mp_attr);
6265   } else if ( name_type(p)==mp_structured_root ) {
6266     p=link(p); goto FOUND;
6267   } else { 
6268     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6269 @:this can't happen var}{\quad var@>
6270     r=mp_get_avail(mp); info(r)=attr_loc(p);
6271   }
6272   link(r)=q; q=r;
6273 FOUND:  
6274   p=parent(p);
6275 }
6276
6277 @ @<Preface the output with a part specifier...@>=
6278 { switch (name_type(p)) {
6279   case mp_x_part_sector: mp_print_char(mp, 'x'); break;
6280   case mp_y_part_sector: mp_print_char(mp, 'y'); break;
6281   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6282   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6283   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6284   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6285   case mp_red_part_sector: mp_print(mp, "red"); break;
6286   case mp_green_part_sector: mp_print(mp, "green"); break;
6287   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6288   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6289   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6290   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6291   case mp_black_part_sector: mp_print(mp, "black"); break;
6292   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6293   case mp_capsule: 
6294     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6295     break;
6296 @.CAPSULE@>
6297   } /* there are no other cases */
6298   mp_print(mp, "part "); 
6299   p=link(p-mp->sector_offset[name_type(p)]);
6300 }
6301
6302 @ The |interesting| function returns |true| if a given variable is not
6303 in a capsule, or if the user wants to trace capsules.
6304
6305 @c 
6306 boolean mp_interesting (MP mp,pointer p) {
6307   small_number t; /* a |name_type| */
6308   if ( mp->internal[mp_tracing_capsules]>0 ) {
6309     return true;
6310   } else { 
6311     t=name_type(p);
6312     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6313       t=name_type(link(p-mp->sector_offset[t]));
6314     return (t!=mp_capsule);
6315   }
6316 }
6317
6318 @ Now here is a subroutine that converts an unstructured type into an
6319 equivalent structured type, by inserting a |mp_structured| node that is
6320 capable of growing. This operation is done only when |name_type(p)=root|,
6321 |subscr|, or |attr|.
6322
6323 The procedure returns a pointer to the new node that has taken node~|p|'s
6324 place in the structure. Node~|p| itself does not move, nor are its
6325 |value| or |type| fields changed in any way.
6326
6327 @c 
6328 pointer mp_new_structure (MP mp,pointer p) {
6329   pointer q,r=0; /* list manipulation registers */
6330   switch (name_type(p)) {
6331   case mp_root: 
6332     q=link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6333     break;
6334   case mp_subscr: 
6335     @<Link a new subscript node |r| in place of node |p|@>;
6336     break;
6337   case mp_attr: 
6338     @<Link a new attribute node |r| in place of node |p|@>;
6339     break;
6340   default: 
6341     mp_confusion(mp, "struct");
6342 @:this can't happen struct}{\quad struct@>
6343     break;
6344   }
6345   link(r)=link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6346   attr_head(r)=p; name_type(p)=mp_structured_root;
6347   q=mp_get_node(mp, attr_node_size); link(p)=q; subscr_head(r)=q;
6348   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; link(q)=end_attr;
6349   attr_loc(q)=collective_subscript; 
6350   return r;
6351 }
6352
6353 @ @<Link a new subscript node |r| in place of node |p|@>=
6354
6355   q=p;
6356   do {  
6357     q=link(q);
6358   } while (name_type(q)!=mp_attr);
6359   q=parent(q); r=subscr_head_loc(q); /* |link(r)=subscr_head(q)| */
6360   do {  
6361     q=r; r=link(r);
6362   } while (r!=p);
6363   r=mp_get_node(mp, subscr_node_size);
6364   link(q)=r; subscript(r)=subscript(p);
6365 }
6366
6367 @ If the attribute is |collective_subscript|, there are two pointers to
6368 node~|p|, so we must change both of them.
6369
6370 @<Link a new attribute node |r| in place of node |p|@>=
6371
6372   q=parent(p); r=attr_head(q);
6373   do {  
6374     q=r; r=link(r);
6375   } while (r!=p);
6376   r=mp_get_node(mp, attr_node_size); link(q)=r;
6377   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6378   if ( attr_loc(p)==collective_subscript ) { 
6379     q=subscr_head_loc(parent(p));
6380     while ( link(q)!=p ) q=link(q);
6381     link(q)=r;
6382   }
6383 }
6384
6385 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6386 list of suffixes; it returns a pointer to the corresponding two-word
6387 value. For example, if |t| points to token \.x followed by a numeric
6388 token containing the value~7, |find_variable| finds where the value of
6389 \.{x7} is stored in memory. This may seem a simple task, and it
6390 usually is, except when \.{x7} has never been referenced before.
6391 Indeed, \.x may never have even been subscripted before; complexities
6392 arise with respect to updating the collective subscript information.
6393
6394 If a macro type is detected anywhere along path~|t|, or if the first
6395 item on |t| isn't a |tag_token|, the value |null| is returned.
6396 Otherwise |p| will be a non-null pointer to a node such that
6397 |undefined<type(p)<mp_structured|.
6398
6399 @d abort_find { return null; }
6400
6401 @c 
6402 pointer mp_find_variable (MP mp,pointer t) {
6403   pointer p,q,r,s; /* nodes in the ``value'' line */
6404   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6405   integer n; /* subscript or attribute */
6406   memory_word save_word; /* temporary storage for a word of |mem| */
6407 @^inner loop@>
6408   p=info(t); t=link(t);
6409   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6410   if ( equiv(p)==null ) mp_new_root(mp, p);
6411   p=equiv(p); pp=p;
6412   while ( t!=null ) { 
6413     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6414     if ( t<mp->hi_mem_min ) {
6415       @<Descend one level for the subscript |value(t)|@>
6416     } else {
6417       @<Descend one level for the attribute |info(t)|@>;
6418     }
6419     t=link(t);
6420   }
6421   if ( type(pp)>=mp_structured ) {
6422     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6423   }
6424   if ( type(p)==mp_structured ) p=attr_head(p);
6425   if ( type(p)==undefined ) { 
6426     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6427     type(p)=type(pp); value(p)=null;
6428   };
6429   return p;
6430 }
6431
6432 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6433 |pp|~stays in the collective line while |p|~goes through actual subscript
6434 values.
6435
6436 @<Make sure that both nodes |p| and |pp|...@>=
6437 if ( type(pp)!=mp_structured ) { 
6438   if ( type(pp)>mp_structured ) abort_find;
6439   ss=mp_new_structure(mp, pp);
6440   if ( p==pp ) p=ss;
6441   pp=ss;
6442 }; /* now |type(pp)=mp_structured| */
6443 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6444   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6445
6446 @ We want this part of the program to be reasonably fast, in case there are
6447 @^inner loop@>
6448 lots of subscripts at the same level of the data structure. Therefore
6449 we store an ``infinite'' value in the word that appears at the end of the
6450 subscript list, even though that word isn't part of a subscript node.
6451
6452 @<Descend one level for the subscript |value(t)|@>=
6453
6454   n=value(t);
6455   pp=link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6456   q=link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6457   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |link(s)=subscr_head(p)| */
6458   do {  
6459     r=s; s=link(s);
6460   } while (n>subscript(s));
6461   if ( n==subscript(s) ) {
6462     p=s;
6463   } else { 
6464     p=mp_get_node(mp, subscr_node_size); link(r)=p; link(p)=s;
6465     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6466   }
6467   mp->mem[subscript_loc(q)]=save_word;
6468 }
6469
6470 @ @<Descend one level for the attribute |info(t)|@>=
6471
6472   n=info(t);
6473   ss=attr_head(pp);
6474   do {  
6475     rr=ss; ss=link(ss);
6476   } while (n>attr_loc(ss));
6477   if ( n<attr_loc(ss) ) { 
6478     qq=mp_get_node(mp, attr_node_size); link(rr)=qq; link(qq)=ss;
6479     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6480     parent(qq)=pp; ss=qq;
6481   }
6482   if ( p==pp ) { 
6483     p=ss; pp=ss;
6484   } else { 
6485     pp=ss; s=attr_head(p);
6486     do {  
6487       r=s; s=link(s);
6488     } while (n>attr_loc(s));
6489     if ( n==attr_loc(s) ) {
6490       p=s;
6491     } else { 
6492       q=mp_get_node(mp, attr_node_size); link(r)=q; link(q)=s;
6493       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6494       parent(q)=p; p=q;
6495     }
6496   }
6497 }
6498
6499 @ Variables lose their former values when they appear in a type declaration,
6500 or when they are defined to be macros or \&{let} equal to something else.
6501 A subroutine will be defined later that recycles the storage associated
6502 with any particular |type| or |value|; our goal now is to study a higher
6503 level process called |flush_variable|, which selectively frees parts of a
6504 variable structure.
6505
6506 This routine has some complexity because of examples such as
6507 `\hbox{\tt numeric x[]a[]b}'
6508 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6509 `\hbox{\tt vardef x[]a[]=...}'
6510 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6511 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6512 to handle such examples is to use recursion; so that's what we~do.
6513 @^recursion@>
6514
6515 Parameter |p| points to the root information of the variable;
6516 parameter |t| points to a list of one-word nodes that represent
6517 suffixes, with |info=collective_subscript| for subscripts.
6518
6519 @<Declarations@>=
6520 @<Declare subroutines for printing expressions@>
6521 @<Declare basic dependency-list subroutines@>
6522 @<Declare the recycling subroutines@>
6523 void mp_flush_cur_exp (MP mp,scaled v) ;
6524 @<Declare the procedure called |flush_below_variable|@>
6525
6526 @ @c 
6527 void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6528   pointer q,r; /* list manipulation */
6529   halfword n; /* attribute to match */
6530   while ( t!=null ) { 
6531     if ( type(p)!=mp_structured ) return;
6532     n=info(t); t=link(t);
6533     if ( n==collective_subscript ) { 
6534       r=subscr_head_loc(p); q=link(r); /* |q=subscr_head(p)| */
6535       while ( name_type(q)==mp_subscr ){ 
6536         mp_flush_variable(mp, q,t,discard_suffixes);
6537         if ( t==null ) {
6538           if ( type(q)==mp_structured ) r=q;
6539           else  { link(r)=link(q); mp_free_node(mp, q,subscr_node_size);   }
6540         } else {
6541           r=q;
6542         }
6543         q=link(r);
6544       }
6545     }
6546     p=attr_head(p);
6547     do {  
6548       r=p; p=link(p);
6549     } while (attr_loc(p)<n);
6550     if ( attr_loc(p)!=n ) return;
6551   }
6552   if ( discard_suffixes ) {
6553     mp_flush_below_variable(mp, p);
6554   } else { 
6555     if ( type(p)==mp_structured ) p=attr_head(p);
6556     mp_recycle_value(mp, p);
6557   }
6558 }
6559
6560 @ The next procedure is simpler; it wipes out everything but |p| itself,
6561 which becomes undefined.
6562
6563 @<Declare the procedure called |flush_below_variable|@>=
6564 void mp_flush_below_variable (MP mp, pointer p);
6565
6566 @ @c
6567 void mp_flush_below_variable (MP mp,pointer p) {
6568    pointer q,r; /* list manipulation registers */
6569   if ( type(p)!=mp_structured ) {
6570     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6571   } else { 
6572     q=subscr_head(p);
6573     while ( name_type(q)==mp_subscr ) { 
6574       mp_flush_below_variable(mp, q); r=q; q=link(q);
6575       mp_free_node(mp, r,subscr_node_size);
6576     }
6577     r=attr_head(p); q=link(r); mp_recycle_value(mp, r);
6578     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6579     else mp_free_node(mp, r,subscr_node_size);
6580     /* we assume that |subscr_node_size=attr_node_size| */
6581     do {  
6582       mp_flush_below_variable(mp, q); r=q; q=link(q); mp_free_node(mp, r,attr_node_size);
6583     } while (q!=end_attr);
6584     type(p)=undefined;
6585   }
6586 }
6587
6588 @ Just before assigning a new value to a variable, we will recycle the
6589 old value and make the old value undefined. The |und_type| routine
6590 determines what type of undefined value should be given, based on
6591 the current type before recycling.
6592
6593 @c 
6594 small_number mp_und_type (MP mp,pointer p) { 
6595   switch (type(p)) {
6596   case undefined: case mp_vacuous:
6597     return undefined;
6598   case mp_boolean_type: case mp_unknown_boolean:
6599     return mp_unknown_boolean;
6600   case mp_string_type: case mp_unknown_string:
6601     return mp_unknown_string;
6602   case mp_pen_type: case mp_unknown_pen:
6603     return mp_unknown_pen;
6604   case mp_path_type: case mp_unknown_path:
6605     return mp_unknown_path;
6606   case mp_picture_type: case mp_unknown_picture:
6607     return mp_unknown_picture;
6608   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6609   case mp_pair_type: case mp_numeric_type: 
6610     return type(p);
6611   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6612     return mp_numeric_type;
6613   } /* there are no other cases */
6614   return 0;
6615 }
6616
6617 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6618 of a symbolic token. It must remove any variable structure or macro
6619 definition that is currently attached to that symbol. If the |saving|
6620 parameter is true, a subsidiary structure is saved instead of destroyed.
6621
6622 @c 
6623 void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6624   pointer q; /* |equiv(p)| */
6625   q=equiv(p);
6626   switch (eq_type(p) % outer_tag)  {
6627   case defined_macro:
6628   case secondary_primary_macro:
6629   case tertiary_secondary_macro:
6630   case expression_tertiary_macro: 
6631     if ( ! saving ) mp_delete_mac_ref(mp, q);
6632     break;
6633   case tag_token:
6634     if ( q!=null ) {
6635       if ( saving ) {
6636         name_type(q)=mp_saved_root;
6637       } else { 
6638         mp_flush_below_variable(mp, q); 
6639             mp_free_node(mp,q,value_node_size); 
6640       }
6641     }
6642     break;
6643   default:
6644     break;
6645   }
6646   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6647 }
6648
6649 @* \[16] Saving and restoring equivalents.
6650 The nested structure given by \&{begingroup} and \&{endgroup}
6651 allows |eqtb| entries to be saved and restored, so that temporary changes
6652 can be made without difficulty.  When the user requests a current value to
6653 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6654 \&{endgroup} ultimately causes the old values to be removed from the save
6655 stack and put back in their former places.
6656
6657 The save stack is a linked list containing three kinds of entries,
6658 distinguished by their |info| fields. If |p| points to a saved item,
6659 then
6660
6661 \smallskip\hang
6662 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6663 such an item to the save stack and each \&{endgroup} cuts back the stack
6664 until the most recent such entry has been removed.
6665
6666 \smallskip\hang
6667 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6668 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6669 commands.
6670
6671 \smallskip\hang
6672 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6673 integer to be restored to internal parameter number~|q|. Such entries
6674 are generated by \&{interim} commands.
6675
6676 \smallskip\noindent
6677 The global variable |save_ptr| points to the top item on the save stack.
6678
6679 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6680 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6681 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6682   link((A))=mp->save_ptr; mp->save_ptr=(A);
6683   }
6684
6685 @<Glob...@>=
6686 pointer save_ptr; /* the most recently saved item */
6687
6688 @ @<Set init...@>=mp->save_ptr=null;
6689
6690 @ The |save_variable| routine is given a hash address |q|; it salts this
6691 address in the save stack, together with its current equivalent,
6692 then makes token~|q| behave as though it were brand new.
6693
6694 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6695 things from the stack when the program is not inside a group, so there's
6696 no point in wasting the space.
6697
6698 @c void mp_save_variable (MP mp,pointer q) {
6699   pointer p; /* temporary register */
6700   if ( mp->save_ptr!=null ){ 
6701     p=mp_get_node(mp, save_node_size); info(p)=q; link(p)=mp->save_ptr;
6702     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6703   }
6704   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6705 }
6706
6707 @ Similarly, |save_internal| is given the location |q| of an internal
6708 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6709 third kind.
6710
6711 @c void mp_save_internal (MP mp,halfword q) {
6712   pointer p; /* new item for the save stack */
6713   if ( mp->save_ptr!=null ){ 
6714      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6715     link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6716   }
6717 }
6718
6719 @ At the end of a group, the |unsave| routine restores all of the saved
6720 equivalents in reverse order. This routine will be called only when there
6721 is at least one boundary item on the save stack.
6722
6723 @c 
6724 void mp_unsave (MP mp) {
6725   pointer q; /* index to saved item */
6726   pointer p; /* temporary register */
6727   while ( info(mp->save_ptr)!=0 ) {
6728     q=info(mp->save_ptr);
6729     if ( q>hash_end ) {
6730       if ( mp->internal[mp_tracing_restores]>0 ) {
6731         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6732         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, '=');
6733         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, '}');
6734         mp_end_diagnostic(mp, false);
6735       }
6736       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6737     } else { 
6738       if ( mp->internal[mp_tracing_restores]>0 ) {
6739         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6740         mp_print_text(q); mp_print_char(mp, '}');
6741         mp_end_diagnostic(mp, false);
6742       }
6743       mp_clear_symbol(mp, q,false);
6744       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6745       if ( eq_type(q) % outer_tag==tag_token ) {
6746         p=equiv(q);
6747         if ( p!=null ) name_type(p)=mp_root;
6748       }
6749     }
6750     p=link(mp->save_ptr); 
6751     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6752   }
6753   p=link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6754 }
6755
6756 @* \[17] Data structures for paths.
6757 When a \MP\ user specifies a path, \MP\ will create a list of knots
6758 and control points for the associated cubic spline curves. If the
6759 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6760 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6761 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6762 @:Bezier}{B\'ezier, Pierre Etienne@>
6763 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6764 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6765 for |0<=t<=1|.
6766
6767 There is a 8-word node for each knot $z_k$, containing one word of
6768 control information and six words for the |x| and |y| coordinates of
6769 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6770 |left_type| and |right_type| fields, which each occupy a quarter of
6771 the first word in the node; they specify properties of the curve as it
6772 enters and leaves the knot. There's also a halfword |link| field,
6773 which points to the following knot, and a final supplementary word (of
6774 which only a quarter is used).
6775
6776 If the path is a closed contour, knots 0 and |n| are identical;
6777 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6778 is not closed, the |left_type| of knot~0 and the |right_type| of knot~|n|
6779 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6780 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6781
6782 @d left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6783 @d right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6784 @d x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */
6785 @d y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6786 @d left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6787 @d left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6788 @d right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6789 @d right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6790 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6791 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6792 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6793 @d left_coord(A)   mp->mem[(A)+2].sc
6794   /* coordinate of previous control point given |x_loc| or |y_loc| */
6795 @d right_coord(A)   mp->mem[(A)+4].sc
6796   /* coordinate of next control point given |x_loc| or |y_loc| */
6797 @d knot_node_size 8 /* number of words in a knot node */
6798
6799 @<Types...@>=
6800 enum mp_knot_type {
6801  mp_endpoint=0, /* |left_type| at path beginning and |right_type| at path end */
6802  mp_explicit, /* |left_type| or |right_type| when control points are known */
6803  mp_given, /* |left_type| or |right_type| when a direction is given */
6804  mp_curl, /* |left_type| or |right_type| when a curl is desired */
6805  mp_open, /* |left_type| or |right_type| when \MP\ should choose the direction */
6806  mp_end_cycle
6807 };
6808
6809 @ Before the B\'ezier control points have been calculated, the memory
6810 space they will ultimately occupy is taken up by information that can be
6811 used to compute them. There are four cases:
6812
6813 \yskip
6814 \textindent{$\bullet$} If |right_type=mp_open|, the curve should leave
6815 the knot in the same direction it entered; \MP\ will figure out a
6816 suitable direction.
6817
6818 \yskip
6819 \textindent{$\bullet$} If |right_type=mp_curl|, the curve should leave the
6820 knot in a direction depending on the angle at which it enters the next
6821 knot and on the curl parameter stored in |right_curl|.
6822
6823 \yskip
6824 \textindent{$\bullet$} If |right_type=mp_given|, the curve should leave the
6825 knot in a nonzero direction stored as an |angle| in |right_given|.
6826
6827 \yskip
6828 \textindent{$\bullet$} If |right_type=mp_explicit|, the B\'ezier control
6829 point for leaving this knot has already been computed; it is in the
6830 |right_x| and |right_y| fields.
6831
6832 \yskip\noindent
6833 The rules for |left_type| are similar, but they refer to the curve entering
6834 the knot, and to \\{left} fields instead of \\{right} fields.
6835
6836 Non-|explicit| control points will be chosen based on ``tension'' parameters
6837 in the |left_tension| and |right_tension| fields. The
6838 `\&{atleast}' option is represented by negative tension values.
6839 @:at_least_}{\&{atleast} primitive@>
6840
6841 For example, the \MP\ path specification
6842 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6843   3 and 4..p},$$
6844 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6845 by the six knots
6846 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6847 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6848 |left_type|&\\{left} info&|x_coord,y_coord|&|right_type|&\\{right} info\cr
6849 \noalign{\yskip}
6850 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6851 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6852 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6853 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6854 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6855 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6856 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6857 Of course, this example is more complicated than anything a normal user
6858 would ever write.
6859
6860 These types must satisfy certain restrictions because of the form of \MP's
6861 path syntax:
6862 (i)~|open| type never appears in the same node together with |endpoint|,
6863 |given|, or |curl|.
6864 (ii)~The |right_type| of a node is |explicit| if and only if the
6865 |left_type| of the following node is |explicit|.
6866 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6867
6868 @d left_curl left_x /* curl information when entering this knot */
6869 @d left_given left_x /* given direction when entering this knot */
6870 @d left_tension left_y /* tension information when entering this knot */
6871 @d right_curl right_x /* curl information when leaving this knot */
6872 @d right_given right_x /* given direction when leaving this knot */
6873 @d right_tension right_y /* tension information when leaving this knot */
6874
6875 @ Knots can be user-supplied, or they can be created by program code,
6876 like the |split_cubic| function, or |copy_path|. The distinction is
6877 needed for the cleanup routine that runs after |split_cubic|, because
6878 it should only delete knots it has previously inserted, and never
6879 anything that was user-supplied. In order to be able to differentiate
6880 one knot from another, we will set |originator(p):=mp_metapost_user| when
6881 it appeared in the actual metapost program, and
6882 |originator(p):=mp_program_code| in all other cases.
6883
6884 @d originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6885
6886 @<Types...@>=
6887 enum {
6888   mp_program_code=0, /* not created by a user */
6889   mp_metapost_user /* created by a user */
6890 };
6891
6892 @ Here is a routine that prints a given knot list
6893 in symbolic form. It illustrates the conventions discussed above,
6894 and checks for anomalies that might arise while \MP\ is being debugged.
6895
6896 @<Declare subroutines for printing expressions@>=
6897 void mp_pr_path (MP mp,pointer h);
6898
6899 @ @c
6900 void mp_pr_path (MP mp,pointer h) {
6901   pointer p,q; /* for list traversal */
6902   p=h;
6903   do {  
6904     q=link(p);
6905     if ( (p==null)||(q==null) ) { 
6906       mp_print_nl(mp, "???"); return; /* this won't happen */
6907 @.???@>
6908     }
6909     @<Print information for adjacent knots |p| and |q|@>;
6910   DONE1:
6911     p=q;
6912     if ( (p!=h)||(left_type(h)!=mp_endpoint) ) {
6913       @<Print two dots, followed by |given| or |curl| if present@>;
6914     }
6915   } while (p!=h);
6916   if ( left_type(h)!=mp_endpoint ) 
6917     mp_print(mp, "cycle");
6918 }
6919
6920 @ @<Print information for adjacent knots...@>=
6921 mp_print_two(mp, x_coord(p),y_coord(p));
6922 switch (right_type(p)) {
6923 case mp_endpoint: 
6924   if ( left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6925 @.open?@>
6926   if ( (left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6927   goto DONE1;
6928   break;
6929 case mp_explicit: 
6930   @<Print control points between |p| and |q|, then |goto done1|@>;
6931   break;
6932 case mp_open: 
6933   @<Print information for a curve that begins |open|@>;
6934   break;
6935 case mp_curl:
6936 case mp_given: 
6937   @<Print information for a curve that begins |curl| or |given|@>;
6938   break;
6939 default:
6940   mp_print(mp, "???"); /* can't happen */
6941 @.???@>
6942   break;
6943 }
6944 if ( left_type(q)<=mp_explicit ) {
6945   mp_print(mp, "..control?"); /* can't happen */
6946 @.control?@>
6947 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
6948   @<Print tension between |p| and |q|@>;
6949 }
6950
6951 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
6952 were |scaled|, the magnitude of a |given| direction vector will be~4096.
6953
6954 @<Print two dots...@>=
6955
6956   mp_print_nl(mp, " ..");
6957   if ( left_type(p)==mp_given ) { 
6958     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, '{');
6959     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ',');
6960     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, '}');
6961   } else if ( left_type(p)==mp_curl ){ 
6962     mp_print(mp, "{curl "); 
6963     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, '}');
6964   }
6965 }
6966
6967 @ @<Print tension between |p| and |q|@>=
6968
6969   mp_print(mp, "..tension ");
6970   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
6971   mp_print_scaled(mp, abs(right_tension(p)));
6972   if ( right_tension(p)!=left_tension(q) ){ 
6973     mp_print(mp, " and ");
6974     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
6975     mp_print_scaled(mp, abs(left_tension(q)));
6976   }
6977 }
6978
6979 @ @<Print control points between |p| and |q|, then |goto done1|@>=
6980
6981   mp_print(mp, "..controls "); 
6982   mp_print_two(mp, right_x(p),right_y(p)); 
6983   mp_print(mp, " and ");
6984   if ( left_type(q)!=mp_explicit ) { 
6985     mp_print(mp, "??"); /* can't happen */
6986 @.??@>
6987   } else {
6988     mp_print_two(mp, left_x(q),left_y(q));
6989   }
6990   goto DONE1;
6991 }
6992
6993 @ @<Print information for a curve that begins |open|@>=
6994 if ( (left_type(p)!=mp_explicit)&&(left_type(p)!=mp_open) ) {
6995   mp_print(mp, "{open?}"); /* can't happen */
6996 @.open?@>
6997 }
6998
6999 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7000 \MP's default curl is present.
7001
7002 @<Print information for a curve that begins |curl|...@>=
7003
7004   if ( left_type(p)==mp_open )  
7005     mp_print(mp, "??"); /* can't happen */
7006 @.??@>
7007   if ( right_type(p)==mp_curl ) { 
7008     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7009   } else { 
7010     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, '{');
7011     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, ','); 
7012     mp_print_scaled(mp, mp->n_sin);
7013   }
7014   mp_print_char(mp, '}');
7015 }
7016
7017 @ It is convenient to have another version of |pr_path| that prints the path
7018 as a diagnostic message.
7019
7020 @<Declare subroutines for printing expressions@>=
7021 void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) { 
7022   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7023 @.Path at line...@>
7024   mp_pr_path(mp, h);
7025   mp_end_diagnostic(mp, true);
7026 }
7027
7028 @ If we want to duplicate a knot node, we can say |copy_knot|:
7029
7030 @c 
7031 pointer mp_copy_knot (MP mp,pointer p) {
7032   pointer q; /* the copy */
7033   int k; /* runs through the words of a knot node */
7034   q=mp_get_node(mp, knot_node_size);
7035   for (k=0;k<knot_node_size;k++) {
7036     mp->mem[q+k]=mp->mem[p+k];
7037   }
7038   originator(q)=originator(p);
7039   return q;
7040 }
7041
7042 @ The |copy_path| routine makes a clone of a given path.
7043
7044 @c 
7045 pointer mp_copy_path (MP mp, pointer p) {
7046   pointer q,pp,qq; /* for list manipulation */
7047   q=mp_copy_knot(mp, p);
7048   qq=q; pp=link(p);
7049   while ( pp!=p ) { 
7050     link(qq)=mp_copy_knot(mp, pp);
7051     qq=link(qq);
7052     pp=link(pp);
7053   }
7054   link(qq)=q;
7055   return q;
7056 }
7057
7058
7059 @ Just before |ship_out|, knot lists are exported for printing.
7060
7061 The |gr_XXXX| macros are defined in |mppsout.h|.
7062
7063 @c 
7064 mp_knot *mp_export_knot (MP mp,pointer p) {
7065   mp_knot *q; /* the copy */
7066   if (p==null)
7067      return NULL;
7068   q = mp_xmalloc(mp, 1, sizeof (mp_knot));
7069   memset(q,0,sizeof (mp_knot));
7070   gr_left_type(q)  = left_type(p);
7071   gr_right_type(q) = right_type(p);
7072   gr_x_coord(q)    = x_coord(p);
7073   gr_y_coord(q)    = y_coord(p);
7074   gr_left_x(q)     = left_x(p);
7075   gr_left_y(q)     = left_y(p);
7076   gr_right_x(q)    = right_x(p);
7077   gr_right_y(q)    = right_y(p);
7078   gr_originator(q) = originator(p);
7079   return q;
7080 }
7081
7082 @ The |export_knot_list| routine therefore also makes a clone 
7083 of a given path.
7084
7085 @c 
7086 mp_knot *mp_export_knot_list (MP mp, pointer p) {
7087   mp_knot *q, *qq; /* for list manipulation */
7088   pointer pp; /* for list manipulation */
7089   if (p==null)
7090      return NULL;
7091   q=mp_export_knot(mp, p);
7092   qq=q; pp=link(p);
7093   while ( pp!=p ) { 
7094     gr_next_knot(qq)=mp_export_knot(mp, pp);
7095     qq=gr_next_knot(qq);
7096     pp=link(pp);
7097   }
7098   gr_next_knot(qq)=q;
7099   return q;
7100 }
7101
7102
7103 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7104 returns a pointer to the first node of the copy, if the path is a cycle,
7105 but to the final node of a non-cyclic copy. The global
7106 variable |path_tail| will point to the final node of the original path;
7107 this trick makes it easier to implement `\&{doublepath}'.
7108
7109 All node types are assumed to be |endpoint| or |explicit| only.
7110
7111 @c 
7112 pointer mp_htap_ypoc (MP mp,pointer p) {
7113   pointer q,pp,qq,rr; /* for list manipulation */
7114   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7115   qq=q; pp=p;
7116   while (1) { 
7117     right_type(qq)=left_type(pp); left_type(qq)=right_type(pp);
7118     x_coord(qq)=x_coord(pp); y_coord(qq)=y_coord(pp);
7119     right_x(qq)=left_x(pp); right_y(qq)=left_y(pp);
7120     left_x(qq)=right_x(pp); left_y(qq)=right_y(pp);
7121     originator(qq)=originator(pp);
7122     if ( link(pp)==p ) { 
7123       link(q)=qq; mp->path_tail=pp; return q;
7124     }
7125     rr=mp_get_node(mp, knot_node_size); link(rr)=qq; qq=rr; pp=link(pp);
7126   }
7127 }
7128
7129 @ @<Glob...@>=
7130 pointer path_tail; /* the node that links to the beginning of a path */
7131
7132 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7133 calling the following subroutine.
7134
7135 @<Declare the recycling subroutines@>=
7136 void mp_toss_knot_list (MP mp,pointer p) ;
7137
7138 @ @c
7139 void mp_toss_knot_list (MP mp,pointer p) {
7140   pointer q; /* the node being freed */
7141   pointer r; /* the next node */
7142   q=p;
7143   do {  
7144     r=link(q); 
7145     mp_free_node(mp, q,knot_node_size); q=r;
7146   } while (q!=p);
7147 }
7148
7149 @* \[18] Choosing control points.
7150 Now we must actually delve into one of \MP's more difficult routines,
7151 the |make_choices| procedure that chooses angles and control points for
7152 the splines of a curve when the user has not specified them explicitly.
7153 The parameter to |make_choices| points to a list of knots and
7154 path information, as described above.
7155
7156 A path decomposes into independent segments at ``breakpoint'' knots,
7157 which are knots whose left and right angles are both prespecified in
7158 some way (i.e., their |left_type| and |right_type| aren't both open).
7159
7160 @c 
7161 @<Declare the procedure called |solve_choices|@>
7162 void mp_make_choices (MP mp,pointer knots) {
7163   pointer h; /* the first breakpoint */
7164   pointer p,q; /* consecutive breakpoints being processed */
7165   @<Other local variables for |make_choices|@>;
7166   check_arith; /* make sure that |arith_error=false| */
7167   if ( mp->internal[mp_tracing_choices]>0 )
7168     mp_print_path(mp, knots,", before choices",true);
7169   @<If consecutive knots are equal, join them explicitly@>;
7170   @<Find the first breakpoint, |h|, on the path;
7171     insert an artificial breakpoint if the path is an unbroken cycle@>;
7172   p=h;
7173   do {  
7174     @<Fill in the control points between |p| and the next breakpoint,
7175       then advance |p| to that breakpoint@>;
7176   } while (p!=h);
7177   if ( mp->internal[mp_tracing_choices]>0 )
7178     mp_print_path(mp, knots,", after choices",true);
7179   if ( mp->arith_error ) {
7180     @<Report an unexpected problem during the choice-making@>;
7181   }
7182 }
7183
7184 @ @<Report an unexpected problem during the choice...@>=
7185
7186   print_err("Some number got too big");
7187 @.Some number got too big@>
7188   help2("The path that I just computed is out of range.")
7189        ("So it will probably look funny. Proceed, for a laugh.");
7190   mp_put_get_error(mp); mp->arith_error=false;
7191 }
7192
7193 @ Two knots in a row with the same coordinates will always be joined
7194 by an explicit ``curve'' whose control points are identical with the
7195 knots.
7196
7197 @<If consecutive knots are equal, join them explicitly@>=
7198 p=knots;
7199 do {  
7200   q=link(p);
7201   if ( x_coord(p)==x_coord(q) && y_coord(p)==y_coord(q) && right_type(p)>mp_explicit ) { 
7202     right_type(p)=mp_explicit;
7203     if ( left_type(p)==mp_open ) { 
7204       left_type(p)=mp_curl; left_curl(p)=unity;
7205     }
7206     left_type(q)=mp_explicit;
7207     if ( right_type(q)==mp_open ) { 
7208       right_type(q)=mp_curl; right_curl(q)=unity;
7209     }
7210     right_x(p)=x_coord(p); left_x(q)=x_coord(p);
7211     right_y(p)=y_coord(p); left_y(q)=y_coord(p);
7212   }
7213   p=q;
7214 } while (p!=knots)
7215
7216 @ If there are no breakpoints, it is necessary to compute the direction
7217 angles around an entire cycle. In this case the |left_type| of the first
7218 node is temporarily changed to |end_cycle|.
7219
7220 @<Find the first breakpoint, |h|, on the path...@>=
7221 h=knots;
7222 while (1) { 
7223   if ( left_type(h)!=mp_open ) break;
7224   if ( right_type(h)!=mp_open ) break;
7225   h=link(h);
7226   if ( h==knots ) { 
7227     left_type(h)=mp_end_cycle; break;
7228   }
7229 }
7230
7231 @ If |right_type(p)<given| and |q=link(p)|, we must have
7232 |right_type(p)=left_type(q)=mp_explicit| or |endpoint|.
7233
7234 @<Fill in the control points between |p| and the next breakpoint...@>=
7235 q=link(p);
7236 if ( right_type(p)>=mp_given ) { 
7237   while ( (left_type(q)==mp_open)&&(right_type(q)==mp_open) ) q=link(q);
7238   @<Fill in the control information between
7239     consecutive breakpoints |p| and |q|@>;
7240 } else if ( right_type(p)==mp_endpoint ) {
7241   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7242 }
7243 p=q
7244
7245 @ This step makes it possible to transform an explicitly computed path without
7246 checking the |left_type| and |right_type| fields.
7247
7248 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7249
7250   right_x(p)=x_coord(p); right_y(p)=y_coord(p);
7251   left_x(q)=x_coord(q); left_y(q)=y_coord(q);
7252 }
7253
7254 @ Before we can go further into the way choices are made, we need to
7255 consider the underlying theory. The basic ideas implemented in |make_choices|
7256 are due to John Hobby, who introduced the notion of ``mock curvature''
7257 @^Hobby, John Douglas@>
7258 at a knot. Angles are chosen so that they preserve mock curvature when
7259 a knot is passed, and this has been found to produce excellent results.
7260
7261 It is convenient to introduce some notations that simplify the necessary
7262 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7263 between knots |k| and |k+1|; and let
7264 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7265 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7266 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7267 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7268 $$\eqalign{z_k^+&=z_k+
7269   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7270  z\k^-&=z\k-
7271   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7272 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7273 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7274 corresponding ``offset angles.'' These angles satisfy the condition
7275 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7276 whenever the curve leaves an intermediate knot~|k| in the direction that
7277 it enters.
7278
7279 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7280 the curve at its beginning and ending points. This means that
7281 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7282 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7283 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7284 z\k^-,z\k^{\phantom+};t)$
7285 has curvature
7286 @^curvature@>
7287 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7288 \qquad{\rm and}\qquad
7289 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7290 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7291 @^mock curvature@>
7292 approximation to this true curvature that arises in the limit for
7293 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7294 The standard velocity function satisfies
7295 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7296 hence the mock curvatures are respectively
7297 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7298 \qquad{\rm and}\qquad
7299 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7300
7301 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7302 determines $\phi_k$ when $\theta_k$ is known, so the task of
7303 angle selection is essentially to choose appropriate values for each
7304 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7305 from $(**)$, we obtain a system of linear equations of the form
7306 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7307 where
7308 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7309 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7310 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7311 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7312 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7313 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7314 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7315 hence they have a unique solution. Moreover, in most cases the tensions
7316 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7317 solution numerically stable, and there is an exponential damping
7318 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7319 a factor of~$O(2^{-j})$.
7320
7321 @ However, we still must consider the angles at the starting and ending
7322 knots of a non-cyclic path. These angles might be given explicitly, or
7323 they might be specified implicitly in terms of an amount of ``curl.''
7324
7325 Let's assume that angles need to be determined for a non-cyclic path
7326 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7327 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7328 have been given for $0<k<n$, and it will be convenient to introduce
7329 equations of the same form for $k=0$ and $k=n$, where
7330 $$A_0=B_0=C_n=D_n=0.$$
7331 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7332 define $C_0=1$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7333 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7334 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7335 mock curvature at $z_1$; i.e.,
7336 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7337 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7338 This equation simplifies to
7339 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7340  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7341  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7342 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7343 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7344 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7345 hence the linear equations remain nonsingular.
7346
7347 Similar considerations apply at the right end, when the final angle $\phi_n$
7348 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7349 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7350 or we have
7351 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7352 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7353   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7354
7355 When |make_choices| chooses angles, it must compute the coefficients of
7356 these linear equations, then solve the equations. To compute the coefficients,
7357 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7358 When the equations are solved, the chosen directions $\theta_k$ are put
7359 back into the form of control points by essentially computing sines and
7360 cosines.
7361
7362 @ OK, we are ready to make the hard choices of |make_choices|.
7363 Most of the work is relegated to an auxiliary procedure
7364 called |solve_choices|, which has been introduced to keep
7365 |make_choices| from being extremely long.
7366
7367 @<Fill in the control information between...@>=
7368 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7369   set $n$ to the length of the path@>;
7370 @<Remove |open| types at the breakpoints@>;
7371 mp_solve_choices(mp, p,q,n)
7372
7373 @ It's convenient to precompute quantities that will be needed several
7374 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7375 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7376 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7377 and $z\k-z_k$ will be stored in |psi[k]|.
7378
7379 @<Glob...@>=
7380 int path_size; /* maximum number of knots between breakpoints of a path */
7381 scaled *delta_x;
7382 scaled *delta_y;
7383 scaled *delta; /* knot differences */
7384 angle  *psi; /* turning angles */
7385
7386 @ @<Allocate or initialize ...@>=
7387 mp->delta_x = NULL;
7388 mp->delta_y = NULL;
7389 mp->delta = NULL;
7390 mp->psi = NULL;
7391
7392 @ @<Dealloc variables@>=
7393 xfree(mp->delta_x);
7394 xfree(mp->delta_y);
7395 xfree(mp->delta);
7396 xfree(mp->psi);
7397
7398 @ @<Other local variables for |make_choices|@>=
7399   int k,n; /* current and final knot numbers */
7400   pointer s,t; /* registers for list traversal */
7401   scaled delx,dely; /* directions where |open| meets |explicit| */
7402   fraction sine,cosine; /* trig functions of various angles */
7403
7404 @ @<Calculate the turning angles...@>=
7405 {
7406 RESTART:
7407   k=0; s=p; n=mp->path_size;
7408   do {  
7409     t=link(s);
7410     mp->delta_x[k]=x_coord(t)-x_coord(s);
7411     mp->delta_y[k]=y_coord(t)-y_coord(s);
7412     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7413     if ( k>0 ) { 
7414       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7415       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7416       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7417         mp_take_fraction(mp, mp->delta_y[k],sine),
7418         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7419           mp_take_fraction(mp, mp->delta_x[k],sine));
7420     }
7421     incr(k); s=t;
7422     if ( k==mp->path_size ) {
7423       mp_reallocate_paths(mp, mp->path_size+(mp->path_size>>2));
7424       goto RESTART; /* retry, loop size has changed */
7425     }
7426     if ( s==q ) n=k;
7427   } while (!((k>=n)&&(left_type(s)!=mp_end_cycle)));
7428   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7429 }
7430
7431 @ When we get to this point of the code, |right_type(p)| is either
7432 |given| or |curl| or |open|. If it is |open|, we must have
7433 |left_type(p)=mp_end_cycle| or |left_type(p)=mp_explicit|. In the latter
7434 case, the |open| type is converted to |given|; however, if the
7435 velocity coming into this knot is zero, the |open| type is
7436 converted to a |curl|, since we don't know the incoming direction.
7437
7438 Similarly, |left_type(q)| is either |given| or |curl| or |open| or
7439 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7440
7441 @<Remove |open| types at the breakpoints@>=
7442 if ( left_type(q)==mp_open ) { 
7443   delx=right_x(q)-x_coord(q); dely=right_y(q)-y_coord(q);
7444   if ( (delx==0)&&(dely==0) ) { 
7445     left_type(q)=mp_curl; left_curl(q)=unity;
7446   } else { 
7447     left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7448   }
7449 }
7450 if ( (right_type(p)==mp_open)&&(left_type(p)==mp_explicit) ) { 
7451   delx=x_coord(p)-left_x(p); dely=y_coord(p)-left_y(p);
7452   if ( (delx==0)&&(dely==0) ) { 
7453     right_type(p)=mp_curl; right_curl(p)=unity;
7454   } else { 
7455     right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7456   }
7457 }
7458
7459 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7460 and exactly one of the breakpoints involves a curl. The simplest case occurs
7461 when |n=1| and there is a curl at both breakpoints; then we simply draw
7462 a straight line.
7463
7464 But before coding up the simple cases, we might as well face the general case,
7465 since we must deal with it sooner or later, and since the general case
7466 is likely to give some insight into the way simple cases can be handled best.
7467
7468 When there is no cycle, the linear equations to be solved form a tridiagonal
7469 system, and we can apply the standard technique of Gaussian elimination
7470 to convert that system to a sequence of equations of the form
7471 $$\theta_0+u_0\theta_1=v_0,\quad
7472 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7473 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7474 \theta_n=v_n.$$
7475 It is possible to do this diagonalization while generating the equations.
7476 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7477 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7478
7479 The procedure is slightly more complex when there is a cycle, but the
7480 basic idea will be nearly the same. In the cyclic case the right-hand
7481 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7482 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7483 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7484 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7485 eliminate the $w$'s from the system, after which the solution can be
7486 obtained as before.
7487
7488 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7489 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7490 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7491 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7492
7493 @<Glob...@>=
7494 angle *theta; /* values of $\theta_k$ */
7495 fraction *uu; /* values of $u_k$ */
7496 angle *vv; /* values of $v_k$ */
7497 fraction *ww; /* values of $w_k$ */
7498
7499 @ @<Allocate or initialize ...@>=
7500 mp->theta = NULL;
7501 mp->uu = NULL;
7502 mp->vv = NULL;
7503 mp->ww = NULL;
7504
7505 @ @<Dealloc variables@>=
7506 xfree(mp->theta);
7507 xfree(mp->uu);
7508 xfree(mp->vv);
7509 xfree(mp->ww);
7510
7511 @ @<Declare |mp_reallocate| functions@>=
7512 void mp_reallocate_paths (MP mp, int l);
7513
7514 @ @c
7515 void mp_reallocate_paths (MP mp, int l) {
7516   XREALLOC (mp->delta_x, l, scaled);
7517   XREALLOC (mp->delta_y, l, scaled);
7518   XREALLOC (mp->delta,   l, scaled);
7519   XREALLOC (mp->psi,     l, angle);
7520   XREALLOC (mp->theta,   l, angle);
7521   XREALLOC (mp->uu,      l, fraction);
7522   XREALLOC (mp->vv,      l, angle);
7523   XREALLOC (mp->ww,      l, fraction);
7524   mp->path_size = l;
7525 }
7526
7527 @ Our immediate problem is to get the ball rolling by setting up the
7528 first equation or by realizing that no equations are needed, and to fit
7529 this initialization into a framework suitable for the overall computation.
7530
7531 @<Declare the procedure called |solve_choices|@>=
7532 @<Declare subroutines needed by |solve_choices|@>
7533 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7534   int k; /* current knot number */
7535   pointer r,s,t; /* registers for list traversal */
7536   @<Other local variables for |solve_choices|@>;
7537   k=0; s=p; r=0;
7538   while (1) { 
7539     t=link(s);
7540     if ( k==0 ) {
7541       @<Get the linear equations started; or |return|
7542         with the control points in place, if linear equations
7543         needn't be solved@>
7544     } else  { 
7545       switch (left_type(s)) {
7546       case mp_end_cycle: case mp_open:
7547         @<Set up equation to match mock curvatures
7548           at $z_k$; then |goto found| with $\theta_n$
7549           adjusted to equal $\theta_0$, if a cycle has ended@>;
7550         break;
7551       case mp_curl:
7552         @<Set up equation for a curl at $\theta_n$
7553           and |goto found|@>;
7554         break;
7555       case mp_given:
7556         @<Calculate the given value of $\theta_n$
7557           and |goto found|@>;
7558         break;
7559       } /* there are no other cases */
7560     }
7561     r=s; s=t; incr(k);
7562   }
7563 FOUND:
7564   @<Finish choosing angles and assigning control points@>;
7565 }
7566
7567 @ On the first time through the loop, we have |k=0| and |r| is not yet
7568 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7569
7570 @<Get the linear equations started...@>=
7571 switch (right_type(s)) {
7572 case mp_given: 
7573   if ( left_type(t)==mp_given ) {
7574     @<Reduce to simple case of two givens  and |return|@>
7575   } else {
7576     @<Set up the equation for a given value of $\theta_0$@>;
7577   }
7578   break;
7579 case mp_curl: 
7580   if ( left_type(t)==mp_curl ) {
7581     @<Reduce to simple case of straight line and |return|@>
7582   } else {
7583     @<Set up the equation for a curl at $\theta_0$@>;
7584   }
7585   break;
7586 case mp_open: 
7587   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7588   /* this begins a cycle */
7589   break;
7590 } /* there are no other cases */
7591
7592 @ The general equation that specifies equality of mock curvature at $z_k$ is
7593 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7594 as derived above. We want to combine this with the already-derived equation
7595 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7596 a new equation
7597 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7598 equation
7599 $$(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}
7600     -A_kw_{k-1}\theta_0$$
7601 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7602 fixed-point arithmetic, avoiding the chance of overflow while retaining
7603 suitable precision.
7604
7605 The calculations will be performed in several registers that
7606 provide temporary storage for intermediate quantities.
7607
7608 @<Other local variables for |solve_choices|@>=
7609 fraction aa,bb,cc,ff,acc; /* temporary registers */
7610 scaled dd,ee; /* likewise, but |scaled| */
7611 scaled lt,rt; /* tension values */
7612
7613 @ @<Set up equation to match mock curvatures...@>=
7614 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7615     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7616     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7617   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7618   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7619   @<Calculate the values of $v_k$ and $w_k$@>;
7620   if ( left_type(s)==mp_end_cycle ) {
7621     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7622   }
7623 }
7624
7625 @ Since tension values are never less than 3/4, the values |aa| and
7626 |bb| computed here are never more than 4/5.
7627
7628 @<Calculate the values $\\{aa}=...@>=
7629 if ( abs(right_tension(r))==unity) { 
7630   aa=fraction_half; dd=2*mp->delta[k];
7631 } else { 
7632   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7633   dd=mp_take_fraction(mp, mp->delta[k],
7634     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7635 }
7636 if ( abs(left_tension(t))==unity ){ 
7637   bb=fraction_half; ee=2*mp->delta[k-1];
7638 } else { 
7639   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7640   ee=mp_take_fraction(mp, mp->delta[k-1],
7641     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7642 }
7643 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7644
7645 @ The ratio to be calculated in this step can be written in the form
7646 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7647   \\{cc}\cdot\\{dd},$$
7648 because of the quantities just calculated. The values of |dd| and |ee|
7649 will not be needed after this step has been performed.
7650
7651 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7652 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7653 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7654   if ( lt<rt ) { 
7655     ff=mp_make_fraction(mp, lt,rt);
7656     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7657     dd=mp_take_fraction(mp, dd,ff);
7658   } else { 
7659     ff=mp_make_fraction(mp, rt,lt);
7660     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7661     ee=mp_take_fraction(mp, ee,ff);
7662   }
7663 }
7664 ff=mp_make_fraction(mp, ee,ee+dd)
7665
7666 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7667 equation was specified by a curl. In that case we must use a special
7668 method of computation to prevent overflow.
7669
7670 Fortunately, the calculations turn out to be even simpler in this ``hard''
7671 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7672 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7673
7674 @<Calculate the values of $v_k$ and $w_k$@>=
7675 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7676 if ( right_type(r)==mp_curl ) { 
7677   mp->ww[k]=0;
7678   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7679 } else { 
7680   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7681     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7682   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7683   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7684   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7685   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7686   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7687 }
7688
7689 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7690 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7691 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7692 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7693 were no cycle.
7694
7695 The idea in the following code is to observe that
7696 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7697 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7698   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7699 so we can solve for $\theta_n=\theta_0$.
7700
7701 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7702
7703 aa=0; bb=fraction_one; /* we have |k=n| */
7704 do {  decr(k);
7705 if ( k==0 ) k=n;
7706   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7707   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7708 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7709 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7710 mp->theta[n]=aa; mp->vv[0]=aa;
7711 for (k=1;k<=n-1;k++) {
7712   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7713 }
7714 goto FOUND;
7715 }
7716
7717 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7718   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7719
7720 @<Calculate the given value of $\theta_n$...@>=
7721
7722   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7723   reduce_angle(mp->theta[n]);
7724   goto FOUND;
7725 }
7726
7727 @ @<Set up the equation for a given value of $\theta_0$@>=
7728
7729   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7730   reduce_angle(mp->vv[0]);
7731   mp->uu[0]=0; mp->ww[0]=0;
7732 }
7733
7734 @ @<Set up the equation for a curl at $\theta_0$@>=
7735 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7736   if ( (rt==unity)&&(lt==unity) )
7737     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7738   else 
7739     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7740   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7741 }
7742
7743 @ @<Set up equation for a curl at $\theta_n$...@>=
7744 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7745   if ( (rt==unity)&&(lt==unity) )
7746     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7747   else 
7748     ff=mp_curl_ratio(mp, cc,lt,rt);
7749   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7750     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7751   goto FOUND;
7752 }
7753
7754 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7755 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7756 a somewhat tedious program to calculate
7757 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7758   \alpha^3\gamma+(3-\beta)\beta^2},$$
7759 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7760 is necessary only if the curl and tension are both large.)
7761 The values of $\alpha$ and $\beta$ will be at most~4/3.
7762
7763 @<Declare subroutines needed by |solve_choices|@>=
7764 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7765                         scaled b_tension) {
7766   fraction alpha,beta,num,denom,ff; /* registers */
7767   alpha=mp_make_fraction(mp, unity,a_tension);
7768   beta=mp_make_fraction(mp, unity,b_tension);
7769   if ( alpha<=beta ) {
7770     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7771     gamma=mp_take_fraction(mp, gamma,ff);
7772     beta=beta / 010000; /* convert |fraction| to |scaled| */
7773     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7774     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7775   } else { 
7776     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7777     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7778     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7779       /* $1365\approx 2^{12}/3$ */
7780     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7781   }
7782   if ( num>=denom+denom+denom+denom ) return fraction_four;
7783   else return mp_make_fraction(mp, num,denom);
7784 }
7785
7786 @ We're in the home stretch now.
7787
7788 @<Finish choosing angles and assigning control points@>=
7789 for (k=n-1;k>=0;k--) {
7790   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7791 }
7792 s=p; k=0;
7793 do {  
7794   t=link(s);
7795   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7796   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7797   mp_set_controls(mp, s,t,k);
7798   incr(k); s=t;
7799 } while (k!=n)
7800
7801 @ The |set_controls| routine actually puts the control points into
7802 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7803 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7804 $\cos\phi$ needed in this calculation.
7805
7806 @<Glob...@>=
7807 fraction st;
7808 fraction ct;
7809 fraction sf;
7810 fraction cf; /* sines and cosines */
7811
7812 @ @<Declare subroutines needed by |solve_choices|@>=
7813 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7814   fraction rr,ss; /* velocities, divided by thrice the tension */
7815   scaled lt,rt; /* tensions */
7816   fraction sine; /* $\sin(\theta+\phi)$ */
7817   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7818   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7819   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7820   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7821     @<Decrease the velocities,
7822       if necessary, to stay inside the bounding triangle@>;
7823   }
7824   right_x(p)=x_coord(p)+mp_take_fraction(mp, 
7825                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7826                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7827   right_y(p)=y_coord(p)+mp_take_fraction(mp, 
7828                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7829                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7830   left_x(q)=x_coord(q)-mp_take_fraction(mp, 
7831                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7832                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7833   left_y(q)=y_coord(q)-mp_take_fraction(mp, 
7834                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7835                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7836   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7837 }
7838
7839 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7840 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7841 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7842 there is no ``bounding triangle.''
7843
7844 @<Decrease the velocities, if necessary...@>=
7845 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7846   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7847                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7848   if ( sine>0 ) {
7849     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7850     if ( right_tension(p)<0 )
7851      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7852       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7853     if ( left_tension(q)<0 )
7854      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7855       ss=mp_make_fraction(mp, abs(mp->st),sine);
7856   }
7857 }
7858
7859 @ Only the simple cases remain to be handled.
7860
7861 @<Reduce to simple case of two givens and |return|@>=
7862
7863   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7864   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7865   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7866   mp_set_controls(mp, p,q,0); return;
7867 }
7868
7869 @ @<Reduce to simple case of straight line and |return|@>=
7870
7871   right_type(p)=mp_explicit; left_type(q)=mp_explicit;
7872   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7873   if ( rt==unity ) {
7874     if ( mp->delta_x[0]>=0 ) right_x(p)=x_coord(p)+((mp->delta_x[0]+1) / 3);
7875     else right_x(p)=x_coord(p)+((mp->delta_x[0]-1) / 3);
7876     if ( mp->delta_y[0]>=0 ) right_y(p)=y_coord(p)+((mp->delta_y[0]+1) / 3);
7877     else right_y(p)=y_coord(p)+((mp->delta_y[0]-1) / 3);
7878   } else { 
7879     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7880     right_x(p)=x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7881     right_y(p)=y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7882   }
7883   if ( lt==unity ) {
7884     if ( mp->delta_x[0]>=0 ) left_x(q)=x_coord(q)-((mp->delta_x[0]+1) / 3);
7885     else left_x(q)=x_coord(q)-((mp->delta_x[0]-1) / 3);
7886     if ( mp->delta_y[0]>=0 ) left_y(q)=y_coord(q)-((mp->delta_y[0]+1) / 3);
7887     else left_y(q)=y_coord(q)-((mp->delta_y[0]-1) / 3);
7888   } else  { 
7889     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7890     left_x(q)=x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7891     left_y(q)=y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7892   }
7893   return;
7894 }
7895
7896 @* \[19] Measuring paths.
7897 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7898 allow the user to measure the bounding box of anything that can go into a
7899 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7900 by just finding the bounding box of the knots and the control points. We
7901 need a more accurate version of the bounding box, but we can still use the
7902 easy estimate to save time by focusing on the interesting parts of the path.
7903
7904 @ Computing an accurate bounding box involves a theme that will come up again
7905 and again. Given a Bernshte{\u\i}n polynomial
7906 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7907 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7908 we can conveniently bisect its range as follows:
7909
7910 \smallskip
7911 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7912
7913 \smallskip
7914 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7915 |0<=k<n-j|, for |0<=j<n|.
7916
7917 \smallskip\noindent
7918 Then
7919 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7920  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7921 This formula gives us the coefficients of polynomials to use over the ranges
7922 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7923
7924 @ Now here's a subroutine that's handy for all sorts of path computations:
7925 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7926 returns the unique |fraction| value |t| between 0 and~1 at which
7927 $B(a,b,c;t)$ changes from positive to negative, or returns
7928 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7929 is already negative at |t=0|), |crossing_point| returns the value zero.
7930
7931 @d no_crossing {  return (fraction_one+1); }
7932 @d one_crossing { return fraction_one; }
7933 @d zero_crossing { return 0; }
7934 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7935
7936 @c fraction mp_do_crossing_point (integer a, integer b, integer c) {
7937   integer d; /* recursive counter */
7938   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7939   if ( a<0 ) zero_crossing;
7940   if ( c>=0 ) { 
7941     if ( b>=0 ) {
7942       if ( c>0 ) { no_crossing; }
7943       else if ( (a==0)&&(b==0) ) { no_crossing;} 
7944       else { one_crossing; } 
7945     }
7946     if ( a==0 ) zero_crossing;
7947   } else if ( a==0 ) {
7948     if ( b<=0 ) zero_crossing;
7949   }
7950   @<Use bisection to find the crossing point, if one exists@>;
7951 }
7952
7953 @ The general bisection method is quite simple when $n=2$, hence
7954 |crossing_point| does not take much time. At each stage in the
7955 recursion we have a subinterval defined by |l| and~|j| such that
7956 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
7957 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
7958
7959 It is convenient for purposes of calculation to combine the values
7960 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
7961 of bisection then corresponds simply to doubling $d$ and possibly
7962 adding~1. Furthermore it proves to be convenient to modify
7963 our previous conventions for bisection slightly, maintaining the
7964 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
7965 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
7966 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
7967
7968 The following code maintains the invariant relations
7969 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
7970 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
7971 it has been constructed in such a way that no arithmetic overflow
7972 will occur if the inputs satisfy
7973 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
7974
7975 @<Use bisection to find the crossing point...@>=
7976 d=1; x0=a; x1=a-b; x2=b-c;
7977 do {  
7978   x=half(x1+x2);
7979   if ( x1-x0>x0 ) { 
7980     x2=x; x0+=x0; d+=d;  
7981   } else { 
7982     xx=x1+x-x0;
7983     if ( xx>x0 ) { 
7984       x2=x; x0+=x0; d+=d;
7985     }  else { 
7986       x0=x0-xx;
7987       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
7988       x1=x; d=d+d+1;
7989     }
7990   }
7991 } while (d<fraction_one);
7992 return (d-fraction_one)
7993
7994 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
7995 a cubic corresponding to the |fraction| value~|t|.
7996
7997 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
7998 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
7999
8000 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8001
8002 @c scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8003   scaled x1,x2,x3; /* intermediate values */
8004   x1=t_of_the_way(knot_coord(p),right_coord(p));
8005   x2=t_of_the_way(right_coord(p),left_coord(q));
8006   x3=t_of_the_way(left_coord(q),knot_coord(q));
8007   x1=t_of_the_way(x1,x2);
8008   x2=t_of_the_way(x2,x3);
8009   return t_of_the_way(x1,x2);
8010 }
8011
8012 @ The actual bounding box information is stored in global variables.
8013 Since it is convenient to address the $x$ and $y$ information
8014 separately, we define arrays indexed by |x_code..y_code| and use
8015 macros to give them more convenient names.
8016
8017 @<Types...@>=
8018 enum mp_bb_code  {
8019   mp_x_code=0, /* index for |minx| and |maxx| */
8020   mp_y_code /* index for |miny| and |maxy| */
8021 } ;
8022
8023
8024 @d minx mp->bbmin[mp_x_code]
8025 @d maxx mp->bbmax[mp_x_code]
8026 @d miny mp->bbmin[mp_y_code]
8027 @d maxy mp->bbmax[mp_y_code]
8028
8029 @<Glob...@>=
8030 scaled bbmin[mp_y_code+1];
8031 scaled bbmax[mp_y_code+1]; 
8032 /* the result of procedures that compute bounding box information */
8033
8034 @ Now we're ready for the key part of the bounding box computation.
8035 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8036 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8037     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8038 $$
8039 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8040 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8041 The |c| parameter is |x_code| or |y_code|.
8042
8043 @c void mp_bound_cubic (MP mp,pointer p, pointer q, small_number c) {
8044   boolean wavy; /* whether we need to look for extremes */
8045   scaled del1,del2,del3,del,dmax; /* proportional to the control
8046      points of a quadratic derived from a cubic */
8047   fraction t,tt; /* where a quadratic crosses zero */
8048   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8049   x=knot_coord(q);
8050   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8051   @<Check the control points against the bounding box and set |wavy:=true|
8052     if any of them lie outside@>;
8053   if ( wavy ) {
8054     del1=right_coord(p)-knot_coord(p);
8055     del2=left_coord(q)-right_coord(p);
8056     del3=knot_coord(q)-left_coord(q);
8057     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8058       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8059     if ( del<0 ) {
8060       negate(del1); negate(del2); negate(del3);
8061     };
8062     t=mp_crossing_point(mp, del1,del2,del3);
8063     if ( t<fraction_one ) {
8064       @<Test the extremes of the cubic against the bounding box@>;
8065     }
8066   }
8067 }
8068
8069 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8070 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8071 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8072
8073 @ @<Check the control points against the bounding box and set...@>=
8074 wavy=true;
8075 if ( mp->bbmin[c]<=right_coord(p) )
8076   if ( right_coord(p)<=mp->bbmax[c] )
8077     if ( mp->bbmin[c]<=left_coord(q) )
8078       if ( left_coord(q)<=mp->bbmax[c] )
8079         wavy=false
8080
8081 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8082 section. We just set |del=0| in that case.
8083
8084 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8085 if ( del1!=0 ) del=del1;
8086 else if ( del2!=0 ) del=del2;
8087 else del=del3;
8088 if ( del!=0 ) {
8089   dmax=abs(del1);
8090   if ( abs(del2)>dmax ) dmax=abs(del2);
8091   if ( abs(del3)>dmax ) dmax=abs(del3);
8092   while ( dmax<fraction_half ) {
8093     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8094   }
8095 }
8096
8097 @ Since |crossing_point| has tried to choose |t| so that
8098 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8099 slope, the value of |del2| computed below should not be positive.
8100 But rounding error could make it slightly positive in which case we
8101 must cut it to zero to avoid confusion.
8102
8103 @<Test the extremes of the cubic against the bounding box@>=
8104
8105   x=mp_eval_cubic(mp, p,q,t);
8106   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8107   del2=t_of_the_way(del2,del3);
8108     /* now |0,del2,del3| represent the derivative on the remaining interval */
8109   if ( del2>0 ) del2=0;
8110   tt=mp_crossing_point(mp, 0,-del2,-del3);
8111   if ( tt<fraction_one ) {
8112     @<Test the second extreme against the bounding box@>;
8113   }
8114 }
8115
8116 @ @<Test the second extreme against the bounding box@>=
8117 {
8118    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8119   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8120 }
8121
8122 @ Finding the bounding box of a path is basically a matter of applying
8123 |bound_cubic| twice for each pair of adjacent knots.
8124
8125 @c void mp_path_bbox (MP mp,pointer h) {
8126   pointer p,q; /* a pair of adjacent knots */
8127    minx=x_coord(h); miny=y_coord(h);
8128   maxx=minx; maxy=miny;
8129   p=h;
8130   do {  
8131     if ( right_type(p)==mp_endpoint ) return;
8132     q=link(p);
8133     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8134     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8135     p=q;
8136   } while (p!=h);
8137 }
8138
8139 @ Another important way to measure a path is to find its arc length.  This
8140 is best done by using the general bisection algorithm to subdivide the path
8141 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8142 by simple means.
8143
8144 Since the arc length is the integral with respect to time of the magnitude of
8145 the velocity, it is natural to use Simpson's rule for the approximation.
8146 @^Simpson's rule@>
8147 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8148 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8149 for the arc length of a path of length~1.  For a cubic spline
8150 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8151 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8152 approximation is
8153 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8154 where
8155 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8156 is the result of the bisection algorithm.
8157
8158 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8159 This could be done via the theoretical error bound for Simpson's rule,
8160 @^Simpson's rule@>
8161 but this is impractical because it requires an estimate of the fourth
8162 derivative of the quantity being integrated.  It is much easier to just perform
8163 a bisection step and see how much the arc length estimate changes.  Since the
8164 error for Simpson's rule is proportional to the fourth power of the sample
8165 spacing, the remaining error is typically about $1\over16$ of the amount of
8166 the change.  We say ``typically'' because the error has a pseudo-random behavior
8167 that could cause the two estimates to agree when each contain large errors.
8168
8169 To protect against disasters such as undetected cusps, the bisection process
8170 should always continue until all the $dz_i$ vectors belong to a single
8171 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8172 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8173 If such a spline happens to produce an erroneous arc length estimate that
8174 is little changed by bisection, the amount of the error is likely to be fairly
8175 small.  We will try to arrange things so that freak accidents of this type do
8176 not destroy the inverse relationship between the \&{arclength} and
8177 \&{arctime} operations.
8178 @:arclength_}{\&{arclength} primitive@>
8179 @:arctime_}{\&{arctime} primitive@>
8180
8181 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8182 @^recursion@>
8183 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8184 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8185 returns the time when the arc length reaches |a_goal| if there is such a time.
8186 Thus the return value is either an arc length less than |a_goal| or, if the
8187 arc length would be at least |a_goal|, it returns a time value decreased by
8188 |two|.  This allows the caller to use the sign of the result to distinguish
8189 between arc lengths and time values.  On certain types of overflow, it is
8190 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8191 Otherwise, the result is always less than |a_goal|.
8192
8193 Rather than halving the control point coordinates on each recursive call to
8194 |arc_test|, it is better to keep them proportional to velocity on the original
8195 curve and halve the results instead.  This means that recursive calls can
8196 potentially use larger error tolerances in their arc length estimates.  How
8197 much larger depends on to what extent the errors behave as though they are
8198 independent of each other.  To save computing time, we use optimistic assumptions
8199 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8200 call.
8201
8202 In addition to the tolerance parameter, |arc_test| should also have parameters
8203 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8204 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8205 and they are needed in different instances of |arc_test|.
8206
8207 @c @<Declare subroutines needed by |arc_test|@>
8208 scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8209                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8210                     scaled v2, scaled a_goal, scaled tol) {
8211   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8212   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8213   scaled v002, v022;
8214     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8215   scaled arc; /* best arc length estimate before recursion */
8216   @<Other local variables in |arc_test|@>;
8217   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8218     |dx2|, |dy2|@>;
8219   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8220     set |arc_test| and |return|@>;
8221   @<Test if the control points are confined to one quadrant or rotating them
8222     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8223   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8224     if ( arc < a_goal ) {
8225       return arc;
8226     } else {
8227        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8228          that time minus |two|@>;
8229     }
8230   } else {
8231     @<Use one or two recursive calls to compute the |arc_test| function@>;
8232   }
8233 }
8234
8235 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8236 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8237 |make_fraction| in this inner loop.
8238 @^inner loop@>
8239
8240 @<Use one or two recursive calls to compute the |arc_test| function@>=
8241
8242   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8243     large as possible@>;
8244   tol = tol + halfp(tol);
8245   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8246                   halfp(v02), a_new, tol);
8247   if ( a<0 )  {
8248      return (-halfp(two-a));
8249   } else { 
8250     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8251     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8252                     halfp(v02), v022, v2, a_new, tol);
8253     if ( b<0 )  
8254       return (-halfp(-b) - half_unit);
8255     else  
8256       return (a + half(b-a));
8257   }
8258 }
8259
8260 @ @<Other local variables in |arc_test|@>=
8261 scaled a,b; /* results of recursive calls */
8262 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8263
8264 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8265 a_aux = el_gordo - a_goal;
8266 if ( a_goal > a_aux ) {
8267   a_aux = a_goal - a_aux;
8268   a_new = el_gordo;
8269 } else { 
8270   a_new = a_goal + a_goal;
8271   a_aux = 0;
8272 }
8273
8274 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8275 to force the additions and subtractions to be done in an order that avoids
8276 overflow.
8277
8278 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8279 if ( a > a_aux ) {
8280   a_aux = a_aux - a;
8281   a_new = a_new + a_aux;
8282 }
8283
8284 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8285 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8286 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8287 this bound.  Note that recursive calls will maintain this invariant.
8288
8289 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8290 dx01 = half(dx0 + dx1);
8291 dx12 = half(dx1 + dx2);
8292 dx02 = half(dx01 + dx12);
8293 dy01 = half(dy0 + dy1);
8294 dy12 = half(dy1 + dy2);
8295 dy02 = half(dy01 + dy12)
8296
8297 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8298 |a_goal=el_gordo| is guaranteed to yield the arc length.
8299
8300 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8301 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8302 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8303 tmp = halfp(v02+2);
8304 arc1 = v002 + half(halfp(v0+tmp) - v002);
8305 arc = v022 + half(halfp(v2+tmp) - v022);
8306 if ( (arc < el_gordo-arc1) )  {
8307   arc = arc+arc1;
8308 } else { 
8309   mp->arith_error = true;
8310   if ( a_goal==el_gordo )  return (el_gordo);
8311   else return (-two);
8312 }
8313
8314 @ @<Other local variables in |arc_test|@>=
8315 scaled tmp, tmp2; /* all purpose temporary registers */
8316 scaled arc1; /* arc length estimate for the first half */
8317
8318 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8319 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8320          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8321 if ( simple )
8322   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8323            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8324 if ( ! simple ) {
8325   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8326            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8327   if ( simple ) 
8328     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8329              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8330 }
8331
8332 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8333 @^Simpson's rule@>
8334 it is appropriate to use the same approximation to decide when the integral
8335 reaches the intermediate value |a_goal|.  At this point
8336 $$\eqalign{
8337     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8338     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8339     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8340     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8341     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8342 }
8343 $$
8344 and
8345 $$ {\vb\dot B(t)\vb\over 3} \approx
8346   \cases{B\left(\hbox{|v0|},
8347       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8348       {1\over 2}\hbox{|v02|}; 2t \right)&
8349     if $t\le{1\over 2}$\cr
8350   B\left({1\over 2}\hbox{|v02|},
8351       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8352       \hbox{|v2|}; 2t-1 \right)&
8353     if $t\ge{1\over 2}$.\cr}
8354  \eqno (*)
8355 $$
8356 We can integrate $\vb\dot B(t)\vb$ by using
8357 $$\int 3B(a,b,c;\tau)\,dt =
8358   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8359 $$
8360
8361 This construction allows us to find the time when the arc length reaches
8362 |a_goal| by solving a cubic equation of the form
8363 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8364 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8365 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8366 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8367 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8368 $\tau$ given $a$, $b$, $c$, and $x$.
8369
8370 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8371
8372   tmp = (v02 + 2) / 4;
8373   if ( a_goal<=arc1 ) {
8374     tmp2 = halfp(v0);
8375     return 
8376       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8377   } else { 
8378     tmp2 = halfp(v2);
8379     return ((half_unit - two) +
8380       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8381   }
8382 }
8383
8384 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8385 $$ B(0, a, a+b, a+b+c; t) = x. $$
8386 This routine is based on |crossing_point| but is simplified by the
8387 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8388 If rounding error causes this condition to be violated slightly, we just ignore
8389 it and proceed with binary search.  This finds a time when the function value
8390 reaches |x| and the slope is positive.
8391
8392 @<Declare subroutines needed by |arc_test|@>=
8393 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8394   scaled ab, bc, ac; /* bisection results */
8395   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8396   integer xx; /* temporary for updating |x| */
8397   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8398 @:this can't happen rising?}{\quad rising?@>
8399   if ( x<=0 ) {
8400         return 0;
8401   } else if ( x >= a+b+c ) {
8402     return unity;
8403   } else { 
8404     t = 1;
8405     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8406       |el_gordo div 3|@>;
8407     do {  
8408       t+=t;
8409       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8410       xx = x - a - ab - ac;
8411       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8412       else { x = x + xx;  a=ac; b=bc; t = t+1; };
8413     } while (t < unity);
8414     return (t - unity);
8415   }
8416 }
8417
8418 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8419 ab = half(a+b);
8420 bc = half(b+c);
8421 ac = half(ab+bc)
8422
8423 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8424
8425 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8426 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8427   a = halfp(a);
8428   b = half(b);
8429   c = halfp(c);
8430   x = halfp(x);
8431 }
8432
8433 @ It is convenient to have a simpler interface to |arc_test| that requires no
8434 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8435 length less than |fraction_four|.
8436
8437 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8438
8439 @c scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8440                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8441   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8442   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8443   v0 = mp_pyth_add(mp, dx0,dy0);
8444   v1 = mp_pyth_add(mp, dx1,dy1);
8445   v2 = mp_pyth_add(mp, dx2,dy2);
8446   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8447     mp->arith_error = true;
8448     if ( a_goal==el_gordo )  return el_gordo;
8449     else return (-two);
8450   } else { 
8451     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8452     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8453                                  v0, v02, v2, a_goal, arc_tol));
8454   }
8455 }
8456
8457 @ Now it is easy to find the arc length of an entire path.
8458
8459 @c scaled mp_get_arc_length (MP mp,pointer h) {
8460   pointer p,q; /* for traversing the path */
8461   scaled a,a_tot; /* current and total arc lengths */
8462   a_tot = 0;
8463   p = h;
8464   while ( right_type(p)!=mp_endpoint ){ 
8465     q = link(p);
8466     a = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8467       left_x(q)-right_x(p), left_y(q)-right_y(p),
8468       x_coord(q)-left_x(q), y_coord(q)-left_y(q), el_gordo);
8469     a_tot = mp_slow_add(mp, a, a_tot);
8470     if ( q==h ) break;  else p=q;
8471   }
8472   check_arith;
8473   return a_tot;
8474 }
8475
8476 @ The inverse operation of finding the time on a path~|h| when the arc length
8477 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8478 is required to handle very large times or negative times on cyclic paths.  For
8479 non-cyclic paths, |arc0| values that are negative or too large cause
8480 |get_arc_time| to return 0 or the length of path~|h|.
8481
8482 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8483 time value greater than the length of the path.  Since it could be much greater,
8484 we must be prepared to compute the arc length of path~|h| and divide this into
8485 |arc0| to find how many multiples of the length of path~|h| to add.
8486
8487 @c scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8488   pointer p,q; /* for traversing the path */
8489   scaled t_tot; /* accumulator for the result */
8490   scaled t; /* the result of |do_arc_test| */
8491   scaled arc; /* portion of |arc0| not used up so far */
8492   integer n; /* number of extra times to go around the cycle */
8493   if ( arc0<0 ) {
8494     @<Deal with a negative |arc0| value and |return|@>;
8495   }
8496   if ( arc0==el_gordo ) decr(arc0);
8497   t_tot = 0;
8498   arc = arc0;
8499   p = h;
8500   while ( (right_type(p)!=mp_endpoint) && (arc>0) ) {
8501     q = link(p);
8502     t = mp_do_arc_test(mp, right_x(p)-x_coord(p), right_y(p)-y_coord(p),
8503       left_x(q)-right_x(p), left_y(q)-right_y(p),
8504       x_coord(q)-left_x(q), y_coord(q)-left_y(q), arc);
8505     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8506     if ( q==h ) {
8507       @<Update |t_tot| and |arc| to avoid going around the cyclic
8508         path too many times but set |arith_error:=true| and |goto done| on
8509         overflow@>;
8510     }
8511     p = q;
8512   }
8513   check_arith;
8514   return t_tot;
8515 }
8516
8517 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8518 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8519 else { t_tot = t_tot + unity;  arc = arc - t;  }
8520
8521 @ @<Deal with a negative |arc0| value and |return|@>=
8522
8523   if ( left_type(h)==mp_endpoint ) {
8524     t_tot=0;
8525   } else { 
8526     p = mp_htap_ypoc(mp, h);
8527     t_tot = -mp_get_arc_time(mp, p, -arc0);
8528     mp_toss_knot_list(mp, p);
8529   }
8530   check_arith;
8531   return t_tot;
8532 }
8533
8534 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8535 if ( arc>0 ) { 
8536   n = arc / (arc0 - arc);
8537   arc = arc - n*(arc0 - arc);
8538   if ( t_tot > (el_gordo / (n+1)) ) { 
8539         return el_gordo;
8540   }
8541   t_tot = (n + 1)*t_tot;
8542 }
8543
8544 @* \[20] Data structures for pens.
8545 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8546 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8547 @:stroke}{\&{stroke} command@>
8548 converted into an area fill as described in the next part of this program.
8549 The mathematics behind this process is based on simple aspects of the theory
8550 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8551 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8552 Foundations of Computer Science {\bf 24} (1983), 100--111].
8553
8554 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8555 @:makepen_}{\&{makepen} primitive@>
8556 This path representation is almost sufficient for our purposes except that
8557 a pen path should always be a convex polygon with the vertices in
8558 counter-clockwise order.
8559 Since we will need to scan pen polygons both forward and backward, a pen
8560 should be represented as a doubly linked ring of knot nodes.  There is
8561 room for the extra back pointer because we do not need the
8562 |left_type| or |right_type| fields.  In fact, we don't need the |left_x|,
8563 |left_y|, |right_x|, or |right_y| fields either but we leave these alone
8564 so that certain procedures can operate on both pens and paths.  In particular,
8565 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8566
8567 @d knil info
8568   /* this replaces the |left_type| and |right_type| fields in a pen knot */
8569
8570 @ The |make_pen| procedure turns a path into a pen by initializing
8571 the |knil| pointers and making sure the knots form a convex polygon.
8572 Thus each cubic in the given path becomes a straight line and the control
8573 points are ignored.  If the path is not cyclic, the ends are connected by a
8574 straight line.
8575
8576 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8577
8578 @c @<Declare a function called |convex_hull|@>
8579 pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8580   pointer p,q; /* two consecutive knots */
8581   q=h;
8582   do {  
8583     p=q; q=link(q);
8584     knil(q)=p;
8585   } while (q!=h);
8586   if ( need_hull ){ 
8587     h=mp_convex_hull(mp, h);
8588     @<Make sure |h| isn't confused with an elliptical pen@>;
8589   }
8590   return h;
8591 }
8592
8593 @ The only information required about an elliptical pen is the overall
8594 transformation that has been applied to the original \&{pencircle}.
8595 @:pencircle_}{\&{pencircle} primitive@>
8596 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8597 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8598 knot node and transformed as if it were a path.
8599
8600 @d pen_is_elliptical(A) ((A)==link((A)))
8601
8602 @c pointer mp_get_pen_circle (MP mp,scaled diam) {
8603   pointer h; /* the knot node to return */
8604   h=mp_get_node(mp, knot_node_size);
8605   link(h)=h; knil(h)=h;
8606   originator(h)=mp_program_code;
8607   x_coord(h)=0; y_coord(h)=0;
8608   left_x(h)=diam; left_y(h)=0;
8609   right_x(h)=0; right_y(h)=diam;
8610   return h;
8611 }
8612
8613 @ If the polygon being returned by |make_pen| has only one vertex, it will
8614 be interpreted as an elliptical pen.  This is no problem since a degenerate
8615 polygon can equally well be thought of as a degenerate ellipse.  We need only
8616 initialize the |left_x|, |left_y|, |right_x|, and |right_y| fields.
8617
8618 @<Make sure |h| isn't confused with an elliptical pen@>=
8619 if ( pen_is_elliptical( h) ){ 
8620   left_x(h)=x_coord(h); left_y(h)=y_coord(h);
8621   right_x(h)=x_coord(h); right_y(h)=y_coord(h);
8622 }
8623
8624 @ We have to cheat a little here but most operations on pens only use
8625 the first three words in each knot node.
8626 @^data structure assumptions@>
8627
8628 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8629 x_coord(test_pen)=-half_unit;
8630 y_coord(test_pen)=0;
8631 x_coord(test_pen+3)=half_unit;
8632 y_coord(test_pen+3)=0;
8633 x_coord(test_pen+6)=0;
8634 y_coord(test_pen+6)=unity;
8635 link(test_pen)=test_pen+3;
8636 link(test_pen+3)=test_pen+6;
8637 link(test_pen+6)=test_pen;
8638 knil(test_pen)=test_pen+6;
8639 knil(test_pen+3)=test_pen;
8640 knil(test_pen+6)=test_pen+3
8641
8642 @ Printing a polygonal pen is very much like printing a path
8643
8644 @<Declare subroutines for printing expressions@>=
8645 void mp_pr_pen (MP mp,pointer h) {
8646   pointer p,q; /* for list traversal */
8647   if ( pen_is_elliptical(h) ) {
8648     @<Print the elliptical pen |h|@>;
8649   } else { 
8650     p=h;
8651     do {  
8652       mp_print_two(mp, x_coord(p),y_coord(p));
8653       mp_print_nl(mp, " .. ");
8654       @<Advance |p| making sure the links are OK and |return| if there is
8655         a problem@>;
8656      } while (p!=h);
8657      mp_print(mp, "cycle");
8658   }
8659 }
8660
8661 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8662 q=link(p);
8663 if ( (q==null) || (knil(q)!=p) ) { 
8664   mp_print_nl(mp, "???"); return; /* this won't happen */
8665 @.???@>
8666 }
8667 p=q
8668
8669 @ @<Print the elliptical pen |h|@>=
8670
8671 mp_print(mp, "pencircle transformed (");
8672 mp_print_scaled(mp, x_coord(h));
8673 mp_print_char(mp, ',');
8674 mp_print_scaled(mp, y_coord(h));
8675 mp_print_char(mp, ',');
8676 mp_print_scaled(mp, left_x(h)-x_coord(h));
8677 mp_print_char(mp, ',');
8678 mp_print_scaled(mp, right_x(h)-x_coord(h));
8679 mp_print_char(mp, ',');
8680 mp_print_scaled(mp, left_y(h)-y_coord(h));
8681 mp_print_char(mp, ',');
8682 mp_print_scaled(mp, right_y(h)-y_coord(h));
8683 mp_print_char(mp, ')');
8684 }
8685
8686 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8687 message.
8688
8689 @<Declare subroutines for printing expressions@>=
8690 void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) { 
8691   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8692 @.Pen at line...@>
8693   mp_pr_pen(mp, h);
8694   mp_end_diagnostic(mp, true);
8695 }
8696
8697 @ Making a polygonal pen into a path involves restoring the |left_type| and
8698 |right_type| fields and setting the control points so as to make a polygonal
8699 path.
8700
8701 @c 
8702 void mp_make_path (MP mp,pointer h) {
8703   pointer p; /* for traversing the knot list */
8704   small_number k; /* a loop counter */
8705   @<Other local variables in |make_path|@>;
8706   if ( pen_is_elliptical(h) ) {
8707     @<Make the elliptical pen |h| into a path@>;
8708   } else { 
8709     p=h;
8710     do {  
8711       left_type(p)=mp_explicit;
8712       right_type(p)=mp_explicit;
8713       @<copy the coordinates of knot |p| into its control points@>;
8714        p=link(p);
8715     } while (p!=h);
8716   }
8717 }
8718
8719 @ @<copy the coordinates of knot |p| into its control points@>=
8720 left_x(p)=x_coord(p);
8721 left_y(p)=y_coord(p);
8722 right_x(p)=x_coord(p);
8723 right_y(p)=y_coord(p)
8724
8725 @ We need an eight knot path to get a good approximation to an ellipse.
8726
8727 @<Make the elliptical pen |h| into a path@>=
8728
8729   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8730   p=h;
8731   for (k=0;k<=7;k++ ) { 
8732     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8733       transforming it appropriately@>;
8734     if ( k==7 ) link(p)=h;  else link(p)=mp_get_node(mp, knot_node_size);
8735     p=link(p);
8736   }
8737 }
8738
8739 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8740 center_x=x_coord(h);
8741 center_y=y_coord(h);
8742 width_x=left_x(h)-center_x;
8743 width_y=left_y(h)-center_y;
8744 height_x=right_x(h)-center_x;
8745 height_y=right_y(h)-center_y
8746
8747 @ @<Other local variables in |make_path|@>=
8748 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8749 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8750 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8751 scaled dx,dy; /* the vector from knot |p| to its right control point */
8752 integer kk;
8753   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8754
8755 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8756 find the point $k/8$ of the way around the circle and the direction vector
8757 to use there.
8758
8759 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8760 kk=(k+6)% 8;
8761 x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8762            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8763 y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8764            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8765 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8766    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8767 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8768    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8769 right_x(p)=x_coord(p)+dx;
8770 right_y(p)=y_coord(p)+dy;
8771 left_x(p)=x_coord(p)-dx;
8772 left_y(p)=y_coord(p)-dy;
8773 left_type(p)=mp_explicit;
8774 right_type(p)=mp_explicit;
8775 originator(p)=mp_program_code
8776
8777 @ @<Glob...@>=
8778 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8779 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8780
8781 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8782 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8783 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8784 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8785   \approx 0.132608244919772.
8786 $$
8787
8788 @<Set init...@>=
8789 mp->half_cos[0]=fraction_half;
8790 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8791 mp->half_cos[2]=0;
8792 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8793 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8794 mp->d_cos[2]=0;
8795 for (k=3;k<= 4;k++ ) { 
8796   mp->half_cos[k]=-mp->half_cos[4-k];
8797   mp->d_cos[k]=-mp->d_cos[4-k];
8798 }
8799 for (k=5;k<= 7;k++ ) { 
8800   mp->half_cos[k]=mp->half_cos[8-k];
8801   mp->d_cos[k]=mp->d_cos[8-k];
8802 }
8803
8804 @ The |convex_hull| function forces a pen polygon to be convex when it is
8805 returned by |make_pen| and after any subsequent transformation where rounding
8806 error might allow the convexity to be lost.
8807 The convex hull algorithm used here is described by F.~P. Preparata and
8808 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8809
8810 @<Declare a function called |convex_hull|@>=
8811 @<Declare a procedure called |move_knot|@>
8812 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8813   pointer l,r; /* the leftmost and rightmost knots */
8814   pointer p,q; /* knots being scanned */
8815   pointer s; /* the starting point for an upcoming scan */
8816   scaled dx,dy; /* a temporary pointer */
8817   if ( pen_is_elliptical(h) ) {
8818      return h;
8819   } else { 
8820     @<Set |l| to the leftmost knot in polygon~|h|@>;
8821     @<Set |r| to the rightmost knot in polygon~|h|@>;
8822     if ( l!=r ) { 
8823       s=link(r);
8824       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8825         move them past~|r|@>;
8826       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8827         move them past~|l|@>;
8828       @<Sort the path from |l| to |r| by increasing $x$@>;
8829       @<Sort the path from |r| to |l| by decreasing $x$@>;
8830     }
8831     if ( l!=link(l) ) {
8832       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8833     }
8834     return l;
8835   }
8836 }
8837
8838 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8839
8840 @<Set |l| to the leftmost knot in polygon~|h|@>=
8841 l=h;
8842 p=link(h);
8843 while ( p!=h ) { 
8844   if ( x_coord(p)<=x_coord(l) )
8845     if ( (x_coord(p)<x_coord(l)) || (y_coord(p)<y_coord(l)) )
8846       l=p;
8847   p=link(p);
8848 }
8849
8850 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8851 r=h;
8852 p=link(h);
8853 while ( p!=h ) { 
8854   if ( x_coord(p)>=x_coord(r) )
8855     if ( (x_coord(p)>x_coord(r)) || (y_coord(p)>y_coord(r)) )
8856       r=p;
8857   p=link(p);
8858 }
8859
8860 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8861 dx=x_coord(r)-x_coord(l);
8862 dy=y_coord(r)-y_coord(l);
8863 p=link(l);
8864 while ( p!=r ) { 
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, r);
8868   p=q;
8869 }
8870
8871 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8872 it after |q|.
8873
8874 @ @<Declare a procedure called |move_knot|@>=
8875 void mp_move_knot (MP mp,pointer p, pointer q) { 
8876   link(knil(p))=link(p);
8877   knil(link(p))=knil(p);
8878   knil(p)=q;
8879   link(p)=link(q);
8880   link(q)=p;
8881   knil(link(p))=p;
8882 }
8883
8884 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8885 p=s;
8886 while ( p!=l ) { 
8887   q=link(p);
8888   if ( mp_ab_vs_cd(mp, dx,y_coord(p)-y_coord(l),dy,x_coord(p)-x_coord(l))<0 )
8889     mp_move_knot(mp, p,l);
8890   p=q;
8891 }
8892
8893 @ The list is likely to be in order already so we just do linear insertions.
8894 Secondary comparisons on $y$ ensure that the sort is consistent with the
8895 choice of |l| and |r|.
8896
8897 @<Sort the path from |l| to |r| by increasing $x$@>=
8898 p=link(l);
8899 while ( p!=r ) { 
8900   q=knil(p);
8901   while ( x_coord(q)>x_coord(p) ) q=knil(q);
8902   while ( x_coord(q)==x_coord(p) ) {
8903     if ( y_coord(q)>y_coord(p) ) q=knil(q); else break;
8904   }
8905   if ( q==knil(p) ) p=link(p);
8906   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8907 }
8908
8909 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8910 p=link(r);
8911 while ( p!=l ){ 
8912   q=knil(p);
8913   while ( x_coord(q)<x_coord(p) ) q=knil(q);
8914   while ( x_coord(q)==x_coord(p) ) {
8915     if ( y_coord(q)<y_coord(p) ) q=knil(q); else break;
8916   }
8917   if ( q==knil(p) ) p=link(p);
8918   else { p=link(p); mp_move_knot(mp, knil(p),q); };
8919 }
8920
8921 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8922 at knot |q|.  There usually will be a left turn so we streamline the case
8923 where the |then| clause is not executed.
8924
8925 @<Do a Gramm scan and remove vertices where there...@>=
8926
8927 p=l; q=link(l);
8928 while (1) { 
8929   dx=x_coord(q)-x_coord(p);
8930   dy=y_coord(q)-y_coord(p);
8931   p=q; q=link(q);
8932   if ( p==l ) break;
8933   if ( p!=r )
8934     if ( mp_ab_vs_cd(mp, dx,y_coord(q)-y_coord(p),dy,x_coord(q)-x_coord(p))<=0 ) {
8935       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
8936     }
8937   }
8938 }
8939
8940 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
8941
8942 s=knil(p);
8943 mp_free_node(mp, p,knot_node_size);
8944 link(s)=q; knil(q)=s;
8945 if ( s==l ) p=s;
8946 else { p=knil(s); q=s; };
8947 }
8948
8949 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
8950 offset associated with the given direction |(x,y)|.  If two different offsets
8951 apply, it chooses one of them.
8952
8953 @c 
8954 void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
8955   pointer p,q; /* consecutive knots */
8956   scaled wx,wy,hx,hy;
8957   /* the transformation matrix for an elliptical pen */
8958   fraction xx,yy; /* untransformed offset for an elliptical pen */
8959   fraction d; /* a temporary register */
8960   if ( pen_is_elliptical(h) ) {
8961     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
8962   } else { 
8963     q=h;
8964     do {  
8965       p=q; q=link(q);
8966     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)>=0));
8967     do {  
8968       p=q; q=link(q);
8969     } while (!(mp_ab_vs_cd(mp, x_coord(q)-x_coord(p),y, y_coord(q)-y_coord(p),x)<=0));
8970     mp->cur_x=x_coord(p);
8971     mp->cur_y=y_coord(p);
8972   }
8973 }
8974
8975 @ @<Glob...@>=
8976 scaled cur_x;
8977 scaled cur_y; /* all-purpose return value registers */
8978
8979 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
8980 if ( (x==0) && (y==0) ) {
8981   mp->cur_x=x_coord(h); mp->cur_y=y_coord(h);  
8982 } else { 
8983   @<Find the non-constant part of the transformation for |h|@>;
8984   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
8985     x+=x; y+=y;  
8986   };
8987   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
8988     untransformed version of |(x,y)|@>;
8989   mp->cur_x=x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
8990   mp->cur_y=y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
8991 }
8992
8993 @ @<Find the non-constant part of the transformation for |h|@>=
8994 wx=left_x(h)-x_coord(h);
8995 wy=left_y(h)-y_coord(h);
8996 hx=right_x(h)-x_coord(h);
8997 hy=right_y(h)-y_coord(h)
8998
8999 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9000 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9001 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9002 d=mp_pyth_add(mp, xx,yy);
9003 if ( d>0 ) { 
9004   xx=half(mp_make_fraction(mp, xx,d));
9005   yy=half(mp_make_fraction(mp, yy,d));
9006 }
9007
9008 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9009 But we can handle that case by just calling |find_offset| twice.  The answer
9010 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9011
9012 @c 
9013 void mp_pen_bbox (MP mp,pointer h) {
9014   pointer p; /* for scanning the knot list */
9015   if ( pen_is_elliptical(h) ) {
9016     @<Find the bounding box of an elliptical pen@>;
9017   } else { 
9018     minx=x_coord(h); maxx=minx;
9019     miny=y_coord(h); maxy=miny;
9020     p=link(h);
9021     while ( p!=h ) {
9022       if ( x_coord(p)<minx ) minx=x_coord(p);
9023       if ( y_coord(p)<miny ) miny=y_coord(p);
9024       if ( x_coord(p)>maxx ) maxx=x_coord(p);
9025       if ( y_coord(p)>maxy ) maxy=y_coord(p);
9026       p=link(p);
9027     }
9028   }
9029 }
9030
9031 @ @<Find the bounding box of an elliptical pen@>=
9032
9033 mp_find_offset(mp, 0,fraction_one,h);
9034 maxx=mp->cur_x;
9035 minx=2*x_coord(h)-mp->cur_x;
9036 mp_find_offset(mp, -fraction_one,0,h);
9037 maxy=mp->cur_y;
9038 miny=2*y_coord(h)-mp->cur_y;
9039 }
9040
9041 @* \[21] Edge structures.
9042 Now we come to \MP's internal scheme for representing pictures.
9043 The representation is very different from \MF's edge structures
9044 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9045 images.  However, the basic idea is somewhat similar in that shapes
9046 are represented via their boundaries.
9047
9048 The main purpose of edge structures is to keep track of graphical objects
9049 until it is time to translate them into \ps.  Since \MP\ does not need to
9050 know anything about an edge structure other than how to translate it into
9051 \ps\ and how to find its bounding box, edge structures can be just linked
9052 lists of graphical objects.  \MP\ has no easy way to determine whether
9053 two such objects overlap, but it suffices to draw the first one first and
9054 let the second one overwrite it if necessary.
9055
9056 @<Types...@>=
9057 enum mp_graphical_object_code {
9058   @<Graphical object codes@>
9059   mp_final_graphic
9060 };
9061
9062 @ Let's consider the types of graphical objects one at a time.
9063 First of all, a filled contour is represented by a eight-word node.  The first
9064 word contains |type| and |link| fields, and the next six words contain a
9065 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9066 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9067 give the relevant information.
9068
9069 @d path_p(A) link((A)+1)
9070   /* a pointer to the path that needs filling */
9071 @d pen_p(A) info((A)+1)
9072   /* a pointer to the pen to fill or stroke with */
9073 @d color_model(A) type((A)+2) /*  the color model  */
9074 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9075 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9076 @d obj_grey_loc obj_red_loc  /* the location for the color */
9077 @d red_val(A) mp->mem[(A)+3].sc
9078   /* the red component of the color in the range $0\ldots1$ */
9079 @d cyan_val red_val
9080 @d grey_val red_val
9081 @d green_val(A) mp->mem[(A)+4].sc
9082   /* the green component of the color in the range $0\ldots1$ */
9083 @d magenta_val green_val
9084 @d blue_val(A) mp->mem[(A)+5].sc
9085   /* the blue component of the color in the range $0\ldots1$ */
9086 @d yellow_val blue_val
9087 @d black_val(A) mp->mem[(A)+6].sc
9088   /* the blue component of the color in the range $0\ldots1$ */
9089 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9090 @:mp_linejoin_}{\&{linejoin} primitive@>
9091 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9092 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9093 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9094   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9095 @d pre_script(A) mp->mem[(A)+8].hh.lh
9096 @d post_script(A) mp->mem[(A)+8].hh.rh
9097 @d fill_node_size 9
9098
9099 @ @<Graphical object codes@>=
9100 mp_fill_code=1,
9101
9102 @ @c 
9103 pointer mp_new_fill_node (MP mp,pointer p) {
9104   /* make a fill node for cyclic path |p| and color black */
9105   pointer t; /* the new node */
9106   t=mp_get_node(mp, fill_node_size);
9107   type(t)=mp_fill_code;
9108   path_p(t)=p;
9109   pen_p(t)=null; /* |null| means don't use a pen */
9110   red_val(t)=0;
9111   green_val(t)=0;
9112   blue_val(t)=0;
9113   black_val(t)=0;
9114   color_model(t)=mp_uninitialized_model;
9115   pre_script(t)=null;
9116   post_script(t)=null;
9117   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9118   return t;
9119 }
9120
9121 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9122 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9123 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9124 else ljoin_val(t)=0;
9125 if ( mp->internal[mp_miterlimit]<unity )
9126   miterlim_val(t)=unity;
9127 else
9128   miterlim_val(t)=mp->internal[mp_miterlimit]
9129
9130 @ A stroked path is represented by an eight-word node that is like a filled
9131 contour node except that it contains the current \&{linecap} value, a scale
9132 factor for the dash pattern, and a pointer that is non-null if the stroke
9133 is to be dashed.  The purpose of the scale factor is to allow a picture to
9134 be transformed without touching the picture that |dash_p| points to.
9135
9136 @d dash_p(A) link((A)+9)
9137   /* a pointer to the edge structure that gives the dash pattern */
9138 @d lcap_val(A) type((A)+9)
9139   /* the value of \&{linecap} */
9140 @:mp_linecap_}{\&{linecap} primitive@>
9141 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9142 @d stroked_node_size 11
9143
9144 @ @<Graphical object codes@>=
9145 mp_stroked_code=2,
9146
9147 @ @c 
9148 pointer mp_new_stroked_node (MP mp,pointer p) {
9149   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9150   pointer t; /* the new node */
9151   t=mp_get_node(mp, stroked_node_size);
9152   type(t)=mp_stroked_code;
9153   path_p(t)=p; pen_p(t)=null;
9154   dash_p(t)=null;
9155   dash_scale(t)=unity;
9156   red_val(t)=0;
9157   green_val(t)=0;
9158   blue_val(t)=0;
9159   black_val(t)=0;
9160   color_model(t)=mp_uninitialized_model;
9161   pre_script(t)=null;
9162   post_script(t)=null;
9163   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9164   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9165   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9166   else lcap_val(t)=0;
9167   return t;
9168 }
9169
9170 @ When a dashed line is computed in a transformed coordinate system, the dash
9171 lengths get scaled like the pen shape and we need to compensate for this.  Since
9172 there is no unique scale factor for an arbitrary transformation, we use the
9173 the square root of the determinant.  The properties of the determinant make it
9174 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9175 except for the initialization of the scale factor |s|.  The factor of 64 is
9176 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9177 to counteract the effect of |take_fraction|.
9178
9179 @<Declare subroutines needed by |print_edges|@>=
9180 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9181   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9182   integer s; /* amount by which the result of |square_rt| needs to be scaled */
9183   @<Initialize |maxabs|@>;
9184   s=64;
9185   while ( (maxabs<fraction_one) && (s>1) ){ 
9186     a+=a; b+=b; c+=c; d+=d;
9187     maxabs+=maxabs; s=halfp(s);
9188   }
9189   return s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c)));
9190 }
9191 @#
9192 scaled mp_get_pen_scale (MP mp,pointer p) { 
9193   return mp_sqrt_det(mp, 
9194     left_x(p)-x_coord(p), right_x(p)-x_coord(p),
9195     left_y(p)-y_coord(p), right_y(p)-y_coord(p));
9196 }
9197
9198 @ @<Internal library ...@>=
9199 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9200
9201
9202 @ @<Initialize |maxabs|@>=
9203 maxabs=abs(a);
9204 if ( abs(b)>maxabs ) maxabs=abs(b);
9205 if ( abs(c)>maxabs ) maxabs=abs(c);
9206 if ( abs(d)>maxabs ) maxabs=abs(d)
9207
9208 @ When a picture contains text, this is represented by a fourteen-word node
9209 where the color information and |type| and |link| fields are augmented by
9210 additional fields that describe the text and  how it is transformed.
9211 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9212 the font and a string number that gives the text to be displayed.
9213 The |width|, |height|, and |depth| fields
9214 give the dimensions of the text at its design size, and the remaining six
9215 words give a transformation to be applied to the text.  The |new_text_node|
9216 function initializes everything to default values so that the text comes out
9217 black with its reference point at the origin.
9218
9219 @d text_p(A) link((A)+1)  /* a string pointer for the text to display */
9220 @d font_n(A) info((A)+1)  /* the font number */
9221 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9222 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9223 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9224 @d text_tx_loc(A) ((A)+11)
9225   /* the first of six locations for transformation parameters */
9226 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9227 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9228 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9229 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9230 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9231 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9232 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9233     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9234 @d text_node_size 17
9235
9236 @ @<Graphical object codes@>=
9237 mp_text_code=3,
9238
9239 @ @c @<Declare text measuring subroutines@>
9240 pointer mp_new_text_node (MP mp,char *f,str_number s) {
9241   /* make a text node for font |f| and text string |s| */
9242   pointer t; /* the new node */
9243   t=mp_get_node(mp, text_node_size);
9244   type(t)=mp_text_code;
9245   text_p(t)=s;
9246   font_n(t)=mp_find_font(mp, f); /* this identifies the font */
9247   red_val(t)=0;
9248   green_val(t)=0;
9249   blue_val(t)=0;
9250   black_val(t)=0;
9251   color_model(t)=mp_uninitialized_model;
9252   pre_script(t)=null;
9253   post_script(t)=null;
9254   tx_val(t)=0; ty_val(t)=0;
9255   txx_val(t)=unity; txy_val(t)=0;
9256   tyx_val(t)=0; tyy_val(t)=unity;
9257   mp_set_text_box(mp, t); /* this finds the bounding box */
9258   return t;
9259 }
9260
9261 @ The last two types of graphical objects that can occur in an edge structure
9262 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9263 @:set_bounds_}{\&{setbounds} primitive@>
9264 to implement because we must keep track of exactly what is being clipped or
9265 bounded when pictures get merged together.  For this reason, each clipping or
9266 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9267 two-word node whose |path_p| gives the relevant path, then there is the list
9268 of objects to clip or bound followed by a two-word node whose second word is
9269 unused.
9270
9271 Using at least two words for each graphical object node allows them all to be
9272 allocated and deallocated similarly with a global array |gr_object_size| to
9273 give the size in words for each object type.
9274
9275 @d start_clip_size 2
9276 @d start_bounds_size 2
9277 @d stop_clip_size 2 /* the second word is not used here */
9278 @d stop_bounds_size 2 /* the second word is not used here */
9279 @#
9280 @d stop_type(A) ((A)+2)
9281   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9282 @d has_color(A) (type((A))<mp_start_clip_code)
9283   /* does a graphical object have color fields? */
9284 @d has_pen(A) (type((A))<mp_text_code)
9285   /* does a graphical object have a |pen_p| field? */
9286 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9287 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9288
9289 @ @<Graphical object codes@>=
9290 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9291 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9292 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9293 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9294
9295 @ @c 
9296 pointer mp_new_bounds_node (MP mp,pointer p, small_number  c) {
9297   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9298   pointer t; /* the new node */
9299   t=mp_get_node(mp, mp->gr_object_size[c]);
9300   type(t)=c;
9301   path_p(t)=p;
9302   return t;
9303 }
9304
9305 @ We need an array to keep track of the sizes of graphical objects.
9306
9307 @<Glob...@>=
9308 small_number gr_object_size[mp_stop_bounds_code+1];
9309
9310 @ @<Set init...@>=
9311 mp->gr_object_size[mp_fill_code]=fill_node_size;
9312 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9313 mp->gr_object_size[mp_text_code]=text_node_size;
9314 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9315 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9316 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9317 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9318
9319 @ All the essential information in an edge structure is encoded as a linked list
9320 of graphical objects as we have just seen, but it is helpful to add some
9321 redundant information.  A single edge structure might be used as a dash pattern
9322 many times, and it would be nice to avoid scanning the same structure
9323 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9324 has a header that gives a list of dashes in a sorted order designed for rapid
9325 translation into \ps.
9326
9327 Each dash is represented by a three-word node containing the initial and final
9328 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9329 the dash node with the next higher $x$-coordinates and the final link points
9330 to a special location called |null_dash|.  (There should be no overlap between
9331 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9332 the period of repetition, this needs to be stored in the edge header along
9333 with a pointer to the list of dash nodes.
9334
9335 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9336 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9337 @d dash_node_size 3
9338 @d dash_list link
9339   /* in an edge header this points to the first dash node */
9340 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9341
9342 @ It is also convenient for an edge header to contain the bounding
9343 box information needed by the \&{llcorner} and \&{urcorner} operators
9344 so that this does not have to be recomputed unnecessarily.  This is done by
9345 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9346 how far the bounding box computation has gotten.  Thus if the user asks for
9347 the bounding box and then adds some more text to the picture before asking
9348 for more bounding box information, the second computation need only look at
9349 the additional text.
9350
9351 When the bounding box has not been computed, the |bblast| pointer points
9352 to a dummy link at the head of the graphical object list while the |minx_val|
9353 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9354 fields contain |-el_gordo|.
9355
9356 Since the bounding box of pictures containing objects of type
9357 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9358 @:mp_true_corners_}{\&{truecorners} primitive@>
9359 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9360 field is needed to keep track of this.
9361
9362 @d minx_val(A) mp->mem[(A)+2].sc
9363 @d miny_val(A) mp->mem[(A)+3].sc
9364 @d maxx_val(A) mp->mem[(A)+4].sc
9365 @d maxy_val(A) mp->mem[(A)+5].sc
9366 @d bblast(A) link((A)+6)  /* last item considered in bounding box computation */
9367 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9368 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9369 @d no_bounds 0
9370   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9371 @d bounds_set 1
9372   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9373 @d bounds_unset 2
9374   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9375
9376 @c 
9377 void mp_init_bbox (MP mp,pointer h) {
9378   /* Initialize the bounding box information in edge structure |h| */
9379   bblast(h)=dummy_loc(h);
9380   bbtype(h)=no_bounds;
9381   minx_val(h)=el_gordo;
9382   miny_val(h)=el_gordo;
9383   maxx_val(h)=-el_gordo;
9384   maxy_val(h)=-el_gordo;
9385 }
9386
9387 @ The only other entries in an edge header are a reference count in the first
9388 word and a pointer to the tail of the object list in the last word.
9389
9390 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9391 @d edge_header_size 8
9392
9393 @c 
9394 void mp_init_edges (MP mp,pointer h) {
9395   /* initialize an edge header to null values */
9396   dash_list(h)=null_dash;
9397   obj_tail(h)=dummy_loc(h);
9398   link(dummy_loc(h))=null;
9399   ref_count(h)=null;
9400   mp_init_bbox(mp, h);
9401 }
9402
9403 @ Here is how edge structures are deleted.  The process can be recursive because
9404 of the need to dereference edge structures that are used as dash patterns.
9405 @^recursion@>
9406
9407 @d add_edge_ref(A) incr(ref_count(A))
9408 @d delete_edge_ref(A) { 
9409    if ( ref_count((A))==null ) 
9410      mp_toss_edges(mp, A);
9411    else 
9412      decr(ref_count(A)); 
9413    }
9414
9415 @<Declare the recycling subroutines@>=
9416 void mp_flush_dash_list (MP mp,pointer h);
9417 pointer mp_toss_gr_object (MP mp,pointer p) ;
9418 void mp_toss_edges (MP mp,pointer h) ;
9419
9420 @ @c void mp_toss_edges (MP mp,pointer h) {
9421   pointer p,q;  /* pointers that scan the list being recycled */
9422   pointer r; /* an edge structure that object |p| refers to */
9423   mp_flush_dash_list(mp, h);
9424   q=link(dummy_loc(h));
9425   while ( (q!=null) ) { 
9426     p=q; q=link(q);
9427     r=mp_toss_gr_object(mp, p);
9428     if ( r!=null ) delete_edge_ref(r);
9429   }
9430   mp_free_node(mp, h,edge_header_size);
9431 }
9432 void mp_flush_dash_list (MP mp,pointer h) {
9433   pointer p,q;  /* pointers that scan the list being recycled */
9434   q=dash_list(h);
9435   while ( q!=null_dash ) { 
9436     p=q; q=link(q);
9437     mp_free_node(mp, p,dash_node_size);
9438   }
9439   dash_list(h)=null_dash;
9440 }
9441 pointer mp_toss_gr_object (MP mp,pointer p) {
9442   /* returns an edge structure that needs to be dereferenced */
9443   pointer e; /* the edge structure to return */
9444   e=null;
9445   @<Prepare to recycle graphical object |p|@>;
9446   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9447   return e;
9448 }
9449
9450 @ @<Prepare to recycle graphical object |p|@>=
9451 switch (type(p)) {
9452 case mp_fill_code: 
9453   mp_toss_knot_list(mp, path_p(p));
9454   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9455   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9456   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9457   break;
9458 case mp_stroked_code: 
9459   mp_toss_knot_list(mp, path_p(p));
9460   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9461   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9462   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9463   e=dash_p(p);
9464   break;
9465 case mp_text_code: 
9466   delete_str_ref(text_p(p));
9467   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9468   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9469   break;
9470 case mp_start_clip_code:
9471 case mp_start_bounds_code: 
9472   mp_toss_knot_list(mp, path_p(p));
9473   break;
9474 case mp_stop_clip_code:
9475 case mp_stop_bounds_code: 
9476   break;
9477 } /* there are no other cases */
9478
9479 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9480 to be done before making a significant change to an edge structure.  Much of
9481 the work is done in a separate routine |copy_objects| that copies a list of
9482 graphical objects into a new edge header.
9483
9484 @c @<Declare a function called |copy_objects|@>
9485 pointer mp_private_edges (MP mp,pointer h) {
9486   /* make a private copy of the edge structure headed by |h| */
9487   pointer hh;  /* the edge header for the new copy */
9488   pointer p,pp;  /* pointers for copying the dash list */
9489   if ( ref_count(h)==null ) {
9490     return h;
9491   } else { 
9492     decr(ref_count(h));
9493     hh=mp_copy_objects(mp, link(dummy_loc(h)),null);
9494     @<Copy the dash list from |h| to |hh|@>;
9495     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9496       point into the new object list@>;
9497     return hh;
9498   }
9499 }
9500
9501 @ Here we use the fact that |dash_list(hh)=link(hh)|.
9502 @^data structure assumptions@>
9503
9504 @<Copy the dash list from |h| to |hh|@>=
9505 pp=hh; p=dash_list(h);
9506 while ( (p!=null_dash) ) { 
9507   link(pp)=mp_get_node(mp, dash_node_size);
9508   pp=link(pp);
9509   start_x(pp)=start_x(p);
9510   stop_x(pp)=stop_x(p);
9511   p=link(p);
9512 }
9513 link(pp)=null_dash;
9514 dash_y(hh)=dash_y(h)
9515
9516
9517 @ |h| is an edge structure
9518
9519 @c
9520 mp_dash_object *mp_export_dashes (MP mp, pointer h) {
9521   mp_dash_object *d;
9522   pointer p;
9523   scaled *dashes = NULL;
9524   int num_dashes = 1;
9525   if (h==null ||  dash_list(h)==null_dash) 
9526         return NULL;
9527   p = dash_list(h);
9528   d = mp_xmalloc(mp,1,sizeof(mp_dash_object));
9529   start_x(null_dash)=start_x(p)+dash_y(h);
9530   while (p != null_dash) { 
9531         dashes = mp_xrealloc(mp, dashes, num_dashes+2, sizeof(scaled));
9532         dashes[(num_dashes-1)] = (stop_x(p)-start_x(p));
9533         dashes[(num_dashes)]   = (start_x(link(p))-stop_x(p));
9534         dashes[(num_dashes+1)] = -1; /* terminus */
9535         num_dashes+=2;
9536     p=link(p);
9537   }
9538   d->array_field  = dashes;
9539   d->offset_field = mp_dash_offset(mp, h);
9540   d->scale_field  = dash_scale(h);
9541   return d;
9542 }
9543
9544
9545
9546 @ @<Copy the bounding box information from |h| to |hh|...@>=
9547 minx_val(hh)=minx_val(h);
9548 miny_val(hh)=miny_val(h);
9549 maxx_val(hh)=maxx_val(h);
9550 maxy_val(hh)=maxy_val(h);
9551 bbtype(hh)=bbtype(h);
9552 p=dummy_loc(h); pp=dummy_loc(hh);
9553 while ((p!=bblast(h)) ) { 
9554   if ( p==null ) mp_confusion(mp, "bblast");
9555 @:this can't happen bblast}{\quad bblast@>
9556   p=link(p); pp=link(pp);
9557 }
9558 bblast(hh)=pp
9559
9560 @ Here is the promised routine for copying graphical objects into a new edge
9561 structure.  It starts copying at object~|p| and stops just before object~|q|.
9562 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9563 structure requires further initialization by |init_bbox|.
9564
9565 @<Declare a function called |copy_objects|@>=
9566 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9567   pointer hh;  /* the new edge header */
9568   pointer pp;  /* the last newly copied object */
9569   small_number k;  /* temporary register */
9570   hh=mp_get_node(mp, edge_header_size);
9571   dash_list(hh)=null_dash;
9572   ref_count(hh)=null;
9573   pp=dummy_loc(hh);
9574   while ( (p!=q) ) {
9575     @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9576   }
9577   obj_tail(hh)=pp;
9578   link(pp)=null;
9579   return hh;
9580 }
9581
9582 @ @<Make |link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9583 { k=mp->gr_object_size[type(p)];
9584   link(pp)=mp_get_node(mp, k);
9585   pp=link(pp);
9586   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9587   @<Fix anything in graphical object |pp| that should differ from the
9588     corresponding field in |p|@>;
9589   p=link(p);
9590 }
9591
9592 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9593 switch (type(p)) {
9594 case mp_start_clip_code:
9595 case mp_start_bounds_code: 
9596   path_p(pp)=mp_copy_path(mp, path_p(p));
9597   break;
9598 case mp_fill_code: 
9599   path_p(pp)=mp_copy_path(mp, path_p(p));
9600   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9601   break;
9602 case mp_stroked_code: 
9603   path_p(pp)=mp_copy_path(mp, path_p(p));
9604   pen_p(pp)=copy_pen(pen_p(p));
9605   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9606   break;
9607 case mp_text_code: 
9608   add_str_ref(text_p(pp));
9609   break;
9610 case mp_stop_clip_code:
9611 case mp_stop_bounds_code: 
9612   break;
9613 }  /* there are no other cases */
9614
9615 @ Here is one way to find an acceptable value for the second argument to
9616 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9617 skips past one picture component, where a ``picture component'' is a single
9618 graphical object, or a start bounds or start clip object and everything up
9619 through the matching stop bounds or stop clip object.  The macro version avoids
9620 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9621 unless |p| points to a stop bounds or stop clip node, in which case it executes
9622 |e| instead.
9623
9624 @d skip_component(A)
9625     if ( ! is_start_or_stop((A)) ) (A)=link((A));
9626     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9627     else 
9628
9629 @c 
9630 pointer mp_skip_1component (MP mp,pointer p) {
9631   integer lev; /* current nesting level */
9632   lev=0;
9633   do {  
9634    if ( is_start_or_stop(p) ) {
9635      if ( is_stop(p) ) decr(lev);  else incr(lev);
9636    }
9637    p=link(p);
9638   } while (lev!=0);
9639   return p;
9640 }
9641
9642 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9643
9644 @<Declare subroutines for printing expressions@>=
9645 @<Declare subroutines needed by |print_edges|@>
9646 void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) {
9647   pointer p;  /* a graphical object to be printed */
9648   pointer hh,pp;  /* temporary pointers */
9649   scaled scf;  /* a scale factor for the dash pattern */
9650   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9651   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9652   p=dummy_loc(h);
9653   while ( link(p)!=null ) { 
9654     p=link(p);
9655     mp_print_ln(mp);
9656     switch (type(p)) {
9657       @<Cases for printing graphical object node |p|@>;
9658     default: 
9659           mp_print(mp, "[unknown object type!]");
9660           break;
9661     }
9662   }
9663   mp_print_nl(mp, "End edges");
9664   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9665 @.End edges?@>
9666   mp_end_diagnostic(mp, true);
9667 }
9668
9669 @ @<Cases for printing graphical object node |p|@>=
9670 case mp_fill_code: 
9671   mp_print(mp, "Filled contour ");
9672   mp_print_obj_color(mp, p);
9673   mp_print_char(mp, ':'); mp_print_ln(mp);
9674   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9675   if ( (pen_p(p)!=null) ) {
9676     @<Print join type for graphical object |p|@>;
9677     mp_print(mp, " with pen"); mp_print_ln(mp);
9678     mp_pr_pen(mp, pen_p(p));
9679   }
9680   break;
9681
9682 @ @<Print join type for graphical object |p|@>=
9683 switch (ljoin_val(p)) {
9684 case 0:
9685   mp_print(mp, "mitered joins limited ");
9686   mp_print_scaled(mp, miterlim_val(p));
9687   break;
9688 case 1:
9689   mp_print(mp, "round joins");
9690   break;
9691 case 2:
9692   mp_print(mp, "beveled joins");
9693   break;
9694 default: 
9695   mp_print(mp, "?? joins");
9696 @.??@>
9697   break;
9698 }
9699
9700 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9701
9702 @<Print join and cap types for stroked node |p|@>=
9703 switch (lcap_val(p)) {
9704 case 0:mp_print(mp, "butt"); break;
9705 case 1:mp_print(mp, "round"); break;
9706 case 2:mp_print(mp, "square"); break;
9707 default: mp_print(mp, "??"); break;
9708 @.??@>
9709 }
9710 mp_print(mp, " ends, ");
9711 @<Print join type for graphical object |p|@>
9712
9713 @ Here is a routine that prints the color of a graphical object if it isn't
9714 black (the default color).
9715
9716 @<Declare subroutines needed by |print_edges|@>=
9717 @<Declare a procedure called |print_compact_node|@>
9718 void mp_print_obj_color (MP mp,pointer p) { 
9719   if ( color_model(p)==mp_grey_model ) {
9720     if ( grey_val(p)>0 ) { 
9721       mp_print(mp, "greyed ");
9722       mp_print_compact_node(mp, obj_grey_loc(p),1);
9723     };
9724   } else if ( color_model(p)==mp_cmyk_model ) {
9725     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9726          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9727       mp_print(mp, "processcolored ");
9728       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9729     };
9730   } else if ( color_model(p)==mp_rgb_model ) {
9731     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9732       mp_print(mp, "colored "); 
9733       mp_print_compact_node(mp, obj_red_loc(p),3);
9734     };
9735   }
9736 }
9737
9738 @ We also need a procedure for printing consecutive scaled values as if they
9739 were a known big node.
9740
9741 @<Declare a procedure called |print_compact_node|@>=
9742 void mp_print_compact_node (MP mp,pointer p, small_number k) {
9743   pointer q;  /* last location to print */
9744   q=p+k-1;
9745   mp_print_char(mp, '(');
9746   while ( p<=q ){ 
9747     mp_print_scaled(mp, mp->mem[p].sc);
9748     if ( p<q ) mp_print_char(mp, ',');
9749     incr(p);
9750   }
9751   mp_print_char(mp, ')');
9752 }
9753
9754 @ @<Cases for printing graphical object node |p|@>=
9755 case mp_stroked_code: 
9756   mp_print(mp, "Filled pen stroke ");
9757   mp_print_obj_color(mp, p);
9758   mp_print_char(mp, ':'); mp_print_ln(mp);
9759   mp_pr_path(mp, path_p(p));
9760   if ( dash_p(p)!=null ) { 
9761     mp_print_nl(mp, "dashed (");
9762     @<Finish printing the dash pattern that |p| refers to@>;
9763   }
9764   mp_print_ln(mp);
9765   @<Print join and cap types for stroked node |p|@>;
9766   mp_print(mp, " with pen"); mp_print_ln(mp);
9767   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9768 @.???@>
9769   else mp_pr_pen(mp, pen_p(p));
9770   break;
9771
9772 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9773 when it is not known to define a suitable dash pattern.  This is disallowed
9774 here because the |dash_p| field should never point to such an edge header.
9775 Note that memory is allocated for |start_x(null_dash)| and we are free to
9776 give it any convenient value.
9777
9778 @<Finish printing the dash pattern that |p| refers to@>=
9779 ok_to_dash=pen_is_elliptical(pen_p(p));
9780 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9781 hh=dash_p(p);
9782 pp=dash_list(hh);
9783 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9784   mp_print(mp, " ??");
9785 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9786   while ( pp!=null_dash ) { 
9787     mp_print(mp, "on ");
9788     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9789     mp_print(mp, " off ");
9790     mp_print_scaled(mp, mp_take_scaled(mp, start_x(link(pp))-stop_x(pp),scf));
9791     pp = link(pp);
9792     if ( pp!=null_dash ) mp_print_char(mp, ' ');
9793   }
9794   mp_print(mp, ") shifted ");
9795   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9796   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9797 }
9798
9799 @ @<Declare subroutines needed by |print_edges|@>=
9800 scaled mp_dash_offset (MP mp,pointer h) {
9801   scaled x;  /* the answer */
9802   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9803 @:this can't happen dash0}{\quad dash0@>
9804   if ( dash_y(h)==0 ) {
9805     x=0; 
9806   } else { 
9807     x=-(start_x(dash_list(h)) % dash_y(h));
9808     if ( x<0 ) x=x+dash_y(h);
9809   }
9810   return x;
9811 }
9812
9813 @ @<Cases for printing graphical object node |p|@>=
9814 case mp_text_code: 
9815   mp_print_char(mp, '"'); mp_print_str(mp,text_p(p));
9816   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9817   mp_print_char(mp, '"'); mp_print_ln(mp);
9818   mp_print_obj_color(mp, p);
9819   mp_print(mp, "transformed ");
9820   mp_print_compact_node(mp, text_tx_loc(p),6);
9821   break;
9822
9823 @ @<Cases for printing graphical object node |p|@>=
9824 case mp_start_clip_code: 
9825   mp_print(mp, "clipping path:");
9826   mp_print_ln(mp);
9827   mp_pr_path(mp, path_p(p));
9828   break;
9829 case mp_stop_clip_code: 
9830   mp_print(mp, "stop clipping");
9831   break;
9832
9833 @ @<Cases for printing graphical object node |p|@>=
9834 case mp_start_bounds_code: 
9835   mp_print(mp, "setbounds path:");
9836   mp_print_ln(mp);
9837   mp_pr_path(mp, path_p(p));
9838   break;
9839 case mp_stop_bounds_code: 
9840   mp_print(mp, "end of setbounds");
9841   break;
9842
9843 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9844 subroutine that scans an edge structure and tries to interpret it as a dash
9845 pattern.  This can only be done when there are no filled regions or clipping
9846 paths and all the pen strokes have the same color.  The first step is to let
9847 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9848 project all the pen stroke paths onto the line $y=y_0$ and require that there
9849 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9850 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9851 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9852
9853 @c @<Declare a procedure called |x_retrace_error|@>
9854 pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9855   pointer p;  /* this scans the stroked nodes in the object list */
9856   pointer p0;  /* if not |null| this points to the first stroked node */
9857   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9858   pointer d,dd;  /* pointers used to create the dash list */
9859   scaled y0;
9860   @<Other local variables in |make_dashes|@>;
9861   y0=0;  /* the initial $y$ coordinate */
9862   if ( dash_list(h)!=null_dash ) 
9863         return h;
9864   p0=null;
9865   p=link(dummy_loc(h));
9866   while ( p!=null ) { 
9867     if ( type(p)!=mp_stroked_code ) {
9868       @<Compain that the edge structure contains a node of the wrong type
9869         and |goto not_found|@>;
9870     }
9871     pp=path_p(p);
9872     if ( p0==null ){ p0=p; y0=y_coord(pp);  };
9873     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9874       or |goto not_found| if there is an error@>;
9875     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9876     p=link(p);
9877   }
9878   if ( dash_list(h)==null_dash ) 
9879     goto NOT_FOUND; /* No error message */
9880   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9881   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9882   return h;
9883 NOT_FOUND: 
9884   @<Flush the dash list, recycle |h| and return |null|@>;
9885 }
9886
9887 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9888
9889 print_err("Picture is too complicated to use as a dash pattern");
9890 help3("When you say `dashed p', picture p should not contain any")
9891   ("text, filled regions, or clipping paths.  This time it did")
9892   ("so I'll just make it a solid line instead.");
9893 mp_put_get_error(mp);
9894 goto NOT_FOUND;
9895 }
9896
9897 @ A similar error occurs when monotonicity fails.
9898
9899 @<Declare a procedure called |x_retrace_error|@>=
9900 void mp_x_retrace_error (MP mp) { 
9901 print_err("Picture is too complicated to use as a dash pattern");
9902 help3("When you say `dashed p', every path in p should be monotone")
9903   ("in x and there must be no overlapping.  This failed")
9904   ("so I'll just make it a solid line instead.");
9905 mp_put_get_error(mp);
9906 }
9907
9908 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
9909 handle the case where the pen stroke |p| is itself dashed.
9910
9911 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
9912 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
9913   an error@>;
9914 rr=pp;
9915 if ( link(pp)!=pp ) {
9916   do {  
9917     qq=rr; rr=link(rr);
9918     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
9919       if there is a problem@>;
9920   } while (right_type(rr)!=mp_endpoint);
9921 }
9922 d=mp_get_node(mp, dash_node_size);
9923 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
9924 if ( x_coord(pp)<x_coord(rr) ) { 
9925   start_x(d)=x_coord(pp);
9926   stop_x(d)=x_coord(rr);
9927 } else { 
9928   start_x(d)=x_coord(rr);
9929   stop_x(d)=x_coord(pp);
9930 }
9931
9932 @ We also need to check for the case where the segment from |qq| to |rr| is
9933 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
9934
9935 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
9936 x0=x_coord(qq);
9937 x1=right_x(qq);
9938 x2=left_x(rr);
9939 x3=x_coord(rr);
9940 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
9941   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
9942     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
9943       mp_x_retrace_error(mp); goto NOT_FOUND;
9944     }
9945   }
9946 }
9947 if ( (x_coord(pp)>x0) || (x0>x3) ) {
9948   if ( (x_coord(pp)<x0) || (x0<x3) ) {
9949     mp_x_retrace_error(mp); goto NOT_FOUND;
9950   }
9951 }
9952
9953 @ @<Other local variables in |make_dashes|@>=
9954   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
9955
9956 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
9957 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
9958   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
9959   print_err("Picture is too complicated to use as a dash pattern");
9960   help3("When you say `dashed p', everything in picture p should")
9961     ("be the same color.  I can\'t handle your color changes")
9962     ("so I'll just make it a solid line instead.");
9963   mp_put_get_error(mp);
9964   goto NOT_FOUND;
9965 }
9966
9967 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
9968 start_x(null_dash)=stop_x(d);
9969 dd=h; /* this makes |link(dd)=dash_list(h)| */
9970 while ( start_x(link(dd))<stop_x(d) )
9971   dd=link(dd);
9972 if ( dd!=h ) {
9973   if ( (stop_x(dd)>start_x(d)) )
9974     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
9975 }
9976 link(d)=link(dd);
9977 link(dd)=d
9978
9979 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
9980 d=dash_list(h);
9981 while ( (link(d)!=null_dash) )
9982   d=link(d);
9983 dd=dash_list(h);
9984 dash_y(h)=stop_x(d)-start_x(dd);
9985 if ( abs(y0)>dash_y(h) ) {
9986   dash_y(h)=abs(y0);
9987 } else if ( d!=dd ) { 
9988   dash_list(h)=link(dd);
9989   stop_x(d)=stop_x(dd)+dash_y(h);
9990   mp_free_node(mp, dd,dash_node_size);
9991 }
9992
9993 @ We get here when the argument is a null picture or when there is an error.
9994 Recovering from an error involves making |dash_list(h)| empty to indicate
9995 that |h| is not known to be a valid dash pattern.  We also dereference |h|
9996 since it is not being used for the return value.
9997
9998 @<Flush the dash list, recycle |h| and return |null|@>=
9999 mp_flush_dash_list(mp, h);
10000 delete_edge_ref(h);
10001 return null
10002
10003 @ Having carefully saved the dashed stroked nodes in the
10004 corresponding dash nodes, we must be prepared to break up these dashes into
10005 smaller dashes.
10006
10007 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10008 d=h;  /* now |link(d)=dash_list(h)| */
10009 while ( link(d)!=null_dash ) {
10010   ds=info(link(d));
10011   if ( ds==null ) { 
10012     d=link(d);
10013   } else {
10014     hh=dash_p(ds);
10015     hsf=dash_scale(ds);
10016     if ( (hh==null) ) mp_confusion(mp, "dash1");
10017 @:this can't happen dash0}{\quad dash1@>
10018     if ( dash_y(hh)==0 ) {
10019       d=link(d);
10020     } else { 
10021       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10022 @:this can't happen dash0}{\quad dash1@>
10023       @<Replace |link(d)| by a dashed version as determined by edge header
10024           |hh| and scale factor |ds|@>;
10025     }
10026   }
10027 }
10028
10029 @ @<Other local variables in |make_dashes|@>=
10030 pointer dln;  /* |link(d)| */
10031 pointer hh;  /* an edge header that tells how to break up |dln| */
10032 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10033 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10034 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10035
10036 @ @<Replace |link(d)| by a dashed version as determined by edge header...@>=
10037 dln=link(d);
10038 dd=dash_list(hh);
10039 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10040         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10041 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10042                    +mp_take_scaled(mp, hsf,dash_y(hh));
10043 stop_x(null_dash)=start_x(null_dash);
10044 @<Advance |dd| until finding the first dash that overlaps |dln| when
10045   offset by |xoff|@>;
10046 while ( start_x(dln)<=stop_x(dln) ) {
10047   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10048   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10049     of |dd|@>;
10050   dd=link(dd);
10051   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10052 }
10053 link(d)=link(dln);
10054 mp_free_node(mp, dln,dash_node_size)
10055
10056 @ The name of this module is a bit of a lie because we just find the
10057 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10058 overlap possible.  It could be that the unoffset version of dash |dln| falls
10059 in the gap between |dd| and its predecessor.
10060
10061 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10062 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10063   dd=link(dd);
10064 }
10065
10066 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10067 if ( dd==null_dash ) { 
10068   dd=dash_list(hh);
10069   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10070 }
10071
10072 @ At this point we already know that
10073 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10074
10075 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10076 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10077   link(d)=mp_get_node(mp, dash_node_size);
10078   d=link(d);
10079   link(d)=dln;
10080   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10081     start_x(d)=start_x(dln);
10082   else 
10083     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10084   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10085     stop_x(d)=stop_x(dln);
10086   else 
10087     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10088 }
10089
10090 @ The next major task is to update the bounding box information in an edge
10091 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10092 header's bounding box to accommodate the box computed by |path_bbox| or
10093 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10094 |maxy|.)
10095
10096 @c void mp_adjust_bbox (MP mp,pointer h) { 
10097   if ( minx<minx_val(h) ) minx_val(h)=minx;
10098   if ( miny<miny_val(h) ) miny_val(h)=miny;
10099   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10100   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10101 }
10102
10103 @ Here is a special routine for updating the bounding box information in
10104 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10105 that is to be stroked with the pen~|pp|.
10106
10107 @c void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10108   pointer q;  /* a knot node adjacent to knot |p| */
10109   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10110   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10111   scaled z;  /* a coordinate being tested against the bounding box */
10112   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10113   integer i; /* a loop counter */
10114   if ( right_type(p)!=mp_endpoint ) { 
10115     q=link(p);
10116     while (1) { 
10117       @<Make |(dx,dy)| the final direction for the path segment from
10118         |q| to~|p|; set~|d|@>;
10119       d=mp_pyth_add(mp, dx,dy);
10120       if ( d>0 ) { 
10121          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10122          for (i=1;i<= 2;i++) { 
10123            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10124              update the bounding box to accommodate it@>;
10125            dx=-dx; dy=-dy; 
10126         }
10127       }
10128       if ( right_type(p)==mp_endpoint ) {
10129          return;
10130       } else {
10131         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10132       } 
10133     }
10134   }
10135 }
10136
10137 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10138 if ( q==link(p) ) { 
10139   dx=x_coord(p)-right_x(p);
10140   dy=y_coord(p)-right_y(p);
10141   if ( (dx==0)&&(dy==0) ) {
10142     dx=x_coord(p)-left_x(q);
10143     dy=y_coord(p)-left_y(q);
10144   }
10145 } else { 
10146   dx=x_coord(p)-left_x(p);
10147   dy=y_coord(p)-left_y(p);
10148   if ( (dx==0)&&(dy==0) ) {
10149     dx=x_coord(p)-right_x(q);
10150     dy=y_coord(p)-right_y(q);
10151   }
10152 }
10153 dx=x_coord(p)-x_coord(q);
10154 dy=y_coord(p)-y_coord(q)
10155
10156 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10157 dx=mp_make_fraction(mp, dx,d);
10158 dy=mp_make_fraction(mp, dy,d);
10159 mp_find_offset(mp, -dy,dx,pp);
10160 xx=mp->cur_x; yy=mp->cur_y
10161
10162 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10163 mp_find_offset(mp, dx,dy,pp);
10164 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10165 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10166   mp_confusion(mp, "box_ends");
10167 @:this can't happen box ends}{\quad\\{box\_ends}@>
10168 z=x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10169 if ( z<minx_val(h) ) minx_val(h)=z;
10170 if ( z>maxx_val(h) ) maxx_val(h)=z;
10171 z=y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10172 if ( z<miny_val(h) ) miny_val(h)=z;
10173 if ( z>maxy_val(h) ) maxy_val(h)=z
10174
10175 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10176 do {  
10177   q=p;
10178   p=link(p);
10179 } while (right_type(p)!=mp_endpoint)
10180
10181 @ The major difficulty in finding the bounding box of an edge structure is the
10182 effect of clipping paths.  We treat them conservatively by only clipping to the
10183 clipping path's bounding box, but this still
10184 requires recursive calls to |set_bbox| in order to find the bounding box of
10185 @^recursion@>
10186 the objects to be clipped.  Such calls are distinguished by the fact that the
10187 boolean parameter |top_level| is false.
10188
10189 @c void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10190   pointer p;  /* a graphical object being considered */
10191   scaled sminx,sminy,smaxx,smaxy;
10192   /* for saving the bounding box during recursive calls */
10193   scaled x0,x1,y0,y1;  /* temporary registers */
10194   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10195   @<Wipe out any existing bounding box information if |bbtype(h)| is
10196   incompatible with |internal[mp_true_corners]|@>;
10197   while ( link(bblast(h))!=null ) { 
10198     p=link(bblast(h));
10199     bblast(h)=p;
10200     switch (type(p)) {
10201     case mp_stop_clip_code: 
10202       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10203 @:this can't happen bbox}{\quad bbox@>
10204       break;
10205     @<Other cases for updating the bounding box based on the type of object |p|@>;
10206     } /* all cases are enumerated above */
10207   }
10208   if ( ! top_level ) mp_confusion(mp, "bbox");
10209 }
10210
10211 @ @<Internal library declarations@>=
10212 void mp_set_bbox (MP mp,pointer h, boolean top_level);
10213
10214 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10215 switch (bbtype(h)) {
10216 case no_bounds: 
10217   break;
10218 case bounds_set: 
10219   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10220   break;
10221 case bounds_unset: 
10222   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10223   break;
10224 } /* there are no other cases */
10225
10226 @ @<Other cases for updating the bounding box...@>=
10227 case mp_fill_code: 
10228   mp_path_bbox(mp, path_p(p));
10229   if ( pen_p(p)!=null ) { 
10230     x0=minx; y0=miny;
10231     x1=maxx; y1=maxy;
10232     mp_pen_bbox(mp, pen_p(p));
10233     minx=minx+x0;
10234     miny=miny+y0;
10235     maxx=maxx+x1;
10236     maxy=maxy+y1;
10237   }
10238   mp_adjust_bbox(mp, h);
10239   break;
10240
10241 @ @<Other cases for updating the bounding box...@>=
10242 case mp_start_bounds_code: 
10243   if ( mp->internal[mp_true_corners]>0 ) {
10244     bbtype(h)=bounds_unset;
10245   } else { 
10246     bbtype(h)=bounds_set;
10247     mp_path_bbox(mp, path_p(p));
10248     mp_adjust_bbox(mp, h);
10249     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10250       |bblast(h)|@>;
10251   }
10252   break;
10253 case mp_stop_bounds_code: 
10254   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10255 @:this can't happen bbox2}{\quad bbox2@>
10256   break;
10257
10258 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10259 lev=1;
10260 while ( lev!=0 ) { 
10261   if ( link(p)==null ) mp_confusion(mp, "bbox2");
10262 @:this can't happen bbox2}{\quad bbox2@>
10263   p=link(p);
10264   if ( type(p)==mp_start_bounds_code ) incr(lev);
10265   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10266 }
10267 bblast(h)=p
10268
10269 @ It saves a lot of grief here to be slightly conservative and not account for
10270 omitted parts of dashed lines.  We also don't worry about the material omitted
10271 when using butt end caps.  The basic computation is for round end caps and
10272 |box_ends| augments it for square end caps.
10273
10274 @<Other cases for updating the bounding box...@>=
10275 case mp_stroked_code: 
10276   mp_path_bbox(mp, path_p(p));
10277   x0=minx; y0=miny;
10278   x1=maxx; y1=maxy;
10279   mp_pen_bbox(mp, pen_p(p));
10280   minx=minx+x0;
10281   miny=miny+y0;
10282   maxx=maxx+x1;
10283   maxy=maxy+y1;
10284   mp_adjust_bbox(mp, h);
10285   if ( (left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10286     mp_box_ends(mp, path_p(p), pen_p(p), h);
10287   break;
10288
10289 @ The height width and depth information stored in a text node determines a
10290 rectangle that needs to be transformed according to the transformation
10291 parameters stored in the text node.
10292
10293 @<Other cases for updating the bounding box...@>=
10294 case mp_text_code: 
10295   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10296   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10297   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10298   minx=tx_val(p);
10299   maxx=minx;
10300   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10301   else         { minx=minx+y1; maxx=maxx+y0;  }
10302   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10303   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10304   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10305   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10306   miny=ty_val(p);
10307   maxy=miny;
10308   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10309   else         { miny=miny+y1; maxy=maxy+y0;  }
10310   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10311   mp_adjust_bbox(mp, h);
10312   break;
10313
10314 @ This case involves a recursive call that advances |bblast(h)| to the node of
10315 type |mp_stop_clip_code| that matches |p|.
10316
10317 @<Other cases for updating the bounding box...@>=
10318 case mp_start_clip_code: 
10319   mp_path_bbox(mp, path_p(p));
10320   x0=minx; y0=miny;
10321   x1=maxx; y1=maxy;
10322   sminx=minx_val(h); sminy=miny_val(h);
10323   smaxx=maxx_val(h); smaxy=maxy_val(h);
10324   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10325     starting at |link(p)|@>;
10326   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10327     |y0|, |y1|@>;
10328   minx=sminx; miny=sminy;
10329   maxx=smaxx; maxy=smaxy;
10330   mp_adjust_bbox(mp, h);
10331   break;
10332
10333 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10334 minx_val(h)=el_gordo;
10335 miny_val(h)=el_gordo;
10336 maxx_val(h)=-el_gordo;
10337 maxy_val(h)=-el_gordo;
10338 mp_set_bbox(mp, h,false)
10339
10340 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10341 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10342 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10343 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10344 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10345
10346 @* \[22] Finding an envelope.
10347 When \MP\ has a path and a polygonal pen, it needs to express the desired
10348 shape in terms of things \ps\ can understand.  The present task is to compute
10349 a new path that describes the region to be filled.  It is convenient to
10350 define this as a two step process where the first step is determining what
10351 offset to use for each segment of the path.
10352
10353 @ Given a pointer |c| to a cyclic path,
10354 and a pointer~|h| to the first knot of a pen polygon,
10355 the |offset_prep| routine changes the path into cubics that are
10356 associated with particular pen offsets. Thus if the cubic between |p|
10357 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10358 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10359 to because |l-k| could be negative.)
10360
10361 After overwriting the type information with offset differences, we no longer
10362 have a true path so we refer to the knot list returned by |offset_prep| as an
10363 ``envelope spec.''
10364 @^envelope spec@>
10365 Since an envelope spec only determines relative changes in pen offsets,
10366 |offset_prep| sets a global variable |spec_offset| to the relative change from
10367 |h| to the first offset.
10368
10369 @d zero_off 16384 /* added to offset changes to make them positive */
10370
10371 @<Glob...@>=
10372 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10373
10374 @ @c @<Declare subroutines needed by |offset_prep|@>
10375 pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10376   halfword n; /* the number of vertices in the pen polygon */
10377   pointer p,q,q0,r,w, ww; /* for list manipulation */
10378   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10379   pointer w0; /* a pointer to pen offset to use just before |p| */
10380   scaled dxin,dyin; /* the direction into knot |p| */
10381   integer turn_amt; /* change in pen offsets for the current cubic */
10382   @<Other local variables for |offset_prep|@>;
10383   dx0=0; dy0=0;
10384   @<Initialize the pen size~|n|@>;
10385   @<Initialize the incoming direction and pen offset at |c|@>;
10386   p=c; k_needed=0;
10387   do {  
10388     q=link(p);
10389     @<Split the cubic between |p| and |q|, if necessary, into cubics
10390       associated with single offsets, after which |q| should
10391       point to the end of the final such cubic@>;
10392   NOT_FOUND:
10393     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10394       might have been introduced by the splitting process@>;
10395   } while (q!=c);
10396   @<Fix the offset change in |info(c)| and set |c| to the return value of
10397     |offset_prep|@>;
10398   return c;
10399 }
10400
10401 @ We shall want to keep track of where certain knots on the cyclic path
10402 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10403 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10404 |offset_prep| updates the following pointers
10405
10406 @<Glob...@>=
10407 pointer spec_p1;
10408 pointer spec_p2; /* pointers to distinguished knots */
10409
10410 @ @<Set init...@>=
10411 mp->spec_p1=null; mp->spec_p2=null;
10412
10413 @ @<Initialize the pen size~|n|@>=
10414 n=0; p=h;
10415 do {  
10416   incr(n);
10417   p=link(p);
10418 } while (p!=h)
10419
10420 @ Since the true incoming direction isn't known yet, we just pick a direction
10421 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10422 later.
10423
10424 @<Initialize the incoming direction and pen offset at |c|@>=
10425 dxin=x_coord(link(h))-x_coord(knil(h));
10426 dyin=y_coord(link(h))-y_coord(knil(h));
10427 if ( (dxin==0)&&(dyin==0) ) {
10428   dxin=y_coord(knil(h))-y_coord(h);
10429   dyin=x_coord(h)-x_coord(knil(h));
10430 }
10431 w0=h
10432
10433 @ We must be careful not to remove the only cubic in a cycle.
10434
10435 But we must also be careful for another reason. If the user-supplied
10436 path starts with a set of degenerate cubics, the target node |q| can
10437 be collapsed to the initial node |p| which might be the same as the
10438 initial node |c| of the curve. This would cause the |offset_prep| routine
10439 to bail out too early, causing distress later on. (See for example
10440 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10441 on Sarovar.)
10442
10443 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10444 q0=q;
10445 do { 
10446   r=link(p);
10447   if ( x_coord(p)==right_x(p) && y_coord(p)==right_y(p) &&
10448        x_coord(p)==left_x(r)  && y_coord(p)==left_y(r) &&
10449        x_coord(p)==x_coord(r) && y_coord(p)==y_coord(r) &&
10450        r!=p ) {
10451       @<Remove the cubic following |p| and update the data structures
10452         to merge |r| into |p|@>;
10453   }
10454   p=r;
10455 } while (p!=q);
10456 /* Check if we removed too much */
10457 if(q!=q0)
10458   q = link(q)
10459
10460 @ @<Remove the cubic following |p| and update the data structures...@>=
10461 { k_needed=info(p)-zero_off;
10462   if ( r==q ) { 
10463     q=p;
10464   } else { 
10465     info(p)=k_needed+info(r);
10466     k_needed=0;
10467   };
10468   if ( r==c ) { info(p)=info(c); c=p; };
10469   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10470   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10471   r=p; mp_remove_cubic(mp, p);
10472 }
10473
10474 @ Not setting the |info| field of the newly created knot allows the splitting
10475 routine to work for paths.
10476
10477 @<Declare subroutines needed by |offset_prep|@>=
10478 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10479   scaled v; /* an intermediate value */
10480   pointer q,r; /* for list manipulation */
10481   q=link(p); r=mp_get_node(mp, knot_node_size); link(p)=r; link(r)=q;
10482   originator(r)=mp_program_code;
10483   left_type(r)=mp_explicit; right_type(r)=mp_explicit;
10484   v=t_of_the_way(right_x(p),left_x(q));
10485   right_x(p)=t_of_the_way(x_coord(p),right_x(p));
10486   left_x(q)=t_of_the_way(left_x(q),x_coord(q));
10487   left_x(r)=t_of_the_way(right_x(p),v);
10488   right_x(r)=t_of_the_way(v,left_x(q));
10489   x_coord(r)=t_of_the_way(left_x(r),right_x(r));
10490   v=t_of_the_way(right_y(p),left_y(q));
10491   right_y(p)=t_of_the_way(y_coord(p),right_y(p));
10492   left_y(q)=t_of_the_way(left_y(q),y_coord(q));
10493   left_y(r)=t_of_the_way(right_y(p),v);
10494   right_y(r)=t_of_the_way(v,left_y(q));
10495   y_coord(r)=t_of_the_way(left_y(r),right_y(r));
10496 }
10497
10498 @ This does not set |info(p)| or |right_type(p)|.
10499
10500 @<Declare subroutines needed by |offset_prep|@>=
10501 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10502   pointer q; /* the node that disappears */
10503   q=link(p); link(p)=link(q);
10504   right_x(p)=right_x(q); right_y(p)=right_y(q);
10505   mp_free_node(mp, q,knot_node_size);
10506 }
10507
10508 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10509 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10510 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10511 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10512 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10513 When listed by increasing $k$, these directions occur in counter-clockwise
10514 order so that $d_k\preceq d\k$ for all~$k$.
10515 The goal of |offset_prep| is to find an offset index~|k| to associate with
10516 each cubic, such that the direction $d(t)$ of the cubic satisfies
10517 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10518 We may have to split a cubic into many pieces before each
10519 piece corresponds to a unique offset.
10520
10521 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10522 info(p)=zero_off+k_needed;
10523 k_needed=0;
10524 @<Prepare for derivative computations;
10525   |goto not_found| if the current cubic is dead@>;
10526 @<Find the initial direction |(dx,dy)|@>;
10527 @<Update |info(p)| and find the offset $w_k$ such that
10528   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10529   the direction change at |p|@>;
10530 @<Find the final direction |(dxin,dyin)|@>;
10531 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10532 @<Complete the offset splitting process@>;
10533 w0=mp_pen_walk(mp, w0,turn_amt)
10534
10535 @ @<Declare subroutines needed by |offset_prep|@>=
10536 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10537   /* walk |k| steps around a pen from |w| */
10538   while ( k>0 ) { w=link(w); decr(k);  };
10539   while ( k<0 ) { w=knil(w); incr(k);  };
10540   return w;
10541 }
10542
10543 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10544 calculated from the quadratic polynomials
10545 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10546 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10547 Since we may be calculating directions from several cubics
10548 split from the current one, it is desirable to do these calculations
10549 without losing too much precision. ``Scaled up'' values of the
10550 derivatives, which will be less tainted by accumulated errors than
10551 derivatives found from the cubics themselves, are maintained in
10552 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10553 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10554 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)$.
10555
10556 @<Other local variables for |offset_prep|@>=
10557 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10558 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10559 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10560 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10561 integer max_coef; /* used while scaling */
10562 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10563 fraction t; /* where the derivative passes through zero */
10564 fraction s; /* a temporary value */
10565
10566 @ @<Prepare for derivative computations...@>=
10567 x0=right_x(p)-x_coord(p);
10568 x2=x_coord(q)-left_x(q);
10569 x1=left_x(q)-right_x(p);
10570 y0=right_y(p)-y_coord(p); y2=y_coord(q)-left_y(q);
10571 y1=left_y(q)-right_y(p);
10572 max_coef=abs(x0);
10573 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10574 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10575 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10576 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10577 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10578 if ( max_coef==0 ) goto NOT_FOUND;
10579 while ( max_coef<fraction_half ) {
10580   double(max_coef);
10581   double(x0); double(x1); double(x2);
10582   double(y0); double(y1); double(y2);
10583 }
10584
10585 @ Let us first solve a special case of the problem: Suppose we
10586 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10587 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10588 $d(0)\succ d_{k-1}$.
10589 Then, in a sense, we're halfway done, since one of the two relations
10590 in $(*)$ is satisfied, and the other couldn't be satisfied for
10591 any other value of~|k|.
10592
10593 Actually, the conditions can be relaxed somewhat since a relation such as
10594 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10595 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10596 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10597 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10598 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10599 counterclockwise direction.
10600
10601 The |fin_offset_prep| subroutine solves the stated subproblem.
10602 It has a parameter called |rise| that is |1| in
10603 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10604 the derivative of the cubic following |p|.
10605 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10606 be set properly.  The |turn_amt| parameter gives the absolute value of the
10607 overall net change in pen offsets.
10608
10609 @<Declare subroutines needed by |offset_prep|@>=
10610 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10611   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10612   integer rise, integer turn_amt)  {
10613   pointer ww; /* for list manipulation */
10614   scaled du,dv; /* for slope calculation */
10615   integer t0,t1,t2; /* test coefficients */
10616   fraction t; /* place where the derivative passes a critical slope */
10617   fraction s; /* slope or reciprocal slope */
10618   integer v; /* intermediate value for updating |x0..y2| */
10619   pointer q; /* original |link(p)| */
10620   q=link(p);
10621   while (1)  { 
10622     if ( rise>0 ) ww=link(w); /* a pointer to $w\k$ */
10623     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10624     @<Compute test coefficients |(t0,t1,t2)|
10625       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10626     t=mp_crossing_point(mp, t0,t1,t2);
10627     if ( t>=fraction_one ) {
10628       if ( turn_amt>0 ) t=fraction_one;  else return;
10629     }
10630     @<Split the cubic at $t$,
10631       and split off another cubic if the derivative crosses back@>;
10632     w=ww;
10633   }
10634 }
10635
10636 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10637 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10638 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10639 begins to fail.
10640
10641 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10642 du=x_coord(ww)-x_coord(w); dv=y_coord(ww)-y_coord(w);
10643 if ( abs(du)>=abs(dv) ) {
10644   s=mp_make_fraction(mp, dv,du);
10645   t0=mp_take_fraction(mp, x0,s)-y0;
10646   t1=mp_take_fraction(mp, x1,s)-y1;
10647   t2=mp_take_fraction(mp, x2,s)-y2;
10648   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10649 } else { 
10650   s=mp_make_fraction(mp, du,dv);
10651   t0=x0-mp_take_fraction(mp, y0,s);
10652   t1=x1-mp_take_fraction(mp, y1,s);
10653   t2=x2-mp_take_fraction(mp, y2,s);
10654   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10655 }
10656 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10657
10658 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10659 $(*)$, and it might cross again and return towards $s_{k-1}$ or $s_k$,
10660 respectively, yielding another solution of $(*)$.
10661
10662 @<Split the cubic at $t$, and split off another...@>=
10663
10664 mp_split_cubic(mp, p,t); p=link(p); info(p)=zero_off+rise;
10665 decr(turn_amt);
10666 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10667 x0=t_of_the_way(v,x1);
10668 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10669 y0=t_of_the_way(v,y1);
10670 if ( turn_amt<0 ) {
10671   t1=t_of_the_way(t1,t2);
10672   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10673   t=mp_crossing_point(mp, 0,-t1,-t2);
10674   if ( t>fraction_one ) t=fraction_one;
10675   incr(turn_amt);
10676   if ( (t==fraction_one)&&(link(p)!=q) ) {
10677     info(link(p))=info(link(p))-rise;
10678   } else { 
10679     mp_split_cubic(mp, p,t); info(link(p))=zero_off-rise;
10680     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10681     x2=t_of_the_way(x1,v);
10682     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10683     y2=t_of_the_way(y1,v);
10684   }
10685 }
10686 }
10687
10688 @ Now we must consider the general problem of |offset_prep|, when
10689 nothing is known about a given cubic. We start by finding its
10690 direction in the vicinity of |t=0|.
10691
10692 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10693 has not yet introduced any more numerical errors.  Thus we can compute
10694 the true initial direction for the given cubic, even if it is almost
10695 degenerate.
10696
10697 @<Find the initial direction |(dx,dy)|@>=
10698 dx=x0; dy=y0;
10699 if ( dx==0 && dy==0 ) { 
10700   dx=x1; dy=y1;
10701   if ( dx==0 && dy==0 ) { 
10702     dx=x2; dy=y2;
10703   }
10704 }
10705 if ( p==c ) { dx0=dx; dy0=dy;  }
10706
10707 @ @<Find the final direction |(dxin,dyin)|@>=
10708 dxin=x2; dyin=y2;
10709 if ( dxin==0 && dyin==0 ) {
10710   dxin=x1; dyin=y1;
10711   if ( dxin==0 && dyin==0 ) {
10712     dxin=x0; dyin=y0;
10713   }
10714 }
10715
10716 @ The next step is to bracket the initial direction between consecutive
10717 edges of the pen polygon.  We must be careful to turn clockwise only if
10718 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10719 counter-clockwise in order to make \&{doublepath} envelopes come out
10720 @:double_path_}{\&{doublepath} primitive@>
10721 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10722
10723 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10724 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10725 w=mp_pen_walk(mp, w0, turn_amt);
10726 w0=w;
10727 info(p)=info(p)+turn_amt
10728
10729 @ Decide how many pen offsets to go away from |w| in order to find the offset
10730 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10731 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10732 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10733
10734 If the pen polygon has only two edges, they could both be parallel
10735 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10736 such edge in order to avoid an infinite loop.
10737
10738 @<Declare subroutines needed by |offset_prep|@>=
10739 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10740                          scaled dy, boolean  ccw) {
10741   pointer ww; /* a neighbor of knot~|w| */
10742   integer s; /* turn amount so far */
10743   integer t; /* |ab_vs_cd| result */
10744   s=0;
10745   if ( ccw ) { 
10746     ww=link(w);
10747     do {  
10748       t=mp_ab_vs_cd(mp, dy,(x_coord(ww)-x_coord(w)),
10749                         dx,(y_coord(ww)-y_coord(w)));
10750       if ( t<0 ) break;
10751       incr(s);
10752       w=ww; ww=link(ww);
10753     } while (t>0);
10754   } else { 
10755     ww=knil(w);
10756     while ( mp_ab_vs_cd(mp, dy,(x_coord(w)-x_coord(ww)),
10757                             dx,(y_coord(w)-y_coord(ww))) < 0) { 
10758       decr(s);
10759       w=ww; ww=knil(ww);
10760     }
10761   }
10762   return s;
10763 }
10764
10765 @ When we're all done, the final offset is |w0| and the final curve direction
10766 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10767 can correct |info(c)| which was erroneously based on an incoming offset
10768 of~|h|.
10769
10770 @d fix_by(A) info(c)=info(c)+(A)
10771
10772 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10773 mp->spec_offset=info(c)-zero_off;
10774 if ( link(c)==c ) {
10775   info(c)=zero_off+n;
10776 } else { 
10777   fix_by(k_needed);
10778   while ( w0!=h ) { fix_by(1); w0=link(w0);  };
10779   while ( info(c)<=zero_off-n ) fix_by(n);
10780   while ( info(c)>zero_off ) fix_by(-n);
10781   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10782 }
10783
10784 @ Finally we want to reduce the general problem to situations that
10785 |fin_offset_prep| can handle. We split the cubic into at most three parts
10786 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10787
10788 @<Complete the offset splitting process@>=
10789 ww=knil(w);
10790 @<Compute test coeff...@>;
10791 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10792   |t:=fraction_one+1|@>;
10793 if ( t>fraction_one ) {
10794   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10795 } else {
10796   mp_split_cubic(mp, p,t); r=link(p);
10797   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10798   x2a=t_of_the_way(x1a,x1);
10799   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10800   y2a=t_of_the_way(y1a,y1);
10801   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10802   info(r)=zero_off-1;
10803   if ( turn_amt>=0 ) {
10804     t1=t_of_the_way(t1,t2);
10805     if ( t1>0 ) t1=0;
10806     t=mp_crossing_point(mp, 0,-t1,-t2);
10807     if ( t>fraction_one ) t=fraction_one;
10808     @<Split off another rising cubic for |fin_offset_prep|@>;
10809     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10810   } else {
10811     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10812   }
10813 }
10814
10815 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10816 mp_split_cubic(mp, r,t); info(link(r))=zero_off+1;
10817 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10818 x0a=t_of_the_way(x1,x1a);
10819 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10820 y0a=t_of_the_way(y1,y1a);
10821 mp_fin_offset_prep(mp, link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10822 x2=x0a; y2=y0a
10823
10824 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10825 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10826 need to decide whether the directions are parallel or antiparallel.  We
10827 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10828 should be avoided when the value of |turn_amt| already determines the
10829 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10830 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10831 crossing and the first crossing cannot be antiparallel.
10832
10833 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10834 t=mp_crossing_point(mp, t0,t1,t2);
10835 if ( turn_amt>=0 ) {
10836   if ( t2<0 ) {
10837     t=fraction_one+1;
10838   } else { 
10839     u0=t_of_the_way(x0,x1);
10840     u1=t_of_the_way(x1,x2);
10841     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10842     v0=t_of_the_way(y0,y1);
10843     v1=t_of_the_way(y1,y2);
10844     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10845     if ( ss<0 ) t=fraction_one+1;
10846   }
10847 } else if ( t>fraction_one ) {
10848   t=fraction_one;
10849 }
10850
10851 @ @<Other local variables for |offset_prep|@>=
10852 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10853 integer ss = 0; /* the part of the dot product computed so far */
10854 int d_sign; /* sign of overall change in direction for this cubic */
10855
10856 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10857 problem to decide which way it loops around but that's OK as long we're
10858 consistent.  To make \&{doublepath} envelopes work properly, reversing
10859 the path should always change the sign of |turn_amt|.
10860
10861 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10862 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10863 if ( d_sign==0 ) {
10864   @<Check rotation direction based on node position@>
10865 }
10866 if ( d_sign==0 ) {
10867   if ( dx==0 ) {
10868     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10869   } else {
10870     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10871   }
10872 }
10873 @<Make |ss| negative if and only if the total change in direction is
10874   more than $180^\circ$@>;
10875 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10876 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10877
10878 @ We check rotation direction by looking at the vector connecting the current
10879 node with the next. If its angle with incoming and outgoing tangents has the
10880 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
10881 Otherwise we proceed to the cusp code.
10882
10883 @<Check rotation direction based on node position@>=
10884 u0=x_coord(q)-x_coord(p);
10885 u1=y_coord(q)-y_coord(p);
10886 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
10887   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
10888
10889 @ In order to be invariant under path reversal, the result of this computation
10890 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
10891 then swapped with |(x2,y2)|.  We make use of the identities
10892 |take_fraction(-a,-b)=take_fraction(a,b)| and
10893 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
10894
10895 @<Make |ss| negative if and only if the total change in direction is...@>=
10896 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
10897 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
10898 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
10899 if ( t0>0 ) {
10900   t=mp_crossing_point(mp, t0,t1,-t0);
10901   u0=t_of_the_way(x0,x1);
10902   u1=t_of_the_way(x1,x2);
10903   v0=t_of_the_way(y0,y1);
10904   v1=t_of_the_way(y1,y2);
10905 } else { 
10906   t=mp_crossing_point(mp, -t0,t1,t0);
10907   u0=t_of_the_way(x2,x1);
10908   u1=t_of_the_way(x1,x0);
10909   v0=t_of_the_way(y2,y1);
10910   v1=t_of_the_way(y1,y0);
10911 }
10912 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
10913    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
10914
10915 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
10916 that the |cur_pen| has not been walked around to the first offset.
10917
10918 @c 
10919 void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, const char *s) {
10920   pointer p,q; /* list traversal */
10921   pointer w; /* the current pen offset */
10922   mp_print_diagnostic(mp, "Envelope spec",s,true);
10923   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
10924   mp_print_ln(mp);
10925   mp_print_two(mp, x_coord(cur_spec),y_coord(cur_spec));
10926   mp_print(mp, " % beginning with offset ");
10927   mp_print_two(mp, x_coord(w),y_coord(w));
10928   do { 
10929     while (1) {  
10930       q=link(p);
10931       @<Print the cubic between |p| and |q|@>;
10932       p=q;
10933           if ((p==cur_spec) || (info(p)!=zero_off)) 
10934         break;
10935     }
10936     if ( info(p)!=zero_off ) {
10937       @<Update |w| as indicated by |info(p)| and print an explanation@>;
10938     }
10939   } while (p!=cur_spec);
10940   mp_print_nl(mp, " & cycle");
10941   mp_end_diagnostic(mp, true);
10942 }
10943
10944 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
10945
10946   w=mp_pen_walk(mp, w, (info(p)-zero_off));
10947   mp_print(mp, " % ");
10948   if ( info(p)>zero_off ) mp_print(mp, "counter");
10949   mp_print(mp, "clockwise to offset ");
10950   mp_print_two(mp, x_coord(w),y_coord(w));
10951 }
10952
10953 @ @<Print the cubic between |p| and |q|@>=
10954
10955   mp_print_nl(mp, "   ..controls ");
10956   mp_print_two(mp, right_x(p),right_y(p));
10957   mp_print(mp, " and ");
10958   mp_print_two(mp, left_x(q),left_y(q));
10959   mp_print_nl(mp, " ..");
10960   mp_print_two(mp, x_coord(q),y_coord(q));
10961 }
10962
10963 @ Once we have an envelope spec, the remaining task to construct the actual
10964 envelope by offsetting each cubic as determined by the |info| fields in
10965 the knots.  First we use |offset_prep| to convert the |c| into an envelope
10966 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
10967 the envelope.
10968
10969 The |ljoin| and |miterlim| parameters control the treatment of points where the
10970 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
10971 The endpoints are easily located because |c| is given in undoubled form
10972 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
10973 track of the endpoints and treat them like very sharp corners.
10974 Butt end caps are treated like beveled joins; round end caps are treated like
10975 round joins; and square end caps are achieved by setting |join_type:=3|.
10976
10977 None of these parameters apply to inside joins where the convolution tracing
10978 has retrograde lines.  In such cases we use a simple connect-the-endpoints
10979 approach that is achieved by setting |join_type:=2|.
10980
10981 @c @<Declare a function called |insert_knot|@>
10982 pointer mp_make_envelope (MP mp,pointer c, pointer h, small_number ljoin,
10983   small_number lcap, scaled miterlim) {
10984   pointer p,q,r,q0; /* for manipulating the path */
10985   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
10986   pointer w,w0; /* the pen knot for the current offset */
10987   scaled qx,qy; /* unshifted coordinates of |q| */
10988   halfword k,k0; /* controls pen edge insertion */
10989   @<Other local variables for |make_envelope|@>;
10990   dxin=0; dyin=0; dxout=0; dyout=0;
10991   mp->spec_p1=null; mp->spec_p2=null;
10992   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
10993   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
10994     the initial offset@>;
10995   w=h;
10996   p=c;
10997   do {  
10998     q=link(p); q0=q;
10999     qx=x_coord(q); qy=y_coord(q);
11000     k=info(q);
11001     k0=k; w0=w;
11002     if ( k!=zero_off ) {
11003       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11004     }
11005     @<Add offset |w| to the cubic from |p| to |q|@>;
11006     while ( k!=zero_off ) { 
11007       @<Step |w| and move |k| one step closer to |zero_off|@>;
11008       if ( (join_type==1)||(k==zero_off) )
11009          q=mp_insert_knot(mp, q,qx+x_coord(w),qy+y_coord(w));
11010     };
11011     if ( q!=link(p) ) {
11012       @<Set |p=link(p)| and add knots between |p| and |q| as
11013         required by |join_type|@>;
11014     }
11015     p=q;
11016   } while (q0!=c);
11017   return c;
11018 }
11019
11020 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11021 c=mp_offset_prep(mp, c,h);
11022 if ( mp->internal[mp_tracing_specs]>0 ) 
11023   mp_print_spec(mp, c,h,"");
11024 h=mp_pen_walk(mp, h,mp->spec_offset)
11025
11026 @ Mitered and squared-off joins depend on path directions that are difficult to
11027 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11028 have degenerate cubics only if the entire cycle collapses to a single
11029 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11030 envelope degenerate as well.
11031
11032 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11033 if ( k<zero_off ) {
11034   join_type=2;
11035 } else {
11036   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11037   else if ( lcap==2 ) join_type=3;
11038   else join_type=2-lcap;
11039   if ( (join_type==0)||(join_type==3) ) {
11040     @<Set the incoming and outgoing directions at |q|; in case of
11041       degeneracy set |join_type:=2|@>;
11042     if ( join_type==0 ) {
11043       @<If |miterlim| is less than the secant of half the angle at |q|
11044         then set |join_type:=2|@>;
11045     }
11046   }
11047 }
11048
11049 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11050
11051   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11052       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11053   if ( tmp<unity )
11054     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11055 }
11056
11057 @ @<Other local variables for |make_envelope|@>=
11058 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11059 scaled tmp; /* a temporary value */
11060
11061 @ The coordinates of |p| have already been shifted unless |p| is the first
11062 knot in which case they get shifted at the very end.
11063
11064 @<Add offset |w| to the cubic from |p| to |q|@>=
11065 right_x(p)=right_x(p)+x_coord(w);
11066 right_y(p)=right_y(p)+y_coord(w);
11067 left_x(q)=left_x(q)+x_coord(w);
11068 left_y(q)=left_y(q)+y_coord(w);
11069 x_coord(q)=x_coord(q)+x_coord(w);
11070 y_coord(q)=y_coord(q)+y_coord(w);
11071 left_type(q)=mp_explicit;
11072 right_type(q)=mp_explicit
11073
11074 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11075 if ( k>zero_off ){ w=link(w); decr(k);  }
11076 else { w=knil(w); incr(k);  }
11077
11078 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11079 the |right_x| and |right_y| fields of |r| are set from |q|.  This is done in
11080 case the cubic containing these control points is ``yet to be examined.''
11081
11082 @<Declare a function called |insert_knot|@>=
11083 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11084   /* returns the inserted knot */
11085   pointer r; /* the new knot */
11086   r=mp_get_node(mp, knot_node_size);
11087   link(r)=link(q); link(q)=r;
11088   right_x(r)=right_x(q);
11089   right_y(r)=right_y(q);
11090   x_coord(r)=x;
11091   y_coord(r)=y;
11092   right_x(q)=x_coord(q);
11093   right_y(q)=y_coord(q);
11094   left_x(r)=x_coord(r);
11095   left_y(r)=y_coord(r);
11096   left_type(r)=mp_explicit;
11097   right_type(r)=mp_explicit;
11098   originator(r)=mp_program_code;
11099   return r;
11100 }
11101
11102 @ After setting |p:=link(p)|, either |join_type=1| or |q=link(p)|.
11103
11104 @<Set |p=link(p)| and add knots between |p| and |q| as...@>=
11105
11106   p=link(p);
11107   if ( (join_type==0)||(join_type==3) ) {
11108     if ( join_type==0 ) {
11109       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11110     } else {
11111       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11112         squared join@>;
11113     }
11114     if ( r!=null ) { 
11115       right_x(r)=x_coord(r);
11116       right_y(r)=y_coord(r);
11117     }
11118   }
11119 }
11120
11121 @ For very small angles, adding a knot is unnecessary and would cause numerical
11122 problems, so we just set |r:=null| in that case.
11123
11124 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11125
11126   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11127   if ( abs(det)<26844 ) { 
11128      r=null; /* sine $<10^{-4}$ */
11129   } else { 
11130     tmp=mp_take_fraction(mp, x_coord(q)-x_coord(p),dyout)-
11131         mp_take_fraction(mp, y_coord(q)-y_coord(p),dxout);
11132     tmp=mp_make_fraction(mp, tmp,det);
11133     r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11134       y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11135   }
11136 }
11137
11138 @ @<Other local variables for |make_envelope|@>=
11139 fraction det; /* a determinant used for mitered join calculations */
11140
11141 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11142
11143   ht_x=y_coord(w)-y_coord(w0);
11144   ht_y=x_coord(w0)-x_coord(w);
11145   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11146     ht_x+=ht_x; ht_y+=ht_y;
11147   }
11148   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11149     product with |(ht_x,ht_y)|@>;
11150   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11151                                   mp_take_fraction(mp, dyin,ht_y));
11152   r=mp_insert_knot(mp, p,x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11153                          y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11154   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11155                                   mp_take_fraction(mp, dyout,ht_y));
11156   r=mp_insert_knot(mp, r,x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11157                          y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11158 }
11159
11160 @ @<Other local variables for |make_envelope|@>=
11161 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11162 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11163 halfword kk; /* keeps track of the pen vertices being scanned */
11164 pointer ww; /* the pen vertex being tested */
11165
11166 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11167 from zero to |max_ht|.
11168
11169 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11170 max_ht=0;
11171 kk=zero_off;
11172 ww=w;
11173 while (1)  { 
11174   @<Step |ww| and move |kk| one step closer to |k0|@>;
11175   if ( kk==k0 ) break;
11176   tmp=mp_take_fraction(mp, (x_coord(ww)-x_coord(w0)),ht_x)+
11177       mp_take_fraction(mp, (y_coord(ww)-y_coord(w0)),ht_y);
11178   if ( tmp>max_ht ) max_ht=tmp;
11179 }
11180
11181
11182 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11183 if ( kk>k0 ) { ww=link(ww); decr(kk);  }
11184 else { ww=knil(ww); incr(kk);  }
11185
11186 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11187 if ( left_type(c)==mp_endpoint ) { 
11188   mp->spec_p1=mp_htap_ypoc(mp, c);
11189   mp->spec_p2=mp->path_tail;
11190   originator(mp->spec_p1)=mp_program_code;
11191   link(mp->spec_p2)=link(mp->spec_p1);
11192   link(mp->spec_p1)=c;
11193   mp_remove_cubic(mp, mp->spec_p1);
11194   c=mp->spec_p1;
11195   if ( c!=link(c) ) {
11196     originator(mp->spec_p2)=mp_program_code;
11197     mp_remove_cubic(mp, mp->spec_p2);
11198   } else {
11199     @<Make |c| look like a cycle of length one@>;
11200   }
11201 }
11202
11203 @ @<Make |c| look like a cycle of length one@>=
11204
11205   left_type(c)=mp_explicit; right_type(c)=mp_explicit;
11206   left_x(c)=x_coord(c); left_y(c)=y_coord(c);
11207   right_x(c)=x_coord(c); right_y(c)=y_coord(c);
11208 }
11209
11210 @ In degenerate situations we might have to look at the knot preceding~|q|.
11211 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11212
11213 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11214 dxin=x_coord(q)-left_x(q);
11215 dyin=y_coord(q)-left_y(q);
11216 if ( (dxin==0)&&(dyin==0) ) {
11217   dxin=x_coord(q)-right_x(p);
11218   dyin=y_coord(q)-right_y(p);
11219   if ( (dxin==0)&&(dyin==0) ) {
11220     dxin=x_coord(q)-x_coord(p);
11221     dyin=y_coord(q)-y_coord(p);
11222     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11223       dxin=dxin+x_coord(w);
11224       dyin=dyin+y_coord(w);
11225     }
11226   }
11227 }
11228 tmp=mp_pyth_add(mp, dxin,dyin);
11229 if ( tmp==0 ) {
11230   join_type=2;
11231 } else { 
11232   dxin=mp_make_fraction(mp, dxin,tmp);
11233   dyin=mp_make_fraction(mp, dyin,tmp);
11234   @<Set the outgoing direction at |q|@>;
11235 }
11236
11237 @ If |q=c| then the coordinates of |r| and the control points between |q|
11238 and~|r| have already been offset by |h|.
11239
11240 @<Set the outgoing direction at |q|@>=
11241 dxout=right_x(q)-x_coord(q);
11242 dyout=right_y(q)-y_coord(q);
11243 if ( (dxout==0)&&(dyout==0) ) {
11244   r=link(q);
11245   dxout=left_x(r)-x_coord(q);
11246   dyout=left_y(r)-y_coord(q);
11247   if ( (dxout==0)&&(dyout==0) ) {
11248     dxout=x_coord(r)-x_coord(q);
11249     dyout=y_coord(r)-y_coord(q);
11250   }
11251 }
11252 if ( q==c ) {
11253   dxout=dxout-x_coord(h);
11254   dyout=dyout-y_coord(h);
11255 }
11256 tmp=mp_pyth_add(mp, dxout,dyout);
11257 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11258 @:this can't happen degerate spec}{\quad degenerate spec@>
11259 dxout=mp_make_fraction(mp, dxout,tmp);
11260 dyout=mp_make_fraction(mp, dyout,tmp)
11261
11262 @* \[23] Direction and intersection times.
11263 A path of length $n$ is defined parametrically by functions $x(t)$ and
11264 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11265 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11266 we shall consider operations that determine special times associated with
11267 given paths: the first time that a path travels in a given direction, and
11268 a pair of times at which two paths cross each other.
11269
11270 @ Let's start with the easier task. The function |find_direction_time| is
11271 given a direction |(x,y)| and a path starting at~|h|. If the path never
11272 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11273 it will be nonnegative.
11274
11275 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11276 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11277 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11278 assumed to match any given direction at time~|t|.
11279
11280 The routine solves this problem in nondegenerate cases by rotating the path
11281 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11282 to find when a given path first travels ``due east.''
11283
11284 @c 
11285 scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11286   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11287   pointer p,q; /* for list traversal */
11288   scaled n; /* the direction time at knot |p| */
11289   scaled tt; /* the direction time within a cubic */
11290   @<Other local variables for |find_direction_time|@>;
11291   @<Normalize the given direction for better accuracy;
11292     but |return| with zero result if it's zero@>;
11293   n=0; p=h; phi=0;
11294   while (1) { 
11295     if ( right_type(p)==mp_endpoint ) break;
11296     q=link(p);
11297     @<Rotate the cubic between |p| and |q|; then
11298       |goto found| if the rotated cubic travels due east at some time |tt|;
11299       but |break| if an entire cyclic path has been traversed@>;
11300     p=q; n=n+unity;
11301   }
11302   return (-unity);
11303 FOUND: 
11304   return (n+tt);
11305 }
11306
11307 @ @<Normalize the given direction for better accuracy...@>=
11308 if ( abs(x)<abs(y) ) { 
11309   x=mp_make_fraction(mp, x,abs(y));
11310   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11311 } else if ( x==0 ) { 
11312   return 0;
11313 } else  { 
11314   y=mp_make_fraction(mp, y,abs(x));
11315   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11316 }
11317
11318 @ Since we're interested in the tangent directions, we work with the
11319 derivative $${1\over3}B'(x_0,x_1,x_2,x_3;t)=
11320 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11321 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11322 in order to achieve better accuracy.
11323
11324 The given path may turn abruptly at a knot, and it might pass the critical
11325 tangent direction at such a time. Therefore we remember the direction |phi|
11326 in which the previous rotated cubic was traveling. (The value of |phi| will be
11327 undefined on the first cubic, i.e., when |n=0|.)
11328
11329 @<Rotate the cubic between |p| and |q|; then...@>=
11330 tt=0;
11331 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11332   points of the rotated derivatives@>;
11333 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11334 if ( n>0 ) { 
11335   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11336   if ( p==h ) break;
11337   };
11338 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11339 @<Exit to |found| if the curve whose derivatives are specified by
11340   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11341
11342 @ @<Other local variables for |find_direction_time|@>=
11343 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11344 angle theta,phi; /* angles of exit and entry at a knot */
11345 fraction t; /* temp storage */
11346
11347 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11348 x1=right_x(p)-x_coord(p); x2=left_x(q)-right_x(p);
11349 x3=x_coord(q)-left_x(q);
11350 y1=right_y(p)-y_coord(p); y2=left_y(q)-right_y(p);
11351 y3=y_coord(q)-left_y(q);
11352 max=abs(x1);
11353 if ( abs(x2)>max ) max=abs(x2);
11354 if ( abs(x3)>max ) max=abs(x3);
11355 if ( abs(y1)>max ) max=abs(y1);
11356 if ( abs(y2)>max ) max=abs(y2);
11357 if ( abs(y3)>max ) max=abs(y3);
11358 if ( max==0 ) goto FOUND;
11359 while ( max<fraction_half ){ 
11360   max+=max; x1+=x1; x2+=x2; x3+=x3;
11361   y1+=y1; y2+=y2; y3+=y3;
11362 }
11363 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11364 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11365 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11366 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11367 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11368 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11369
11370 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11371 theta=mp_n_arg(mp, x1,y1);
11372 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11373 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11374
11375 @ In this step we want to use the |crossing_point| routine to find the
11376 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11377 Several complications arise: If the quadratic equation has a double root,
11378 the curve never crosses zero, and |crossing_point| will find nothing;
11379 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11380 equation has simple roots, or only one root, we may have to negate it
11381 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11382 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11383 identically zero.
11384
11385 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11386 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11387 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11388   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11389     either |goto found| or |goto done|@>;
11390 }
11391 if ( y1<=0 ) {
11392   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11393   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11394 }
11395 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11396   $B(x_1,x_2,x_3;t)\ge0$@>;
11397 DONE:
11398
11399 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11400 two roots, because we know that it isn't identically zero.
11401
11402 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11403 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11404 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11405 subject to rounding errors. Yet this code optimistically tries to
11406 do the right thing.
11407
11408 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11409
11410 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11411 t=mp_crossing_point(mp, y1,y2,y3);
11412 if ( t>fraction_one ) goto DONE;
11413 y2=t_of_the_way(y2,y3);
11414 x1=t_of_the_way(x1,x2);
11415 x2=t_of_the_way(x2,x3);
11416 x1=t_of_the_way(x1,x2);
11417 if ( x1>=0 ) we_found_it;
11418 if ( y2>0 ) y2=0;
11419 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11420 if ( t>fraction_one ) goto DONE;
11421 x1=t_of_the_way(x1,x2);
11422 x2=t_of_the_way(x2,x3);
11423 if ( t_of_the_way(x1,x2)>=0 ) { 
11424   t=t_of_the_way(tt,fraction_one); we_found_it;
11425 }
11426
11427 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11428     either |goto found| or |goto done|@>=
11429
11430   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11431     t=mp_make_fraction(mp, y1,y1-y2);
11432     x1=t_of_the_way(x1,x2);
11433     x2=t_of_the_way(x2,x3);
11434     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11435   } else if ( y3==0 ) {
11436     if ( y1==0 ) {
11437       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11438     } else if ( x3>=0 ) {
11439       tt=unity; goto FOUND;
11440     }
11441   }
11442   goto DONE;
11443 }
11444
11445 @ At this point we know that the derivative of |y(t)| is identically zero,
11446 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11447 traveling east.
11448
11449 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11450
11451   t=mp_crossing_point(mp, -x1,-x2,-x3);
11452   if ( t<=fraction_one ) we_found_it;
11453   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11454     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11455   }
11456 }
11457
11458 @ The intersection of two cubics can be found by an interesting variant
11459 of the general bisection scheme described in the introduction to
11460 |crossing_point|.\
11461 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)$,
11462 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11463 if an intersection exists. First we find the smallest rectangle that
11464 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11465 the smallest rectangle that encloses
11466 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11467 But if the rectangles do overlap, we bisect the intervals, getting
11468 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11469 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11470 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11471 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11472 levels of bisection we will have determined the intersection times $t_1$
11473 and~$t_2$ to $l$~bits of accuracy.
11474
11475 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11476 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11477 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11478 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11479 to determine when the enclosing rectangles overlap. Here's why:
11480 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11481 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11482 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11483 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11484 overlap if and only if $u\submin\L x\submax$ and
11485 $x\submin\L u\submax$. Letting
11486 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11487   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11488 we have $2^lu\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11489 reduces to
11490 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11491 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11492 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11493 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11494 because of the overlap condition; i.e., we know that $X\submin$,
11495 $X\submax$, and their relatives are bounded, hence $X\submax-
11496 U\submin$ and $X\submin-U\submax$ are bounded.
11497
11498 @ Incidentally, if the given cubics intersect more than once, the process
11499 just sketched will not necessarily find the lexicographically smallest pair
11500 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11501 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11502 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11503 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11504 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11505 Shuffled order agrees with lexicographic order if all pairs of solutions
11506 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11507 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11508 and the bisection algorithm would be substantially less efficient if it were
11509 constrained by lexicographic order.
11510
11511 For example, suppose that an overlap has been found for $l=3$ and
11512 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11513 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11514 Then there is probably an intersection in one of the subintervals
11515 $(.1011,.011x)$; but lexicographic order would require us to explore
11516 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11517 want to store all of the subdivision data for the second path, so the
11518 subdivisions would have to be regenerated many times. Such inefficiencies
11519 would be associated with every `1' in the binary representation of~$t_1$.
11520
11521 @ The subdivision process introduces rounding errors, hence we need to
11522 make a more liberal test for overlap. It is not hard to show that the
11523 computed values of $U_i$ differ from the truth by at most~$l$, on
11524 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11525 If $\beta$ is an upper bound on the absolute error in the computed
11526 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11527 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11528 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11529
11530 More accuracy is obtained if we try the algorithm first with |tol=0|;
11531 the more liberal tolerance is used only if an exact approach fails.
11532 It is convenient to do this double-take by letting `3' in the preceding
11533 paragraph be a parameter, which is first 0, then 3.
11534
11535 @<Glob...@>=
11536 unsigned int tol_step; /* either 0 or 3, usually */
11537
11538 @ We shall use an explicit stack to implement the recursive bisection
11539 method described above. The |bisect_stack| array will contain numerous 5-word
11540 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11541 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11542
11543 The following macros define the allocation of stack positions to
11544 the quantities needed for bisection-intersection.
11545
11546 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11547 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11548 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11549 @d stack_min(A) mp->bisect_stack[(A)+3]
11550   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11551 @d stack_max(A) mp->bisect_stack[(A)+4]
11552   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11553 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11554 @#
11555 @d u_packet(A) ((A)-5)
11556 @d v_packet(A) ((A)-10)
11557 @d x_packet(A) ((A)-15)
11558 @d y_packet(A) ((A)-20)
11559 @d l_packets (mp->bisect_ptr-int_packets)
11560 @d r_packets mp->bisect_ptr
11561 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11562 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11563 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11564 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11565 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11566 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11567 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11568 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11569 @#
11570 @d u1l stack_1(ul_packet) /* $U'_1$ */
11571 @d u2l stack_2(ul_packet) /* $U'_2$ */
11572 @d u3l stack_3(ul_packet) /* $U'_3$ */
11573 @d v1l stack_1(vl_packet) /* $V'_1$ */
11574 @d v2l stack_2(vl_packet) /* $V'_2$ */
11575 @d v3l stack_3(vl_packet) /* $V'_3$ */
11576 @d x1l stack_1(xl_packet) /* $X'_1$ */
11577 @d x2l stack_2(xl_packet) /* $X'_2$ */
11578 @d x3l stack_3(xl_packet) /* $X'_3$ */
11579 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11580 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11581 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11582 @d u1r stack_1(ur_packet) /* $U''_1$ */
11583 @d u2r stack_2(ur_packet) /* $U''_2$ */
11584 @d u3r stack_3(ur_packet) /* $U''_3$ */
11585 @d v1r stack_1(vr_packet) /* $V''_1$ */
11586 @d v2r stack_2(vr_packet) /* $V''_2$ */
11587 @d v3r stack_3(vr_packet) /* $V''_3$ */
11588 @d x1r stack_1(xr_packet) /* $X''_1$ */
11589 @d x2r stack_2(xr_packet) /* $X''_2$ */
11590 @d x3r stack_3(xr_packet) /* $X''_3$ */
11591 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11592 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11593 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11594 @#
11595 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11596 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11597 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11598 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11599 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11600 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11601
11602 @<Glob...@>=
11603 integer *bisect_stack;
11604 unsigned int bisect_ptr;
11605
11606 @ @<Allocate or initialize ...@>=
11607 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11608
11609 @ @<Dealloc variables@>=
11610 xfree(mp->bisect_stack);
11611
11612 @ @<Check the ``constant''...@>=
11613 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11614
11615 @ Computation of the min and max is a tedious but fairly fast sequence of
11616 instructions; exactly four comparisons are made in each branch.
11617
11618 @d set_min_max(A) 
11619   if ( stack_1((A))<0 ) {
11620     if ( stack_3((A))>=0 ) {
11621       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11622       else stack_min((A))=stack_1((A));
11623       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11624       if ( stack_max((A))<0 ) stack_max((A))=0;
11625     } else { 
11626       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11627       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11628       stack_max((A))=stack_1((A))+stack_2((A));
11629       if ( stack_max((A))<0 ) stack_max((A))=0;
11630     }
11631   } else if ( stack_3((A))<=0 ) {
11632     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11633     else stack_max((A))=stack_1((A));
11634     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11635     if ( stack_min((A))>0 ) stack_min((A))=0;
11636   } else  { 
11637     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11638     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11639     stack_min((A))=stack_1((A))+stack_2((A));
11640     if ( stack_min((A))>0 ) stack_min((A))=0;
11641   }
11642
11643 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11644 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11645 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11646 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11647 plus the |scaled| values of $t_1$ and~$t_2$.
11648
11649 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11650 finds no intersection. The routine gives up and gives an approximate answer
11651 if it has backtracked
11652 more than 5000 times (otherwise there are cases where several minutes
11653 of fruitless computation would be possible).
11654
11655 @d max_patience 5000
11656
11657 @<Glob...@>=
11658 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11659 integer time_to_go; /* this many backtracks before giving up */
11660 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11661
11662 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11663 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,link(p))|
11664 and |(pp,link(pp))|, respectively.
11665
11666 @c void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11667   pointer q,qq; /* |link(p)|, |link(pp)| */
11668   mp->time_to_go=max_patience; mp->max_t=2;
11669   @<Initialize for intersections at level zero@>;
11670 CONTINUE:
11671   while (1) { 
11672     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11673     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11674     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11675     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11676     { 
11677       if ( mp->cur_t>=mp->max_t ){ 
11678         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11679            mp->cur_t=halfp(mp->cur_t+1); 
11680                mp->cur_tt=halfp(mp->cur_tt+1); 
11681            return;
11682         }
11683         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11684       }
11685       @<Subdivide for a new level of intersection@>;
11686       goto CONTINUE;
11687     }
11688     if ( mp->time_to_go>0 ) {
11689       decr(mp->time_to_go);
11690     } else { 
11691       while ( mp->appr_t<unity ) { 
11692         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11693       }
11694       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11695     }
11696     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11697   }
11698 }
11699
11700 @ The following variables are global, although they are used only by
11701 |cubic_intersection|, because it is necessary on some machines to
11702 split |cubic_intersection| up into two procedures.
11703
11704 @<Glob...@>=
11705 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11706 integer tol; /* bound on the uncertainty in the overlap test */
11707 unsigned int uv;
11708 unsigned int xy; /* pointers to the current packets of interest */
11709 integer three_l; /* |tol_step| times the bisection level */
11710 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11711
11712 @ We shall assume that the coordinates are sufficiently non-extreme that
11713 integer overflow will not occur.
11714 @^overflow in arithmetic@>
11715
11716 @<Initialize for intersections at level zero@>=
11717 q=link(p); qq=link(pp); mp->bisect_ptr=int_packets;
11718 u1r=right_x(p)-x_coord(p); u2r=left_x(q)-right_x(p);
11719 u3r=x_coord(q)-left_x(q); set_min_max(ur_packet);
11720 v1r=right_y(p)-y_coord(p); v2r=left_y(q)-right_y(p);
11721 v3r=y_coord(q)-left_y(q); set_min_max(vr_packet);
11722 x1r=right_x(pp)-x_coord(pp); x2r=left_x(qq)-right_x(pp);
11723 x3r=x_coord(qq)-left_x(qq); set_min_max(xr_packet);
11724 y1r=right_y(pp)-y_coord(pp); y2r=left_y(qq)-right_y(pp);
11725 y3r=y_coord(qq)-left_y(qq); set_min_max(yr_packet);
11726 mp->delx=x_coord(p)-x_coord(pp); mp->dely=y_coord(p)-y_coord(pp);
11727 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11728 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11729
11730 @ @<Subdivide for a new level of intersection@>=
11731 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11732 stack_uv=mp->uv; stack_xy=mp->xy;
11733 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11734 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11735 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11736 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11737 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11738 u3l=half(u2l+u2r); u1r=u3l;
11739 set_min_max(ul_packet); set_min_max(ur_packet);
11740 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11741 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11742 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11743 v3l=half(v2l+v2r); v1r=v3l;
11744 set_min_max(vl_packet); set_min_max(vr_packet);
11745 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11746 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11747 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11748 x3l=half(x2l+x2r); x1r=x3l;
11749 set_min_max(xl_packet); set_min_max(xr_packet);
11750 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11751 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11752 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11753 y3l=half(y2l+y2r); y1r=y3l;
11754 set_min_max(yl_packet); set_min_max(yr_packet);
11755 mp->uv=l_packets; mp->xy=l_packets;
11756 mp->delx+=mp->delx; mp->dely+=mp->dely;
11757 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11758 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11759
11760 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11761 NOT_FOUND: 
11762 if ( odd(mp->cur_tt) ) {
11763   if ( odd(mp->cur_t) ) {
11764      @<Descend to the previous level and |goto not_found|@>;
11765   } else { 
11766     incr(mp->cur_t);
11767     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11768       +stack_3(u_packet(mp->uv));
11769     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11770       +stack_3(v_packet(mp->uv));
11771     mp->uv=mp->uv+int_packets; /* switch from |l_packets| to |r_packets| */
11772     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11773          /* switch from |r_packets| to |l_packets| */
11774     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11775       +stack_3(x_packet(mp->xy));
11776     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11777       +stack_3(y_packet(mp->xy));
11778   }
11779 } else { 
11780   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11781   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11782     -stack_3(x_packet(mp->xy));
11783   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11784     -stack_3(y_packet(mp->xy));
11785   mp->xy=mp->xy+int_packets; /* switch from |l_packets| to |r_packets| */
11786 }
11787
11788 @ @<Descend to the previous level...@>=
11789
11790   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11791   if ( mp->cur_t==0 ) return;
11792   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11793   mp->three_l=mp->three_l-mp->tol_step;
11794   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11795   mp->uv=stack_uv; mp->xy=stack_xy;
11796   goto NOT_FOUND;
11797 }
11798
11799 @ The |path_intersection| procedure is much simpler.
11800 It invokes |cubic_intersection| in lexicographic order until finding a
11801 pair of cubics that intersect. The final intersection times are placed in
11802 |cur_t| and~|cur_tt|.
11803
11804 @c void mp_path_intersection (MP mp,pointer h, pointer hh) {
11805   pointer p,pp; /* link registers that traverse the given paths */
11806   integer n,nn; /* integer parts of intersection times, minus |unity| */
11807   @<Change one-point paths into dead cycles@>;
11808   mp->tol_step=0;
11809   do {  
11810     n=-unity; p=h;
11811     do {  
11812       if ( right_type(p)!=mp_endpoint ) { 
11813         nn=-unity; pp=hh;
11814         do {  
11815           if ( right_type(pp)!=mp_endpoint )  { 
11816             mp_cubic_intersection(mp, p,pp);
11817             if ( mp->cur_t>0 ) { 
11818               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11819               return;
11820             }
11821           }
11822           nn=nn+unity; pp=link(pp);
11823         } while (pp!=hh);
11824       }
11825       n=n+unity; p=link(p);
11826     } while (p!=h);
11827     mp->tol_step=mp->tol_step+3;
11828   } while (mp->tol_step<=3);
11829   mp->cur_t=-unity; mp->cur_tt=-unity;
11830 }
11831
11832 @ @<Change one-point paths...@>=
11833 if ( right_type(h)==mp_endpoint ) {
11834   right_x(h)=x_coord(h); left_x(h)=x_coord(h);
11835   right_y(h)=y_coord(h); left_y(h)=y_coord(h); right_type(h)=mp_explicit;
11836 }
11837 if ( right_type(hh)==mp_endpoint ) {
11838   right_x(hh)=x_coord(hh); left_x(hh)=x_coord(hh);
11839   right_y(hh)=y_coord(hh); left_y(hh)=y_coord(hh); right_type(hh)=mp_explicit;
11840 }
11841
11842 @* \[24] Dynamic linear equations.
11843 \MP\ users define variables implicitly by stating equations that should be
11844 satisfied; the computer is supposed to be smart enough to solve those equations.
11845 And indeed, the computer tries valiantly to do so, by distinguishing five
11846 different types of numeric values:
11847
11848 \smallskip\hang
11849 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11850 of the variable whose address is~|p|.
11851
11852 \smallskip\hang
11853 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11854 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11855 as a |scaled| number plus a sum of independent variables with |fraction|
11856 coefficients.
11857
11858 \smallskip\hang
11859 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11860 number'' reflecting the time this variable was first used in an equation;
11861 also |0<=m<64|, and each dependent variable
11862 that refers to this one is actually referring to the future value of
11863 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11864 scaling are sometimes needed to keep the coefficients in dependency lists
11865 from getting too large. The value of~|m| will always be even.)
11866
11867 \smallskip\hang
11868 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11869 equation before, but it has been explicitly declared to be numeric.
11870
11871 \smallskip\hang
11872 |type(p)=undefined| means that variable |p| hasn't appeared before.
11873
11874 \smallskip\noindent
11875 We have actually discussed these five types in the reverse order of their
11876 history during a computation: Once |known|, a variable never again
11877 becomes |dependent|; once |dependent|, it almost never again becomes
11878 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
11879 and once |mp_numeric_type|, it never again becomes |undefined| (except
11880 of course when the user specifically decides to scrap the old value
11881 and start again). A backward step may, however, take place: Sometimes
11882 a |dependent| variable becomes |mp_independent| again, when one of the
11883 independent variables it depends on is reverting to |undefined|.
11884
11885
11886 The next patch detects overflow of independent-variable serial
11887 numbers. Diagnosed and patched by Thorsten Dahlheimer.
11888
11889 @d s_scale 64 /* the serial numbers are multiplied by this factor */
11890 @d new_indep(A)  /* create a new independent variable */
11891   { if ( mp->serial_no>el_gordo-s_scale )
11892     mp_fatal_error(mp, "variable instance identifiers exhausted");
11893   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
11894   value((A))=mp->serial_no;
11895   }
11896
11897 @<Glob...@>=
11898 integer serial_no; /* the most recent serial number, times |s_scale| */
11899
11900 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
11901
11902 @ But how are dependency lists represented? It's simple: The linear combination
11903 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
11904 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
11905 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
11906 of $\alpha_1$; and |link(p)| points to the dependency list
11907 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
11908 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
11909 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
11910 they appear in decreasing order of their |value| fields (i.e., of
11911 their serial numbers). \ (It is convenient to use decreasing order,
11912 since |value(null)=0|. If the independent variables were not sorted by
11913 serial number but by some other criterion, such as their location in |mem|,
11914 the equation-solving mechanism would be too system-dependent, because
11915 the ordering can affect the computed results.)
11916
11917 The |link| field in the node that contains the constant term $\beta$ is
11918 called the {\sl final link\/} of the dependency list. \MP\ maintains
11919 a doubly-linked master list of all dependency lists, in terms of a permanently
11920 allocated node
11921 in |mem| called |dep_head|. If there are no dependencies, we have
11922 |link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
11923 otherwise |link(dep_head)| points to the first dependent variable, say~|p|,
11924 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
11925 points to its dependency list. If the final link of that dependency list
11926 occurs in location~|q|, then |link(q)| points to the next dependent
11927 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
11928
11929 @d dep_list(A) link(value_loc((A)))
11930   /* half of the |value| field in a |dependent| variable */
11931 @d prev_dep(A) info(value_loc((A)))
11932   /* the other half; makes a doubly linked list */
11933 @d dep_node_size 2 /* the number of words per dependency node */
11934
11935 @<Initialize table entries...@>= mp->serial_no=0;
11936 link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
11937 info(dep_head)=null; dep_list(dep_head)=null;
11938
11939 @ Actually the description above contains a little white lie. There's
11940 another kind of variable called |mp_proto_dependent|, which is
11941 just like a |dependent| one except that the $\alpha$ coefficients
11942 in its dependency list are |scaled| instead of being fractions.
11943 Proto-dependency lists are mixed with dependency lists in the
11944 nodes reachable from |dep_head|.
11945
11946 @ Here is a procedure that prints a dependency list in symbolic form.
11947 The second parameter should be either |dependent| or |mp_proto_dependent|,
11948 to indicate the scaling of the coefficients.
11949
11950 @<Declare subroutines for printing expressions@>=
11951 void mp_print_dependency (MP mp,pointer p, small_number t) {
11952   integer v; /* a coefficient */
11953   pointer pp,q; /* for list manipulation */
11954   pp=p;
11955   while (1) { 
11956     v=abs(value(p)); q=info(p);
11957     if ( q==null ) { /* the constant term */
11958       if ( (v!=0)||(p==pp) ) {
11959          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, '+');
11960          mp_print_scaled(mp, value(p));
11961       }
11962       return;
11963     }
11964     @<Print the coefficient, unless it's $\pm1.0$@>;
11965     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
11966 @:this can't happen dep}{\quad dep@>
11967     mp_print_variable_name(mp, q); v=value(q) % s_scale;
11968     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
11969     p=link(p);
11970   }
11971 }
11972
11973 @ @<Print the coefficient, unless it's $\pm1.0$@>=
11974 if ( value(p)<0 ) mp_print_char(mp, '-');
11975 else if ( p!=pp ) mp_print_char(mp, '+');
11976 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
11977 if ( v!=unity ) mp_print_scaled(mp, v)
11978
11979 @ The maximum absolute value of a coefficient in a given dependency list
11980 is returned by the following simple function.
11981
11982 @c fraction mp_max_coef (MP mp,pointer p) {
11983   fraction x; /* the maximum so far */
11984   x=0;
11985   while ( info(p)!=null ) {
11986     if ( abs(value(p))>x ) x=abs(value(p));
11987     p=link(p);
11988   }
11989   return x;
11990 }
11991
11992 @ One of the main operations needed on dependency lists is to add a multiple
11993 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
11994 to dependency lists and |f| is a fraction.
11995
11996 If the coefficient of any independent variable becomes |coef_bound| or
11997 more, in absolute value, this procedure changes the type of that variable
11998 to `|independent_needing_fix|', and sets the global variable |fix_needed|
11999 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12000 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12001 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12002 2.3723$, the safer value 7/3 is taken as the threshold.)
12003
12004 The changes mentioned in the preceding paragraph are actually done only if
12005 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12006 it is |false| only when \MP\ is making a dependency list that will soon
12007 be equated to zero.
12008
12009 Several procedures that act on dependency lists, including |p_plus_fq|,
12010 set the global variable |dep_final| to the final (constant term) node of
12011 the dependency list that they produce.
12012
12013 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12014 @d independent_needing_fix 0
12015
12016 @<Glob...@>=
12017 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12018 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12019 pointer dep_final; /* location of the constant term and final link */
12020
12021 @ @<Set init...@>=
12022 mp->fix_needed=false; mp->watch_coefs=true;
12023
12024 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12025 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12026 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12027 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12028
12029 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12030
12031 The final link of the dependency list or proto-dependency list returned
12032 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12033 constant term of the result will be located in the same |mem| location
12034 as the original constant term of~|p|.
12035
12036 Coefficients of the result are assumed to be zero if they are less than
12037 a certain threshold. This compensates for inevitable rounding errors,
12038 and tends to make more variables `|known|'. The threshold is approximately
12039 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12040 proto-dependencies.
12041
12042 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12043 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12044 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12045 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12046
12047 @<Declare basic dependency-list subroutines@>=
12048 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12049                       pointer q, small_number t, small_number tt) ;
12050
12051 @ @c
12052 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12053                       pointer q, small_number t, small_number tt) {
12054   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12055   pointer r,s; /* for list manipulation */
12056   integer threshold; /* defines a neighborhood of zero */
12057   integer v; /* temporary register */
12058   if ( t==mp_dependent ) threshold=fraction_threshold;
12059   else threshold=scaled_threshold;
12060   r=temp_head; pp=info(p); qq=info(q);
12061   while (1) {
12062     if ( pp==qq ) {
12063       if ( pp==null ) {
12064        break;
12065       } else {
12066         @<Contribute a term from |p|, plus |f| times the
12067           corresponding term from |q|@>
12068       }
12069     } else if ( value(pp)<value(qq) ) {
12070       @<Contribute a term from |q|, multiplied by~|f|@>
12071     } else { 
12072      link(r)=p; r=p; p=link(p); pp=info(p);
12073     }
12074   }
12075   if ( t==mp_dependent )
12076     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12077   else  
12078     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12079   link(r)=p; mp->dep_final=p; 
12080   return link(temp_head);
12081 }
12082
12083 @ @<Contribute a term from |p|, plus |f|...@>=
12084
12085   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12086   else v=value(p)+mp_take_scaled(mp, f,value(q));
12087   value(p)=v; s=p; p=link(p);
12088   if ( abs(v)<threshold ) {
12089     mp_free_node(mp, s,dep_node_size);
12090   } else {
12091     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12092       type(qq)=independent_needing_fix; mp->fix_needed=true;
12093     }
12094     link(r)=s; r=s;
12095   };
12096   pp=info(p); q=link(q); qq=info(q);
12097 }
12098
12099 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12100
12101   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12102   else v=mp_take_scaled(mp, f,value(q));
12103   if ( abs(v)>halfp(threshold) ) { 
12104     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12105     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12106       type(qq)=independent_needing_fix; mp->fix_needed=true;
12107     }
12108     link(r)=s; r=s;
12109   }
12110   q=link(q); qq=info(q);
12111 }
12112
12113 @ It is convenient to have another subroutine for the special case
12114 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12115 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12116
12117 @c pointer mp_p_plus_q (MP mp,pointer p, pointer q, small_number t) {
12118   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12119   pointer r,s; /* for list manipulation */
12120   integer threshold; /* defines a neighborhood of zero */
12121   integer v; /* temporary register */
12122   if ( t==mp_dependent ) threshold=fraction_threshold;
12123   else threshold=scaled_threshold;
12124   r=temp_head; pp=info(p); qq=info(q);
12125   while (1) {
12126     if ( pp==qq ) {
12127       if ( pp==null ) {
12128         break;
12129       } else {
12130         @<Contribute a term from |p|, plus the
12131           corresponding term from |q|@>
12132       }
12133     } else { 
12134           if ( value(pp)<value(qq) ) {
12135         s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12136         q=link(q); qq=info(q); link(r)=s; r=s;
12137       } else { 
12138         link(r)=p; r=p; p=link(p); pp=info(p);
12139       }
12140     }
12141   }
12142   value(p)=mp_slow_add(mp, value(p),value(q));
12143   link(r)=p; mp->dep_final=p; 
12144   return link(temp_head);
12145 }
12146
12147 @ @<Contribute a term from |p|, plus the...@>=
12148
12149   v=value(p)+value(q);
12150   value(p)=v; s=p; p=link(p); pp=info(p);
12151   if ( abs(v)<threshold ) {
12152     mp_free_node(mp, s,dep_node_size);
12153   } else { 
12154     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12155       type(qq)=independent_needing_fix; mp->fix_needed=true;
12156     }
12157     link(r)=s; r=s;
12158   }
12159   q=link(q); qq=info(q);
12160 }
12161
12162 @ A somewhat simpler routine will multiply a dependency list
12163 by a given constant~|v|. The constant is either a |fraction| less than
12164 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12165 convert a dependency list to a proto-dependency list.
12166 Parameters |t0| and |t1| are the list types before and after;
12167 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12168 and |v_is_scaled=true|.
12169
12170 @c pointer mp_p_times_v (MP mp,pointer p, integer v, small_number t0,
12171                          small_number t1, boolean v_is_scaled) {
12172   pointer r,s; /* for list manipulation */
12173   integer w; /* tentative coefficient */
12174   integer threshold;
12175   boolean scaling_down;
12176   if ( t0!=t1 ) scaling_down=true; else scaling_down=(!v_is_scaled);
12177   if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12178   else threshold=half_scaled_threshold;
12179   r=temp_head;
12180   while ( info(p)!=null ) {    
12181     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12182     else w=mp_take_scaled(mp, v,value(p));
12183     if ( abs(w)<=threshold ) { 
12184       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12185     } else {
12186       if ( abs(w)>=coef_bound ) { 
12187         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12188       }
12189       link(r)=p; r=p; value(p)=w; p=link(p);
12190     }
12191   }
12192   link(r)=p;
12193   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12194   else value(p)=mp_take_fraction(mp, value(p),v);
12195   return link(temp_head);
12196 }
12197
12198 @ Similarly, we sometimes need to divide a dependency list
12199 by a given |scaled| constant.
12200
12201 @<Declare basic dependency-list subroutines@>=
12202 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12203   t0, small_number t1) ;
12204
12205 @ @c
12206 pointer mp_p_over_v (MP mp,pointer p, scaled v, small_number 
12207   t0, small_number t1) {
12208   pointer r,s; /* for list manipulation */
12209   integer w; /* tentative coefficient */
12210   integer threshold;
12211   boolean scaling_down;
12212   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12213   if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12214   else threshold=half_scaled_threshold;
12215   r=temp_head;
12216   while ( info( p)!=null ) {
12217     if ( scaling_down ) {
12218       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12219       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12220     } else {
12221       w=mp_make_scaled(mp, value(p),v);
12222     }
12223     if ( abs(w)<=threshold ) {
12224       s=link(p); mp_free_node(mp, p,dep_node_size); p=s;
12225     } else { 
12226       if ( abs(w)>=coef_bound ) {
12227          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12228       }
12229       link(r)=p; r=p; value(p)=w; p=link(p);
12230     }
12231   }
12232   link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12233   return link(temp_head);
12234 }
12235
12236 @ Here's another utility routine for dependency lists. When an independent
12237 variable becomes dependent, we want to remove it from all existing
12238 dependencies. The |p_with_x_becoming_q| function computes the
12239 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12240
12241 This procedure has basically the same calling conventions as |p_plus_fq|:
12242 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12243 final link are inherited from~|p|; and the fourth parameter tells whether
12244 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12245 is not altered if |x| does not occur in list~|p|.
12246
12247 @c pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12248            pointer x, pointer q, small_number t) {
12249   pointer r,s; /* for list manipulation */
12250   integer v; /* coefficient of |x| */
12251   integer sx; /* serial number of |x| */
12252   s=p; r=temp_head; sx=value(x);
12253   while ( value(info(s))>sx ) { r=s; s=link(s); };
12254   if ( info(s)!=x ) { 
12255     return p;
12256   } else { 
12257     link(temp_head)=p; link(r)=link(s); v=value(s);
12258     mp_free_node(mp, s,dep_node_size);
12259     return mp_p_plus_fq(mp, link(temp_head),v,q,t,mp_dependent);
12260   }
12261 }
12262
12263 @ Here's a simple procedure that reports an error when a variable
12264 has just received a known value that's out of the required range.
12265
12266 @<Declare basic dependency-list subroutines@>=
12267 void mp_val_too_big (MP mp,scaled x) ;
12268
12269 @ @c void mp_val_too_big (MP mp,scaled x) { 
12270   if ( mp->internal[mp_warning_check]>0 ) { 
12271     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, ')');
12272 @.Value is too large@>
12273     help4("The equation I just processed has given some variable")
12274       ("a value of 4096 or more. Continue and I'll try to cope")
12275       ("with that big value; but it might be dangerous.")
12276       ("(Set warningcheck:=0 to suppress this message.)");
12277     mp_error(mp);
12278   }
12279 }
12280
12281 @ When a dependent variable becomes known, the following routine
12282 removes its dependency list. Here |p| points to the variable, and
12283 |q| points to the dependency list (which is one node long).
12284
12285 @<Declare basic dependency-list subroutines@>=
12286 void mp_make_known (MP mp,pointer p, pointer q) ;
12287
12288 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12289   int t; /* the previous type */
12290   prev_dep(link(q))=prev_dep(p);
12291   link(prev_dep(p))=link(q); t=type(p);
12292   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12293   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12294   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12295     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12296 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12297     mp_print_variable_name(mp, p); 
12298     mp_print_char(mp, '='); mp_print_scaled(mp, value(p));
12299     mp_end_diagnostic(mp, false);
12300   }
12301   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12302     mp->cur_type=mp_known; mp->cur_exp=value(p);
12303     mp_free_node(mp, p,value_node_size);
12304   }
12305 }
12306
12307 @ The |fix_dependencies| routine is called into action when |fix_needed|
12308 has been triggered. The program keeps a list~|s| of independent variables
12309 whose coefficients must be divided by~4.
12310
12311 In unusual cases, this fixup process might reduce one or more coefficients
12312 to zero, so that a variable will become known more or less by default.
12313
12314 @<Declare basic dependency-list subroutines@>=
12315 void mp_fix_dependencies (MP mp);
12316
12317 @ @c void mp_fix_dependencies (MP mp) {
12318   pointer p,q,r,s,t; /* list manipulation registers */
12319   pointer x; /* an independent variable */
12320   r=link(dep_head); s=null;
12321   while ( r!=dep_head ){ 
12322     t=r;
12323     @<Run through the dependency list for variable |t|, fixing
12324       all nodes, and ending with final link~|q|@>;
12325     r=link(q);
12326     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12327   }
12328   while ( s!=null ) { 
12329     p=link(s); x=info(s); free_avail(s); s=p;
12330     type(x)=mp_independent; value(x)=value(x)+2;
12331   }
12332   mp->fix_needed=false;
12333 }
12334
12335 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12336
12337 @<Run through the dependency list for variable |t|...@>=
12338 r=value_loc(t); /* |link(r)=dep_list(t)| */
12339 while (1) { 
12340   q=link(r); x=info(q);
12341   if ( x==null ) break;
12342   if ( type(x)<=independent_being_fixed ) {
12343     if ( type(x)<independent_being_fixed ) {
12344       p=mp_get_avail(mp); link(p)=s; s=p;
12345       info(s)=x; type(x)=independent_being_fixed;
12346     }
12347     value(q)=value(q) / 4;
12348     if ( value(q)==0 ) {
12349       link(r)=link(q); mp_free_node(mp, q,dep_node_size); q=r;
12350     }
12351   }
12352   r=q;
12353 }
12354
12355
12356 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12357 linking it into the list of all known dependencies. We assume that
12358 |dep_final| points to the final node of list~|p|.
12359
12360 @c void mp_new_dep (MP mp,pointer q, pointer p) {
12361   pointer r; /* what used to be the first dependency */
12362   dep_list(q)=p; prev_dep(q)=dep_head;
12363   r=link(dep_head); link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12364   link(dep_head)=q;
12365 }
12366
12367 @ Here is one of the ways a dependency list gets started.
12368 The |const_dependency| routine produces a list that has nothing but
12369 a constant term.
12370
12371 @c pointer mp_const_dependency (MP mp, scaled v) {
12372   mp->dep_final=mp_get_node(mp, dep_node_size);
12373   value(mp->dep_final)=v; info(mp->dep_final)=null;
12374   return mp->dep_final;
12375 }
12376
12377 @ And here's a more interesting way to start a dependency list from scratch:
12378 The parameter to |single_dependency| is the location of an
12379 independent variable~|x|, and the result is the simple dependency list
12380 `|x+0|'.
12381
12382 In the unlikely event that the given independent variable has been doubled so
12383 often that we can't refer to it with a nonzero coefficient,
12384 |single_dependency| returns the simple list `0'.  This case can be
12385 recognized by testing that the returned list pointer is equal to
12386 |dep_final|.
12387
12388 @c pointer mp_single_dependency (MP mp,pointer p) {
12389   pointer q; /* the new dependency list */
12390   integer m; /* the number of doublings */
12391   m=value(p) % s_scale;
12392   if ( m>28 ) {
12393     return mp_const_dependency(mp, 0);
12394   } else { 
12395     q=mp_get_node(mp, dep_node_size);
12396     value(q)=two_to_the(28-m); info(q)=p;
12397     link(q)=mp_const_dependency(mp, 0);
12398     return q;
12399   }
12400 }
12401
12402 @ We sometimes need to make an exact copy of a dependency list.
12403
12404 @c pointer mp_copy_dep_list (MP mp,pointer p) {
12405   pointer q; /* the new dependency list */
12406   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12407   while (1) { 
12408     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12409     if ( info(mp->dep_final)==null ) break;
12410     link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12411     mp->dep_final=link(mp->dep_final); p=link(p);
12412   }
12413   return q;
12414 }
12415
12416 @ But how do variables normally become known? Ah, now we get to the heart of the
12417 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12418 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12419 appears. It equates this list to zero, by choosing an independent variable
12420 with the largest coefficient and making it dependent on the others. The
12421 newly dependent variable is eliminated from all current dependencies,
12422 thereby possibly making other dependent variables known.
12423
12424 The given list |p| is, of course, totally destroyed by all this processing.
12425
12426 @c void mp_linear_eq (MP mp, pointer p, small_number t) {
12427   pointer q,r,s; /* for link manipulation */
12428   pointer x; /* the variable that loses its independence */
12429   integer n; /* the number of times |x| had been halved */
12430   integer v; /* the coefficient of |x| in list |p| */
12431   pointer prev_r; /* lags one step behind |r| */
12432   pointer final_node; /* the constant term of the new dependency list */
12433   integer w; /* a tentative coefficient */
12434    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12435   x=info(q); n=value(x) % s_scale;
12436   @<Divide list |p| by |-v|, removing node |q|@>;
12437   if ( mp->internal[mp_tracing_equations]>0 ) {
12438     @<Display the new dependency@>;
12439   }
12440   @<Simplify all existing dependencies by substituting for |x|@>;
12441   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12442   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12443 }
12444
12445 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12446 q=p; r=link(p); v=value(q);
12447 while ( info(r)!=null ) { 
12448   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12449   r=link(r);
12450 }
12451
12452 @ Here we want to change the coefficients from |scaled| to |fraction|,
12453 except in the constant term. In the common case of a trivial equation
12454 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12455
12456 @<Divide list |p| by |-v|, removing node |q|@>=
12457 s=temp_head; link(s)=p; r=p;
12458 do { 
12459   if ( r==q ) {
12460     link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12461   } else  { 
12462     w=mp_make_fraction(mp, value(r),v);
12463     if ( abs(w)<=half_fraction_threshold ) {
12464       link(s)=link(r); mp_free_node(mp, r,dep_node_size);
12465     } else { 
12466       value(r)=-w; s=r;
12467     }
12468   }
12469   r=link(s);
12470 } while (info(r)!=null);
12471 if ( t==mp_proto_dependent ) {
12472   value(r)=-mp_make_scaled(mp, value(r),v);
12473 } else if ( v!=-fraction_one ) {
12474   value(r)=-mp_make_fraction(mp, value(r),v);
12475 }
12476 final_node=r; p=link(temp_head)
12477
12478 @ @<Display the new dependency@>=
12479 if ( mp_interesting(mp, x) ) {
12480   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12481   mp_print_variable_name(mp, x);
12482 @:]]]\#\#_}{\.{\#\#}@>
12483   w=n;
12484   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12485   mp_print_char(mp, '='); mp_print_dependency(mp, p,mp_dependent); 
12486   mp_end_diagnostic(mp, false);
12487 }
12488
12489 @ @<Simplify all existing dependencies by substituting for |x|@>=
12490 prev_r=dep_head; r=link(dep_head);
12491 while ( r!=dep_head ) {
12492   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12493   if ( info(q)==null ) {
12494     mp_make_known(mp, r,q);
12495   } else { 
12496     dep_list(r)=q;
12497     do {  q=link(q); } while (info(q)!=null);
12498     prev_r=q;
12499   }
12500   r=link(prev_r);
12501 }
12502
12503 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12504 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12505 if ( info(p)==null ) {
12506   type(x)=mp_known;
12507   value(x)=value(p);
12508   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12509   mp_free_node(mp, p,dep_node_size);
12510   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12511     mp->cur_exp=value(x); mp->cur_type=mp_known;
12512     mp_free_node(mp, x,value_node_size);
12513   }
12514 } else { 
12515   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12516   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12517 }
12518
12519 @ @<Divide list |p| by $2^n$@>=
12520
12521   s=temp_head; link(temp_head)=p; r=p;
12522   do {  
12523     if ( n>30 ) w=0;
12524     else w=value(r) / two_to_the(n);
12525     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12526       link(s)=link(r);
12527       mp_free_node(mp, r,dep_node_size);
12528     } else { 
12529       value(r)=w; s=r;
12530     }
12531     r=link(s);
12532   } while (info(s)!=null);
12533   p=link(temp_head);
12534 }
12535
12536 @ The |check_mem| procedure, which is used only when \MP\ is being
12537 debugged, makes sure that the current dependency lists are well formed.
12538
12539 @<Check the list of linear dependencies@>=
12540 q=dep_head; p=link(q);
12541 while ( p!=dep_head ) {
12542   if ( prev_dep(p)!=q ) {
12543     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12544 @.Bad PREVDEP...@>
12545   }
12546   p=dep_list(p);
12547   while (1) {
12548     r=info(p); q=p; p=link(q);
12549     if ( r==null ) break;
12550     if ( value(info(p))>=value(r) ) {
12551       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12552 @.Out of order...@>
12553     }
12554   }
12555 }
12556
12557 @* \[25] Dynamic nonlinear equations.
12558 Variables of numeric type are maintained by the general scheme of
12559 independent, dependent, and known values that we have just studied;
12560 and the components of pair and transform variables are handled in the
12561 same way. But \MP\ also has five other types of values: \&{boolean},
12562 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12563
12564 Equations are allowed between nonlinear quantities, but only in a
12565 simple form. Two variables that haven't yet been assigned values are
12566 either equal to each other, or they're not.
12567
12568 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12569 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12570 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12571 |null| (which means that no other variables are equivalent to this one), or
12572 it points to another variable of the same undefined type. The pointers in the
12573 latter case form a cycle of nodes, which we shall call a ``ring.''
12574 Rings of undefined variables may include capsules, which arise as
12575 intermediate results within expressions or as \&{expr} parameters to macros.
12576
12577 When one member of a ring receives a value, the same value is given to
12578 all the other members. In the case of paths and pictures, this implies
12579 making separate copies of a potentially large data structure; users should
12580 restrain their enthusiasm for such generality, unless they have lots and
12581 lots of memory space.
12582
12583 @ The following procedure is called when a capsule node is being
12584 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12585
12586 @c pointer mp_new_ring_entry (MP mp,pointer p) {
12587   pointer q; /* the new capsule node */
12588   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12589   type(q)=type(p);
12590   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12591   value(p)=q;
12592   return q;
12593 }
12594
12595 @ Conversely, we might delete a capsule or a variable before it becomes known.
12596 The following procedure simply detaches a quantity from its ring,
12597 without recycling the storage.
12598
12599 @<Declare the recycling subroutines@>=
12600 void mp_ring_delete (MP mp,pointer p) {
12601   pointer q; 
12602   q=value(p);
12603   if ( q!=null ) if ( q!=p ){ 
12604     while ( value(q)!=p ) q=value(q);
12605     value(q)=value(p);
12606   }
12607 }
12608
12609 @ Eventually there might be an equation that assigns values to all of the
12610 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12611 propagation of values.
12612
12613 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12614 value, it will soon be recycled.
12615
12616 @c void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12617   small_number t; /* the type of ring |p| */
12618   pointer q,r; /* link manipulation registers */
12619   t=type(p)-unknown_tag; q=value(p);
12620   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12621   do {  
12622     r=value(q); type(q)=t;
12623     switch (t) {
12624     case mp_boolean_type: value(q)=v; break;
12625     case mp_string_type: value(q)=v; add_str_ref(v); break;
12626     case mp_pen_type: value(q)=copy_pen(v); break;
12627     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12628     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12629     } /* there ain't no more cases */
12630     q=r;
12631   } while (q!=p);
12632 }
12633
12634 @ If two members of rings are equated, and if they have the same type,
12635 the |ring_merge| procedure is called on to make them equivalent.
12636
12637 @c void mp_ring_merge (MP mp,pointer p, pointer q) {
12638   pointer r; /* traverses one list */
12639   r=value(p);
12640   while ( r!=p ) {
12641     if ( r==q ) {
12642       @<Exclaim about a redundant equation@>;
12643       return;
12644     };
12645     r=value(r);
12646   }
12647   r=value(p); value(p)=value(q); value(q)=r;
12648 }
12649
12650 @ @<Exclaim about a redundant equation@>=
12651
12652   print_err("Redundant equation");
12653 @.Redundant equation@>
12654   help2("I already knew that this equation was true.")
12655    ("But perhaps no harm has been done; let's continue.");
12656   mp_put_get_error(mp);
12657 }
12658
12659 @* \[26] Introduction to the syntactic routines.
12660 Let's pause a moment now and try to look at the Big Picture.
12661 The \MP\ program consists of three main parts: syntactic routines,
12662 semantic routines, and output routines. The chief purpose of the
12663 syntactic routines is to deliver the user's input to the semantic routines,
12664 while parsing expressions and locating operators and operands. The
12665 semantic routines act as an interpreter responding to these operators,
12666 which may be regarded as commands. And the output routines are
12667 periodically called on to produce compact font descriptions that can be
12668 used for typesetting or for making interim proof drawings. We have
12669 discussed the basic data structures and many of the details of semantic
12670 operations, so we are good and ready to plunge into the part of \MP\ that
12671 actually controls the activities.
12672
12673 Our current goal is to come to grips with the |get_next| procedure,
12674 which is the keystone of \MP's input mechanism. Each call of |get_next|
12675 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12676 representing the next input token.
12677 $$\vbox{\halign{#\hfil\cr
12678   \hbox{|cur_cmd| denotes a command code from the long list of codes
12679    given earlier;}\cr
12680   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12681   \hbox{|cur_sym| is the hash address of the symbolic token that was
12682    just scanned,}\cr
12683   \hbox{\qquad or zero in the case of a numeric or string
12684    or capsule token.}\cr}}$$
12685 Underlying this external behavior of |get_next| is all the machinery
12686 necessary to convert from character files to tokens. At a given time we
12687 may be only partially finished with the reading of several files (for
12688 which \&{input} was specified), and partially finished with the expansion
12689 of some user-defined macros and/or some macro parameters, and partially
12690 finished reading some text that the user has inserted online,
12691 and so on. When reading a character file, the characters must be
12692 converted to tokens; comments and blank spaces must
12693 be removed, numeric and string tokens must be evaluated.
12694
12695 To handle these situations, which might all be present simultaneously,
12696 \MP\ uses various stacks that hold information about the incomplete
12697 activities, and there is a finite state control for each level of the
12698 input mechanism. These stacks record the current state of an implicitly
12699 recursive process, but the |get_next| procedure is not recursive.
12700
12701 @<Glob...@>=
12702 eight_bits cur_cmd; /* current command set by |get_next| */
12703 integer cur_mod; /* operand of current command */
12704 halfword cur_sym; /* hash address of current symbol */
12705
12706 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12707 command code and its modifier.
12708 It consists of a rather tedious sequence of print
12709 commands, and most of it is essentially an inverse to the |primitive|
12710 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12711 all of this procedure appears elsewhere in the program, together with the
12712 corresponding |primitive| calls.
12713
12714 @<Declare the procedure called |print_cmd_mod|@>=
12715 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12716  switch (c) {
12717   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12718   default: mp_print(mp, "[unknown command code!]"); break;
12719   }
12720 }
12721
12722 @ Here is a procedure that displays a given command in braces, in the
12723 user's transcript file.
12724
12725 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12726
12727 @c 
12728 void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12729   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12730   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, '}');
12731   mp_end_diagnostic(mp, false);
12732 }
12733
12734 @* \[27] Input stacks and states.
12735 The state of \MP's input mechanism appears in the input stack, whose
12736 entries are records with five fields, called |index|, |start|, |loc|,
12737 |limit|, and |name|. The top element of this stack is maintained in a
12738 global variable for which no subscripting needs to be done; the other
12739 elements of the stack appear in an array. Hence the stack is declared thus:
12740
12741 @<Types...@>=
12742 typedef struct {
12743   quarterword index_field;
12744   halfword start_field, loc_field, limit_field, name_field;
12745 } in_state_record;
12746
12747 @ @<Glob...@>=
12748 in_state_record *input_stack;
12749 integer input_ptr; /* first unused location of |input_stack| */
12750 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12751 in_state_record cur_input; /* the ``top'' input state */
12752 int stack_size; /* maximum number of simultaneous input sources */
12753
12754 @ @<Allocate or initialize ...@>=
12755 mp->stack_size = 300;
12756 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12757
12758 @ @<Dealloc variables@>=
12759 xfree(mp->input_stack);
12760
12761 @ We've already defined the special variable |loc==cur_input.loc_field|
12762 in our discussion of basic input-output routines. The other components of
12763 |cur_input| are defined in the same way:
12764
12765 @d index mp->cur_input.index_field /* reference for buffer information */
12766 @d start mp->cur_input.start_field /* starting position in |buffer| */
12767 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12768 @d name mp->cur_input.name_field /* name of the current file */
12769
12770 @ Let's look more closely now at the five control variables
12771 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12772 assuming that \MP\ is reading a line of characters that have been input
12773 from some file or from the user's terminal. There is an array called
12774 |buffer| that acts as a stack of all lines of characters that are
12775 currently being read from files, including all lines on subsidiary
12776 levels of the input stack that are not yet completed. \MP\ will return to
12777 the other lines when it is finished with the present input file.
12778
12779 (Incidentally, on a machine with byte-oriented addressing, it would be
12780 appropriate to combine |buffer| with the |str_pool| array,
12781 letting the buffer entries grow downward from the top of the string pool
12782 and checking that these two tables don't bump into each other.)
12783
12784 The line we are currently working on begins in position |start| of the
12785 buffer; the next character we are about to read is |buffer[loc]|; and
12786 |limit| is the location of the last character present. We always have
12787 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12788 that the end of a line is easily sensed.
12789
12790 The |name| variable is a string number that designates the name of
12791 the current file, if we are reading an ordinary text file.  Special codes
12792 |is_term..max_spec_src| indicate other sources of input text.
12793
12794 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12795 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12796 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12797 @d max_spec_src is_scantok
12798
12799 @ Additional information about the current line is available via the
12800 |index| variable, which counts how many lines of characters are present
12801 in the buffer below the current level. We have |index=0| when reading
12802 from the terminal and prompting the user for each line; then if the user types,
12803 e.g., `\.{input figs}', we will have |index=1| while reading
12804 the file \.{figs.mp}. However, it does not follow that |index| is the
12805 same as the input stack pointer, since many of the levels on the input
12806 stack may come from token lists and some |index| values may correspond
12807 to \.{MPX} files that are not currently on the stack.
12808
12809 The global variable |in_open| is equal to the highest |index| value counting
12810 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12811 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12812 when we are not reading a token list.
12813
12814 If we are not currently reading from the terminal,
12815 we are reading from the file variable |input_file[index]|. We use
12816 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12817 and |cur_file| as an abbreviation for |input_file[index]|.
12818
12819 When \MP\ is not reading from the terminal, the global variable |line| contains
12820 the line number in the current file, for use in error messages. More precisely,
12821 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12822 the line number for each file in the |input_file| array.
12823
12824 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12825 array so that the name doesn't get lost when the file is temporarily removed
12826 from the input stack.
12827 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12828 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12829 Since this is not an \.{MPX} file, we have
12830 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12831 This |name| field is set to |finished| when |input_file[k]| is completely
12832 read.
12833
12834 If more information about the input state is needed, it can be
12835 included in small arrays like those shown here. For example,
12836 the current page or segment number in the input file might be put
12837 into a variable |page|, that is really a macro for the current entry
12838 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12839 by analogy with |line_stack|.
12840 @^system dependencies@>
12841
12842 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12843 @d cur_file mp->input_file[index] /* the current |void *| variable */
12844 @d line mp->line_stack[index] /* current line number in the current source file */
12845 @d in_name mp->iname_stack[index] /* a string used to construct \.{MPX} file names */
12846 @d in_area mp->iarea_stack[index] /* another string for naming \.{MPX} files */
12847 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12848 @d mpx_reading (mp->mpx_name[index]>absent)
12849   /* when reading a file, is it an \.{MPX} file? */
12850 @d finished 0
12851   /* |name_field| value when the corresponding \.{MPX} file is finished */
12852
12853 @<Glob...@>=
12854 integer in_open; /* the number of lines in the buffer, less one */
12855 unsigned int open_parens; /* the number of open text files */
12856 void  * *input_file ;
12857 integer *line_stack ; /* the line number for each file */
12858 char *  *iname_stack; /* used for naming \.{MPX} files */
12859 char *  *iarea_stack; /* used for naming \.{MPX} files */
12860 halfword*mpx_name  ;
12861
12862 @ @<Allocate or ...@>=
12863 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
12864 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
12865 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12866 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
12867 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
12868 {
12869   int k;
12870   for (k=0;k<=mp->max_in_open;k++) {
12871     mp->iname_stack[k] =NULL;
12872     mp->iarea_stack[k] =NULL;
12873   }
12874 }
12875
12876 @ @<Dealloc variables@>=
12877 {
12878   int l;
12879   for (l=0;l<=mp->max_in_open;l++) {
12880     xfree(mp->iname_stack[l]);
12881     xfree(mp->iarea_stack[l]);
12882   }
12883 }
12884 xfree(mp->input_file);
12885 xfree(mp->line_stack);
12886 xfree(mp->iname_stack);
12887 xfree(mp->iarea_stack);
12888 xfree(mp->mpx_name);
12889
12890
12891 @ However, all this discussion about input state really applies only to the
12892 case that we are inputting from a file. There is another important case,
12893 namely when we are currently getting input from a token list. In this case
12894 |index>max_in_open|, and the conventions about the other state variables
12895 are different:
12896
12897 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
12898 the node that will be read next. If |loc=null|, the token list has been
12899 fully read.
12900
12901 \yskip\hang|start| points to the first node of the token list; this node
12902 may or may not contain a reference count, depending on the type of token
12903 list involved.
12904
12905 \yskip\hang|token_type|, which takes the place of |index| in the
12906 discussion above, is a code number that explains what kind of token list
12907 is being scanned.
12908
12909 \yskip\hang|name| points to the |eqtb| address of the control sequence
12910 being expanded, if the current token list is a macro not defined by
12911 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
12912 can be deduced by looking at their first two parameters.
12913
12914 \yskip\hang|param_start|, which takes the place of |limit|, tells where
12915 the parameters of the current macro or loop text begin in the |param_stack|.
12916
12917 \yskip\noindent The |token_type| can take several values, depending on
12918 where the current token list came from:
12919
12920 \yskip
12921 \indent|forever_text|, if the token list being scanned is the body of
12922 a \&{forever} loop;
12923
12924 \indent|loop_text|, if the token list being scanned is the body of
12925 a \&{for} or \&{forsuffixes} loop;
12926
12927 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
12928
12929 \indent|backed_up|, if the token list being scanned has been inserted as
12930 `to be read again'.
12931
12932 \indent|inserted|, if the token list being scanned has been inserted as
12933 part of error recovery;
12934
12935 \indent|macro|, if the expansion of a user-defined symbolic token is being
12936 scanned.
12937
12938 \yskip\noindent
12939 The token list begins with a reference count if and only if |token_type=
12940 macro|.
12941 @^reference counts@>
12942
12943 @d token_type index /* type of current token list */
12944 @d token_state (index>(int)mp->max_in_open) /* are we scanning a token list? */
12945 @d file_state (index<=(int)mp->max_in_open) /* are we scanning a file line? */
12946 @d param_start limit /* base of macro parameters in |param_stack| */
12947 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
12948 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
12949 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
12950 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
12951 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
12952 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
12953
12954 @ The |param_stack| is an auxiliary array used to hold pointers to the token
12955 lists for parameters at the current level and subsidiary levels of input.
12956 This stack grows at a different rate from the others.
12957
12958 @<Glob...@>=
12959 pointer *param_stack;  /* token list pointers for parameters */
12960 integer param_ptr; /* first unused entry in |param_stack| */
12961 integer max_param_stack;  /* largest value of |param_ptr| */
12962
12963 @ @<Allocate or initialize ...@>=
12964 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
12965
12966 @ @<Dealloc variables@>=
12967 xfree(mp->param_stack);
12968
12969 @ Notice that the |line| isn't valid when |token_state| is true because it
12970 depends on |index|.  If we really need to know the line number for the
12971 topmost file in the index stack we use the following function.  If a page
12972 number or other information is needed, this routine should be modified to
12973 compute it as well.
12974 @^system dependencies@>
12975
12976 @<Declare a function called |true_line|@>=
12977 integer mp_true_line (MP mp) {
12978   int k; /* an index into the input stack */
12979   if ( file_state && (name>max_spec_src) ) {
12980     return line;
12981   } else { 
12982     k=mp->input_ptr;
12983     while ((k>0) &&
12984            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
12985             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
12986       decr(k);
12987     }
12988     return (k>0 ? mp->line_stack[(k-1)] : 0 );
12989   }
12990 }
12991
12992 @ Thus, the ``current input state'' can be very complicated indeed; there
12993 can be many levels and each level can arise in a variety of ways. The
12994 |show_context| procedure, which is used by \MP's error-reporting routine to
12995 print out the current input state on all levels down to the most recent
12996 line of characters from an input file, illustrates most of these conventions.
12997 The global variable |file_ptr| contains the lowest level that was
12998 displayed by this procedure.
12999
13000 @<Glob...@>=
13001 integer file_ptr; /* shallowest level shown by |show_context| */
13002
13003 @ The status at each level is indicated by printing two lines, where the first
13004 line indicates what was read so far and the second line shows what remains
13005 to be read. The context is cropped, if necessary, so that the first line
13006 contains at most |half_error_line| characters, and the second contains
13007 at most |error_line|. Non-current input levels whose |token_type| is
13008 `|backed_up|' are shown only if they have not been fully read.
13009
13010 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13011   int old_setting; /* saved |selector| setting */
13012   @<Local variables for formatting calculations@>
13013   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13014   /* store current state */
13015   while (1) { 
13016     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13017     @<Display the current context@>;
13018     if ( file_state )
13019       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13020     decr(mp->file_ptr);
13021   }
13022   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13023 }
13024
13025 @ @<Display the current context@>=
13026 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13027    (token_type!=backed_up) || (loc!=null) ) {
13028     /* we omit backed-up token lists that have already been read */
13029   mp->tally=0; /* get ready to count characters */
13030   old_setting=mp->selector;
13031   if ( file_state ) {
13032     @<Print location of current line@>;
13033     @<Pseudoprint the line@>;
13034   } else { 
13035     @<Print type of token list@>;
13036     @<Pseudoprint the token list@>;
13037   }
13038   mp->selector=old_setting; /* stop pseudoprinting */
13039   @<Print two lines using the tricky pseudoprinted information@>;
13040 }
13041
13042 @ This routine should be changed, if necessary, to give the best possible
13043 indication of where the current line resides in the input file.
13044 For example, on some systems it is best to print both a page and line number.
13045 @^system dependencies@>
13046
13047 @<Print location of current line@>=
13048 if ( name>max_spec_src ) {
13049   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13050 } else if ( terminal_input ) {
13051   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13052   else mp_print_nl(mp, "<insert>");
13053 } else if ( name==is_scantok ) {
13054   mp_print_nl(mp, "<scantokens>");
13055 } else {
13056   mp_print_nl(mp, "<read>");
13057 }
13058 mp_print_char(mp, ' ')
13059
13060 @ Can't use case statement here because the |token_type| is not
13061 a constant expression.
13062
13063 @<Print type of token list@>=
13064 {
13065   if(token_type==forever_text) {
13066     mp_print_nl(mp, "<forever> ");
13067   } else if (token_type==loop_text) {
13068     @<Print the current loop value@>;
13069   } else if (token_type==parameter) {
13070     mp_print_nl(mp, "<argument> "); 
13071   } else if (token_type==backed_up) { 
13072     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13073     else mp_print_nl(mp, "<to be read again> ");
13074   } else if (token_type==inserted) {
13075     mp_print_nl(mp, "<inserted text> ");
13076   } else if (token_type==macro) {
13077     mp_print_ln(mp);
13078     if ( name!=null ) mp_print_text(name);
13079     else @<Print the name of a \&{vardef}'d macro@>;
13080     mp_print(mp, "->");
13081   } else {
13082     mp_print_nl(mp, "?");/* this should never happen */
13083 @.?\relax@>
13084   }
13085 }
13086
13087 @ The parameter that corresponds to a loop text is either a token list
13088 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13089 We'll discuss capsules later; for now, all we need to know is that
13090 the |link| field in a capsule parameter is |void| and that
13091 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13092
13093 @<Print the current loop value@>=
13094 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13095   if ( p!=null ) {
13096     if ( link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13097     else mp_show_token_list(mp, p,null,20,mp->tally);
13098   }
13099   mp_print(mp, ")> ");
13100 }
13101
13102 @ The first two parameters of a macro defined by \&{vardef} will be token
13103 lists representing the macro's prefix and ``at point.'' By putting these
13104 together, we get the macro's full name.
13105
13106 @<Print the name of a \&{vardef}'d macro@>=
13107 { p=mp->param_stack[param_start];
13108   if ( p==null ) {
13109     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13110   } else { 
13111     q=p;
13112     while ( link(q)!=null ) q=link(q);
13113     link(q)=mp->param_stack[param_start+1];
13114     mp_show_token_list(mp, p,null,20,mp->tally);
13115     link(q)=null;
13116   }
13117 }
13118
13119 @ Now it is necessary to explain a little trick. We don't want to store a long
13120 string that corresponds to a token list, because that string might take up
13121 lots of memory; and we are printing during a time when an error message is
13122 being given, so we dare not do anything that might overflow one of \MP's
13123 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13124 that stores characters into a buffer of length |error_line|, where character
13125 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13126 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13127 |tally:=0| and |trick_count:=1000000|; then when we reach the
13128 point where transition from line 1 to line 2 should occur, we
13129 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13130 tally+1+error_line-half_error_line)|. At the end of the
13131 pseudoprinting, the values of |first_count|, |tally|, and
13132 |trick_count| give us all the information we need to print the two lines,
13133 and all of the necessary text is in |trick_buf|.
13134
13135 Namely, let |l| be the length of the descriptive information that appears
13136 on the first line. The length of the context information gathered for that
13137 line is |k=first_count|, and the length of the context information
13138 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13139 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13140 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13141 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13142 and print `\.{...}' followed by
13143 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13144 where subscripts of |trick_buf| are circular modulo |error_line|. The
13145 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13146 unless |n+m>error_line|; in the latter case, further cropping is done.
13147 This is easier to program than to explain.
13148
13149 @<Local variables for formatting...@>=
13150 int i; /* index into |buffer| */
13151 integer l; /* length of descriptive information on line 1 */
13152 integer m; /* context information gathered for line 2 */
13153 int n; /* length of line 1 */
13154 integer p; /* starting or ending place in |trick_buf| */
13155 integer q; /* temporary index */
13156
13157 @ The following code tells the print routines to gather
13158 the desired information.
13159
13160 @d begin_pseudoprint { 
13161   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13162   mp->trick_count=1000000;
13163 }
13164 @d set_trick_count {
13165   mp->first_count=mp->tally;
13166   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13167   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13168 }
13169
13170 @ And the following code uses the information after it has been gathered.
13171
13172 @<Print two lines using the tricky pseudoprinted information@>=
13173 if ( mp->trick_count==1000000 ) set_trick_count;
13174   /* |set_trick_count| must be performed */
13175 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13176 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13177 if ( l+mp->first_count<=mp->half_error_line ) {
13178   p=0; n=l+mp->first_count;
13179 } else  { 
13180   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13181   n=mp->half_error_line;
13182 }
13183 for (q=p;q<=mp->first_count-1;q++) {
13184   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13185 }
13186 mp_print_ln(mp);
13187 for (q=1;q<=n;q++) {
13188   mp_print_char(mp, ' '); /* print |n| spaces to begin line~2 */
13189 }
13190 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13191 else p=mp->first_count+(mp->error_line-n-3);
13192 for (q=mp->first_count;q<=p-1;q++) {
13193   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13194 }
13195 if ( m+n>mp->error_line ) mp_print(mp, "...")
13196
13197 @ But the trick is distracting us from our current goal, which is to
13198 understand the input state. So let's concentrate on the data structures that
13199 are being pseudoprinted as we finish up the |show_context| procedure.
13200
13201 @<Pseudoprint the line@>=
13202 begin_pseudoprint;
13203 if ( limit>0 ) {
13204   for (i=start;i<=limit-1;i++) {
13205     if ( i==loc ) set_trick_count;
13206     mp_print_str(mp, mp->buffer[i]);
13207   }
13208 }
13209
13210 @ @<Pseudoprint the token list@>=
13211 begin_pseudoprint;
13212 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13213 else mp_show_macro(mp, start,loc,100000)
13214
13215 @ Here is the missing piece of |show_token_list| that is activated when the
13216 token beginning line~2 is about to be shown:
13217
13218 @<Do magic computation@>=set_trick_count
13219
13220 @* \[28] Maintaining the input stacks.
13221 The following subroutines change the input status in commonly needed ways.
13222
13223 First comes |push_input|, which stores the current state and creates a
13224 new level (having, initially, the same properties as the old).
13225
13226 @d push_input  { /* enter a new input level, save the old */
13227   if ( mp->input_ptr>mp->max_in_stack ) {
13228     mp->max_in_stack=mp->input_ptr;
13229     if ( mp->input_ptr==mp->stack_size ) {
13230       int l = (mp->stack_size+(mp->stack_size>>2));
13231       XREALLOC(mp->input_stack, l, in_state_record);
13232       mp->stack_size = l;
13233     }         
13234   }
13235   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13236   incr(mp->input_ptr);
13237 }
13238
13239 @ And of course what goes up must come down.
13240
13241 @d pop_input { /* leave an input level, re-enter the old */
13242     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13243   }
13244
13245 @ Here is a procedure that starts a new level of token-list input, given
13246 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13247 set |name|, reset~|loc|, and increase the macro's reference count.
13248
13249 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13250
13251 @c void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13252   push_input; start=p; token_type=t;
13253   param_start=mp->param_ptr; loc=p;
13254 }
13255
13256 @ When a token list has been fully scanned, the following computations
13257 should be done as we leave that level of input.
13258 @^inner loop@>
13259
13260 @c void mp_end_token_list (MP mp) { /* leave a token-list input level */
13261   pointer p; /* temporary register */
13262   if ( token_type>=backed_up ) { /* token list to be deleted */
13263     if ( token_type<=inserted ) { 
13264       mp_flush_token_list(mp, start); goto DONE;
13265     } else {
13266       mp_delete_mac_ref(mp, start); /* update reference count */
13267     }
13268   }
13269   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13270     decr(mp->param_ptr);
13271     p=mp->param_stack[mp->param_ptr];
13272     if ( p!=null ) {
13273       if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
13274         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13275       } else {
13276         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13277       }
13278     }
13279   }
13280 DONE: 
13281   pop_input; check_interrupt;
13282 }
13283
13284 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13285 token by the |cur_tok| routine.
13286 @^inner loop@>
13287
13288 @c @<Declare the procedure called |make_exp_copy|@>
13289 pointer mp_cur_tok (MP mp) {
13290   pointer p; /* a new token node */
13291   small_number save_type; /* |cur_type| to be restored */
13292   integer save_exp; /* |cur_exp| to be restored */
13293   if ( mp->cur_sym==0 ) {
13294     if ( mp->cur_cmd==capsule_token ) {
13295       save_type=mp->cur_type; save_exp=mp->cur_exp;
13296       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); link(p)=null;
13297       mp->cur_type=save_type; mp->cur_exp=save_exp;
13298     } else { 
13299       p=mp_get_node(mp, token_node_size);
13300       value(p)=mp->cur_mod; name_type(p)=mp_token;
13301       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13302       else type(p)=mp_string_type;
13303     }
13304   } else { 
13305     fast_get_avail(p); info(p)=mp->cur_sym;
13306   }
13307   return p;
13308 }
13309
13310 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13311 seen. The |back_input| procedure takes care of this by putting the token
13312 just scanned back into the input stream, ready to be read again.
13313 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13314
13315 @<Declarations@>= 
13316 void mp_back_input (MP mp);
13317
13318 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13319   pointer p; /* a token list of length one */
13320   p=mp_cur_tok(mp);
13321   while ( token_state &&(loc==null) ) 
13322     mp_end_token_list(mp); /* conserve stack space */
13323   back_list(p);
13324 }
13325
13326 @ The |back_error| routine is used when we want to restore or replace an
13327 offending token just before issuing an error message.  We disable interrupts
13328 during the call of |back_input| so that the help message won't be lost.
13329
13330 @<Declarations@>=
13331 void mp_error (MP mp);
13332 void mp_back_error (MP mp);
13333
13334 @ @c void mp_back_error (MP mp) { /* back up one token and call |error| */
13335   mp->OK_to_interrupt=false; 
13336   mp_back_input(mp); 
13337   mp->OK_to_interrupt=true; mp_error(mp);
13338 }
13339 void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13340   mp->OK_to_interrupt=false; 
13341   mp_back_input(mp); token_type=inserted;
13342   mp->OK_to_interrupt=true; mp_error(mp);
13343 }
13344
13345 @ The |begin_file_reading| procedure starts a new level of input for lines
13346 of characters to be read from a file, or as an insertion from the
13347 terminal. It does not take care of opening the file, nor does it set |loc|
13348 or |limit| or |line|.
13349 @^system dependencies@>
13350
13351 @c void mp_begin_file_reading (MP mp) { 
13352   if ( mp->in_open==mp->max_in_open ) 
13353     mp_overflow(mp, "text input levels",mp->max_in_open);
13354 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13355   if ( mp->first==mp->buf_size ) 
13356     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13357   incr(mp->in_open); push_input; index=mp->in_open;
13358   mp->mpx_name[index]=absent;
13359   start=mp->first;
13360   name=is_term; /* |terminal_input| is now |true| */
13361 }
13362
13363 @ Conversely, the variables must be downdated when such a level of input
13364 is finished.  Any associated \.{MPX} file must also be closed and popped
13365 off the file stack.
13366
13367 @c void mp_end_file_reading (MP mp) { 
13368   if ( mp->in_open>index ) {
13369     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13370       mp_confusion(mp, "endinput");
13371 @:this can't happen endinput}{\quad endinput@>
13372     } else { 
13373       (mp->close_file)(mp,mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13374       delete_str_ref(mp->mpx_name[mp->in_open]);
13375       decr(mp->in_open);
13376     }
13377   }
13378   mp->first=start;
13379   if ( index!=mp->in_open ) mp_confusion(mp, "endinput");
13380   if ( name>max_spec_src ) {
13381     (mp->close_file)(mp,cur_file);
13382     delete_str_ref(name);
13383     xfree(in_name); 
13384     xfree(in_area);
13385   }
13386   pop_input; decr(mp->in_open);
13387 }
13388
13389 @ Here is a function that tries to resume input from an \.{MPX} file already
13390 associated with the current input file.  It returns |false| if this doesn't
13391 work.
13392
13393 @c boolean mp_begin_mpx_reading (MP mp) { 
13394   if ( mp->in_open!=index+1 ) {
13395      return false;
13396   } else { 
13397     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13398 @:this can't happen mpx}{\quad mpx@>
13399     if ( mp->first==mp->buf_size ) 
13400       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
13401     push_input; index=mp->in_open;
13402     start=mp->first;
13403     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13404     @<Put an empty line in the input buffer@>;
13405     return true;
13406   }
13407 }
13408
13409 @ This procedure temporarily stops reading an \.{MPX} file.
13410
13411 @c void mp_end_mpx_reading (MP mp) { 
13412   if ( mp->in_open!=index ) mp_confusion(mp, "mpx");
13413 @:this can't happen mpx}{\quad mpx@>
13414   if ( loc<limit ) {
13415     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13416   }
13417   mp->first=start;
13418   pop_input;
13419 }
13420
13421 @ Here we enforce a restriction that simplifies the input stacks considerably.
13422 This should not inconvenience the user because \.{MPX} files are generated
13423 by an auxiliary program called \.{DVItoMP}.
13424
13425 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13426
13427 print_err("`mpxbreak' must be at the end of a line");
13428 help4("This file contains picture expressions for btex...etex")
13429   ("blocks.  Such files are normally generated automatically")
13430   ("but this one seems to be messed up.  I'm going to ignore")
13431   ("the rest of this line.");
13432 mp_error(mp);
13433 }
13434
13435 @ In order to keep the stack from overflowing during a long sequence of
13436 inserted `\.{show}' commands, the following routine removes completed
13437 error-inserted lines from memory.
13438
13439 @c void mp_clear_for_error_prompt (MP mp) { 
13440   while ( file_state && terminal_input &&
13441     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13442   mp_print_ln(mp); clear_terminal;
13443 }
13444
13445 @ To get \MP's whole input mechanism going, we perform the following
13446 actions.
13447
13448 @<Initialize the input routines@>=
13449 { mp->input_ptr=0; mp->max_in_stack=0;
13450   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13451   mp->param_ptr=0; mp->max_param_stack=0;
13452   mp->first=1;
13453   start=1; index=0; line=0; name=is_term;
13454   mp->mpx_name[0]=absent;
13455   mp->force_eof=false;
13456   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13457   limit=mp->last; mp->first=mp->last+1; 
13458   /* |init_terminal| has set |loc| and |last| */
13459 }
13460
13461 @* \[29] Getting the next token.
13462 The heart of \MP's input mechanism is the |get_next| procedure, which
13463 we shall develop in the next few sections of the program. Perhaps we
13464 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13465 eyes and mouth, reading the source files and gobbling them up. And it also
13466 helps \MP\ to regurgitate stored token lists that are to be processed again.
13467
13468 The main duty of |get_next| is to input one token and to set |cur_cmd|
13469 and |cur_mod| to that token's command code and modifier. Furthermore, if
13470 the input token is a symbolic token, that token's |hash| address
13471 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13472
13473 Underlying this simple description is a certain amount of complexity
13474 because of all the cases that need to be handled.
13475 However, the inner loop of |get_next| is reasonably short and fast.
13476
13477 @ Before getting into |get_next|, we need to consider a mechanism by which
13478 \MP\ helps keep errors from propagating too far. Whenever the program goes
13479 into a mode where it keeps calling |get_next| repeatedly until a certain
13480 condition is met, it sets |scanner_status| to some value other than |normal|.
13481 Then if an input file ends, or if an `\&{outer}' symbol appears,
13482 an appropriate error recovery will be possible.
13483
13484 The global variable |warning_info| helps in this error recovery by providing
13485 additional information. For example, |warning_info| might indicate the
13486 name of a macro whose replacement text is being scanned.
13487
13488 @d normal 0 /* |scanner_status| at ``quiet times'' */
13489 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13490 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13491 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13492 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13493 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13494 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13495 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13496
13497 @<Glob...@>=
13498 integer scanner_status; /* are we scanning at high speed? */
13499 integer warning_info; /* if so, what else do we need to know,
13500     in case an error occurs? */
13501
13502 @ @<Initialize the input routines@>=
13503 mp->scanner_status=normal;
13504
13505 @ The following subroutine
13506 is called when an `\&{outer}' symbolic token has been scanned or
13507 when the end of a file has been reached. These two cases are distinguished
13508 by |cur_sym|, which is zero at the end of a file.
13509
13510 @c boolean mp_check_outer_validity (MP mp) {
13511   pointer p; /* points to inserted token list */
13512   if ( mp->scanner_status==normal ) {
13513     return true;
13514   } else if ( mp->scanner_status==tex_flushing ) {
13515     @<Check if the file has ended while flushing \TeX\ material and set the
13516       result value for |check_outer_validity|@>;
13517   } else { 
13518     mp->deletions_allowed=false;
13519     @<Back up an outer symbolic token so that it can be reread@>;
13520     if ( mp->scanner_status>skipping ) {
13521       @<Tell the user what has run away and try to recover@>;
13522     } else { 
13523       print_err("Incomplete if; all text was ignored after line ");
13524 @.Incomplete if...@>
13525       mp_print_int(mp, mp->warning_info);
13526       help3("A forbidden `outer' token occurred in skipped text.")
13527         ("This kind of error happens when you say `if...' and forget")
13528         ("the matching `fi'. I've inserted a `fi'; this might work.");
13529       if ( mp->cur_sym==0 ) 
13530         mp->help_line[2]="The file ended while I was skipping conditional text.";
13531       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13532     }
13533     mp->deletions_allowed=true; 
13534         return false;
13535   }
13536 }
13537
13538 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13539 if ( mp->cur_sym!=0 ) { 
13540    return true;
13541 } else { 
13542   mp->deletions_allowed=false;
13543   print_err("TeX mode didn't end; all text was ignored after line ");
13544   mp_print_int(mp, mp->warning_info);
13545   help2("The file ended while I was looking for the `etex' to")
13546     ("finish this TeX material.  I've inserted `etex' now.");
13547   mp->cur_sym = frozen_etex;
13548   mp_ins_error(mp);
13549   mp->deletions_allowed=true;
13550   return false;
13551 }
13552
13553 @ @<Back up an outer symbolic token so that it can be reread@>=
13554 if ( mp->cur_sym!=0 ) {
13555   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13556   back_list(p); /* prepare to read the symbolic token again */
13557 }
13558
13559 @ @<Tell the user what has run away...@>=
13560
13561   mp_runaway(mp); /* print the definition-so-far */
13562   if ( mp->cur_sym==0 ) {
13563     print_err("File ended");
13564 @.File ended while scanning...@>
13565   } else { 
13566     print_err("Forbidden token found");
13567 @.Forbidden token found...@>
13568   }
13569   mp_print(mp, " while scanning ");
13570   help4("I suspect you have forgotten an `enddef',")
13571     ("causing me to read past where you wanted me to stop.")
13572     ("I'll try to recover; but if the error is serious,")
13573     ("you'd better type `E' or `X' now and fix your file.");
13574   switch (mp->scanner_status) {
13575     @<Complete the error message,
13576       and set |cur_sym| to a token that might help recover from the error@>
13577   } /* there are no other cases */
13578   mp_ins_error(mp);
13579 }
13580
13581 @ As we consider various kinds of errors, it is also appropriate to
13582 change the first line of the help message just given; |help_line[3]|
13583 points to the string that might be changed.
13584
13585 @<Complete the error message,...@>=
13586 case flushing: 
13587   mp_print(mp, "to the end of the statement");
13588   mp->help_line[3]="A previous error seems to have propagated,";
13589   mp->cur_sym=frozen_semicolon;
13590   break;
13591 case absorbing: 
13592   mp_print(mp, "a text argument");
13593   mp->help_line[3]="It seems that a right delimiter was left out,";
13594   if ( mp->warning_info==0 ) {
13595     mp->cur_sym=frozen_end_group;
13596   } else { 
13597     mp->cur_sym=frozen_right_delimiter;
13598     equiv(frozen_right_delimiter)=mp->warning_info;
13599   }
13600   break;
13601 case var_defining:
13602 case op_defining: 
13603   mp_print(mp, "the definition of ");
13604   if ( mp->scanner_status==op_defining ) 
13605      mp_print_text(mp->warning_info);
13606   else 
13607      mp_print_variable_name(mp, mp->warning_info);
13608   mp->cur_sym=frozen_end_def;
13609   break;
13610 case loop_defining: 
13611   mp_print(mp, "the text of a "); 
13612   mp_print_text(mp->warning_info);
13613   mp_print(mp, " loop");
13614   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13615   mp->cur_sym=frozen_end_for;
13616   break;
13617
13618 @ The |runaway| procedure displays the first part of the text that occurred
13619 when \MP\ began its special |scanner_status|, if that text has been saved.
13620
13621 @<Declare the procedure called |runaway|@>=
13622 void mp_runaway (MP mp) { 
13623   if ( mp->scanner_status>flushing ) { 
13624      mp_print_nl(mp, "Runaway ");
13625          switch (mp->scanner_status) { 
13626          case absorbing: mp_print(mp, "text?"); break;
13627          case var_defining: 
13628      case op_defining: mp_print(mp,"definition?"); break;
13629      case loop_defining: mp_print(mp, "loop?"); break;
13630      } /* there are no other cases */
13631      mp_print_ln(mp); 
13632      mp_show_token_list(mp, link(hold_head),null,mp->error_line-10,0);
13633   }
13634 }
13635
13636 @ We need to mention a procedure that may be called by |get_next|.
13637
13638 @<Declarations@>= 
13639 void mp_firm_up_the_line (MP mp);
13640
13641 @ And now we're ready to take the plunge into |get_next| itself.
13642 Note that the behavior depends on the |scanner_status| because percent signs
13643 and double quotes need to be passed over when skipping TeX material.
13644
13645 @c 
13646 void mp_get_next (MP mp) {
13647   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13648 @^inner loop@>
13649   /*restart*/ /* go here to get the next input token */
13650   /*exit*/ /* go here when the next input token has been got */
13651   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13652   /*found*/ /* go here when the end of a symbolic token has been found */
13653   /*switch*/ /* go here to branch on the class of an input character */
13654   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13655     /* go here at crucial stages when scanning a number */
13656   int k; /* an index into |buffer| */
13657   ASCII_code c; /* the current character in the buffer */
13658   ASCII_code class; /* its class number */
13659   integer n,f; /* registers for decimal-to-binary conversion */
13660 RESTART: 
13661   mp->cur_sym=0;
13662   if ( file_state ) {
13663     @<Input from external file; |goto restart| if no input found,
13664     or |return| if a non-symbolic token is found@>;
13665   } else {
13666     @<Input from token list; |goto restart| if end of list or
13667       if a parameter needs to be expanded,
13668       or |return| if a non-symbolic token is found@>;
13669   }
13670 COMMON_ENDING: 
13671   @<Finish getting the symbolic token in |cur_sym|;
13672    |goto restart| if it is illegal@>;
13673 }
13674
13675 @ When a symbolic token is declared to be `\&{outer}', its command code
13676 is increased by |outer_tag|.
13677 @^inner loop@>
13678
13679 @<Finish getting the symbolic token in |cur_sym|...@>=
13680 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13681 if ( mp->cur_cmd>=outer_tag ) {
13682   if ( mp_check_outer_validity(mp) ) 
13683     mp->cur_cmd=mp->cur_cmd-outer_tag;
13684   else 
13685     goto RESTART;
13686 }
13687
13688 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13689 to have a special test for end-of-line.
13690 @^inner loop@>
13691
13692 @<Input from external file;...@>=
13693
13694 SWITCH: 
13695   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13696   switch (class) {
13697   case digit_class: goto START_NUMERIC_TOKEN; break;
13698   case period_class: 
13699     class=mp->char_class[mp->buffer[loc]];
13700     if ( class>period_class ) {
13701       goto SWITCH;
13702     } else if ( class<period_class ) { /* |class=digit_class| */
13703       n=0; goto START_DECIMAL_TOKEN;
13704     }
13705 @:. }{\..\ token@>
13706     break;
13707   case space_class: goto SWITCH; break;
13708   case percent_class: 
13709     if ( mp->scanner_status==tex_flushing ) {
13710       if ( loc<limit ) goto SWITCH;
13711     }
13712     @<Move to next line of file, or |goto restart| if there is no next line@>;
13713     check_interrupt;
13714     goto SWITCH;
13715     break;
13716   case string_class: 
13717     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13718     else @<Get a string token and |return|@>;
13719     break;
13720   case isolated_classes: 
13721     k=loc-1; goto FOUND; break;
13722   case invalid_class: 
13723     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13724     else @<Decry the invalid character and |goto restart|@>;
13725     break;
13726   default: break; /* letters, etc. */
13727   }
13728   k=loc-1;
13729   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13730   goto FOUND;
13731 START_NUMERIC_TOKEN:
13732   @<Get the integer part |n| of a numeric token;
13733     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13734 START_DECIMAL_TOKEN:
13735   @<Get the fraction part |f| of a numeric token@>;
13736 FIN_NUMERIC_TOKEN:
13737   @<Pack the numeric and fraction parts of a numeric token
13738     and |return|@>;
13739 FOUND: 
13740   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13741 }
13742
13743 @ We go to |restart| instead of to |SWITCH|, because we might enter
13744 |token_state| after the error has been dealt with
13745 (cf.\ |clear_for_error_prompt|).
13746
13747 @<Decry the invalid...@>=
13748
13749   print_err("Text line contains an invalid character");
13750 @.Text line contains...@>
13751   help2("A funny symbol that I can\'t read has just been input.")
13752     ("Continue, and I'll forget that it ever happened.");
13753   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13754   goto RESTART;
13755 }
13756
13757 @ @<Get a string token and |return|@>=
13758
13759   if ( mp->buffer[loc]=='"' ) {
13760     mp->cur_mod=rts("");
13761   } else { 
13762     k=loc; mp->buffer[limit+1]='"';
13763     do {  
13764      incr(loc);
13765     } while (mp->buffer[loc]!='"');
13766     if ( loc>limit ) {
13767       @<Decry the missing string delimiter and |goto restart|@>;
13768     }
13769     if ( loc==k+1 ) {
13770       mp->cur_mod=mp->buffer[k];
13771     } else { 
13772       str_room(loc-k);
13773       do {  
13774         append_char(mp->buffer[k]); incr(k);
13775       } while (k!=loc);
13776       mp->cur_mod=mp_make_string(mp);
13777     }
13778   }
13779   incr(loc); mp->cur_cmd=string_token; 
13780   return;
13781 }
13782
13783 @ We go to |restart| after this error message, not to |SWITCH|,
13784 because the |clear_for_error_prompt| routine might have reinstated
13785 |token_state| after |error| has finished.
13786
13787 @<Decry the missing string delimiter and |goto restart|@>=
13788
13789   loc=limit; /* the next character to be read on this line will be |"%"| */
13790   print_err("Incomplete string token has been flushed");
13791 @.Incomplete string token...@>
13792   help3("Strings should finish on the same line as they began.")
13793     ("I've deleted the partial string; you might want to")
13794     ("insert another by typing, e.g., `I\"new string\"'.");
13795   mp->deletions_allowed=false; mp_error(mp);
13796   mp->deletions_allowed=true; 
13797   goto RESTART;
13798 }
13799
13800 @ @<Get the integer part |n| of a numeric token...@>=
13801 n=c-'0';
13802 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13803   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13804   incr(loc);
13805 }
13806 if ( mp->buffer[loc]=='.' ) 
13807   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13808     goto DONE;
13809 f=0; 
13810 goto FIN_NUMERIC_TOKEN;
13811 DONE: incr(loc)
13812
13813 @ @<Get the fraction part |f| of a numeric token@>=
13814 k=0;
13815 do { 
13816   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13817     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13818   }
13819   incr(loc);
13820 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13821 f=mp_round_decimals(mp, k);
13822 if ( f==unity ) {
13823   incr(n); f=0;
13824 }
13825
13826 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13827 if ( n<32768 ) {
13828   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13829 } else if ( mp->scanner_status!=tex_flushing ) {
13830   print_err("Enormous number has been reduced");
13831 @.Enormous number...@>
13832   help2("I can\'t handle numbers bigger than 32767.99998;")
13833     ("so I've changed your constant to that maximum amount.");
13834   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13835   mp->cur_mod=el_gordo;
13836 }
13837 mp->cur_cmd=numeric_token; return
13838
13839 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13840
13841   mp->cur_mod=n*unity+f;
13842   if ( mp->cur_mod>=fraction_one ) {
13843     if ( (mp->internal[mp_warning_check]>0) &&
13844          (mp->scanner_status!=tex_flushing) ) {
13845       print_err("Number is too large (");
13846       mp_print_scaled(mp, mp->cur_mod);
13847       mp_print_char(mp, ')');
13848       help3("It is at least 4096. Continue and I'll try to cope")
13849       ("with that big value; but it might be dangerous.")
13850       ("(Set warningcheck:=0 to suppress this message.)");
13851       mp_error(mp);
13852     }
13853   }
13854 }
13855
13856 @ Let's consider now what happens when |get_next| is looking at a token list.
13857 @^inner loop@>
13858
13859 @<Input from token list;...@>=
13860 if ( loc>=mp->hi_mem_min ) { /* one-word token */
13861   mp->cur_sym=info(loc); loc=link(loc); /* move to next */
13862   if ( mp->cur_sym>=expr_base ) {
13863     if ( mp->cur_sym>=suffix_base ) {
13864       @<Insert a suffix or text parameter and |goto restart|@>;
13865     } else { 
13866       mp->cur_cmd=capsule_token;
13867       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
13868       mp->cur_sym=0; return;
13869     }
13870   }
13871 } else if ( loc>null ) {
13872   @<Get a stored numeric or string or capsule token and |return|@>
13873 } else { /* we are done with this token list */
13874   mp_end_token_list(mp); goto RESTART; /* resume previous level */
13875 }
13876
13877 @ @<Insert a suffix or text parameter...@>=
13878
13879   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
13880   /* |param_size=text_base-suffix_base| */
13881   mp_begin_token_list(mp,
13882                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
13883                       parameter);
13884   goto RESTART;
13885 }
13886
13887 @ @<Get a stored numeric or string or capsule token...@>=
13888
13889   if ( name_type(loc)==mp_token ) {
13890     mp->cur_mod=value(loc);
13891     if ( type(loc)==mp_known ) {
13892       mp->cur_cmd=numeric_token;
13893     } else { 
13894       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
13895     }
13896   } else { 
13897     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
13898   };
13899   loc=link(loc); return;
13900 }
13901
13902 @ All of the easy branches of |get_next| have now been taken care of.
13903 There is one more branch.
13904
13905 @<Move to next line of file, or |goto restart|...@>=
13906 if ( name>max_spec_src ) {
13907   @<Read next line of file into |buffer|, or
13908     |goto restart| if the file has ended@>;
13909 } else { 
13910   if ( mp->input_ptr>0 ) {
13911      /* text was inserted during error recovery or by \&{scantokens} */
13912     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
13913   }
13914   if ( mp->selector<log_only || mp->selector>=write_file) mp_open_log_file(mp);
13915   if ( mp->interaction>mp_nonstop_mode ) {
13916     if ( limit==start ) /* previous line was empty */
13917       mp_print_nl(mp, "(Please type a command or say `end')");
13918 @.Please type...@>
13919     mp_print_ln(mp); mp->first=start;
13920     prompt_input("*"); /* input on-line into |buffer| */
13921 @.*\relax@>
13922     limit=mp->last; mp->buffer[limit]='%';
13923     mp->first=limit+1; loc=start;
13924   } else {
13925     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
13926 @.job aborted@>
13927     /* nonstop mode, which is intended for overnight batch processing,
13928     never waits for on-line input */
13929   }
13930 }
13931
13932 @ The global variable |force_eof| is normally |false|; it is set |true|
13933 by an \&{endinput} command.
13934
13935 @<Glob...@>=
13936 boolean force_eof; /* should the next \&{input} be aborted early? */
13937
13938 @ We must decrement |loc| in order to leave the buffer in a valid state
13939 when an error condition causes us to |goto restart| without calling
13940 |end_file_reading|.
13941
13942 @<Read next line of file into |buffer|, or
13943   |goto restart| if the file has ended@>=
13944
13945   incr(line); mp->first=start;
13946   if ( ! mp->force_eof ) {
13947     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
13948       mp_firm_up_the_line(mp); /* this sets |limit| */
13949     else 
13950       mp->force_eof=true;
13951   };
13952   if ( mp->force_eof ) {
13953     mp->force_eof=false;
13954     decr(loc);
13955     if ( mpx_reading ) {
13956       @<Complain that the \.{MPX} file ended unexpectly; then set
13957         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
13958     } else { 
13959       mp_print_char(mp, ')'); decr(mp->open_parens);
13960       update_terminal; /* show user that file has been read */
13961       mp_end_file_reading(mp); /* resume previous level */
13962       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
13963       else goto RESTART;
13964     }
13965   }
13966   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; /* ready to read */
13967 }
13968
13969 @ We should never actually come to the end of an \.{MPX} file because such
13970 files should have an \&{mpxbreak} after the translation of the last
13971 \&{btex}$\,\ldots\,$\&{etex} block.
13972
13973 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
13974
13975   mp->mpx_name[index]=finished;
13976   print_err("mpx file ended unexpectedly");
13977   help4("The file had too few picture expressions for btex...etex")
13978     ("blocks.  Such files are normally generated automatically")
13979     ("but this one got messed up.  You might want to insert a")
13980     ("picture expression now.");
13981   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13982   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
13983 }
13984
13985 @ Sometimes we want to make it look as though we have just read a blank line
13986 without really doing so.
13987
13988 @<Put an empty line in the input buffer@>=
13989 mp->last=mp->first; limit=mp->last; /* simulate |input_ln| and |firm_up_the_line| */
13990 mp->buffer[limit]='%'; mp->first=limit+1; loc=start
13991
13992 @ If the user has set the |mp_pausing| parameter to some positive value,
13993 and if nonstop mode has not been selected, each line of input is displayed
13994 on the terminal and the transcript file, followed by `\.{=>}'.
13995 \MP\ waits for a response. If the response is null (i.e., if nothing is
13996 typed except perhaps a few blank spaces), the original
13997 line is accepted as it stands; otherwise the line typed is
13998 used instead of the line in the file.
13999
14000 @c void mp_firm_up_the_line (MP mp) {
14001   size_t k; /* an index into |buffer| */
14002   limit=mp->last;
14003   if ( mp->internal[mp_pausing]>0) if ( mp->interaction>mp_nonstop_mode ) {
14004     wake_up_terminal; mp_print_ln(mp);
14005     if ( start<limit ) {
14006       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14007         mp_print_str(mp, mp->buffer[k]);
14008       } 
14009     }
14010     mp->first=limit; prompt_input("=>"); /* wait for user response */
14011 @.=>@>
14012     if ( mp->last>mp->first ) {
14013       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14014         mp->buffer[k+start-mp->first]=mp->buffer[k];
14015       }
14016       limit=start+mp->last-mp->first;
14017     }
14018   }
14019 }
14020
14021 @* \[30] Dealing with \TeX\ material.
14022 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14023 features need to be implemented at a low level in the scanning process
14024 so that \MP\ can stay in synch with the a preprocessor that treats
14025 blocks of \TeX\ material as they occur in the input file without trying
14026 to expand \MP\ macros.  Thus we need a special version of |get_next|
14027 that does not expand macros and such but does handle \&{btex},
14028 \&{verbatimtex}, etc.
14029
14030 The special version of |get_next| is called |get_t_next|.  It works by flushing
14031 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14032 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14033 \&{btex}, and switching back when it sees \&{mpxbreak}.
14034
14035 @d btex_code 0
14036 @d verbatim_code 1
14037
14038 @ @<Put each...@>=
14039 mp_primitive(mp, "btex",start_tex,btex_code);
14040 @:btex_}{\&{btex} primitive@>
14041 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14042 @:verbatimtex_}{\&{verbatimtex} primitive@>
14043 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14044 @:etex_}{\&{etex} primitive@>
14045 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14046 @:mpx_break_}{\&{mpxbreak} primitive@>
14047
14048 @ @<Cases of |print_cmd...@>=
14049 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14050   else mp_print(mp, "verbatimtex"); break;
14051 case etex_marker: mp_print(mp, "etex"); break;
14052 case mpx_break: mp_print(mp, "mpxbreak"); break;
14053
14054 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14055 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14056 is encountered.
14057
14058 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14059
14060 @<Declarations@>=
14061 void mp_start_mpx_input (MP mp);
14062
14063 @ @c 
14064 void mp_t_next (MP mp) {
14065   int old_status; /* saves the |scanner_status| */
14066   integer old_info; /* saves the |warning_info| */
14067   while ( mp->cur_cmd<=max_pre_command ) {
14068     if ( mp->cur_cmd==mpx_break ) {
14069       if ( ! file_state || (mp->mpx_name[index]==absent) ) {
14070         @<Complain about a misplaced \&{mpxbreak}@>;
14071       } else { 
14072         mp_end_mpx_reading(mp); 
14073         goto TEX_FLUSH;
14074       }
14075     } else if ( mp->cur_cmd==start_tex ) {
14076       if ( token_state || (name<=max_spec_src) ) {
14077         @<Complain that we are not reading a file@>;
14078       } else if ( mpx_reading ) {
14079         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14080       } else if ( (mp->cur_mod!=verbatim_code)&&
14081                   (mp->mpx_name[index]!=finished) ) {
14082         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14083       } else {
14084         goto TEX_FLUSH;
14085       }
14086     } else {
14087        @<Complain about a misplaced \&{etex}@>;
14088     }
14089     goto COMMON_ENDING;
14090   TEX_FLUSH: 
14091     @<Flush the \TeX\ material@>;
14092   COMMON_ENDING: 
14093     mp_get_next(mp);
14094   }
14095 }
14096
14097 @ We could be in the middle of an operation such as skipping false conditional
14098 text when \TeX\ material is encountered, so we must be careful to save the
14099 |scanner_status|.
14100
14101 @<Flush the \TeX\ material@>=
14102 old_status=mp->scanner_status;
14103 old_info=mp->warning_info;
14104 mp->scanner_status=tex_flushing;
14105 mp->warning_info=line;
14106 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14107 mp->scanner_status=old_status;
14108 mp->warning_info=old_info
14109
14110 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14111 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14112 help4("This file contains picture expressions for btex...etex")
14113   ("blocks.  Such files are normally generated automatically")
14114   ("but this one seems to be messed up.  I'll just keep going")
14115   ("and hope for the best.");
14116 mp_error(mp);
14117 }
14118
14119 @ @<Complain that we are not reading a file@>=
14120 { print_err("You can only use `btex' or `verbatimtex' in a file");
14121 help3("I'll have to ignore this preprocessor command because it")
14122   ("only works when there is a file to preprocess.  You might")
14123   ("want to delete everything up to the next `etex`.");
14124 mp_error(mp);
14125 }
14126
14127 @ @<Complain about a misplaced \&{mpxbreak}@>=
14128 { print_err("Misplaced mpxbreak");
14129 help2("I'll ignore this preprocessor command because it")
14130   ("doesn't belong here");
14131 mp_error(mp);
14132 }
14133
14134 @ @<Complain about a misplaced \&{etex}@>=
14135 { print_err("Extra etex will be ignored");
14136 help1("There is no btex or verbatimtex for this to match");
14137 mp_error(mp);
14138 }
14139
14140 @* \[31] Scanning macro definitions.
14141 \MP\ has a variety of ways to tuck tokens away into token lists for later
14142 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14143 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14144 All such operations are handled by the routines in this part of the program.
14145
14146 The modifier part of each command code is zero for the ``ending delimiters''
14147 like \&{enddef} and \&{endfor}.
14148
14149 @d start_def 1 /* command modifier for \&{def} */
14150 @d var_def 2 /* command modifier for \&{vardef} */
14151 @d end_def 0 /* command modifier for \&{enddef} */
14152 @d start_forever 1 /* command modifier for \&{forever} */
14153 @d end_for 0 /* command modifier for \&{endfor} */
14154
14155 @<Put each...@>=
14156 mp_primitive(mp, "def",macro_def,start_def);
14157 @:def_}{\&{def} primitive@>
14158 mp_primitive(mp, "vardef",macro_def,var_def);
14159 @:var_def_}{\&{vardef} primitive@>
14160 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14161 @:primary_def_}{\&{primarydef} primitive@>
14162 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14163 @:secondary_def_}{\&{secondarydef} primitive@>
14164 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14165 @:tertiary_def_}{\&{tertiarydef} primitive@>
14166 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14167 @:end_def_}{\&{enddef} primitive@>
14168 @#
14169 mp_primitive(mp, "for",iteration,expr_base);
14170 @:for_}{\&{for} primitive@>
14171 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14172 @:for_suffixes_}{\&{forsuffixes} primitive@>
14173 mp_primitive(mp, "forever",iteration,start_forever);
14174 @:forever_}{\&{forever} primitive@>
14175 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14176 @:end_for_}{\&{endfor} primitive@>
14177
14178 @ @<Cases of |print_cmd...@>=
14179 case macro_def:
14180   if ( m<=var_def ) {
14181     if ( m==start_def ) mp_print(mp, "def");
14182     else if ( m<start_def ) mp_print(mp, "enddef");
14183     else mp_print(mp, "vardef");
14184   } else if ( m==secondary_primary_macro ) { 
14185     mp_print(mp, "primarydef");
14186   } else if ( m==tertiary_secondary_macro ) { 
14187     mp_print(mp, "secondarydef");
14188   } else { 
14189     mp_print(mp, "tertiarydef");
14190   }
14191   break;
14192 case iteration: 
14193   if ( m<=start_forever ) {
14194     if ( m==start_forever ) mp_print(mp, "forever"); 
14195     else mp_print(mp, "endfor");
14196   } else if ( m==expr_base ) {
14197     mp_print(mp, "for"); 
14198   } else { 
14199     mp_print(mp, "forsuffixes");
14200   }
14201   break;
14202
14203 @ Different macro-absorbing operations have different syntaxes, but they
14204 also have a lot in common. There is a list of special symbols that are to
14205 be replaced by parameter tokens; there is a special command code that
14206 ends the definition; the quotation conventions are identical.  Therefore
14207 it makes sense to have most of the work done by a single subroutine. That
14208 subroutine is called |scan_toks|.
14209
14210 The first parameter to |scan_toks| is the command code that will
14211 terminate scanning (either |macro_def| or |iteration|).
14212
14213 The second parameter, |subst_list|, points to a (possibly empty) list
14214 of two-word nodes whose |info| and |value| fields specify symbol tokens
14215 before and after replacement. The list will be returned to free storage
14216 by |scan_toks|.
14217
14218 The third parameter is simply appended to the token list that is built.
14219 And the final parameter tells how many of the special operations
14220 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14221 When such parameters are present, they are called \.{(SUFFIX0)},
14222 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14223
14224 @c pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14225   subst_list, pointer tail_end, small_number suffix_count) {
14226   pointer p; /* tail of the token list being built */
14227   pointer q; /* temporary for link management */
14228   integer balance; /* left delimiters minus right delimiters */
14229   p=hold_head; balance=1; link(hold_head)=null;
14230   while (1) { 
14231     get_t_next;
14232     if ( mp->cur_sym>0 ) {
14233       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14234       if ( mp->cur_cmd==terminator ) {
14235         @<Adjust the balance; |break| if it's zero@>;
14236       } else if ( mp->cur_cmd==macro_special ) {
14237         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14238       }
14239     }
14240     link(p)=mp_cur_tok(mp); p=link(p);
14241   }
14242   link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14243   return link(hold_head);
14244 }
14245
14246 @ @<Substitute for |cur_sym|...@>=
14247
14248   q=subst_list;
14249   while ( q!=null ) {
14250     if ( info(q)==mp->cur_sym ) {
14251       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14252     }
14253     q=link(q);
14254   }
14255 }
14256
14257 @ @<Adjust the balance; |break| if it's zero@>=
14258 if ( mp->cur_mod>0 ) {
14259   incr(balance);
14260 } else { 
14261   decr(balance);
14262   if ( balance==0 )
14263     break;
14264 }
14265
14266 @ Four commands are intended to be used only within macro texts: \&{quote},
14267 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14268 code called |macro_special|.
14269
14270 @d quote 0 /* |macro_special| modifier for \&{quote} */
14271 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14272 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14273 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14274
14275 @<Put each...@>=
14276 mp_primitive(mp, "quote",macro_special,quote);
14277 @:quote_}{\&{quote} primitive@>
14278 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14279 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14280 mp_primitive(mp, "@@",macro_special,macro_at);
14281 @:]]]\AT!_}{\.{\AT!} primitive@>
14282 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14283 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14284
14285 @ @<Cases of |print_cmd...@>=
14286 case macro_special: 
14287   switch (m) {
14288   case macro_prefix: mp_print(mp, "#@@"); break;
14289   case macro_at: mp_print_char(mp, '@@'); break;
14290   case macro_suffix: mp_print(mp, "@@#"); break;
14291   default: mp_print(mp, "quote"); break;
14292   }
14293   break;
14294
14295 @ @<Handle quoted...@>=
14296
14297   if ( mp->cur_mod==quote ) { get_t_next; } 
14298   else if ( mp->cur_mod<=suffix_count ) 
14299     mp->cur_sym=suffix_base-1+mp->cur_mod;
14300 }
14301
14302 @ Here is a routine that's used whenever a token will be redefined. If
14303 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14304 substituted; the latter is redefinable but essentially impossible to use,
14305 hence \MP's tables won't get fouled up.
14306
14307 @c void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14308 RESTART: 
14309   get_t_next;
14310   if ( (mp->cur_sym==0)||(mp->cur_sym>frozen_inaccessible) ) {
14311     print_err("Missing symbolic token inserted");
14312 @.Missing symbolic token...@>
14313     help3("Sorry: You can\'t redefine a number, string, or expr.")
14314       ("I've inserted an inaccessible symbol so that your")
14315       ("definition will be completed without mixing me up too badly.");
14316     if ( mp->cur_sym>0 )
14317       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14318     else if ( mp->cur_cmd==string_token ) 
14319       delete_str_ref(mp->cur_mod);
14320     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14321   }
14322 }
14323
14324 @ Before we actually redefine a symbolic token, we need to clear away its
14325 former value, if it was a variable. The following stronger version of
14326 |get_symbol| does that.
14327
14328 @c void mp_get_clear_symbol (MP mp) { 
14329   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14330 }
14331
14332 @ Here's another little subroutine; it checks that an equals sign
14333 or assignment sign comes along at the proper place in a macro definition.
14334
14335 @c void mp_check_equals (MP mp) { 
14336   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14337      mp_missing_err(mp, "=");
14338 @.Missing `='@>
14339     help5("The next thing in this `def' should have been `=',")
14340       ("because I've already looked at the definition heading.")
14341       ("But don't worry; I'll pretend that an equals sign")
14342       ("was present. Everything from here to `enddef'")
14343       ("will be the replacement text of this macro.");
14344     mp_back_error(mp);
14345   }
14346 }
14347
14348 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14349 handled now that we have |scan_toks|.  In this case there are
14350 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14351 |expr_base| and |expr_base+1|).
14352
14353 @c void mp_make_op_def (MP mp) {
14354   command_code m; /* the type of definition */
14355   pointer p,q,r; /* for list manipulation */
14356   m=mp->cur_mod;
14357   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14358   info(q)=mp->cur_sym; value(q)=expr_base;
14359   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14360   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14361   info(p)=mp->cur_sym; value(p)=expr_base+1; link(p)=q;
14362   get_t_next; mp_check_equals(mp);
14363   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14364   r=mp_get_avail(mp); link(q)=r; info(r)=general_macro;
14365   link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14366   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14367   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14368 }
14369
14370 @ Parameters to macros are introduced by the keywords \&{expr},
14371 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14372
14373 @<Put each...@>=
14374 mp_primitive(mp, "expr",param_type,expr_base);
14375 @:expr_}{\&{expr} primitive@>
14376 mp_primitive(mp, "suffix",param_type,suffix_base);
14377 @:suffix_}{\&{suffix} primitive@>
14378 mp_primitive(mp, "text",param_type,text_base);
14379 @:text_}{\&{text} primitive@>
14380 mp_primitive(mp, "primary",param_type,primary_macro);
14381 @:primary_}{\&{primary} primitive@>
14382 mp_primitive(mp, "secondary",param_type,secondary_macro);
14383 @:secondary_}{\&{secondary} primitive@>
14384 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14385 @:tertiary_}{\&{tertiary} primitive@>
14386
14387 @ @<Cases of |print_cmd...@>=
14388 case param_type:
14389   if ( m>=expr_base ) {
14390     if ( m==expr_base ) mp_print(mp, "expr");
14391     else if ( m==suffix_base ) mp_print(mp, "suffix");
14392     else mp_print(mp, "text");
14393   } else if ( m<secondary_macro ) {
14394     mp_print(mp, "primary");
14395   } else if ( m==secondary_macro ) {
14396     mp_print(mp, "secondary");
14397   } else {
14398     mp_print(mp, "tertiary");
14399   }
14400   break;
14401
14402 @ Let's turn next to the more complex processing associated with \&{def}
14403 and \&{vardef}. When the following procedure is called, |cur_mod|
14404 should be either |start_def| or |var_def|.
14405
14406 @c @<Declare the procedure called |check_delimiter|@>
14407 @<Declare the function called |scan_declared_variable|@>
14408 void mp_scan_def (MP mp) {
14409   int m; /* the type of definition */
14410   int n; /* the number of special suffix parameters */
14411   int k; /* the total number of parameters */
14412   int c; /* the kind of macro we're defining */
14413   pointer r; /* parameter-substitution list */
14414   pointer q; /* tail of the macro token list */
14415   pointer p; /* temporary storage */
14416   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14417   pointer l_delim,r_delim; /* matching delimiters */
14418   m=mp->cur_mod; c=general_macro; link(hold_head)=null;
14419   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14420   @<Scan the token or variable to be defined;
14421     set |n|, |scanner_status|, and |warning_info|@>;
14422   k=n;
14423   if ( mp->cur_cmd==left_delimiter ) {
14424     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14425   }
14426   if ( mp->cur_cmd==param_type ) {
14427     @<Absorb undelimited parameters, putting them into list |r|@>;
14428   }
14429   mp_check_equals(mp);
14430   p=mp_get_avail(mp); info(p)=c; link(q)=p;
14431   @<Attach the replacement text to the tail of node |p|@>;
14432   mp->scanner_status=normal; mp_get_x_next(mp);
14433 }
14434
14435 @ We don't put `|frozen_end_group|' into the replacement text of
14436 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14437
14438 @<Attach the replacement text to the tail of node |p|@>=
14439 if ( m==start_def ) {
14440   link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14441 } else { 
14442   q=mp_get_avail(mp); info(q)=mp->bg_loc; link(p)=q;
14443   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14444   link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14445 }
14446 if ( mp->warning_info==bad_vardef ) 
14447   mp_flush_token_list(mp, value(bad_vardef))
14448
14449 @ @<Glob...@>=
14450 int bg_loc;
14451 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14452
14453 @ @<Scan the token or variable to be defined;...@>=
14454 if ( m==start_def ) {
14455   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14456   mp->scanner_status=op_defining; n=0;
14457   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14458 } else { 
14459   p=mp_scan_declared_variable(mp);
14460   mp_flush_variable(mp, equiv(info(p)),link(p),true);
14461   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14462   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14463   mp->scanner_status=var_defining; n=2;
14464   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14465     n=3; get_t_next;
14466   }
14467   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14468 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14469
14470 @ @<Change to `\.{a bad variable}'@>=
14471
14472   print_err("This variable already starts with a macro");
14473 @.This variable already...@>
14474   help2("After `vardef a' you can\'t say `vardef a.b'.")
14475     ("So I'll have to discard this definition.");
14476   mp_error(mp); mp->warning_info=bad_vardef;
14477 }
14478
14479 @ @<Initialize table entries...@>=
14480 name_type(bad_vardef)=mp_root; link(bad_vardef)=frozen_bad_vardef;
14481 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14482
14483 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14484 do {  
14485   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14486   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14487    base=mp->cur_mod;
14488   } else { 
14489     print_err("Missing parameter type; `expr' will be assumed");
14490 @.Missing parameter type@>
14491     help1("You should've had `expr' or `suffix' or `text' here.");
14492     mp_back_error(mp); base=expr_base;
14493   }
14494   @<Absorb parameter tokens for type |base|@>;
14495   mp_check_delimiter(mp, l_delim,r_delim);
14496   get_t_next;
14497 } while (mp->cur_cmd==left_delimiter)
14498
14499 @ @<Absorb parameter tokens for type |base|@>=
14500 do { 
14501   link(q)=mp_get_avail(mp); q=link(q); info(q)=base+k;
14502   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14503   value(p)=base+k; info(p)=mp->cur_sym;
14504   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14505 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14506   incr(k); link(p)=r; r=p; get_t_next;
14507 } while (mp->cur_cmd==comma)
14508
14509 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14510
14511   p=mp_get_node(mp, token_node_size);
14512   if ( mp->cur_mod<expr_base ) {
14513     c=mp->cur_mod; value(p)=expr_base+k;
14514   } else { 
14515     value(p)=mp->cur_mod+k;
14516     if ( mp->cur_mod==expr_base ) c=expr_macro;
14517     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14518     else c=text_macro;
14519   }
14520   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14521   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; link(p)=r; r=p; get_t_next;
14522   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14523     c=of_macro; p=mp_get_node(mp, token_node_size);
14524     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14525     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14526     link(p)=r; r=p; get_t_next;
14527   }
14528 }
14529
14530 @* \[32] Expanding the next token.
14531 Only a few command codes |<min_command| can possibly be returned by
14532 |get_t_next|; in increasing order, they are
14533 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14534 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14535
14536 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14537 like |get_t_next| except that it keeps getting more tokens until
14538 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14539 macros and removes conditionals or iterations or input instructions that
14540 might be present.
14541
14542 It follows that |get_x_next| might invoke itself recursively. In fact,
14543 there is massive recursion, since macro expansion can involve the
14544 scanning of arbitrarily complex expressions, which in turn involve
14545 macro expansion and conditionals, etc.
14546 @^recursion@>
14547
14548 Therefore it's necessary to declare a whole bunch of |forward|
14549 procedures at this point, and to insert some other procedures
14550 that will be invoked by |get_x_next|.
14551
14552 @<Declarations@>= 
14553 void mp_scan_primary (MP mp);
14554 void mp_scan_secondary (MP mp);
14555 void mp_scan_tertiary (MP mp);
14556 void mp_scan_expression (MP mp);
14557 void mp_scan_suffix (MP mp);
14558 @<Declare the procedure called |macro_call|@>
14559 void mp_get_boolean (MP mp);
14560 void mp_pass_text (MP mp);
14561 void mp_conditional (MP mp);
14562 void mp_start_input (MP mp);
14563 void mp_begin_iteration (MP mp);
14564 void mp_resume_iteration (MP mp);
14565 void mp_stop_iteration (MP mp);
14566
14567 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14568 when it has to do exotic expansion commands.
14569
14570 @c void mp_expand (MP mp) {
14571   pointer p; /* for list manipulation */
14572   size_t k; /* something that we hope is |<=buf_size| */
14573   pool_pointer j; /* index into |str_pool| */
14574   if ( mp->internal[mp_tracing_commands]>unity ) 
14575     if ( mp->cur_cmd!=defined_macro )
14576       show_cur_cmd_mod;
14577   switch (mp->cur_cmd)  {
14578   case if_test:
14579     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14580     break;
14581   case fi_or_else:
14582     @<Terminate the current conditional and skip to \&{fi}@>;
14583     break;
14584   case input:
14585     @<Initiate or terminate input from a file@>;
14586     break;
14587   case iteration:
14588     if ( mp->cur_mod==end_for ) {
14589       @<Scold the user for having an extra \&{endfor}@>;
14590     } else {
14591       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14592     }
14593     break;
14594   case repeat_loop: 
14595     @<Repeat a loop@>;
14596     break;
14597   case exit_test: 
14598     @<Exit a loop if the proper time has come@>;
14599     break;
14600   case relax: 
14601     break;
14602   case expand_after: 
14603     @<Expand the token after the next token@>;
14604     break;
14605   case scan_tokens: 
14606     @<Put a string into the input buffer@>;
14607     break;
14608   case defined_macro:
14609    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14610    break;
14611   }; /* there are no other cases */
14612 }
14613
14614 @ @<Scold the user...@>=
14615
14616   print_err("Extra `endfor'");
14617 @.Extra `endfor'@>
14618   help2("I'm not currently working on a for loop,")
14619     ("so I had better not try to end anything.");
14620   mp_error(mp);
14621 }
14622
14623 @ The processing of \&{input} involves the |start_input| subroutine,
14624 which will be declared later; the processing of \&{endinput} is trivial.
14625
14626 @<Put each...@>=
14627 mp_primitive(mp, "input",input,0);
14628 @:input_}{\&{input} primitive@>
14629 mp_primitive(mp, "endinput",input,1);
14630 @:end_input_}{\&{endinput} primitive@>
14631
14632 @ @<Cases of |print_cmd_mod|...@>=
14633 case input: 
14634   if ( m==0 ) mp_print(mp, "input");
14635   else mp_print(mp, "endinput");
14636   break;
14637
14638 @ @<Initiate or terminate input...@>=
14639 if ( mp->cur_mod>0 ) mp->force_eof=true;
14640 else mp_start_input(mp)
14641
14642 @ We'll discuss the complicated parts of loop operations later. For now
14643 it suffices to know that there's a global variable called |loop_ptr|
14644 that will be |null| if no loop is in progress.
14645
14646 @<Repeat a loop@>=
14647 { while ( token_state &&(loc==null) ) 
14648     mp_end_token_list(mp); /* conserve stack space */
14649   if ( mp->loop_ptr==null ) {
14650     print_err("Lost loop");
14651 @.Lost loop@>
14652     help2("I'm confused; after exiting from a loop, I still seem")
14653       ("to want to repeat it. I'll try to forget the problem.");
14654     mp_error(mp);
14655   } else {
14656     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14657   }
14658 }
14659
14660 @ @<Exit a loop if the proper time has come@>=
14661 { mp_get_boolean(mp);
14662   if ( mp->internal[mp_tracing_commands]>unity ) 
14663     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14664   if ( mp->cur_exp==true_code ) {
14665     if ( mp->loop_ptr==null ) {
14666       print_err("No loop is in progress");
14667 @.No loop is in progress@>
14668       help1("Why say `exitif' when there's nothing to exit from?");
14669       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14670     } else {
14671      @<Exit prematurely from an iteration@>;
14672     }
14673   } else if ( mp->cur_cmd!=semicolon ) {
14674     mp_missing_err(mp, ";");
14675 @.Missing `;'@>
14676     help2("After `exitif <boolean exp>' I expect to see a semicolon.")
14677     ("I shall pretend that one was there."); mp_back_error(mp);
14678   }
14679 }
14680
14681 @ Here we use the fact that |forever_text| is the only |token_type| that
14682 is less than |loop_text|.
14683
14684 @<Exit prematurely...@>=
14685 { p=null;
14686   do {  
14687     if ( file_state ) {
14688       mp_end_file_reading(mp);
14689     } else { 
14690       if ( token_type<=loop_text ) p=start;
14691       mp_end_token_list(mp);
14692     }
14693   } while (p==null);
14694   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14695 @.loop confusion@>
14696   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14697 }
14698
14699 @ @<Expand the token after the next token@>=
14700 { get_t_next;
14701   p=mp_cur_tok(mp); get_t_next;
14702   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14703   else mp_back_input(mp);
14704   back_list(p);
14705 }
14706
14707 @ @<Put a string into the input buffer@>=
14708 { mp_get_x_next(mp); mp_scan_primary(mp);
14709   if ( mp->cur_type!=mp_string_type ) {
14710     mp_disp_err(mp, null,"Not a string");
14711 @.Not a string@>
14712     help2("I'm going to flush this expression, since")
14713        ("scantokens should be followed by a known string.");
14714     mp_put_get_flush_error(mp, 0);
14715   } else { 
14716     mp_back_input(mp);
14717     if ( length(mp->cur_exp)>0 )
14718        @<Pretend we're reading a new one-line file@>;
14719   }
14720 }
14721
14722 @ @<Pretend we're reading a new one-line file@>=
14723 { mp_begin_file_reading(mp); name=is_scantok;
14724   k=mp->first+length(mp->cur_exp);
14725   if ( k>=mp->max_buf_stack ) {
14726     while ( k>=mp->buf_size ) {
14727       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
14728     }
14729     mp->max_buf_stack=k+1;
14730   }
14731   j=mp->str_start[mp->cur_exp]; limit=k;
14732   while ( mp->first<(size_t)limit ) {
14733     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14734   }
14735   mp->buffer[limit]='%'; mp->first=limit+1; loc=start; 
14736   mp_flush_cur_exp(mp, 0);
14737 }
14738
14739 @ Here finally is |get_x_next|.
14740
14741 The expression scanning routines to be considered later
14742 communicate via the global quantities |cur_type| and |cur_exp|;
14743 we must be very careful to save and restore these quantities while
14744 macros are being expanded.
14745 @^inner loop@>
14746
14747 @<Declarations@>=
14748 void mp_get_x_next (MP mp);
14749
14750 @ @c void mp_get_x_next (MP mp) {
14751   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14752   get_t_next;
14753   if ( mp->cur_cmd<min_command ) {
14754     save_exp=mp_stash_cur_exp(mp);
14755     do {  
14756       if ( mp->cur_cmd==defined_macro ) 
14757         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14758       else 
14759         mp_expand(mp);
14760       get_t_next;
14761      } while (mp->cur_cmd<min_command);
14762      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14763   }
14764 }
14765
14766 @ Now let's consider the |macro_call| procedure, which is used to start up
14767 all user-defined macros. Since the arguments to a macro might be expressions,
14768 |macro_call| is recursive.
14769 @^recursion@>
14770
14771 The first parameter to |macro_call| points to the reference count of the
14772 token list that defines the macro. The second parameter contains any
14773 arguments that have already been parsed (see below).  The third parameter
14774 points to the symbolic token that names the macro. If the third parameter
14775 is |null|, the macro was defined by \&{vardef}, so its name can be
14776 reconstructed from the prefix and ``at'' arguments found within the
14777 second parameter.
14778
14779 What is this second parameter? It's simply a linked list of one-word items,
14780 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14781 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14782 the first scanned argument, and |link(arg_list)| points to the list of
14783 further arguments (if any).
14784
14785 Arguments of type \&{expr} are so-called capsules, which we will
14786 discuss later when we concentrate on expressions; they can be
14787 recognized easily because their |link| field is |void|. Arguments of type
14788 \&{suffix} and \&{text} are token lists without reference counts.
14789
14790 @ After argument scanning is complete, the arguments are moved to the
14791 |param_stack|. (They can't be put on that stack any sooner, because
14792 the stack is growing and shrinking in unpredictable ways as more arguments
14793 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14794 the replacement text of the macro is placed at the top of the \MP's
14795 input stack, so that |get_t_next| will proceed to read it next.
14796
14797 @<Declare the procedure called |macro_call|@>=
14798 @<Declare the procedure called |print_macro_name|@>
14799 @<Declare the procedure called |print_arg|@>
14800 @<Declare the procedure called |scan_text_arg|@>
14801 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14802                     pointer macro_name) ;
14803
14804 @ @c
14805 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14806                     pointer macro_name) {
14807   /* invokes a user-defined control sequence */
14808   pointer r; /* current node in the macro's token list */
14809   pointer p,q; /* for list manipulation */
14810   integer n; /* the number of arguments */
14811   pointer tail = 0; /* tail of the argument list */
14812   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14813   r=link(def_ref); add_mac_ref(def_ref);
14814   if ( arg_list==null ) {
14815     n=0;
14816   } else {
14817    @<Determine the number |n| of arguments already supplied,
14818     and set |tail| to the tail of |arg_list|@>;
14819   }
14820   if ( mp->internal[mp_tracing_macros]>0 ) {
14821     @<Show the text of the macro being expanded, and the existing arguments@>;
14822   }
14823   @<Scan the remaining arguments, if any; set |r| to the first token
14824     of the replacement text@>;
14825   @<Feed the arguments and replacement text to the scanner@>;
14826 }
14827
14828 @ @<Show the text of the macro...@>=
14829 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14830 mp_print_macro_name(mp, arg_list,macro_name);
14831 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14832 mp_show_macro(mp, def_ref,null,100000);
14833 if ( arg_list!=null ) {
14834   n=0; p=arg_list;
14835   do {  
14836     q=info(p);
14837     mp_print_arg(mp, q,n,0);
14838     incr(n); p=link(p);
14839   } while (p!=null);
14840 }
14841 mp_end_diagnostic(mp, false)
14842
14843
14844 @ @<Declare the procedure called |print_macro_name|@>=
14845 void mp_print_macro_name (MP mp,pointer a, pointer n);
14846
14847 @ @c
14848 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14849   pointer p,q; /* they traverse the first part of |a| */
14850   if ( n!=null ) {
14851     mp_print_text(n);
14852   } else  { 
14853     p=info(a);
14854     if ( p==null ) {
14855       mp_print_text(info(info(link(a))));
14856     } else { 
14857       q=p;
14858       while ( link(q)!=null ) q=link(q);
14859       link(q)=info(link(a));
14860       mp_show_token_list(mp, p,null,1000,0);
14861       link(q)=null;
14862     }
14863   }
14864 }
14865
14866 @ @<Declare the procedure called |print_arg|@>=
14867 void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
14868
14869 @ @c
14870 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
14871   if ( link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
14872   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
14873   else mp_print_nl(mp, "(TEXT");
14874   mp_print_int(mp, n); mp_print(mp, ")<-");
14875   if ( link(q)==mp_void ) mp_print_exp(mp, q,1);
14876   else mp_show_token_list(mp, q,null,1000,0);
14877 }
14878
14879 @ @<Determine the number |n| of arguments already supplied...@>=
14880 {  
14881   n=1; tail=arg_list;
14882   while ( link(tail)!=null ) { 
14883     incr(n); tail=link(tail);
14884   }
14885 }
14886
14887 @ @<Scan the remaining arguments, if any; set |r|...@>=
14888 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
14889 while ( info(r)>=expr_base ) { 
14890   @<Scan the delimited argument represented by |info(r)|@>;
14891   r=link(r);
14892 }
14893 if ( mp->cur_cmd==comma ) {
14894   print_err("Too many arguments to ");
14895 @.Too many arguments...@>
14896   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, ';');
14897   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
14898 @.Missing `)'...@>
14899   mp_print(mp, "' has been inserted");
14900   help3("I'm going to assume that the comma I just read was a")
14901    ("right delimiter, and then I'll begin expanding the macro.")
14902    ("You might want to delete some tokens before continuing.");
14903   mp_error(mp);
14904 }
14905 if ( info(r)!=general_macro ) {
14906   @<Scan undelimited argument(s)@>;
14907 }
14908 r=link(r)
14909
14910 @ At this point, the reader will find it advisable to review the explanation
14911 of token list format that was presented earlier, paying special attention to
14912 the conventions that apply only at the beginning of a macro's token list.
14913
14914 On the other hand, the reader will have to take the expression-parsing
14915 aspects of the following program on faith; we will explain |cur_type|
14916 and |cur_exp| later. (Several things in this program depend on each other,
14917 and it's necessary to jump into the circle somewhere.)
14918
14919 @<Scan the delimited argument represented by |info(r)|@>=
14920 if ( mp->cur_cmd!=comma ) {
14921   mp_get_x_next(mp);
14922   if ( mp->cur_cmd!=left_delimiter ) {
14923     print_err("Missing argument to ");
14924 @.Missing argument...@>
14925     mp_print_macro_name(mp, arg_list,macro_name);
14926     help3("That macro has more parameters than you thought.")
14927      ("I'll continue by pretending that each missing argument")
14928      ("is either zero or null.");
14929     if ( info(r)>=suffix_base ) {
14930       mp->cur_exp=null; mp->cur_type=mp_token_list;
14931     } else { 
14932       mp->cur_exp=0; mp->cur_type=mp_known;
14933     }
14934     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
14935     goto FOUND;
14936   }
14937   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
14938 }
14939 @<Scan the argument represented by |info(r)|@>;
14940 if ( mp->cur_cmd!=comma ) 
14941   @<Check that the proper right delimiter was present@>;
14942 FOUND:  
14943 @<Append the current expression to |arg_list|@>
14944
14945 @ @<Check that the proper right delim...@>=
14946 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
14947   if ( info(link(r))>=expr_base ) {
14948     mp_missing_err(mp, ",");
14949 @.Missing `,'@>
14950     help3("I've finished reading a macro argument and am about to")
14951       ("read another; the arguments weren't delimited correctly.")
14952        ("You might want to delete some tokens before continuing.");
14953     mp_back_error(mp); mp->cur_cmd=comma;
14954   } else { 
14955     mp_missing_err(mp, str(text(r_delim)));
14956 @.Missing `)'@>
14957     help2("I've gotten to the end of the macro parameter list.")
14958        ("You might want to delete some tokens before continuing.");
14959     mp_back_error(mp);
14960   }
14961 }
14962
14963 @ A \&{suffix} or \&{text} parameter will have been scanned as
14964 a token list pointed to by |cur_exp|, in which case we will have
14965 |cur_type=token_list|.
14966
14967 @<Append the current expression to |arg_list|@>=
14968
14969   p=mp_get_avail(mp);
14970   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
14971   else info(p)=mp_stash_cur_exp(mp);
14972   if ( mp->internal[mp_tracing_macros]>0 ) {
14973     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
14974     mp_end_diagnostic(mp, false);
14975   }
14976   if ( arg_list==null ) arg_list=p;
14977   else link(tail)=p;
14978   tail=p; incr(n);
14979 }
14980
14981 @ @<Scan the argument represented by |info(r)|@>=
14982 if ( info(r)>=text_base ) {
14983   mp_scan_text_arg(mp, l_delim,r_delim);
14984 } else { 
14985   mp_get_x_next(mp);
14986   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
14987   else mp_scan_expression(mp);
14988 }
14989
14990 @ The parameters to |scan_text_arg| are either a pair of delimiters
14991 or zero; the latter case is for undelimited text arguments, which
14992 end with the first semicolon or \&{endgroup} or \&{end} that is not
14993 contained in a group.
14994
14995 @<Declare the procedure called |scan_text_arg|@>=
14996 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
14997
14998 @ @c
14999 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15000   integer balance; /* excess of |l_delim| over |r_delim| */
15001   pointer p; /* list tail */
15002   mp->warning_info=l_delim; mp->scanner_status=absorbing;
15003   p=hold_head; balance=1; link(hold_head)=null;
15004   while (1)  { 
15005     get_t_next;
15006     if ( l_delim==0 ) {
15007       @<Adjust the balance for an undelimited argument; |break| if done@>;
15008     } else {
15009           @<Adjust the balance for a delimited argument; |break| if done@>;
15010     }
15011     link(p)=mp_cur_tok(mp); p=link(p);
15012   }
15013   mp->cur_exp=link(hold_head); mp->cur_type=mp_token_list;
15014   mp->scanner_status=normal;
15015 }
15016
15017 @ @<Adjust the balance for a delimited argument...@>=
15018 if ( mp->cur_cmd==right_delimiter ) { 
15019   if ( mp->cur_mod==l_delim ) { 
15020     decr(balance);
15021     if ( balance==0 ) break;
15022   }
15023 } else if ( mp->cur_cmd==left_delimiter ) {
15024   if ( mp->cur_mod==r_delim ) incr(balance);
15025 }
15026
15027 @ @<Adjust the balance for an undelimited...@>=
15028 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15029   if ( balance==1 ) { break; }
15030   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15031 } else if ( mp->cur_cmd==begin_group ) { 
15032   incr(balance); 
15033 }
15034
15035 @ @<Scan undelimited argument(s)@>=
15036
15037   if ( info(r)<text_macro ) {
15038     mp_get_x_next(mp);
15039     if ( info(r)!=suffix_macro ) {
15040       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15041     }
15042   }
15043   switch (info(r)) {
15044   case primary_macro:mp_scan_primary(mp); break;
15045   case secondary_macro:mp_scan_secondary(mp); break;
15046   case tertiary_macro:mp_scan_tertiary(mp); break;
15047   case expr_macro:mp_scan_expression(mp); break;
15048   case of_macro:
15049     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15050     break;
15051   case suffix_macro:
15052     @<Scan a suffix with optional delimiters@>;
15053     break;
15054   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15055   } /* there are no other cases */
15056   mp_back_input(mp); 
15057   @<Append the current expression to |arg_list|@>;
15058 }
15059
15060 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15061
15062   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15063   if ( mp->internal[mp_tracing_macros]>0 ) { 
15064     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15065     mp_end_diagnostic(mp, false);
15066   }
15067   if ( arg_list==null ) arg_list=p; else link(tail)=p;
15068   tail=p;incr(n);
15069   if ( mp->cur_cmd!=of_token ) {
15070     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15071 @.Missing `of'@>
15072     mp_print_macro_name(mp, arg_list,macro_name);
15073     help1("I've got the first argument; will look now for the other.");
15074     mp_back_error(mp);
15075   }
15076   mp_get_x_next(mp); mp_scan_primary(mp);
15077 }
15078
15079 @ @<Scan a suffix with optional delimiters@>=
15080
15081   if ( mp->cur_cmd!=left_delimiter ) {
15082     l_delim=null;
15083   } else { 
15084     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15085   };
15086   mp_scan_suffix(mp);
15087   if ( l_delim!=null ) {
15088     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15089       mp_missing_err(mp, str(text(r_delim)));
15090 @.Missing `)'@>
15091       help2("I've gotten to the end of the macro parameter list.")
15092          ("You might want to delete some tokens before continuing.");
15093       mp_back_error(mp);
15094     }
15095     mp_get_x_next(mp);
15096   }
15097 }
15098
15099 @ Before we put a new token list on the input stack, it is wise to clean off
15100 all token lists that have recently been depleted. Then a user macro that ends
15101 with a call to itself will not require unbounded stack space.
15102
15103 @<Feed the arguments and replacement text to the scanner@>=
15104 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15105 if ( mp->param_ptr+n>mp->max_param_stack ) {
15106   mp->max_param_stack=mp->param_ptr+n;
15107   if ( mp->max_param_stack>mp->param_size )
15108     mp_overflow(mp, "parameter stack size",mp->param_size);
15109 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15110 }
15111 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15112 if ( n>0 ) {
15113   p=arg_list;
15114   do {  
15115    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=link(p);
15116   } while (p!=null);
15117   mp_flush_list(mp, arg_list);
15118 }
15119
15120 @ It's sometimes necessary to put a single argument onto |param_stack|.
15121 The |stack_argument| subroutine does this.
15122
15123 @c void mp_stack_argument (MP mp,pointer p) { 
15124   if ( mp->param_ptr==mp->max_param_stack ) {
15125     incr(mp->max_param_stack);
15126     if ( mp->max_param_stack>mp->param_size )
15127       mp_overflow(mp, "parameter stack size",mp->param_size);
15128 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15129   }
15130   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15131 }
15132
15133 @* \[33] Conditional processing.
15134 Let's consider now the way \&{if} commands are handled.
15135
15136 Conditions can be inside conditions, and this nesting has a stack
15137 that is independent of other stacks.
15138 Four global variables represent the top of the condition stack:
15139 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15140 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15141 the largest code of a |fi_or_else| command that is syntactically legal;
15142 and |if_line| is the line number at which the current conditional began.
15143
15144 If no conditions are currently in progress, the condition stack has the
15145 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15146 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15147 |link| fields of the first word contain |if_limit|, |cur_if|, and
15148 |cond_ptr| at the next level, and the second word contains the
15149 corresponding |if_line|.
15150
15151 @d if_node_size 2 /* number of words in stack entry for conditionals */
15152 @d if_line_field(A) mp->mem[(A)+1].cint
15153 @d if_code 1 /* code for \&{if} being evaluated */
15154 @d fi_code 2 /* code for \&{fi} */
15155 @d else_code 3 /* code for \&{else} */
15156 @d else_if_code 4 /* code for \&{elseif} */
15157
15158 @<Glob...@>=
15159 pointer cond_ptr; /* top of the condition stack */
15160 integer if_limit; /* upper bound on |fi_or_else| codes */
15161 small_number cur_if; /* type of conditional being worked on */
15162 integer if_line; /* line where that conditional began */
15163
15164 @ @<Set init...@>=
15165 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15166
15167 @ @<Put each...@>=
15168 mp_primitive(mp, "if",if_test,if_code);
15169 @:if_}{\&{if} primitive@>
15170 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15171 @:fi_}{\&{fi} primitive@>
15172 mp_primitive(mp, "else",fi_or_else,else_code);
15173 @:else_}{\&{else} primitive@>
15174 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15175 @:else_if_}{\&{elseif} primitive@>
15176
15177 @ @<Cases of |print_cmd_mod|...@>=
15178 case if_test:
15179 case fi_or_else: 
15180   switch (m) {
15181   case if_code:mp_print(mp, "if"); break;
15182   case fi_code:mp_print(mp, "fi");  break;
15183   case else_code:mp_print(mp, "else"); break;
15184   default: mp_print(mp, "elseif"); break;
15185   }
15186   break;
15187
15188 @ Here is a procedure that ignores text until coming to an \&{elseif},
15189 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15190 nesting. After it has acted, |cur_mod| will indicate the token that
15191 was found.
15192
15193 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15194 makes the skipping process a bit simpler.
15195
15196 @c 
15197 void mp_pass_text (MP mp) {
15198   integer l = 0;
15199   mp->scanner_status=skipping;
15200   mp->warning_info=mp_true_line(mp);
15201   while (1)  { 
15202     get_t_next;
15203     if ( mp->cur_cmd<=fi_or_else ) {
15204       if ( mp->cur_cmd<fi_or_else ) {
15205         incr(l);
15206       } else { 
15207         if ( l==0 ) break;
15208         if ( mp->cur_mod==fi_code ) decr(l);
15209       }
15210     } else {
15211       @<Decrease the string reference count,
15212        if the current token is a string@>;
15213     }
15214   }
15215   mp->scanner_status=normal;
15216 }
15217
15218 @ @<Decrease the string reference count...@>=
15219 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15220
15221 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15222 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15223 condition has been evaluated, a colon will be inserted.
15224 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15225
15226 @<Push the condition stack@>=
15227 { p=mp_get_node(mp, if_node_size); link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15228   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15229   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15230   mp->cur_if=if_code;
15231 }
15232
15233 @ @<Pop the condition stack@>=
15234 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15235   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=link(p);
15236   mp_free_node(mp, p,if_node_size);
15237 }
15238
15239 @ Here's a procedure that changes the |if_limit| code corresponding to
15240 a given value of |cond_ptr|.
15241
15242 @c void mp_change_if_limit (MP mp,small_number l, pointer p) {
15243   pointer q;
15244   if ( p==mp->cond_ptr ) {
15245     mp->if_limit=l; /* that's the easy case */
15246   } else  { 
15247     q=mp->cond_ptr;
15248     while (1) { 
15249       if ( q==null ) mp_confusion(mp, "if");
15250 @:this can't happen if}{\quad if@>
15251       if ( link(q)==p ) { 
15252         type(q)=l; return;
15253       }
15254       q=link(q);
15255     }
15256   }
15257 }
15258
15259 @ The user is supposed to put colons into the proper parts of conditional
15260 statements. Therefore, \MP\ has to check for their presence.
15261
15262 @c 
15263 void mp_check_colon (MP mp) { 
15264   if ( mp->cur_cmd!=colon ) { 
15265     mp_missing_err(mp, ":");
15266 @.Missing `:'@>
15267     help2("There should've been a colon after the condition.")
15268          ("I shall pretend that one was there.");;
15269     mp_back_error(mp);
15270   }
15271 }
15272
15273 @ A condition is started when the |get_x_next| procedure encounters
15274 an |if_test| command; in that case |get_x_next| calls |conditional|,
15275 which is a recursive procedure.
15276 @^recursion@>
15277
15278 @c void mp_conditional (MP mp) {
15279   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15280   int new_if_limit; /* future value of |if_limit| */
15281   pointer p; /* temporary register */
15282   @<Push the condition stack@>; 
15283   save_cond_ptr=mp->cond_ptr;
15284 RESWITCH: 
15285   mp_get_boolean(mp); new_if_limit=else_if_code;
15286   if ( mp->internal[mp_tracing_commands]>unity ) {
15287     @<Display the boolean value of |cur_exp|@>;
15288   }
15289 FOUND: 
15290   mp_check_colon(mp);
15291   if ( mp->cur_exp==true_code ) {
15292     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15293     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15294   };
15295   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15296 DONE: 
15297   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15298   if ( mp->cur_mod==fi_code ) {
15299     @<Pop the condition stack@>
15300   } else if ( mp->cur_mod==else_if_code ) {
15301     goto RESWITCH;
15302   } else  { 
15303     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15304     goto FOUND;
15305   }
15306 }
15307
15308 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15309 \&{else}: \\{bar} \&{fi}', the first \&{else}
15310 that we come to after learning that the \&{if} is false is not the
15311 \&{else} we're looking for. Hence the following curious logic is needed.
15312
15313 @<Skip to \&{elseif}...@>=
15314 while (1) { 
15315   mp_pass_text(mp);
15316   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15317   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15318 }
15319
15320
15321 @ @<Display the boolean value...@>=
15322 { mp_begin_diagnostic(mp);
15323   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15324   else mp_print(mp, "{false}");
15325   mp_end_diagnostic(mp, false);
15326 }
15327
15328 @ The processing of conditionals is complete except for the following
15329 code, which is actually part of |get_x_next|. It comes into play when
15330 \&{elseif}, \&{else}, or \&{fi} is scanned.
15331
15332 @<Terminate the current conditional and skip to \&{fi}@>=
15333 if ( mp->cur_mod>mp->if_limit ) {
15334   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15335     mp_missing_err(mp, ":");
15336 @.Missing `:'@>
15337     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15338   } else  { 
15339     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15340 @.Extra else@>
15341 @.Extra elseif@>
15342 @.Extra fi@>
15343     help1("I'm ignoring this; it doesn't match any if.");
15344     mp_error(mp);
15345   }
15346 } else  { 
15347   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15348   @<Pop the condition stack@>;
15349 }
15350
15351 @* \[34] Iterations.
15352 To bring our treatment of |get_x_next| to a close, we need to consider what
15353 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15354
15355 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15356 that are currently active. If |loop_ptr=null|, no loops are in progress;
15357 otherwise |info(loop_ptr)| points to the iterative text of the current
15358 (innermost) loop, and |link(loop_ptr)| points to the data for any other
15359 loops that enclose the current one.
15360
15361 A loop-control node also has two other fields, called |loop_type| and
15362 |loop_list|, whose contents depend on the type of loop:
15363
15364 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15365 points to a list of one-word nodes whose |info| fields point to the
15366 remaining argument values of a suffix list and expression list.
15367
15368 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15369 `\&{forever}'.
15370
15371 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15372 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15373 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15374 progression.
15375
15376 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15377 header and |loop_list(loop_ptr)| points into the graphical object list for
15378 that edge header.
15379
15380 \yskip\noindent In the case of a progression node, the first word is not used
15381 because the link field of words in the dynamic memory area cannot be arbitrary.
15382
15383 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15384 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15385 @d loop_list(A) link(loop_list_loc((A))) /* the remaining list elements */
15386 @d loop_node_size 2 /* the number of words in a loop control node */
15387 @d progression_node_size 4 /* the number of words in a progression node */
15388 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15389 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15390 @d progression_flag (null+2)
15391   /* |loop_type| value when |loop_list| points to a progression node */
15392
15393 @<Glob...@>=
15394 pointer loop_ptr; /* top of the loop-control-node stack */
15395
15396 @ @<Set init...@>=
15397 mp->loop_ptr=null;
15398
15399 @ If the expressions that define an arithmetic progression in
15400 a \&{for} loop don't have known numeric values, the |bad_for|
15401 subroutine screams at the user.
15402
15403 @c void mp_bad_for (MP mp, const char * s) {
15404   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15405 @.Improper...replaced by 0@>
15406   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15407   help4("When you say `for x=a step b until c',")
15408     ("the initial value `a' and the step size `b'")
15409     ("and the final value `c' must have known numeric values.")
15410     ("I'm zeroing this one. Proceed, with fingers crossed.");
15411   mp_put_get_flush_error(mp, 0);
15412 }
15413
15414 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15415 has just been scanned. (This code requires slight familiarity with
15416 expression-parsing routines that we have not yet discussed; but it seems
15417 to belong in the present part of the program, even though the original author
15418 didn't write it until later. The reader may wish to come back to it.)
15419
15420 @c void mp_begin_iteration (MP mp) {
15421   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15422   halfword n; /* hash address of the current symbol */
15423   pointer s; /* the new loop-control node */
15424   pointer p; /* substitution list for |scan_toks| */
15425   pointer q;  /* link manipulation register */
15426   pointer pp; /* a new progression node */
15427   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15428   if ( m==start_forever ){ 
15429     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15430   } else { 
15431     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15432     info(p)=mp->cur_sym; value(p)=m;
15433     mp_get_x_next(mp);
15434     if ( mp->cur_cmd==within_token ) {
15435       @<Set up a picture iteration@>;
15436     } else { 
15437       @<Check for the |"="| or |":="| in a loop header@>;
15438       @<Scan the values to be used in the loop@>;
15439     }
15440   }
15441   @<Check for the presence of a colon@>;
15442   @<Scan the loop text and put it on the loop control stack@>;
15443   mp_resume_iteration(mp);
15444 }
15445
15446 @ @<Check for the |"="| or |":="| in a loop header@>=
15447 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15448   mp_missing_err(mp, "=");
15449 @.Missing `='@>
15450   help3("The next thing in this loop should have been `=' or `:='.")
15451     ("But don't worry; I'll pretend that an equals sign")
15452     ("was present, and I'll look for the values next.");
15453   mp_back_error(mp);
15454 }
15455
15456 @ @<Check for the presence of a colon@>=
15457 if ( mp->cur_cmd!=colon ) { 
15458   mp_missing_err(mp, ":");
15459 @.Missing `:'@>
15460   help3("The next thing in this loop should have been a `:'.")
15461     ("So I'll pretend that a colon was present;")
15462     ("everything from here to `endfor' will be iterated.");
15463   mp_back_error(mp);
15464 }
15465
15466 @ We append a special |frozen_repeat_loop| token in place of the
15467 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15468 at the proper time to cause the loop to be repeated.
15469
15470 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15471 he will be foiled by the |get_symbol| routine, which keeps frozen
15472 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15473 token, so it won't be lost accidentally.)
15474
15475 @ @<Scan the loop text...@>=
15476 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15477 mp->scanner_status=loop_defining; mp->warning_info=n;
15478 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15479 link(s)=mp->loop_ptr; mp->loop_ptr=s
15480
15481 @ @<Initialize table...@>=
15482 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15483 text(frozen_repeat_loop)=intern(" ENDFOR");
15484
15485 @ The loop text is inserted into \MP's scanning apparatus by the
15486 |resume_iteration| routine.
15487
15488 @c void mp_resume_iteration (MP mp) {
15489   pointer p,q; /* link registers */
15490   p=loop_type(mp->loop_ptr);
15491   if ( p==progression_flag ) { 
15492     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15493     mp->cur_exp=value(p);
15494     if ( @<The arithmetic progression has ended@> ) {
15495       mp_stop_iteration(mp);
15496       return;
15497     }
15498     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15499     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15500   } else if ( p==null ) { 
15501     p=loop_list(mp->loop_ptr);
15502     if ( p==null ) {
15503       mp_stop_iteration(mp);
15504       return;
15505     }
15506     loop_list(mp->loop_ptr)=link(p); q=info(p); free_avail(p);
15507   } else if ( p==mp_void ) { 
15508     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15509   } else {
15510     @<Make |q| a capsule containing the next picture component from
15511       |loop_list(loop_ptr)| or |goto not_found|@>;
15512   }
15513   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15514   mp_stack_argument(mp, q);
15515   if ( mp->internal[mp_tracing_commands]>unity ) {
15516      @<Trace the start of a loop@>;
15517   }
15518   return;
15519 NOT_FOUND:
15520   mp_stop_iteration(mp);
15521 }
15522
15523 @ @<The arithmetic progression has ended@>=
15524 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15525  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15526
15527 @ @<Trace the start of a loop@>=
15528
15529   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15530 @.loop value=n@>
15531   if ( (q!=null)&&(link(q)==mp_void) ) mp_print_exp(mp, q,1);
15532   else mp_show_token_list(mp, q,null,50,0);
15533   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
15534 }
15535
15536 @ @<Make |q| a capsule containing the next picture component from...@>=
15537 { q=loop_list(mp->loop_ptr);
15538   if ( q==null ) goto NOT_FOUND;
15539   skip_component(q) goto NOT_FOUND;
15540   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15541   mp_init_bbox(mp, mp->cur_exp);
15542   mp->cur_type=mp_picture_type;
15543   loop_list(mp->loop_ptr)=q;
15544   q=mp_stash_cur_exp(mp);
15545 }
15546
15547 @ A level of loop control disappears when |resume_iteration| has decided
15548 not to resume, or when an \&{exitif} construction has removed the loop text
15549 from the input stack.
15550
15551 @c void mp_stop_iteration (MP mp) {
15552   pointer p,q; /* the usual */
15553   p=loop_type(mp->loop_ptr);
15554   if ( p==progression_flag )  {
15555     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15556   } else if ( p==null ){ 
15557     q=loop_list(mp->loop_ptr);
15558     while ( q!=null ) {
15559       p=info(q);
15560       if ( p!=null ) {
15561         if ( link(p)==mp_void ) { /* it's an \&{expr} parameter */
15562           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15563         } else {
15564           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15565         }
15566       }
15567       p=q; q=link(q); free_avail(p);
15568     }
15569   } else if ( p>progression_flag ) {
15570     delete_edge_ref(p);
15571   }
15572   p=mp->loop_ptr; mp->loop_ptr=link(p); mp_flush_token_list(mp, info(p));
15573   mp_free_node(mp, p,loop_node_size);
15574 }
15575
15576 @ Now that we know all about loop control, we can finish up
15577 the missing portion of |begin_iteration| and we'll be done.
15578
15579 The following code is performed after the `\.=' has been scanned in
15580 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15581 (if |m=suffix_base|).
15582
15583 @<Scan the values to be used in the loop@>=
15584 loop_type(s)=null; q=loop_list_loc(s); link(q)=null; /* |link(q)=loop_list(s)| */
15585 do {  
15586   mp_get_x_next(mp);
15587   if ( m!=expr_base ) {
15588     mp_scan_suffix(mp);
15589   } else { 
15590     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15591           goto CONTINUE;
15592     mp_scan_expression(mp);
15593     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15594       @<Prepare for step-until construction and |break|@>;
15595     }
15596     mp->cur_exp=mp_stash_cur_exp(mp);
15597   }
15598   link(q)=mp_get_avail(mp); q=link(q); 
15599   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15600 CONTINUE:
15601   ;
15602 } while (mp->cur_cmd==comma)
15603
15604 @ @<Prepare for step-until construction and |break|@>=
15605
15606   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15607   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15608   mp_get_x_next(mp); mp_scan_expression(mp);
15609   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15610   step_size(pp)=mp->cur_exp;
15611   if ( mp->cur_cmd!=until_token ) { 
15612     mp_missing_err(mp, "until");
15613 @.Missing `until'@>
15614     help2("I assume you meant to say `until' after `step'.")
15615       ("So I'll look for the final value and colon next.");
15616     mp_back_error(mp);
15617   }
15618   mp_get_x_next(mp); mp_scan_expression(mp);
15619   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15620   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15621   loop_type(s)=progression_flag; 
15622   break;
15623 }
15624
15625 @ The last case is when we have just seen ``\&{within}'', and we need to
15626 parse a picture expression and prepare to iterate over it.
15627
15628 @<Set up a picture iteration@>=
15629 { mp_get_x_next(mp);
15630   mp_scan_expression(mp);
15631   @<Make sure the current expression is a known picture@>;
15632   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15633   q=link(dummy_loc(mp->cur_exp));
15634   if ( q!= null ) 
15635     if ( is_start_or_stop(q) )
15636       if ( mp_skip_1component(mp, q)==null ) q=link(q);
15637   loop_list(s)=q;
15638 }
15639
15640 @ @<Make sure the current expression is a known picture@>=
15641 if ( mp->cur_type!=mp_picture_type ) {
15642   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15643   help1("When you say `for x in p', p must be a known picture.");
15644   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15645   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15646 }
15647
15648 @* \[35] File names.
15649 It's time now to fret about file names.  Besides the fact that different
15650 operating systems treat files in different ways, we must cope with the
15651 fact that completely different naming conventions are used by different
15652 groups of people. The following programs show what is required for one
15653 particular operating system; similar routines for other systems are not
15654 difficult to devise.
15655 @^system dependencies@>
15656
15657 \MP\ assumes that a file name has three parts: the name proper; its
15658 ``extension''; and a ``file area'' where it is found in an external file
15659 system.  The extension of an input file is assumed to be
15660 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15661 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15662 metric files that describe characters in any fonts created by \MP; it is
15663 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15664 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15665 The file area can be arbitrary on input files, but files are usually
15666 output to the user's current area.  If an input file cannot be
15667 found on the specified area, \MP\ will look for it on a special system
15668 area; this special area is intended for commonly used input files.
15669
15670 Simple uses of \MP\ refer only to file names that have no explicit
15671 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15672 instead of `\.{input} \.{cmr10.new}'. Simple file
15673 names are best, because they make the \MP\ source files portable;
15674 whenever a file name consists entirely of letters and digits, it should be
15675 treated in the same way by all implementations of \MP. However, users
15676 need the ability to refer to other files in their environment, especially
15677 when responding to error messages concerning unopenable files; therefore
15678 we want to let them use the syntax that appears in their favorite
15679 operating system.
15680
15681 @ \MP\ uses the same conventions that have proved to be satisfactory for
15682 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15683 @^system dependencies@>
15684 the system-independent parts of \MP\ are expressed in terms
15685 of three system-dependent
15686 procedures called |begin_name|, |more_name|, and |end_name|. In
15687 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15688 the system-independent driver program does the operations
15689 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
15690 \,|end_name|.$$
15691 These three procedures communicate with each other via global variables.
15692 Afterwards the file name will appear in the string pool as three strings
15693 called |cur_name|\penalty10000\hskip-.05em,
15694 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15695 |""|), unless they were explicitly specified by the user.
15696
15697 Actually the situation is slightly more complicated, because \MP\ needs
15698 to know when the file name ends. The |more_name| routine is a function
15699 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15700 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15701 returns |false|; or, it returns |true| and $c_n$ is the last character
15702 on the current input line. In other words,
15703 |more_name| is supposed to return |true| unless it is sure that the
15704 file name has been completely scanned; and |end_name| is supposed to be able
15705 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15706 whether $|more_name|(c_n)$ returned |true| or |false|.
15707
15708 @<Glob...@>=
15709 char * cur_name; /* name of file just scanned */
15710 char * cur_area; /* file area just scanned, or \.{""} */
15711 char * cur_ext; /* file extension just scanned, or \.{""} */
15712
15713 @ It is easier to maintain reference counts if we assign initial values.
15714
15715 @<Set init...@>=
15716 mp->cur_name=xstrdup(""); 
15717 mp->cur_area=xstrdup(""); 
15718 mp->cur_ext=xstrdup("");
15719
15720 @ @<Dealloc variables@>=
15721 xfree(mp->cur_area);
15722 xfree(mp->cur_name);
15723 xfree(mp->cur_ext);
15724
15725 @ The file names we shall deal with for illustrative purposes have the
15726 following structure:  If the name contains `\.>' or `\.:', the file area
15727 consists of all characters up to and including the final such character;
15728 otherwise the file area is null.  If the remaining file name contains
15729 `\..', the file extension consists of all such characters from the first
15730 remaining `\..' to the end, otherwise the file extension is null.
15731 @^system dependencies@>
15732
15733 We can scan such file names easily by using two global variables that keep track
15734 of the occurrences of area and extension delimiters.  Note that these variables
15735 cannot be of type |pool_pointer| because a string pool compaction could occur
15736 while scanning a file name.
15737
15738 @<Glob...@>=
15739 integer area_delimiter;
15740   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15741 integer ext_delimiter; /* the relevant `\..', if any */
15742
15743 @ Here now is the first of the system-dependent routines for file name scanning.
15744 @^system dependencies@>
15745
15746 @<Declare subroutines for parsing file names@>=
15747 void mp_begin_name (MP mp) { 
15748   xfree(mp->cur_name); 
15749   xfree(mp->cur_area); 
15750   xfree(mp->cur_ext);
15751   mp->area_delimiter=-1; 
15752   mp->ext_delimiter=-1;
15753 }
15754
15755 @ And here's the second.
15756 @^system dependencies@>
15757
15758 @<Declare subroutines for parsing file names@>=
15759 boolean mp_more_name (MP mp, ASCII_code c) { 
15760   if (c==' ') {
15761     return false;
15762   } else { 
15763     if ( (c=='>')||(c==':') ) { 
15764       mp->area_delimiter=mp->pool_ptr; 
15765       mp->ext_delimiter=-1;
15766     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15767       mp->ext_delimiter=mp->pool_ptr;
15768     }
15769     str_room(1); append_char(c); /* contribute |c| to the current string */
15770     return true;
15771   }
15772 }
15773
15774 @ The third.
15775 @^system dependencies@>
15776
15777 @d copy_pool_segment(A,B,C) { 
15778       A = xmalloc(C+1,sizeof(char)); 
15779       strncpy(A,(char *)(mp->str_pool+B),C);  
15780       A[C] = 0;}
15781
15782 @<Declare subroutines for parsing file names@>=
15783 void mp_end_name (MP mp) {
15784   pool_pointer s; /* length of area, name, and extension */
15785   unsigned int len;
15786   /* "my/w.mp" */
15787   s = mp->str_start[mp->str_ptr];
15788   if ( mp->area_delimiter<0 ) {    
15789     mp->cur_area=xstrdup("");
15790   } else {
15791     len = mp->area_delimiter-s; 
15792     copy_pool_segment(mp->cur_area,s,len);
15793     s += len+1;
15794   }
15795   if ( mp->ext_delimiter<0 ) {
15796     mp->cur_ext=xstrdup("");
15797     len = mp->pool_ptr-s; 
15798   } else {
15799     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(mp->pool_ptr-mp->ext_delimiter));
15800     len = mp->ext_delimiter-s;
15801   }
15802   copy_pool_segment(mp->cur_name,s,len);
15803   mp->pool_ptr=s; /* don't need this partial string */
15804 }
15805
15806 @ Conversely, here is a routine that takes three strings and prints a file
15807 name that might have produced them. (The routine is system dependent, because
15808 some operating systems put the file area last instead of first.)
15809 @^system dependencies@>
15810
15811 @<Basic printing...@>=
15812 void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15813   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15814 }
15815
15816 @ Another system-dependent routine is needed to convert three internal
15817 \MP\ strings
15818 to the |name_of_file| value that is used to open files. The present code
15819 allows both lowercase and uppercase letters in the file name.
15820 @^system dependencies@>
15821
15822 @d append_to_name(A) { c=(A); 
15823   if ( k<file_name_size ) {
15824     mp->name_of_file[k]=xchr(c);
15825     incr(k);
15826   }
15827 }
15828
15829 @<Declare subroutines for parsing file names@>=
15830 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) {
15831   integer k; /* number of positions filled in |name_of_file| */
15832   ASCII_code c; /* character being packed */
15833   const char *j; /* a character  index */
15834   k=0;
15835   assert(n);
15836   if (a!=NULL) {
15837     for (j=a;*j;j++) { append_to_name(*j); }
15838   }
15839   for (j=n;*j;j++) { append_to_name(*j); }
15840   if (e!=NULL) {
15841     for (j=e;*j;j++) { append_to_name(*j); }
15842   }
15843   mp->name_of_file[k]=0;
15844   mp->name_length=k; 
15845 }
15846
15847 @ @<Internal library declarations@>=
15848 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) ;
15849
15850 @ A messier routine is also needed, since mem file names must be scanned
15851 before \MP's string mechanism has been initialized. We shall use the
15852 global variable |MP_mem_default| to supply the text for default system areas
15853 and extensions related to mem files.
15854 @^system dependencies@>
15855
15856 @d mem_default_length 9 /* length of the |MP_mem_default| string */
15857 @d mem_ext_length 4 /* length of its `\.{.mem}' part */
15858 @d mem_extension ".mem" /* the extension, as a \.{WEB} constant */
15859
15860 @<Glob...@>=
15861 char *MP_mem_default;
15862
15863 @ @<Option variables@>=
15864 char *mem_name; /* for commandline */
15865
15866 @ @<Allocate or initialize ...@>=
15867 mp->MP_mem_default = xstrdup("plain.mem");
15868 mp->mem_name = xstrdup(opt->mem_name);
15869 @.plain@>
15870 @^system dependencies@>
15871
15872 @ @<Dealloc variables@>=
15873 xfree(mp->MP_mem_default);
15874 xfree(mp->mem_name);
15875
15876 @ @<Check the ``constant'' values for consistency@>=
15877 if ( mem_default_length>file_name_size ) mp->bad=20;
15878
15879 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
15880 from the first |n| characters of |MP_mem_default|, followed by
15881 |buffer[a..b-1]|, followed by the last |mem_ext_length| characters of
15882 |MP_mem_default|.
15883
15884 We dare not give error messages here, since \MP\ calls this routine before
15885 the |error| routine is ready to roll. Instead, we simply drop excess characters,
15886 since the error will be detected in another way when a strange file name
15887 isn't found.
15888 @^system dependencies@>
15889
15890 @c void mp_pack_buffered_name (MP mp,small_number n, integer a,
15891                                integer b) {
15892   integer k; /* number of positions filled in |name_of_file| */
15893   ASCII_code c; /* character being packed */
15894   integer j; /* index into |buffer| or |MP_mem_default| */
15895   if ( n+b-a+1+mem_ext_length>file_name_size )
15896     b=a+file_name_size-n-1-mem_ext_length;
15897   k=0;
15898   for (j=0;j<n;j++) {
15899     append_to_name(xord((int)mp->MP_mem_default[j]));
15900   }
15901   for (j=a;j<b;j++) {
15902     append_to_name(mp->buffer[j]);
15903   }
15904   for (j=mem_default_length-mem_ext_length;
15905       j<mem_default_length;j++) {
15906     append_to_name(xord((int)mp->MP_mem_default[j]));
15907   } 
15908   mp->name_of_file[k]=0;
15909   mp->name_length=k; 
15910 }
15911
15912 @ Here is the only place we use |pack_buffered_name|. This part of the program
15913 becomes active when a ``virgin'' \MP\ is trying to get going, just after
15914 the preliminary initialization, or when the user is substituting another
15915 mem file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
15916 contains the first line of input in |buffer[loc..(last-1)]|, where
15917 |loc<last| and |buffer[loc]<>" "|.
15918
15919 @<Declarations@>=
15920 boolean mp_open_mem_file (MP mp) ;
15921
15922 @ @c
15923 boolean mp_open_mem_file (MP mp) {
15924   int j; /* the first space after the file name */
15925   if (mp->mem_name!=NULL) {
15926     mp->mem_file = (mp->open_file)(mp,mp->mem_name, "r", mp_filetype_memfile);
15927     if ( mp->mem_file ) return true;
15928   }
15929   j=loc;
15930   if ( mp->buffer[loc]=='&' ) {
15931     incr(loc); j=loc; mp->buffer[mp->last]=' ';
15932     while ( mp->buffer[j]!=' ' ) incr(j);
15933     mp_pack_buffered_name(mp, 0,loc,j); /* try first without the system file area */
15934     if ( mp_w_open_in(mp, &mp->mem_file) ) goto FOUND;
15935     wake_up_terminal;
15936     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
15937 @.Sorry, I can't find...@>
15938     update_terminal;
15939   }
15940   /* now pull out all the stops: try for the system \.{plain} file */
15941   mp_pack_buffered_name(mp, mem_default_length-mem_ext_length,0,0);
15942   if ( ! mp_w_open_in(mp, &mp->mem_file) ) {
15943     wake_up_terminal;
15944     wterm_ln("I can\'t find the PLAIN mem file!\n");
15945 @.I can't find PLAIN...@>
15946 @.plain@>
15947     return false;
15948   }
15949 FOUND:
15950   loc=j; return true;
15951 }
15952
15953 @ Operating systems often make it possible to determine the exact name (and
15954 possible version number) of a file that has been opened. The following routine,
15955 which simply makes a \MP\ string from the value of |name_of_file|, should
15956 ideally be changed to deduce the full name of file~|f|, which is the file
15957 most recently opened, if it is possible to do this.
15958 @^system dependencies@>
15959
15960 @<Declarations@>=
15961 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
15962 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
15963 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
15964
15965 @ @c 
15966 str_number mp_make_name_string (MP mp) {
15967   int k; /* index into |name_of_file| */
15968   str_room(mp->name_length);
15969   for (k=0;k<mp->name_length;k++) {
15970     append_char(xord((int)mp->name_of_file[k]));
15971   }
15972   return mp_make_string(mp);
15973 }
15974
15975 @ Now let's consider the ``driver''
15976 routines by which \MP\ deals with file names
15977 in a system-independent manner.  First comes a procedure that looks for a
15978 file name in the input by taking the information from the input buffer.
15979 (We can't use |get_next|, because the conversion to tokens would
15980 destroy necessary information.)
15981
15982 This procedure doesn't allow semicolons or percent signs to be part of
15983 file names, because of other conventions of \MP.
15984 {\sl The {\logos METAFONT\/}book} doesn't
15985 use semicolons or percents immediately after file names, but some users
15986 no doubt will find it natural to do so; therefore system-dependent
15987 changes to allow such characters in file names should probably
15988 be made with reluctance, and only when an entire file name that
15989 includes special characters is ``quoted'' somehow.
15990 @^system dependencies@>
15991
15992 @c void mp_scan_file_name (MP mp) { 
15993   mp_begin_name(mp);
15994   while ( mp->buffer[loc]==' ' ) incr(loc);
15995   while (1) { 
15996     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
15997     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
15998     incr(loc);
15999   }
16000   mp_end_name(mp);
16001 }
16002
16003 @ Here is another version that takes its input from a string.
16004
16005 @<Declare subroutines for parsing file names@>=
16006 void mp_str_scan_file (MP mp,  str_number s) {
16007   pool_pointer p,q; /* current position and stopping point */
16008   mp_begin_name(mp);
16009   p=mp->str_start[s]; q=str_stop(s);
16010   while ( p<q ){ 
16011     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16012     incr(p);
16013   }
16014   mp_end_name(mp);
16015 }
16016
16017 @ And one that reads from a |char*|.
16018
16019 @<Declare subroutines for parsing file names@>=
16020 void mp_ptr_scan_file (MP mp,  char *s) {
16021   char *p, *q; /* current position and stopping point */
16022   mp_begin_name(mp);
16023   p=s; q=p+strlen(s);
16024   while ( p<q ){ 
16025     if ( ! mp_more_name(mp, *p)) break;
16026     p++;
16027   }
16028   mp_end_name(mp);
16029 }
16030
16031
16032 @ The global variable |job_name| contains the file name that was first
16033 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16034 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16035
16036 @<Glob...@>=
16037 boolean log_opened; /* has the transcript file been opened? */
16038 char *log_name; /* full name of the log file */
16039
16040 @ @<Option variables@>=
16041 char *job_name; /* principal file name */
16042
16043 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16044 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16045 except of course for a short time just after |job_name| has become nonzero.
16046
16047 @<Allocate or ...@>=
16048 mp->job_name=mp_xstrdup(mp, opt->job_name); 
16049 mp->log_opened=false;
16050
16051 @ @<Dealloc variables@>=
16052 xfree(mp->job_name);
16053
16054 @ Here is a routine that manufactures the output file names, assuming that
16055 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16056 and |cur_ext|.
16057
16058 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16059
16060 @<Declarations@>=
16061 void mp_pack_job_name (MP mp, const char *s) ;
16062
16063 @ @c 
16064 void mp_pack_job_name (MP mp, const char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16065   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16066   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16067   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16068   pack_cur_name;
16069 }
16070
16071 @ If some trouble arises when \MP\ tries to open a file, the following
16072 routine calls upon the user to supply another file name. Parameter~|s|
16073 is used in the error message to identify the type of file; parameter~|e|
16074 is the default extension if none is given. Upon exit from the routine,
16075 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16076 ready for another attempt at file opening.
16077
16078 @<Declarations@>=
16079 void mp_prompt_file_name (MP mp, const char * s, const char * e) ;
16080
16081 @ @c void mp_prompt_file_name (MP mp, const char * s, const char * e) {
16082   size_t k; /* index into |buffer| */
16083   char * saved_cur_name;
16084   if ( mp->interaction==mp_scroll_mode ) 
16085         wake_up_terminal;
16086   if (strcmp(s,"input file name")==0) {
16087         print_err("I can\'t find file `");
16088 @.I can't find file x@>
16089   } else {
16090         print_err("I can\'t write on file `");
16091   }
16092 @.I can't write on file x@>
16093   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16094   mp_print(mp, "'.");
16095   if (strcmp(e,"")==0) 
16096         mp_show_context(mp);
16097   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16098 @.Please type...@>
16099   if ( mp->interaction<mp_scroll_mode )
16100     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16101 @.job aborted, file error...@>
16102   saved_cur_name = xstrdup(mp->cur_name);
16103   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16104   if (strcmp(mp->cur_ext,"")==0) 
16105         mp->cur_ext=xstrdup(e);
16106   if (strlen(mp->cur_name)==0) {
16107     mp->cur_name=saved_cur_name;
16108   } else {
16109     xfree(saved_cur_name);
16110   }
16111   pack_cur_name;
16112 }
16113
16114 @ @<Scan file name in the buffer@>=
16115
16116   mp_begin_name(mp); k=mp->first;
16117   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16118   while (1) { 
16119     if ( k==mp->last ) break;
16120     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16121     incr(k);
16122   }
16123   mp_end_name(mp);
16124 }
16125
16126 @ The |open_log_file| routine is used to open the transcript file and to help
16127 it catch up to what has previously been printed on the terminal.
16128
16129 @c void mp_open_log_file (MP mp) {
16130   int old_setting; /* previous |selector| setting */
16131   int k; /* index into |months| and |buffer| */
16132   int l; /* end of first input line */
16133   integer m; /* the current month */
16134   const char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16135     /* abbreviations of month names */
16136   old_setting=mp->selector;
16137   if ( mp->job_name==NULL ) {
16138      mp->job_name=xstrdup("mpout");
16139   }
16140   mp_pack_job_name(mp,".log");
16141   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16142     @<Try to get a different log file name@>;
16143   }
16144   mp->log_name=xstrdup(mp->name_of_file);
16145   mp->selector=log_only; mp->log_opened=true;
16146   @<Print the banner line, including the date and time@>;
16147   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16148     /* make sure bottom level is in memory */
16149 @.**@>
16150   if (!mp->noninteractive) {
16151     mp_print_nl(mp, "**");
16152     l=mp->input_stack[0].limit_field-1; /* last position of first line */
16153     for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16154     mp_print_ln(mp); /* now the transcript file contains the first line of input */
16155   }
16156   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16157 }
16158
16159 @ @<Dealloc variables@>=
16160 xfree(mp->log_name);
16161
16162 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16163 unable to print error messages or even to |show_context|.
16164 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16165 routine will not be invoked because |log_opened| will be false.
16166
16167 The normal idea of |mp_batch_mode| is that nothing at all should be written
16168 on the terminal. However, in the unusual case that
16169 no log file could be opened, we make an exception and allow
16170 an explanatory message to be seen.
16171
16172 Incidentally, the program always refers to the log file as a `\.{transcript
16173 file}', because some systems cannot use the extension `\.{.log}' for
16174 this file.
16175
16176 @<Try to get a different log file name@>=
16177 {  
16178   mp->selector=term_only;
16179   mp_prompt_file_name(mp, "transcript file name",".log");
16180 }
16181
16182 @ @<Print the banner...@>=
16183
16184   wlog(banner);
16185   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16186   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16187   mp_print_char(mp, ' ');
16188   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16189   for (k=3*m-3;k<3*m;k++) { wlog_chr(months[k]); }
16190   mp_print_char(mp, ' '); 
16191   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16192   mp_print_char(mp, ' ');
16193   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16194   mp_print_dd(mp, m / 60); mp_print_char(mp, ':'); mp_print_dd(mp, m % 60);
16195 }
16196
16197 @ The |try_extension| function tries to open an input file determined by
16198 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16199 can't find the file in |cur_area| or the appropriate system area.
16200
16201 @c boolean mp_try_extension (MP mp, const char *ext) { 
16202   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16203   in_name=xstrdup(mp->cur_name); 
16204   in_area=xstrdup(mp->cur_area);
16205   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16206     return true;
16207   } else { 
16208     mp_pack_file_name(mp, mp->cur_name,NULL,ext);
16209     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16210   }
16211 }
16212
16213 @ Let's turn now to the procedure that is used to initiate file reading
16214 when an `\.{input}' command is being processed.
16215
16216 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16217   char *fname = NULL;
16218   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16219   while (1) { 
16220     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16221     if ( strlen(mp->cur_ext)==0 ) {
16222       if ( mp_try_extension(mp, ".mp") ) break;
16223       else if ( mp_try_extension(mp, "") ) break;
16224       else if ( mp_try_extension(mp, ".mf") ) break;
16225       /* |else do_nothing; | */
16226     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16227       break;
16228     }
16229     mp_end_file_reading(mp); /* remove the level that didn't work */
16230     mp_prompt_file_name(mp, "input file name","");
16231   }
16232   name=mp_a_make_name_string(mp, cur_file);
16233   fname = xstrdup(mp->name_of_file);
16234   if ( mp->job_name==NULL ) {
16235     mp->job_name=xstrdup(mp->cur_name); 
16236     mp_open_log_file(mp);
16237   } /* |open_log_file| doesn't |show_context|, so |limit|
16238         and |loc| needn't be set to meaningful values yet */
16239   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16240   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
16241   mp_print_char(mp, '('); incr(mp->open_parens); mp_print(mp, fname); 
16242   xfree(fname);
16243   update_terminal;
16244   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16245   @<Read the first line of the new file@>;
16246 }
16247
16248 @ This code should be omitted if |a_make_name_string| returns something other
16249 than just a copy of its argument and the full file name is needed for opening
16250 \.{MPX} files or implementing the switch-to-editor option.
16251 @^system dependencies@>
16252
16253 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16254 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16255
16256 @ If the file is empty, it is considered to contain a single blank line,
16257 so there is no need to test the return value.
16258
16259 @<Read the first line...@>=
16260
16261   line=1;
16262   (void)mp_input_ln(mp, cur_file ); 
16263   mp_firm_up_the_line(mp);
16264   mp->buffer[limit]='%'; mp->first=limit+1; loc=start;
16265 }
16266
16267 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16268 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16269 if ( token_state ) { 
16270   print_err("File names can't appear within macros");
16271 @.File names can't...@>
16272   help3("Sorry...I've converted what follows to tokens,")
16273     ("possibly garbaging the name you gave.")
16274     ("Please delete the tokens and insert the name again.");
16275   mp_error(mp);
16276 }
16277 if ( file_state ) {
16278   mp_scan_file_name(mp);
16279 } else { 
16280    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16281    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16282    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16283 }
16284
16285 @ The following simple routine starts reading the \.{MPX} file associated
16286 with the current input file.
16287
16288 @c void mp_start_mpx_input (MP mp) {
16289   char *origname = NULL; /* a copy of nameoffile */
16290   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16291   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16292     |goto not_found| if there is a problem@>;
16293   mp_begin_file_reading(mp);
16294   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16295     mp_end_file_reading(mp);
16296     goto NOT_FOUND;
16297   }
16298   name=mp_a_make_name_string(mp, cur_file);
16299   mp->mpx_name[index]=name; add_str_ref(name);
16300   @<Read the first line of the new file@>;
16301   return;
16302 NOT_FOUND: 
16303     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16304   xfree(origname);
16305 }
16306
16307 @ This should ideally be changed to do whatever is necessary to create the
16308 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16309 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16310 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16311 completely different typesetting program if suitable postprocessor is
16312 available to perform the function of \.{DVItoMP}.)
16313 @^system dependencies@>
16314
16315 @ @<Exported types@>=
16316 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16317
16318 @ @<Option variables@>=
16319 mp_run_make_mpx_command run_make_mpx;
16320
16321 @ @<Allocate or initialize ...@>=
16322 set_callback_option(run_make_mpx);
16323
16324 @ @<Internal library declarations@>=
16325 int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16326
16327 @ The default does nothing.
16328 @c 
16329 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16330   (void)mp;
16331   (void)origname;
16332   (void)mtxname;
16333   return false;
16334 }
16335
16336 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16337   |goto not_found| if there is a problem@>=
16338 origname = mp_xstrdup(mp,mp->name_of_file);
16339 *(origname+strlen(origname)-1)=0; /* drop the x */
16340 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16341   goto NOT_FOUND 
16342
16343 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16344 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16345 mp_print_nl(mp, ">> ");
16346 mp_print(mp, origname);
16347 mp_print_nl(mp, ">> ");
16348 mp_print(mp, mp->name_of_file);
16349 mp_print_nl(mp, "! Unable to make mpx file");
16350 help4("The two files given above are one of your source files")
16351   ("and an auxiliary file I need to read to find out what your")
16352   ("btex..etex blocks mean. If you don't know why I had trouble,")
16353   ("try running it manually through MPtoTeX, TeX, and DVItoMP");
16354 succumb;
16355
16356 @ The last file-opening commands are for files accessed via the \&{readfrom}
16357 @:read_from_}{\&{readfrom} primitive@>
16358 operator and the \&{write} command.  Such files are stored in separate arrays.
16359 @:write_}{\&{write} primitive@>
16360
16361 @<Types in the outer block@>=
16362 typedef unsigned int readf_index; /* |0..max_read_files| */
16363 typedef unsigned int write_index;  /* |0..max_write_files| */
16364
16365 @ @<Glob...@>=
16366 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16367 void ** rd_file; /* \&{readfrom} files */
16368 char ** rd_fname; /* corresponding file name or 0 if file not open */
16369 readf_index read_files; /* number of valid entries in the above arrays */
16370 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16371 void ** wr_file; /* \&{write} files */
16372 char ** wr_fname; /* corresponding file name or 0 if file not open */
16373 write_index write_files; /* number of valid entries in the above arrays */
16374
16375 @ @<Allocate or initialize ...@>=
16376 mp->max_read_files=8;
16377 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16378 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16379 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16380 mp->read_files=0;
16381 mp->max_write_files=8;
16382 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16383 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16384 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16385 mp->write_files=0;
16386
16387
16388 @ This routine starts reading the file named by string~|s| without setting
16389 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16390 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16391
16392 @c boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16393   mp_ptr_scan_file(mp, s);
16394   pack_cur_name;
16395   mp_begin_file_reading(mp);
16396   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (mp_filetype_text+n)) ) 
16397         goto NOT_FOUND;
16398   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16399     (mp->close_file)(mp,mp->rd_file[n]); 
16400         goto NOT_FOUND; 
16401   }
16402   mp->rd_fname[n]=xstrdup(mp->name_of_file);
16403   return true;
16404 NOT_FOUND: 
16405   mp_end_file_reading(mp);
16406   return false;
16407 }
16408
16409 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16410
16411 @<Declarations@>=
16412 void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16413
16414 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16415   mp_ptr_scan_file(mp, s);
16416   pack_cur_name;
16417   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (mp_filetype_text+n)) )
16418     mp_prompt_file_name(mp, "file name for write output","");
16419   mp->wr_fname[n]=xstrdup(mp->name_of_file);
16420 }
16421
16422
16423 @* \[36] Introduction to the parsing routines.
16424 We come now to the central nervous system that sparks many of \MP's activities.
16425 By evaluating expressions, from their primary constituents to ever larger
16426 subexpressions, \MP\ builds the structures that ultimately define complete
16427 pictures or fonts of type.
16428
16429 Four mutually recursive subroutines are involved in this process: We call them
16430 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16431 and |scan_expression|.}$$
16432 @^recursion@>
16433 Each of them is parameterless and begins with the first token to be scanned
16434 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16435 the value of the primary or secondary or tertiary or expression that was
16436 found will appear in the global variables |cur_type| and |cur_exp|. The
16437 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16438 and |cur_sym|.
16439
16440 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16441 backup mechanisms have been added in order to provide reasonable error
16442 recovery.
16443
16444 @<Glob...@>=
16445 small_number cur_type; /* the type of the expression just found */
16446 integer cur_exp; /* the value of the expression just found */
16447
16448 @ @<Set init...@>=
16449 mp->cur_exp=0;
16450
16451 @ Many different kinds of expressions are possible, so it is wise to have
16452 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16453
16454 \smallskip\hang
16455 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16456 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16457 construction in which there was no expression before the \&{endgroup}.
16458 In this case |cur_exp| has some irrelevant value.
16459
16460 \smallskip\hang
16461 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16462 or |false_code|.
16463
16464 \smallskip\hang
16465 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16466 node that is in 
16467 a ring of equivalent booleans whose value has not yet been defined.
16468
16469 \smallskip\hang
16470 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16471 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16472 includes this particular reference.
16473
16474 \smallskip\hang
16475 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16476 node that is in
16477 a ring of equivalent strings whose value has not yet been defined.
16478
16479 \smallskip\hang
16480 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16481 else points to any of the nodes in this pen.  The pen may be polygonal or
16482 elliptical.
16483
16484 \smallskip\hang
16485 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16486 node that is in
16487 a ring of equivalent pens whose value has not yet been defined.
16488
16489 \smallskip\hang
16490 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16491 a path; nobody else points to this particular path. The control points of
16492 the path will have been chosen.
16493
16494 \smallskip\hang
16495 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16496 node that is in
16497 a ring of equivalent paths whose value has not yet been defined.
16498
16499 \smallskip\hang
16500 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16501 There may be other pointers to this particular set of edges.  The header node
16502 contains a reference count that includes this particular reference.
16503
16504 \smallskip\hang
16505 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16506 node that is in
16507 a ring of equivalent pictures whose value has not yet been defined.
16508
16509 \smallskip\hang
16510 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16511 capsule node. The |value| part of this capsule
16512 points to a transform node that contains six numeric values,
16513 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16514
16515 \smallskip\hang
16516 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16517 capsule node. The |value| part of this capsule
16518 points to a color node that contains three numeric values,
16519 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16520
16521 \smallskip\hang
16522 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16523 capsule node. The |value| part of this capsule
16524 points to a color node that contains four numeric values,
16525 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16526
16527 \smallskip\hang
16528 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16529 node whose type is |mp_pair_type|. The |value| part of this capsule
16530 points to a pair node that contains two numeric values,
16531 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16532
16533 \smallskip\hang
16534 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16535
16536 \smallskip\hang
16537 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16538 is |dependent|. The |dep_list| field in this capsule points to the associated
16539 dependency list.
16540
16541 \smallskip\hang
16542 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16543 capsule node. The |dep_list| field in this capsule
16544 points to the associated dependency list.
16545
16546 \smallskip\hang
16547 |cur_type=independent| means that |cur_exp| points to a capsule node
16548 whose type is |independent|. This somewhat unusual case can arise, for
16549 example, in the expression
16550 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16551
16552 \smallskip\hang
16553 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16554 tokens. 
16555
16556 \smallskip\noindent
16557 The possible settings of |cur_type| have been listed here in increasing
16558 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16559 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16560 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16561 |token_list|.
16562
16563 @ Capsules are two-word nodes that have a similar meaning
16564 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|,
16565 and their |type| field is one of the possibilities for |cur_type| listed above.
16566 Also |link<=void| in capsules that aren't part of a token list.
16567
16568 The |value| field of a capsule is, in most cases, the value that
16569 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16570 However, when |cur_exp| would point to a capsule,
16571 no extra layer of indirection is present; the |value|
16572 field is what would have been called |value(cur_exp)| if it had not been
16573 encapsulated.  Furthermore, if the type is |dependent| or
16574 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16575 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16576 always part of the general |dep_list| structure.
16577
16578 The |get_x_next| routine is careful not to change the values of |cur_type|
16579 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16580 call a macro, which might parse an expression, which might execute lots of
16581 commands in a group; hence it's possible that |cur_type| might change
16582 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16583 |known| or |independent|, during the time |get_x_next| is called. The
16584 programs below are careful to stash sensitive intermediate results in
16585 capsules, so that \MP's generality doesn't cause trouble.
16586
16587 Here's a procedure that illustrates these conventions. It takes
16588 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16589 and stashes them away in a
16590 capsule. It is not used when |cur_type=mp_token_list|.
16591 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16592 copy path lists or to update reference counts, etc.
16593
16594 The special link |mp_void| is put on the capsule returned by
16595 |stash_cur_exp|, because this procedure is used to store macro parameters
16596 that must be easily distinguishable from token lists.
16597
16598 @<Declare the stashing/unstashing routines@>=
16599 pointer mp_stash_cur_exp (MP mp) {
16600   pointer p; /* the capsule that will be returned */
16601   switch (mp->cur_type) {
16602   case unknown_types:
16603   case mp_transform_type:
16604   case mp_color_type:
16605   case mp_pair_type:
16606   case mp_dependent:
16607   case mp_proto_dependent:
16608   case mp_independent: 
16609   case mp_cmykcolor_type:
16610     p=mp->cur_exp;
16611     break;
16612   default: 
16613     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16614     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16615     break;
16616   }
16617   mp->cur_type=mp_vacuous; link(p)=mp_void; 
16618   return p;
16619 }
16620
16621 @ The inverse of |stash_cur_exp| is the following procedure, which
16622 deletes an unnecessary capsule and puts its contents into |cur_type|
16623 and |cur_exp|.
16624
16625 The program steps of \MP\ can be divided into two categories: those in
16626 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16627 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16628 information or not. It's important not to ignore them when they're alive,
16629 and it's important not to pay attention to them when they're dead.
16630
16631 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16632 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16633 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16634 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16635 only when they are alive or dormant.
16636
16637 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16638 are alive or dormant. The \\{unstash} procedure assumes that they are
16639 dead or dormant; it resuscitates them.
16640
16641 @<Declare the stashing/unstashing...@>=
16642 void mp_unstash_cur_exp (MP mp,pointer p) ;
16643
16644 @ @c
16645 void mp_unstash_cur_exp (MP mp,pointer p) { 
16646   mp->cur_type=type(p);
16647   switch (mp->cur_type) {
16648   case unknown_types:
16649   case mp_transform_type:
16650   case mp_color_type:
16651   case mp_pair_type:
16652   case mp_dependent: 
16653   case mp_proto_dependent:
16654   case mp_independent:
16655   case mp_cmykcolor_type: 
16656     mp->cur_exp=p;
16657     break;
16658   default:
16659     mp->cur_exp=value(p);
16660     mp_free_node(mp, p,value_node_size);
16661     break;
16662   }
16663 }
16664
16665 @ The following procedure prints the values of expressions in an
16666 abbreviated format. If its first parameter |p| is null, the value of
16667 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16668 containing the desired value. The second parameter controls the amount of
16669 output. If it is~0, dependency lists will be abbreviated to
16670 `\.{linearform}' unless they consist of a single term.  If it is greater
16671 than~1, complicated structures (pens, pictures, and paths) will be displayed
16672 in full.
16673 @.linearform@>
16674
16675 @<Declare subroutines for printing expressions@>=
16676 @<Declare the procedure called |print_dp|@>
16677 @<Declare the stashing/unstashing routines@>
16678 void mp_print_exp (MP mp,pointer p, small_number verbosity) {
16679   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16680   small_number t; /* the type of the expression */
16681   pointer q; /* a big node being displayed */
16682   integer v=0; /* the value of the expression */
16683   if ( p!=null ) {
16684     restore_cur_exp=false;
16685   } else { 
16686     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16687   }
16688   t=type(p);
16689   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16690   @<Print an abbreviated value of |v| with format depending on |t|@>;
16691   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16692 }
16693
16694 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16695 switch (t) {
16696 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16697 case mp_boolean_type:
16698   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16699   break;
16700 case unknown_types: case mp_numeric_type:
16701   @<Display a variable that's been declared but not defined@>;
16702   break;
16703 case mp_string_type:
16704   mp_print_char(mp, '"'); mp_print_str(mp, v); mp_print_char(mp, '"');
16705   break;
16706 case mp_pen_type: case mp_path_type: case mp_picture_type:
16707   @<Display a complex type@>;
16708   break;
16709 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16710   if ( v==null ) mp_print_type(mp, t);
16711   else @<Display a big node@>;
16712   break;
16713 case mp_known:mp_print_scaled(mp, v); break;
16714 case mp_dependent: case mp_proto_dependent:
16715   mp_print_dp(mp, t,v,verbosity);
16716   break;
16717 case mp_independent:mp_print_variable_name(mp, p); break;
16718 default: mp_confusion(mp, "exp"); break;
16719 @:this can't happen exp}{\quad exp@>
16720 }
16721
16722 @ @<Display a big node@>=
16723
16724   mp_print_char(mp, '('); q=v+mp->big_node_size[t];
16725   do {  
16726     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16727     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16728     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16729     v=v+2;
16730     if ( v!=q ) mp_print_char(mp, ',');
16731   } while (v!=q);
16732   mp_print_char(mp, ')');
16733 }
16734
16735 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16736 in the log file only, unless the user has given a positive value to
16737 \\{tracingonline}.
16738
16739 @<Display a complex type@>=
16740 if ( verbosity<=1 ) {
16741   mp_print_type(mp, t);
16742 } else { 
16743   if ( mp->selector==term_and_log )
16744    if ( mp->internal[mp_tracing_online]<=0 ) {
16745     mp->selector=term_only;
16746     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16747     mp->selector=term_and_log;
16748   };
16749   switch (t) {
16750   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16751   case mp_path_type:mp_print_path(mp, v,"",false); break;
16752   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16753   } /* there are no other cases */
16754 }
16755
16756 @ @<Declare the procedure called |print_dp|@>=
16757 void mp_print_dp (MP mp,small_number t, pointer p, 
16758                   small_number verbosity)  {
16759   pointer q; /* the node following |p| */
16760   q=link(p);
16761   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16762   else mp_print(mp, "linearform");
16763 }
16764
16765 @ The displayed name of a variable in a ring will not be a capsule unless
16766 the ring consists entirely of capsules.
16767
16768 @<Display a variable that's been declared but not defined@>=
16769 { mp_print_type(mp, t);
16770 if ( v!=null )
16771   { mp_print_char(mp, ' ');
16772   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16773   mp_print_variable_name(mp, v);
16774   };
16775 }
16776
16777 @ When errors are detected during parsing, it is often helpful to
16778 display an expression just above the error message, using |exp_err|
16779 or |disp_err| instead of |print_err|.
16780
16781 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16782
16783 @<Declare subroutines for printing expressions@>=
16784 void mp_disp_err (MP mp,pointer p, const char *s) { 
16785   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16786   mp_print_nl(mp, ">> ");
16787 @.>>@>
16788   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16789   if (strlen(s)) { 
16790     mp_print_nl(mp, "! "); mp_print(mp, s);
16791 @.!\relax@>
16792   }
16793 }
16794
16795 @ If |cur_type| and |cur_exp| contain relevant information that should
16796 be recycled, we will use the following procedure, which changes |cur_type|
16797 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16798 and |cur_exp| as either alive or dormant after this has been done,
16799 because |cur_exp| will not contain a pointer value.
16800
16801 @ @c void mp_flush_cur_exp (MP mp,scaled v) { 
16802   switch (mp->cur_type) {
16803   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16804   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16805     mp_recycle_value(mp, mp->cur_exp); 
16806     mp_free_node(mp, mp->cur_exp,value_node_size);
16807     break;
16808   case mp_string_type:
16809     delete_str_ref(mp->cur_exp); break;
16810   case mp_pen_type: case mp_path_type: 
16811     mp_toss_knot_list(mp, mp->cur_exp); break;
16812   case mp_picture_type:
16813     delete_edge_ref(mp->cur_exp); break;
16814   default: 
16815     break;
16816   }
16817   mp->cur_type=mp_known; mp->cur_exp=v;
16818 }
16819
16820 @ There's a much more general procedure that is capable of releasing
16821 the storage associated with any two-word value packet.
16822
16823 @<Declare the recycling subroutines@>=
16824 void mp_recycle_value (MP mp,pointer p) ;
16825
16826 @ @c void mp_recycle_value (MP mp,pointer p) {
16827   small_number t; /* a type code */
16828   integer vv; /* another value */
16829   pointer q,r,s,pp; /* link manipulation registers */
16830   integer v=0; /* a value */
16831   t=type(p);
16832   if ( t<mp_dependent ) v=value(p);
16833   switch (t) {
16834   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16835   case mp_numeric_type:
16836     break;
16837   case unknown_types:
16838     mp_ring_delete(mp, p); break;
16839   case mp_string_type:
16840     delete_str_ref(v); break;
16841   case mp_path_type: case mp_pen_type:
16842     mp_toss_knot_list(mp, v); break;
16843   case mp_picture_type:
16844     delete_edge_ref(v); break;
16845   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
16846   case mp_transform_type:
16847     @<Recycle a big node@>; break; 
16848   case mp_dependent: case mp_proto_dependent:
16849     @<Recycle a dependency list@>; break;
16850   case mp_independent:
16851     @<Recycle an independent variable@>; break;
16852   case mp_token_list: case mp_structured:
16853     mp_confusion(mp, "recycle"); break;
16854 @:this can't happen recycle}{\quad recycle@>
16855   case mp_unsuffixed_macro: case mp_suffixed_macro:
16856     mp_delete_mac_ref(mp, value(p)); break;
16857   } /* there are no other cases */
16858   type(p)=undefined;
16859 }
16860
16861 @ @<Recycle a big node@>=
16862 if ( v!=null ){ 
16863   q=v+mp->big_node_size[t];
16864   do {  
16865     q=q-2; mp_recycle_value(mp, q);
16866   } while (q!=v);
16867   mp_free_node(mp, v,mp->big_node_size[t]);
16868 }
16869
16870 @ @<Recycle a dependency list@>=
16871
16872   q=dep_list(p);
16873   while ( info(q)!=null ) q=link(q);
16874   link(prev_dep(p))=link(q);
16875   prev_dep(link(q))=prev_dep(p);
16876   link(q)=null; mp_flush_node_list(mp, dep_list(p));
16877 }
16878
16879 @ When an independent variable disappears, it simply fades away, unless
16880 something depends on it. In the latter case, a dependent variable whose
16881 coefficient of dependence is maximal will take its place.
16882 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
16883 as part of his Ph.D. thesis (Stanford University, December 1982).
16884 @^Zabala Salelles, Ignacio Andr\'es@>
16885
16886 For example, suppose that variable $x$ is being recycled, and that the
16887 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
16888 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
16889 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
16890 we will print `\.{\#\#\# -2x=-y+a}'.
16891
16892 There's a slight complication, however: An independent variable $x$
16893 can occur both in dependency lists and in proto-dependency lists.
16894 This makes it necessary to be careful when deciding which coefficient
16895 is maximal.
16896
16897 Furthermore, this complication is not so slight when
16898 a proto-dependent variable is chosen to become independent. For example,
16899 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
16900 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
16901 large coefficient `50'.
16902
16903 In order to deal with these complications without wasting too much time,
16904 we shall link together the occurrences of~$x$ among all the linear
16905 dependencies, maintaining separate lists for the dependent and
16906 proto-dependent cases.
16907
16908 @<Recycle an independent variable@>=
16909
16910   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
16911   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
16912   q=link(dep_head);
16913   while ( q!=dep_head ) { 
16914     s=value_loc(q); /* now |link(s)=dep_list(q)| */
16915     while (1) { 
16916       r=link(s);
16917       if ( info(r)==null ) break;
16918       if ( info(r)!=p ) { 
16919         s=r;
16920       } else  { 
16921         t=type(q); link(s)=link(r); info(r)=q;
16922         if ( abs(value(r))>mp->max_c[t] ) {
16923           @<Record a new maximum coefficient of type |t|@>;
16924         } else { 
16925           link(r)=mp->max_link[t]; mp->max_link[t]=r;
16926         }
16927       }
16928     } 
16929     q=link(r);
16930   }
16931   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
16932     @<Choose a dependent variable to take the place of the disappearing
16933     independent variable, and change all remaining dependencies
16934     accordingly@>;
16935   }
16936 }
16937
16938 @ The code for independency removal makes use of three two-word arrays.
16939
16940 @<Glob...@>=
16941 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
16942 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
16943 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
16944
16945 @ @<Record a new maximum coefficient...@>=
16946
16947   if ( mp->max_c[t]>0 ) {
16948     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16949   }
16950   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
16951 }
16952
16953 @ @<Choose a dependent...@>=
16954
16955   if ( (mp->max_c[mp_dependent] / 010000) >= mp->max_c[mp_proto_dependent] )
16956     t=mp_dependent;
16957   else 
16958     t=mp_proto_dependent;
16959   @<Determine the dependency list |s| to substitute for the independent
16960     variable~|p|@>;
16961   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
16962   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
16963     link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
16964   }
16965   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
16966   else { @<Substitute new proto-dependencies in place of |p|@>;}
16967   mp_flush_node_list(mp, s);
16968   if ( mp->fix_needed ) mp_fix_dependencies(mp);
16969   check_arith;
16970 }
16971
16972 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
16973 and |info(s)| points to the dependent variable~|pp| of type~|t| from
16974 whose dependency list we have removed node~|s|. We must reinsert
16975 node~|s| into the dependency list, with coefficient $-1.0$, and with
16976 |pp| as the new independent variable. Since |pp| will have a larger serial
16977 number than any other variable, we can put node |s| at the head of the
16978 list.
16979
16980 @<Determine the dep...@>=
16981 s=mp->max_ptr[t]; pp=info(s); v=value(s);
16982 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
16983 r=dep_list(pp); link(s)=r;
16984 while ( info(r)!=null ) r=link(r);
16985 q=link(r); link(r)=null;
16986 prev_dep(q)=prev_dep(pp); link(prev_dep(pp))=q;
16987 new_indep(pp);
16988 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
16989 if ( mp->internal[mp_tracing_equations]>0 ) { 
16990   @<Show the transformed dependency@>; 
16991 }
16992
16993 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
16994 by the dependency list~|s|.
16995
16996 @<Show the transformed...@>=
16997 if ( mp_interesting(mp, p) ) {
16998   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
16999 @:]]]\#\#\#_}{\.{\#\#\#}@>
17000   if ( v>0 ) mp_print_char(mp, '-');
17001   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17002   else vv=mp->max_c[mp_proto_dependent];
17003   if ( vv!=unity ) mp_print_scaled(mp, vv);
17004   mp_print_variable_name(mp, p);
17005   while ( value(p) % s_scale>0 ) {
17006     mp_print(mp, "*4"); value(p)=value(p)-2;
17007   }
17008   if ( t==mp_dependent ) mp_print_char(mp, '='); else mp_print(mp, " = ");
17009   mp_print_dependency(mp, s,t);
17010   mp_end_diagnostic(mp, false);
17011 }
17012
17013 @ Finally, there are dependent and proto-dependent variables whose
17014 dependency lists must be brought up to date.
17015
17016 @<Substitute new dependencies...@>=
17017 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17018   r=mp->max_link[t];
17019   while ( r!=null ) {
17020     q=info(r);
17021     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17022      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17023     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17024     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17025   }
17026 }
17027
17028 @ @<Substitute new proto...@>=
17029 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17030   r=mp->max_link[t];
17031   while ( r!=null ) {
17032     q=info(r);
17033     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17034       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17035         mp->cur_type=mp_proto_dependent;
17036       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,
17037          mp_dependent,mp_proto_dependent);
17038       type(q)=mp_proto_dependent; 
17039       value(r)=mp_round_fraction(mp, value(r));
17040     }
17041     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17042        mp_make_scaled(mp, value(r),-v),s,
17043        mp_proto_dependent,mp_proto_dependent);
17044     if ( dep_list(q)==mp->dep_final ) 
17045        mp_make_known(mp, q,mp->dep_final);
17046     q=r; r=link(r); mp_free_node(mp, q,dep_node_size);
17047   }
17048 }
17049
17050 @ Here are some routines that provide handy combinations of actions
17051 that are often needed during error recovery. For example,
17052 `|flush_error|' flushes the current expression, replaces it by
17053 a given value, and calls |error|.
17054
17055 Errors often are detected after an extra token has already been scanned.
17056 The `\\{put\_get}' routines put that token back before calling |error|;
17057 then they get it back again. (Or perhaps they get another token, if
17058 the user has changed things.)
17059
17060 @<Declarations@>=
17061 void mp_flush_error (MP mp,scaled v);
17062 void mp_put_get_error (MP mp);
17063 void mp_put_get_flush_error (MP mp,scaled v) ;
17064
17065 @ @c
17066 void mp_flush_error (MP mp,scaled v) { 
17067   mp_error(mp); mp_flush_cur_exp(mp, v); 
17068 }
17069 void mp_put_get_error (MP mp) { 
17070   mp_back_error(mp); mp_get_x_next(mp); 
17071 }
17072 void mp_put_get_flush_error (MP mp,scaled v) { 
17073   mp_put_get_error(mp);
17074   mp_flush_cur_exp(mp, v); 
17075 }
17076
17077 @ A global variable |var_flag| is set to a special command code
17078 just before \MP\ calls |scan_expression|, if the expression should be
17079 treated as a variable when this command code immediately follows. For
17080 example, |var_flag| is set to |assignment| at the beginning of a
17081 statement, because we want to know the {\sl location\/} of a variable at
17082 the left of `\.{:=}', not the {\sl value\/} of that variable.
17083
17084 The |scan_expression| subroutine calls |scan_tertiary|,
17085 which calls |scan_secondary|, which calls |scan_primary|, which sets
17086 |var_flag:=0|. In this way each of the scanning routines ``knows''
17087 when it has been called with a special |var_flag|, but |var_flag| is
17088 usually zero.
17089
17090 A variable preceding a command that equals |var_flag| is converted to a
17091 token list rather than a value. Furthermore, an `\.{=}' sign following an
17092 expression with |var_flag=assignment| is not considered to be a relation
17093 that produces boolean expressions.
17094
17095
17096 @<Glob...@>=
17097 int var_flag; /* command that wants a variable */
17098
17099 @ @<Set init...@>=
17100 mp->var_flag=0;
17101
17102 @* \[37] Parsing primary expressions.
17103 The first parsing routine, |scan_primary|, is also the most complicated one,
17104 since it involves so many different cases. But each case---with one
17105 exception---is fairly simple by itself.
17106
17107 When |scan_primary| begins, the first token of the primary to be scanned
17108 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17109 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17110 earlier. If |cur_cmd| is not between |min_primary_command| and
17111 |max_primary_command|, inclusive, a syntax error will be signaled.
17112
17113 @<Declare the basic parsing subroutines@>=
17114 void mp_scan_primary (MP mp) {
17115   pointer p,q,r; /* for list manipulation */
17116   quarterword c; /* a primitive operation code */
17117   int my_var_flag; /* initial value of |my_var_flag| */
17118   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17119   @<Other local variables for |scan_primary|@>;
17120   my_var_flag=mp->var_flag; mp->var_flag=0;
17121 RESTART:
17122   check_arith;
17123   @<Supply diagnostic information, if requested@>;
17124   switch (mp->cur_cmd) {
17125   case left_delimiter:
17126     @<Scan a delimited primary@>; break;
17127   case begin_group:
17128     @<Scan a grouped primary@>; break;
17129   case string_token:
17130     @<Scan a string constant@>; break;
17131   case numeric_token:
17132     @<Scan a primary that starts with a numeric token@>; break;
17133   case nullary:
17134     @<Scan a nullary operation@>; break;
17135   case unary: case type_name: case cycle: case plus_or_minus:
17136     @<Scan a unary operation@>; break;
17137   case primary_binary:
17138     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17139   case str_op:
17140     @<Convert a suffix to a string@>; break;
17141   case internal_quantity:
17142     @<Scan an internal numeric quantity@>; break;
17143   case capsule_token:
17144     mp_make_exp_copy(mp, mp->cur_mod); break;
17145   case tag_token:
17146     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17147   default: 
17148     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17149 @.A primary expression...@>
17150   }
17151   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17152 DONE: 
17153   if ( mp->cur_cmd==left_bracket ) {
17154     if ( mp->cur_type>=mp_known ) {
17155       @<Scan a mediation construction@>;
17156     }
17157   }
17158 }
17159
17160
17161
17162 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17163
17164 @c void mp_bad_exp (MP mp, const char * s) {
17165   int save_flag;
17166   print_err(s); mp_print(mp, " expression can't begin with `");
17167   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17168   mp_print_char(mp, '\'');
17169   help4("I'm afraid I need some sort of value in order to continue,")
17170     ("so I've tentatively inserted `0'. You may want to")
17171     ("delete this zero and insert something else;")
17172     ("see Chapter 27 of The METAFONTbook for an example.");
17173 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17174   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17175   mp->cur_mod=0; mp_ins_error(mp);
17176   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17177   mp->var_flag=save_flag;
17178 }
17179
17180 @ @<Supply diagnostic information, if requested@>=
17181 #ifdef DEBUG
17182 if ( mp->panicking ) mp_check_mem(mp, false);
17183 #endif
17184 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17185   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17186 }
17187
17188 @ @<Scan a delimited primary@>=
17189
17190   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17191   mp_get_x_next(mp); mp_scan_expression(mp);
17192   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17193     @<Scan the rest of a delimited set of numerics@>;
17194   } else {
17195     mp_check_delimiter(mp, l_delim,r_delim);
17196   }
17197 }
17198
17199 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17200 within a ``big node.''
17201
17202 @c void mp_stash_in (MP mp,pointer p) {
17203   pointer q; /* temporary register */
17204   type(p)=mp->cur_type;
17205   if ( mp->cur_type==mp_known ) {
17206     value(p)=mp->cur_exp;
17207   } else { 
17208     if ( mp->cur_type==mp_independent ) {
17209       @<Stash an independent |cur_exp| into a big node@>;
17210     } else { 
17211       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17212       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17213       link(prev_dep(p))=p;
17214     }
17215     mp_free_node(mp, mp->cur_exp,value_node_size);
17216   }
17217   mp->cur_type=mp_vacuous;
17218 }
17219
17220 @ In rare cases the current expression can become |independent|. There
17221 may be many dependency lists pointing to such an independent capsule,
17222 so we can't simply move it into place within a big node. Instead,
17223 we copy it, then recycle it.
17224
17225 @ @<Stash an independent |cur_exp|...@>=
17226
17227   q=mp_single_dependency(mp, mp->cur_exp);
17228   if ( q==mp->dep_final ){ 
17229     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17230   } else { 
17231     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17232   }
17233   mp_recycle_value(mp, mp->cur_exp);
17234 }
17235
17236 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17237 are synonymous with |x_part_loc| and |y_part_loc|.
17238
17239 @<Scan the rest of a delimited set of numerics@>=
17240
17241 p=mp_stash_cur_exp(mp);
17242 mp_get_x_next(mp); mp_scan_expression(mp);
17243 @<Make sure the second part of a pair or color has a numeric type@>;
17244 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17245 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17246 else type(q)=mp_pair_type;
17247 mp_init_big_node(mp, q); r=value(q);
17248 mp_stash_in(mp, y_part_loc(r));
17249 mp_unstash_cur_exp(mp, p);
17250 mp_stash_in(mp, x_part_loc(r));
17251 if ( mp->cur_cmd==comma ) {
17252   @<Scan the last of a triplet of numerics@>;
17253 }
17254 if ( mp->cur_cmd==comma ) {
17255   type(q)=mp_cmykcolor_type;
17256   mp_init_big_node(mp, q); t=value(q);
17257   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17258   value(cyan_part_loc(t))=value(red_part_loc(r));
17259   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17260   value(magenta_part_loc(t))=value(green_part_loc(r));
17261   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17262   value(yellow_part_loc(t))=value(blue_part_loc(r));
17263   mp_recycle_value(mp, r);
17264   r=t;
17265   @<Scan the last of a quartet of numerics@>;
17266 }
17267 mp_check_delimiter(mp, l_delim,r_delim);
17268 mp->cur_type=type(q);
17269 mp->cur_exp=q;
17270 }
17271
17272 @ @<Make sure the second part of a pair or color has a numeric type@>=
17273 if ( mp->cur_type<mp_known ) {
17274   exp_err("Nonnumeric ypart has been replaced by 0");
17275 @.Nonnumeric...replaced by 0@>
17276   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';")
17277     ("but after finding a nice `a' I found a `b' that isn't")
17278     ("of numeric type. So I've changed that part to zero.")
17279     ("(The b that I didn't like appears above the error message.)");
17280   mp_put_get_flush_error(mp, 0);
17281 }
17282
17283 @ @<Scan the last of a triplet of numerics@>=
17284
17285   mp_get_x_next(mp); mp_scan_expression(mp);
17286   if ( mp->cur_type<mp_known ) {
17287     exp_err("Nonnumeric third part has been replaced by 0");
17288 @.Nonnumeric...replaced by 0@>
17289     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'")
17290       ("isn't of numeric type. So I've changed that part to zero.")
17291       ("(The c that I didn't like appears above the error message.)");
17292     mp_put_get_flush_error(mp, 0);
17293   }
17294   mp_stash_in(mp, blue_part_loc(r));
17295 }
17296
17297 @ @<Scan the last of a quartet of numerics@>=
17298
17299   mp_get_x_next(mp); mp_scan_expression(mp);
17300   if ( mp->cur_type<mp_known ) {
17301     exp_err("Nonnumeric blackpart has been replaced by 0");
17302 @.Nonnumeric...replaced by 0@>
17303     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't")
17304       ("of numeric type. So I've changed that part to zero.")
17305       ("(The k that I didn't like appears above the error message.)");
17306     mp_put_get_flush_error(mp, 0);
17307   }
17308   mp_stash_in(mp, black_part_loc(r));
17309 }
17310
17311 @ The local variable |group_line| keeps track of the line
17312 where a \&{begingroup} command occurred; this will be useful
17313 in an error message if the group doesn't actually end.
17314
17315 @<Other local variables for |scan_primary|@>=
17316 integer group_line; /* where a group began */
17317
17318 @ @<Scan a grouped primary@>=
17319
17320   group_line=mp_true_line(mp);
17321   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17322   save_boundary_item(p);
17323   do {  
17324     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17325   } while (mp->cur_cmd==semicolon);
17326   if ( mp->cur_cmd!=end_group ) {
17327     print_err("A group begun on line ");
17328 @.A group...never ended@>
17329     mp_print_int(mp, group_line);
17330     mp_print(mp, " never ended");
17331     help2("I saw a `begingroup' back there that hasn't been matched")
17332          ("by `endgroup'. So I've inserted `endgroup' now.");
17333     mp_back_error(mp); mp->cur_cmd=end_group;
17334   }
17335   mp_unsave(mp); 
17336     /* this might change |cur_type|, if independent variables are recycled */
17337   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17338 }
17339
17340 @ @<Scan a string constant@>=
17341
17342   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17343 }
17344
17345 @ Later we'll come to procedures that perform actual operations like
17346 addition, square root, and so on; our purpose now is to do the parsing.
17347 But we might as well mention those future procedures now, so that the
17348 suspense won't be too bad:
17349
17350 \smallskip
17351 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17352 `\&{true}' or `\&{pencircle}');
17353
17354 \smallskip
17355 |do_unary(c)| applies a primitive operation to the current expression;
17356
17357 \smallskip
17358 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17359 and the current expression.
17360
17361 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17362
17363 @ @<Scan a unary operation@>=
17364
17365   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17366   mp_do_unary(mp, c); goto DONE;
17367 }
17368
17369 @ A numeric token might be a primary by itself, or it might be the
17370 numerator of a fraction composed solely of numeric tokens, or it might
17371 multiply the primary that follows (provided that the primary doesn't begin
17372 with a plus sign or a minus sign). The code here uses the facts that
17373 |max_primary_command=plus_or_minus| and
17374 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17375 than unity, we try to retain higher precision when we use it in scalar
17376 multiplication.
17377
17378 @<Other local variables for |scan_primary|@>=
17379 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17380
17381 @ @<Scan a primary that starts with a numeric token@>=
17382
17383   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17384   if ( mp->cur_cmd!=slash ) { 
17385     num=0; denom=0;
17386   } else { 
17387     mp_get_x_next(mp);
17388     if ( mp->cur_cmd!=numeric_token ) { 
17389       mp_back_input(mp);
17390       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17391       goto DONE;
17392     }
17393     num=mp->cur_exp; denom=mp->cur_mod;
17394     if ( denom==0 ) { @<Protest division by zero@>; }
17395     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17396     check_arith; mp_get_x_next(mp);
17397   }
17398   if ( mp->cur_cmd>=min_primary_command ) {
17399    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17400      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17401      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17402        mp_do_binary(mp, p,times);
17403      } else {
17404        mp_frac_mult(mp, num,denom);
17405        mp_free_node(mp, p,value_node_size);
17406      }
17407     }
17408   }
17409   goto DONE;
17410 }
17411
17412 @ @<Protest division...@>=
17413
17414   print_err("Division by zero");
17415 @.Division by zero@>
17416   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17417 }
17418
17419 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17420
17421   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17422   if ( mp->cur_cmd!=of_token ) {
17423     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17424     mp_print_cmd_mod(mp, primary_binary,c);
17425 @.Missing `of'@>
17426     help1("I've got the first argument; will look now for the other.");
17427     mp_back_error(mp);
17428   }
17429   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17430   mp_do_binary(mp, p,c); goto DONE;
17431 }
17432
17433 @ @<Convert a suffix to a string@>=
17434
17435   mp_get_x_next(mp); mp_scan_suffix(mp); 
17436   mp->old_setting=mp->selector; mp->selector=new_string;
17437   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17438   mp_flush_token_list(mp, mp->cur_exp);
17439   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17440   mp->cur_type=mp_string_type;
17441   goto DONE;
17442 }
17443
17444 @ If an internal quantity appears all by itself on the left of an
17445 assignment, we return a token list of length one, containing the address
17446 of the internal quantity plus |hash_end|. (This accords with the conventions
17447 of the save stack, as described earlier.)
17448
17449 @<Scan an internal...@>=
17450
17451   q=mp->cur_mod;
17452   if ( my_var_flag==assignment ) {
17453     mp_get_x_next(mp);
17454     if ( mp->cur_cmd==assignment ) {
17455       mp->cur_exp=mp_get_avail(mp);
17456       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17457       goto DONE;
17458     }
17459     mp_back_input(mp);
17460   }
17461   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17462 }
17463
17464 @ The most difficult part of |scan_primary| has been saved for last, since
17465 it was necessary to build up some confidence first. We can now face the task
17466 of scanning a variable.
17467
17468 As we scan a variable, we build a token list containing the relevant
17469 names and subscript values, simultaneously following along in the
17470 ``collective'' structure to see if we are actually dealing with a macro
17471 instead of a value.
17472
17473 The local variables |pre_head| and |post_head| will point to the beginning
17474 of the prefix and suffix lists; |tail| will point to the end of the list
17475 that is currently growing.
17476
17477 Another local variable, |tt|, contains partial information about the
17478 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17479 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17480 doesn't bother to update its information about type. And if
17481 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17482
17483 @ @<Other local variables for |scan_primary|@>=
17484 pointer pre_head,post_head,tail;
17485   /* prefix and suffix list variables */
17486 small_number tt; /* approximation to the type of the variable-so-far */
17487 pointer t; /* a token */
17488 pointer macro_ref = 0; /* reference count for a suffixed macro */
17489
17490 @ @<Scan a variable primary...@>=
17491
17492   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17493   while (1) { 
17494     t=mp_cur_tok(mp); link(tail)=t;
17495     if ( tt!=undefined ) {
17496        @<Find the approximate type |tt| and corresponding~|q|@>;
17497       if ( tt>=mp_unsuffixed_macro ) {
17498         @<Either begin an unsuffixed macro call or
17499           prepare for a suffixed one@>;
17500       }
17501     }
17502     mp_get_x_next(mp); tail=t;
17503     if ( mp->cur_cmd==left_bracket ) {
17504       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17505     }
17506     if ( mp->cur_cmd>max_suffix_token ) break;
17507     if ( mp->cur_cmd<min_suffix_token ) break;
17508   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17509   @<Handle unusual cases that masquerade as variables, and |goto restart|
17510     or |goto done| if appropriate;
17511     otherwise make a copy of the variable and |goto done|@>;
17512 }
17513
17514 @ @<Either begin an unsuffixed macro call or...@>=
17515
17516   link(tail)=null;
17517   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17518     post_head=mp_get_avail(mp); tail=post_head; link(tail)=t;
17519     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17520   } else {
17521     @<Set up unsuffixed macro call and |goto restart|@>;
17522   }
17523 }
17524
17525 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17526
17527   mp_get_x_next(mp); mp_scan_expression(mp);
17528   if ( mp->cur_cmd!=right_bracket ) {
17529     @<Put the left bracket and the expression back to be rescanned@>;
17530   } else { 
17531     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17532     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17533   }
17534 }
17535
17536 @ The left bracket that we thought was introducing a subscript might have
17537 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17538 So we don't issue an error message at this point; but we do want to back up
17539 so as to avoid any embarrassment about our incorrect assumption.
17540
17541 @<Put the left bracket and the expression back to be rescanned@>=
17542
17543   mp_back_input(mp); /* that was the token following the current expression */
17544   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17545   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17546 }
17547
17548 @ Here's a routine that puts the current expression back to be read again.
17549
17550 @c void mp_back_expr (MP mp) {
17551   pointer p; /* capsule token */
17552   p=mp_stash_cur_exp(mp); link(p)=null; back_list(p);
17553 }
17554
17555 @ Unknown subscripts lead to the following error message.
17556
17557 @c void mp_bad_subscript (MP mp) { 
17558   exp_err("Improper subscript has been replaced by zero");
17559 @.Improper subscript...@>
17560   help3("A bracketed subscript must have a known numeric value;")
17561     ("unfortunately, what I found was the value that appears just")
17562     ("above this error message. So I'll try a zero subscript.");
17563   mp_flush_error(mp, 0);
17564 }
17565
17566 @ Every time we call |get_x_next|, there's a chance that the variable we've
17567 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17568 into the variable structure; we need to start searching from the root each time.
17569
17570 @<Find the approximate type |tt| and corresponding~|q|@>=
17571 @^inner loop@>
17572
17573   p=link(pre_head); q=info(p); tt=undefined;
17574   if ( eq_type(q) % outer_tag==tag_token ) {
17575     q=equiv(q);
17576     if ( q==null ) goto DONE2;
17577     while (1) { 
17578       p=link(p);
17579       if ( p==null ) {
17580         tt=type(q); goto DONE2;
17581       };
17582       if ( type(q)!=mp_structured ) goto DONE2;
17583       q=link(attr_head(q)); /* the |collective_subscript| attribute */
17584       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17585         do {  q=link(q); } while (! (attr_loc(q)>=info(p)));
17586         if ( attr_loc(q)>info(p) ) goto DONE2;
17587       }
17588     }
17589   }
17590 DONE2:
17591   ;
17592 }
17593
17594 @ How do things stand now? Well, we have scanned an entire variable name,
17595 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17596 |cur_sym| represent the token that follows. If |post_head=null|, a
17597 token list for this variable name starts at |link(pre_head)|, with all
17598 subscripts evaluated. But if |post_head<>null|, the variable turned out
17599 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17600 |post_head| is the head of a token list containing both `\.{\AT!}' and
17601 the suffix.
17602
17603 Our immediate problem is to see if this variable still exists. (Variable
17604 structures can change drastically whenever we call |get_x_next|; users
17605 aren't supposed to do this, but the fact that it is possible means that
17606 we must be cautious.)
17607
17608 The following procedure prints an error message when a variable
17609 unexpectedly disappears. Its help message isn't quite right for
17610 our present purposes, but we'll be able to fix that up.
17611
17612 @c 
17613 void mp_obliterated (MP mp,pointer q) { 
17614   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17615   mp_print(mp, " has been obliterated");
17616 @.Variable...obliterated@>
17617   help5("It seems you did a nasty thing---probably by accident,")
17618     ("but nevertheless you nearly hornswoggled me...")
17619     ("While I was evaluating the right-hand side of this")
17620     ("command, something happened, and the left-hand side")
17621     ("is no longer a variable! So I won't change anything.");
17622 }
17623
17624 @ If the variable does exist, we also need to check
17625 for a few other special cases before deciding that a plain old ordinary
17626 variable has, indeed, been scanned.
17627
17628 @<Handle unusual cases that masquerade as variables...@>=
17629 if ( post_head!=null ) {
17630   @<Set up suffixed macro call and |goto restart|@>;
17631 }
17632 q=link(pre_head); free_avail(pre_head);
17633 if ( mp->cur_cmd==my_var_flag ) { 
17634   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17635 }
17636 p=mp_find_variable(mp, q);
17637 if ( p!=null ) {
17638   mp_make_exp_copy(mp, p);
17639 } else { 
17640   mp_obliterated(mp, q);
17641   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17642   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17643   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17644   mp_put_get_flush_error(mp, 0);
17645 }
17646 mp_flush_node_list(mp, q); 
17647 goto DONE
17648
17649 @ The only complication associated with macro calling is that the prefix
17650 and ``at'' parameters must be packaged in an appropriate list of lists.
17651
17652 @<Set up unsuffixed macro call and |goto restart|@>=
17653
17654   p=mp_get_avail(mp); info(pre_head)=link(pre_head); link(pre_head)=p;
17655   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17656   mp_get_x_next(mp); 
17657   goto RESTART;
17658 }
17659
17660 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17661 we don't care, because we have reserved a pointer (|macro_ref|) to its
17662 token list.
17663
17664 @<Set up suffixed macro call and |goto restart|@>=
17665
17666   mp_back_input(mp); p=mp_get_avail(mp); q=link(post_head);
17667   info(pre_head)=link(pre_head); link(pre_head)=post_head;
17668   info(post_head)=q; link(post_head)=p; info(p)=link(q); link(q)=null;
17669   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17670   mp_get_x_next(mp); goto RESTART;
17671 }
17672
17673 @ Our remaining job is simply to make a copy of the value that has been
17674 found. Some cases are harder than others, but complexity arises solely
17675 because of the multiplicity of possible cases.
17676
17677 @<Declare the procedure called |make_exp_copy|@>=
17678 @<Declare subroutines needed by |make_exp_copy|@>
17679 void mp_make_exp_copy (MP mp,pointer p) {
17680   pointer q,r,t; /* registers for list manipulation */
17681 RESTART: 
17682   mp->cur_type=type(p);
17683   switch (mp->cur_type) {
17684   case mp_vacuous: case mp_boolean_type: case mp_known:
17685     mp->cur_exp=value(p); break;
17686   case unknown_types:
17687     mp->cur_exp=mp_new_ring_entry(mp, p);
17688     break;
17689   case mp_string_type: 
17690     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17691     break;
17692   case mp_picture_type:
17693     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17694     break;
17695   case mp_pen_type:
17696     mp->cur_exp=copy_pen(value(p));
17697     break; 
17698   case mp_path_type:
17699     mp->cur_exp=mp_copy_path(mp, value(p));
17700     break;
17701   case mp_transform_type: case mp_color_type: 
17702   case mp_cmykcolor_type: case mp_pair_type:
17703     @<Copy the big node |p|@>;
17704     break;
17705   case mp_dependent: case mp_proto_dependent:
17706     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17707     break;
17708   case mp_numeric_type: 
17709     new_indep(p); goto RESTART;
17710     break;
17711   case mp_independent: 
17712     q=mp_single_dependency(mp, p);
17713     if ( q==mp->dep_final ){ 
17714       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,dep_node_size);
17715     } else { 
17716       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17717     }
17718     break;
17719   default: 
17720     mp_confusion(mp, "copy");
17721 @:this can't happen copy}{\quad copy@>
17722     break;
17723   }
17724 }
17725
17726 @ The |encapsulate| subroutine assumes that |dep_final| is the
17727 tail of dependency list~|p|.
17728
17729 @<Declare subroutines needed by |make_exp_copy|@>=
17730 void mp_encapsulate (MP mp,pointer p) { 
17731   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17732   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17733 }
17734
17735 @ The most tedious case arises when the user refers to a
17736 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17737 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17738 or |known|.
17739
17740 @<Copy the big node |p|@>=
17741
17742   if ( value(p)==null ) 
17743     mp_init_big_node(mp, p);
17744   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17745   mp_init_big_node(mp, t);
17746   q=value(p)+mp->big_node_size[mp->cur_type]; 
17747   r=value(t)+mp->big_node_size[mp->cur_type];
17748   do {  
17749     q=q-2; r=r-2; mp_install(mp, r,q);
17750   } while (q!=value(p));
17751   mp->cur_exp=t;
17752 }
17753
17754 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17755 a big node that will be part of a capsule.
17756
17757 @<Declare subroutines needed by |make_exp_copy|@>=
17758 void mp_install (MP mp,pointer r, pointer q) {
17759   pointer p; /* temporary register */
17760   if ( type(q)==mp_known ){ 
17761     value(r)=value(q); type(r)=mp_known;
17762   } else  if ( type(q)==mp_independent ) {
17763     p=mp_single_dependency(mp, q);
17764     if ( p==mp->dep_final ) {
17765       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,dep_node_size);
17766     } else  { 
17767       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17768     }
17769   } else {
17770     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17771   }
17772 }
17773
17774 @ Expressions of the form `\.{a[b,c]}' are converted into
17775 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17776 provided that \.a is numeric.
17777
17778 @<Scan a mediation...@>=
17779
17780   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17781   if ( mp->cur_cmd!=comma ) {
17782     @<Put the left bracket and the expression back...@>;
17783     mp_unstash_cur_exp(mp, p);
17784   } else { 
17785     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17786     if ( mp->cur_cmd!=right_bracket ) {
17787       mp_missing_err(mp, "]");
17788 @.Missing `]'@>
17789       help3("I've scanned an expression of the form `a[b,c',")
17790       ("so a right bracket should have come next.")
17791       ("I shall pretend that one was there.");
17792       mp_back_error(mp);
17793     }
17794     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17795     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17796     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17797   }
17798 }
17799
17800 @ Here is a comparatively simple routine that is used to scan the
17801 \&{suffix} parameters of a macro.
17802
17803 @<Declare the basic parsing subroutines@>=
17804 void mp_scan_suffix (MP mp) {
17805   pointer h,t; /* head and tail of the list being built */
17806   pointer p; /* temporary register */
17807   h=mp_get_avail(mp); t=h;
17808   while (1) { 
17809     if ( mp->cur_cmd==left_bracket ) {
17810       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17811     }
17812     if ( mp->cur_cmd==numeric_token ) {
17813       p=mp_new_num_tok(mp, mp->cur_mod);
17814     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17815        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17816     } else {
17817       break;
17818     }
17819     link(t)=p; t=p; mp_get_x_next(mp);
17820   }
17821   mp->cur_exp=link(h); free_avail(h); mp->cur_type=mp_token_list;
17822 }
17823
17824 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17825
17826   mp_get_x_next(mp); mp_scan_expression(mp);
17827   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17828   if ( mp->cur_cmd!=right_bracket ) {
17829      mp_missing_err(mp, "]");
17830 @.Missing `]'@>
17831     help3("I've seen a `[' and a subscript value, in a suffix,")
17832       ("so a right bracket should have come next.")
17833       ("I shall pretend that one was there.");
17834     mp_back_error(mp);
17835   }
17836   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
17837 }
17838
17839 @* \[38] Parsing secondary and higher expressions.
17840
17841 After the intricacies of |scan_primary|\kern-1pt,
17842 the |scan_secondary| routine is
17843 refreshingly simple. It's not trivial, but the operations are relatively
17844 straightforward; the main difficulty is, again, that expressions and data
17845 structures might change drastically every time we call |get_x_next|, so a
17846 cautious approach is mandatory. For example, a macro defined by
17847 \&{primarydef} might have disappeared by the time its second argument has
17848 been scanned; we solve this by increasing the reference count of its token
17849 list, so that the macro can be called even after it has been clobbered.
17850
17851 @<Declare the basic parsing subroutines@>=
17852 void mp_scan_secondary (MP mp) {
17853   pointer p; /* for list manipulation */
17854   halfword c,d; /* operation codes or modifiers */
17855   pointer mac_name; /* token defined with \&{primarydef} */
17856 RESTART:
17857   if ((mp->cur_cmd<min_primary_command)||
17858       (mp->cur_cmd>max_primary_command) )
17859     mp_bad_exp(mp, "A secondary");
17860 @.A secondary expression...@>
17861   mp_scan_primary(mp);
17862 CONTINUE: 
17863   if ( mp->cur_cmd<=max_secondary_command &&
17864        mp->cur_cmd>=min_secondary_command ) {
17865     p=mp_stash_cur_exp(mp); 
17866     c=mp->cur_mod; d=mp->cur_cmd;
17867     if ( d==secondary_primary_macro ) { 
17868       mac_name=mp->cur_sym; 
17869       add_mac_ref(c);
17870     }
17871     mp_get_x_next(mp); 
17872     mp_scan_primary(mp);
17873     if ( d!=secondary_primary_macro ) {
17874       mp_do_binary(mp, p,c);
17875     } else { 
17876       mp_back_input(mp); 
17877       mp_binary_mac(mp, p,c,mac_name);
17878       decr(ref_count(c)); 
17879       mp_get_x_next(mp); 
17880       goto RESTART;
17881     }
17882     goto CONTINUE;
17883   }
17884 }
17885
17886 @ The following procedure calls a macro that has two parameters,
17887 |p| and |cur_exp|.
17888
17889 @c void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
17890   pointer q,r; /* nodes in the parameter list */
17891   q=mp_get_avail(mp); r=mp_get_avail(mp); link(q)=r;
17892   info(q)=p; info(r)=mp_stash_cur_exp(mp);
17893   mp_macro_call(mp, c,q,n);
17894 }
17895
17896 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
17897
17898 @<Declare the basic parsing subroutines@>=
17899 void mp_scan_tertiary (MP mp) {
17900   pointer p; /* for list manipulation */
17901   halfword c,d; /* operation codes or modifiers */
17902   pointer mac_name; /* token defined with \&{secondarydef} */
17903 RESTART:
17904   if ((mp->cur_cmd<min_primary_command)||
17905       (mp->cur_cmd>max_primary_command) )
17906     mp_bad_exp(mp, "A tertiary");
17907 @.A tertiary expression...@>
17908   mp_scan_secondary(mp);
17909 CONTINUE: 
17910   if ( mp->cur_cmd<=max_tertiary_command ) {
17911     if ( mp->cur_cmd>=min_tertiary_command ) {
17912       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17913       if ( d==tertiary_secondary_macro ) { 
17914         mac_name=mp->cur_sym; add_mac_ref(c);
17915       };
17916       mp_get_x_next(mp); mp_scan_secondary(mp);
17917       if ( d!=tertiary_secondary_macro ) {
17918         mp_do_binary(mp, p,c);
17919       } else { 
17920         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17921         decr(ref_count(c)); mp_get_x_next(mp); 
17922         goto RESTART;
17923       }
17924       goto CONTINUE;
17925     }
17926   }
17927 }
17928
17929 @ Finally we reach the deepest level in our quartet of parsing routines.
17930 This one is much like the others; but it has an extra complication from
17931 paths, which materialize here.
17932
17933 @d continue_path 25 /* a label inside of |scan_expression| */
17934 @d finish_path 26 /* another */
17935
17936 @<Declare the basic parsing subroutines@>=
17937 void mp_scan_expression (MP mp) {
17938   pointer p,q,r,pp,qq; /* for list manipulation */
17939   halfword c,d; /* operation codes or modifiers */
17940   int my_var_flag; /* initial value of |var_flag| */
17941   pointer mac_name; /* token defined with \&{tertiarydef} */
17942   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
17943   scaled x,y; /* explicit coordinates or tension at a path join */
17944   int t; /* knot type following a path join */
17945   t=0; y=0; x=0;
17946   my_var_flag=mp->var_flag; mac_name=null;
17947 RESTART:
17948   if ((mp->cur_cmd<min_primary_command)||
17949       (mp->cur_cmd>max_primary_command) )
17950     mp_bad_exp(mp, "An");
17951 @.An expression...@>
17952   mp_scan_tertiary(mp);
17953 CONTINUE: 
17954   if ( mp->cur_cmd<=max_expression_command )
17955     if ( mp->cur_cmd>=min_expression_command ) {
17956       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
17957         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
17958         if ( d==expression_tertiary_macro ) {
17959           mac_name=mp->cur_sym; add_mac_ref(c);
17960         }
17961         if ( (d<ampersand)||((d==ampersand)&&
17962              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
17963           @<Scan a path construction operation;
17964             but |return| if |p| has the wrong type@>;
17965         } else { 
17966           mp_get_x_next(mp); mp_scan_tertiary(mp);
17967           if ( d!=expression_tertiary_macro ) {
17968             mp_do_binary(mp, p,c);
17969           } else  { 
17970             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
17971             decr(ref_count(c)); mp_get_x_next(mp); 
17972             goto RESTART;
17973           }
17974         }
17975         goto CONTINUE;
17976      }
17977   }
17978 }
17979
17980 @ The reader should review the data structure conventions for paths before
17981 hoping to understand the next part of this code.
17982
17983 @<Scan a path construction operation...@>=
17984
17985   cycle_hit=false;
17986   @<Convert the left operand, |p|, into a partial path ending at~|q|;
17987     but |return| if |p| doesn't have a suitable type@>;
17988 CONTINUE_PATH: 
17989   @<Determine the path join parameters;
17990     but |goto finish_path| if there's only a direction specifier@>;
17991   if ( mp->cur_cmd==cycle ) {
17992     @<Get ready to close a cycle@>;
17993   } else { 
17994     mp_scan_tertiary(mp);
17995     @<Convert the right operand, |cur_exp|,
17996       into a partial path from |pp| to~|qq|@>;
17997   }
17998   @<Join the partial paths and reset |p| and |q| to the head and tail
17999     of the result@>;
18000   if ( mp->cur_cmd>=min_expression_command )
18001     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18002 FINISH_PATH:
18003   @<Choose control points for the path and put the result into |cur_exp|@>;
18004 }
18005
18006 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18007
18008   mp_unstash_cur_exp(mp, p);
18009   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18010   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18011   else return;
18012   q=p;
18013   while ( link(q)!=p ) q=link(q);
18014   if ( left_type(p)!=mp_endpoint ) { /* open up a cycle */
18015     r=mp_copy_knot(mp, p); link(q)=r; q=r;
18016   }
18017   left_type(p)=mp_open; right_type(q)=mp_open;
18018 }
18019
18020 @ A pair of numeric values is changed into a knot node for a one-point path
18021 when \MP\ discovers that the pair is part of a path.
18022
18023 @c @<Declare the procedure called |known_pair|@>
18024 pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18025   pointer q; /* the new node */
18026   q=mp_get_node(mp, knot_node_size); left_type(q)=mp_endpoint;
18027   right_type(q)=mp_endpoint; originator(q)=mp_metapost_user; link(q)=q;
18028   mp_known_pair(mp); x_coord(q)=mp->cur_x; y_coord(q)=mp->cur_y;
18029   return q;
18030 }
18031
18032 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18033 of the current expression, assuming that the current expression is a
18034 pair of known numerics. Unknown components are zeroed, and the
18035 current expression is flushed.
18036
18037 @<Declare the procedure called |known_pair|@>=
18038 void mp_known_pair (MP mp) {
18039   pointer p; /* the pair node */
18040   if ( mp->cur_type!=mp_pair_type ) {
18041     exp_err("Undefined coordinates have been replaced by (0,0)");
18042 @.Undefined coordinates...@>
18043     help5("I need x and y numbers for this part of the path.")
18044       ("The value I found (see above) was no good;")
18045       ("so I'll try to keep going by using zero instead.")
18046       ("(Chapter 27 of The METAFONTbook explains that")
18047 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18048       ("you might want to type `I ??" "?' now.)");
18049     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18050   } else { 
18051     p=value(mp->cur_exp);
18052      @<Make sure that both |x| and |y| parts of |p| are known;
18053        copy them into |cur_x| and |cur_y|@>;
18054     mp_flush_cur_exp(mp, 0);
18055   }
18056 }
18057
18058 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18059 if ( type(x_part_loc(p))==mp_known ) {
18060   mp->cur_x=value(x_part_loc(p));
18061 } else { 
18062   mp_disp_err(mp, x_part_loc(p),
18063     "Undefined x coordinate has been replaced by 0");
18064 @.Undefined coordinates...@>
18065   help5("I need a `known' x value for this part of the path.")
18066     ("The value I found (see above) was no good;")
18067     ("so I'll try to keep going by using zero instead.")
18068     ("(Chapter 27 of The METAFONTbook explains that")
18069 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18070     ("you might want to type `I ??" "?' now.)");
18071   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18072 }
18073 if ( type(y_part_loc(p))==mp_known ) {
18074   mp->cur_y=value(y_part_loc(p));
18075 } else { 
18076   mp_disp_err(mp, y_part_loc(p),
18077     "Undefined y coordinate has been replaced by 0");
18078   help5("I need a `known' y value for this part of the path.")
18079     ("The value I found (see above) was no good;")
18080     ("so I'll try to keep going by using zero instead.")
18081     ("(Chapter 27 of The METAFONTbook explains that")
18082     ("you might want to type `I ??" "?' now.)");
18083   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18084 }
18085
18086 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18087
18088 @<Determine the path join parameters...@>=
18089 if ( mp->cur_cmd==left_brace ) {
18090   @<Put the pre-join direction information into node |q|@>;
18091 }
18092 d=mp->cur_cmd;
18093 if ( d==path_join ) {
18094   @<Determine the tension and/or control points@>;
18095 } else if ( d!=ampersand ) {
18096   goto FINISH_PATH;
18097 }
18098 mp_get_x_next(mp);
18099 if ( mp->cur_cmd==left_brace ) {
18100   @<Put the post-join direction information into |x| and |t|@>;
18101 } else if ( right_type(q)!=mp_explicit ) {
18102   t=mp_open; x=0;
18103 }
18104
18105 @ The |scan_direction| subroutine looks at the directional information
18106 that is enclosed in braces, and also scans ahead to the following character.
18107 A type code is returned, either |open| (if the direction was $(0,0)$),
18108 or |curl| (if the direction was a curl of known value |cur_exp|), or
18109 |given| (if the direction is given by the |angle| value that now
18110 appears in |cur_exp|).
18111
18112 There's nothing difficult about this subroutine, but the program is rather
18113 lengthy because a variety of potential errors need to be nipped in the bud.
18114
18115 @c small_number mp_scan_direction (MP mp) {
18116   int t; /* the type of information found */
18117   scaled x; /* an |x| coordinate */
18118   mp_get_x_next(mp);
18119   if ( mp->cur_cmd==curl_command ) {
18120      @<Scan a curl specification@>;
18121   } else {
18122     @<Scan a given direction@>;
18123   }
18124   if ( mp->cur_cmd!=right_brace ) {
18125     mp_missing_err(mp, "}");
18126 @.Missing `\char`\}'@>
18127     help3("I've scanned a direction spec for part of a path,")
18128       ("so a right brace should have come next.")
18129       ("I shall pretend that one was there.");
18130     mp_back_error(mp);
18131   }
18132   mp_get_x_next(mp); 
18133   return t;
18134 }
18135
18136 @ @<Scan a curl specification@>=
18137 { mp_get_x_next(mp); mp_scan_expression(mp);
18138 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18139   exp_err("Improper curl has been replaced by 1");
18140 @.Improper curl@>
18141   help1("A curl must be a known, nonnegative number.");
18142   mp_put_get_flush_error(mp, unity);
18143 }
18144 t=mp_curl;
18145 }
18146
18147 @ @<Scan a given direction@>=
18148 { mp_scan_expression(mp);
18149   if ( mp->cur_type>mp_pair_type ) {
18150     @<Get given directions separated by commas@>;
18151   } else {
18152     mp_known_pair(mp);
18153   }
18154   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18155   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18156 }
18157
18158 @ @<Get given directions separated by commas@>=
18159
18160   if ( mp->cur_type!=mp_known ) {
18161     exp_err("Undefined x coordinate has been replaced by 0");
18162 @.Undefined coordinates...@>
18163     help5("I need a `known' x value for this part of the path.")
18164       ("The value I found (see above) was no good;")
18165       ("so I'll try to keep going by using zero instead.")
18166       ("(Chapter 27 of The METAFONTbook explains that")
18167 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18168       ("you might want to type `I ??" "?' now.)");
18169     mp_put_get_flush_error(mp, 0);
18170   }
18171   x=mp->cur_exp;
18172   if ( mp->cur_cmd!=comma ) {
18173     mp_missing_err(mp, ",");
18174 @.Missing `,'@>
18175     help2("I've got the x coordinate of a path direction;")
18176       ("will look for the y coordinate next.");
18177     mp_back_error(mp);
18178   }
18179   mp_get_x_next(mp); mp_scan_expression(mp);
18180   if ( mp->cur_type!=mp_known ) {
18181      exp_err("Undefined y coordinate has been replaced by 0");
18182     help5("I need a `known' y value for this part of the path.")
18183       ("The value I found (see above) was no good;")
18184       ("so I'll try to keep going by using zero instead.")
18185       ("(Chapter 27 of The METAFONTbook explains that")
18186       ("you might want to type `I ??" "?' now.)");
18187     mp_put_get_flush_error(mp, 0);
18188   }
18189   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18190 }
18191
18192 @ At this point |right_type(q)| is usually |open|, but it may have been
18193 set to some other value by a previous operation. We must maintain
18194 the value of |right_type(q)| in cases such as
18195 `\.{..\{curl2\}z\{0,0\}..}'.
18196
18197 @<Put the pre-join...@>=
18198
18199   t=mp_scan_direction(mp);
18200   if ( t!=mp_open ) {
18201     right_type(q)=t; right_given(q)=mp->cur_exp;
18202     if ( left_type(q)==mp_open ) {
18203       left_type(q)=t; left_given(q)=mp->cur_exp;
18204     } /* note that |left_given(q)=left_curl(q)| */
18205   }
18206 }
18207
18208 @ Since |left_tension| and |left_y| share the same position in knot nodes,
18209 and since |left_given| is similarly equivalent to |left_x|, we use
18210 |x| and |y| to hold the given direction and tension information when
18211 there are no explicit control points.
18212
18213 @<Put the post-join...@>=
18214
18215   t=mp_scan_direction(mp);
18216   if ( right_type(q)!=mp_explicit ) x=mp->cur_exp;
18217   else t=mp_explicit; /* the direction information is superfluous */
18218 }
18219
18220 @ @<Determine the tension and/or...@>=
18221
18222   mp_get_x_next(mp);
18223   if ( mp->cur_cmd==tension ) {
18224     @<Set explicit tensions@>;
18225   } else if ( mp->cur_cmd==controls ) {
18226     @<Set explicit control points@>;
18227   } else  { 
18228     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18229     goto DONE;
18230   };
18231   if ( mp->cur_cmd!=path_join ) {
18232      mp_missing_err(mp, "..");
18233 @.Missing `..'@>
18234     help1("A path join command should end with two dots.");
18235     mp_back_error(mp);
18236   }
18237 DONE:
18238   ;
18239 }
18240
18241 @ @<Set explicit tensions@>=
18242
18243   mp_get_x_next(mp); y=mp->cur_cmd;
18244   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18245   mp_scan_primary(mp);
18246   @<Make sure that the current expression is a valid tension setting@>;
18247   if ( y==at_least ) negate(mp->cur_exp);
18248   right_tension(q)=mp->cur_exp;
18249   if ( mp->cur_cmd==and_command ) {
18250     mp_get_x_next(mp); y=mp->cur_cmd;
18251     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18252     mp_scan_primary(mp);
18253     @<Make sure that the current expression is a valid tension setting@>;
18254     if ( y==at_least ) negate(mp->cur_exp);
18255   }
18256   y=mp->cur_exp;
18257 }
18258
18259 @ @d min_tension three_quarter_unit
18260
18261 @<Make sure that the current expression is a valid tension setting@>=
18262 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18263   exp_err("Improper tension has been set to 1");
18264 @.Improper tension@>
18265   help1("The expression above should have been a number >=3/4.");
18266   mp_put_get_flush_error(mp, unity);
18267 }
18268
18269 @ @<Set explicit control points@>=
18270
18271   right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18272   mp_known_pair(mp); right_x(q)=mp->cur_x; right_y(q)=mp->cur_y;
18273   if ( mp->cur_cmd!=and_command ) {
18274     x=right_x(q); y=right_y(q);
18275   } else { 
18276     mp_get_x_next(mp); mp_scan_primary(mp);
18277     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18278   }
18279 }
18280
18281 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18282
18283   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18284   else pp=mp->cur_exp;
18285   qq=pp;
18286   while ( link(qq)!=pp ) qq=link(qq);
18287   if ( left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18288     r=mp_copy_knot(mp, pp); link(qq)=r; qq=r;
18289   }
18290   left_type(pp)=mp_open; right_type(qq)=mp_open;
18291 }
18292
18293 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18294 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18295 shouldn't have length zero.
18296
18297 @<Get ready to close a cycle@>=
18298
18299   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18300   if ( d==ampersand ) if ( p==q ) {
18301     d=path_join; right_tension(q)=unity; y=unity;
18302   }
18303 }
18304
18305 @ @<Join the partial paths and reset |p| and |q|...@>=
18306
18307 if ( d==ampersand ) {
18308   if ( (x_coord(q)!=x_coord(pp))||(y_coord(q)!=y_coord(pp)) ) {
18309     print_err("Paths don't touch; `&' will be changed to `..'");
18310 @.Paths don't touch@>
18311     help3("When you join paths `p&q', the ending point of p")
18312       ("must be exactly equal to the starting point of q.")
18313       ("So I'm going to pretend that you said `p..q' instead.");
18314     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18315   }
18316 }
18317 @<Plug an opening in |right_type(pp)|, if possible@>;
18318 if ( d==ampersand ) {
18319   @<Splice independent paths together@>;
18320 } else  { 
18321   @<Plug an opening in |right_type(q)|, if possible@>;
18322   link(q)=pp; left_y(pp)=y;
18323   if ( t!=mp_open ) { left_x(pp)=x; left_type(pp)=t;  };
18324 }
18325 q=qq;
18326 }
18327
18328 @ @<Plug an opening in |right_type(q)|...@>=
18329 if ( right_type(q)==mp_open ) {
18330   if ( (left_type(q)==mp_curl)||(left_type(q)==mp_given) ) {
18331     right_type(q)=left_type(q); right_given(q)=left_given(q);
18332   }
18333 }
18334
18335 @ @<Plug an opening in |right_type(pp)|...@>=
18336 if ( right_type(pp)==mp_open ) {
18337   if ( (t==mp_curl)||(t==mp_given) ) {
18338     right_type(pp)=t; right_given(pp)=x;
18339   }
18340 }
18341
18342 @ @<Splice independent paths together@>=
18343
18344   if ( left_type(q)==mp_open ) if ( right_type(q)==mp_open ) {
18345     left_type(q)=mp_curl; left_curl(q)=unity;
18346   }
18347   if ( right_type(pp)==mp_open ) if ( t==mp_open ) {
18348     right_type(pp)=mp_curl; right_curl(pp)=unity;
18349   }
18350   right_type(q)=right_type(pp); link(q)=link(pp);
18351   right_x(q)=right_x(pp); right_y(q)=right_y(pp);
18352   mp_free_node(mp, pp,knot_node_size);
18353   if ( qq==pp ) qq=q;
18354 }
18355
18356 @ @<Choose control points for the path...@>=
18357 if ( cycle_hit ) { 
18358   if ( d==ampersand ) p=q;
18359 } else  { 
18360   left_type(p)=mp_endpoint;
18361   if ( right_type(p)==mp_open ) { 
18362     right_type(p)=mp_curl; right_curl(p)=unity;
18363   }
18364   right_type(q)=mp_endpoint;
18365   if ( left_type(q)==mp_open ) { 
18366     left_type(q)=mp_curl; left_curl(q)=unity;
18367   }
18368   link(q)=p;
18369 }
18370 mp_make_choices(mp, p);
18371 mp->cur_type=mp_path_type; mp->cur_exp=p
18372
18373 @ Finally, we sometimes need to scan an expression whose value is
18374 supposed to be either |true_code| or |false_code|.
18375
18376 @<Declare the basic parsing subroutines@>=
18377 void mp_get_boolean (MP mp) { 
18378   mp_get_x_next(mp); mp_scan_expression(mp);
18379   if ( mp->cur_type!=mp_boolean_type ) {
18380     exp_err("Undefined condition will be treated as `false'");
18381 @.Undefined condition...@>
18382     help2("The expression shown above should have had a definite")
18383       ("true-or-false value. I'm changing it to `false'.");
18384     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18385   }
18386 }
18387
18388 @* \[39] Doing the operations.
18389 The purpose of parsing is primarily to permit people to avoid piles of
18390 parentheses. But the real work is done after the structure of an expression
18391 has been recognized; that's when new expressions are generated. We
18392 turn now to the guts of \MP, which handles individual operators that
18393 have come through the parsing mechanism.
18394
18395 We'll start with the easy ones that take no operands, then work our way
18396 up to operators with one and ultimately two arguments. In other words,
18397 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18398 that are invoked periodically by the expression scanners.
18399
18400 First let's make sure that all of the primitive operators are in the
18401 hash table. Although |scan_primary| and its relatives made use of the
18402 \\{cmd} code for these operators, the \\{do} routines base everything
18403 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18404 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18405
18406 @<Put each...@>=
18407 mp_primitive(mp, "true",nullary,true_code);
18408 @:true_}{\&{true} primitive@>
18409 mp_primitive(mp, "false",nullary,false_code);
18410 @:false_}{\&{false} primitive@>
18411 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18412 @:null_picture_}{\&{nullpicture} primitive@>
18413 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18414 @:null_pen_}{\&{nullpen} primitive@>
18415 mp_primitive(mp, "jobname",nullary,job_name_op);
18416 @:job_name_}{\&{jobname} primitive@>
18417 mp_primitive(mp, "readstring",nullary,read_string_op);
18418 @:read_string_}{\&{readstring} primitive@>
18419 mp_primitive(mp, "pencircle",nullary,pen_circle);
18420 @:pen_circle_}{\&{pencircle} primitive@>
18421 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18422 @:normal_deviate_}{\&{normaldeviate} primitive@>
18423 mp_primitive(mp, "readfrom",unary,read_from_op);
18424 @:read_from_}{\&{readfrom} primitive@>
18425 mp_primitive(mp, "closefrom",unary,close_from_op);
18426 @:close_from_}{\&{closefrom} primitive@>
18427 mp_primitive(mp, "odd",unary,odd_op);
18428 @:odd_}{\&{odd} primitive@>
18429 mp_primitive(mp, "known",unary,known_op);
18430 @:known_}{\&{known} primitive@>
18431 mp_primitive(mp, "unknown",unary,unknown_op);
18432 @:unknown_}{\&{unknown} primitive@>
18433 mp_primitive(mp, "not",unary,not_op);
18434 @:not_}{\&{not} primitive@>
18435 mp_primitive(mp, "decimal",unary,decimal);
18436 @:decimal_}{\&{decimal} primitive@>
18437 mp_primitive(mp, "reverse",unary,reverse);
18438 @:reverse_}{\&{reverse} primitive@>
18439 mp_primitive(mp, "makepath",unary,make_path_op);
18440 @:make_path_}{\&{makepath} primitive@>
18441 mp_primitive(mp, "makepen",unary,make_pen_op);
18442 @:make_pen_}{\&{makepen} primitive@>
18443 mp_primitive(mp, "oct",unary,oct_op);
18444 @:oct_}{\&{oct} primitive@>
18445 mp_primitive(mp, "hex",unary,hex_op);
18446 @:hex_}{\&{hex} primitive@>
18447 mp_primitive(mp, "ASCII",unary,ASCII_op);
18448 @:ASCII_}{\&{ASCII} primitive@>
18449 mp_primitive(mp, "char",unary,char_op);
18450 @:char_}{\&{char} primitive@>
18451 mp_primitive(mp, "length",unary,length_op);
18452 @:length_}{\&{length} primitive@>
18453 mp_primitive(mp, "turningnumber",unary,turning_op);
18454 @:turning_number_}{\&{turningnumber} primitive@>
18455 mp_primitive(mp, "xpart",unary,x_part);
18456 @:x_part_}{\&{xpart} primitive@>
18457 mp_primitive(mp, "ypart",unary,y_part);
18458 @:y_part_}{\&{ypart} primitive@>
18459 mp_primitive(mp, "xxpart",unary,xx_part);
18460 @:xx_part_}{\&{xxpart} primitive@>
18461 mp_primitive(mp, "xypart",unary,xy_part);
18462 @:xy_part_}{\&{xypart} primitive@>
18463 mp_primitive(mp, "yxpart",unary,yx_part);
18464 @:yx_part_}{\&{yxpart} primitive@>
18465 mp_primitive(mp, "yypart",unary,yy_part);
18466 @:yy_part_}{\&{yypart} primitive@>
18467 mp_primitive(mp, "redpart",unary,red_part);
18468 @:red_part_}{\&{redpart} primitive@>
18469 mp_primitive(mp, "greenpart",unary,green_part);
18470 @:green_part_}{\&{greenpart} primitive@>
18471 mp_primitive(mp, "bluepart",unary,blue_part);
18472 @:blue_part_}{\&{bluepart} primitive@>
18473 mp_primitive(mp, "cyanpart",unary,cyan_part);
18474 @:cyan_part_}{\&{cyanpart} primitive@>
18475 mp_primitive(mp, "magentapart",unary,magenta_part);
18476 @:magenta_part_}{\&{magentapart} primitive@>
18477 mp_primitive(mp, "yellowpart",unary,yellow_part);
18478 @:yellow_part_}{\&{yellowpart} primitive@>
18479 mp_primitive(mp, "blackpart",unary,black_part);
18480 @:black_part_}{\&{blackpart} primitive@>
18481 mp_primitive(mp, "greypart",unary,grey_part);
18482 @:grey_part_}{\&{greypart} primitive@>
18483 mp_primitive(mp, "colormodel",unary,color_model_part);
18484 @:color_model_part_}{\&{colormodel} primitive@>
18485 mp_primitive(mp, "fontpart",unary,font_part);
18486 @:font_part_}{\&{fontpart} primitive@>
18487 mp_primitive(mp, "textpart",unary,text_part);
18488 @:text_part_}{\&{textpart} primitive@>
18489 mp_primitive(mp, "pathpart",unary,path_part);
18490 @:path_part_}{\&{pathpart} primitive@>
18491 mp_primitive(mp, "penpart",unary,pen_part);
18492 @:pen_part_}{\&{penpart} primitive@>
18493 mp_primitive(mp, "dashpart",unary,dash_part);
18494 @:dash_part_}{\&{dashpart} primitive@>
18495 mp_primitive(mp, "sqrt",unary,sqrt_op);
18496 @:sqrt_}{\&{sqrt} primitive@>
18497 mp_primitive(mp, "mexp",unary,m_exp_op);
18498 @:m_exp_}{\&{mexp} primitive@>
18499 mp_primitive(mp, "mlog",unary,m_log_op);
18500 @:m_log_}{\&{mlog} primitive@>
18501 mp_primitive(mp, "sind",unary,sin_d_op);
18502 @:sin_d_}{\&{sind} primitive@>
18503 mp_primitive(mp, "cosd",unary,cos_d_op);
18504 @:cos_d_}{\&{cosd} primitive@>
18505 mp_primitive(mp, "floor",unary,floor_op);
18506 @:floor_}{\&{floor} primitive@>
18507 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18508 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18509 mp_primitive(mp, "charexists",unary,char_exists_op);
18510 @:char_exists_}{\&{charexists} primitive@>
18511 mp_primitive(mp, "fontsize",unary,font_size);
18512 @:font_size_}{\&{fontsize} primitive@>
18513 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18514 @:ll_corner_}{\&{llcorner} primitive@>
18515 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18516 @:lr_corner_}{\&{lrcorner} primitive@>
18517 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18518 @:ul_corner_}{\&{ulcorner} primitive@>
18519 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18520 @:ur_corner_}{\&{urcorner} primitive@>
18521 mp_primitive(mp, "arclength",unary,arc_length);
18522 @:arc_length_}{\&{arclength} primitive@>
18523 mp_primitive(mp, "angle",unary,angle_op);
18524 @:angle_}{\&{angle} primitive@>
18525 mp_primitive(mp, "cycle",cycle,cycle_op);
18526 @:cycle_}{\&{cycle} primitive@>
18527 mp_primitive(mp, "stroked",unary,stroked_op);
18528 @:stroked_}{\&{stroked} primitive@>
18529 mp_primitive(mp, "filled",unary,filled_op);
18530 @:filled_}{\&{filled} primitive@>
18531 mp_primitive(mp, "textual",unary,textual_op);
18532 @:textual_}{\&{textual} primitive@>
18533 mp_primitive(mp, "clipped",unary,clipped_op);
18534 @:clipped_}{\&{clipped} primitive@>
18535 mp_primitive(mp, "bounded",unary,bounded_op);
18536 @:bounded_}{\&{bounded} primitive@>
18537 mp_primitive(mp, "+",plus_or_minus,plus);
18538 @:+ }{\.{+} primitive@>
18539 mp_primitive(mp, "-",plus_or_minus,minus);
18540 @:- }{\.{-} primitive@>
18541 mp_primitive(mp, "*",secondary_binary,times);
18542 @:* }{\.{*} primitive@>
18543 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18544 @:/ }{\.{/} primitive@>
18545 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18546 @:++_}{\.{++} primitive@>
18547 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18548 @:+-+_}{\.{+-+} primitive@>
18549 mp_primitive(mp, "or",tertiary_binary,or_op);
18550 @:or_}{\&{or} primitive@>
18551 mp_primitive(mp, "and",and_command,and_op);
18552 @:and_}{\&{and} primitive@>
18553 mp_primitive(mp, "<",expression_binary,less_than);
18554 @:< }{\.{<} primitive@>
18555 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18556 @:<=_}{\.{<=} primitive@>
18557 mp_primitive(mp, ">",expression_binary,greater_than);
18558 @:> }{\.{>} primitive@>
18559 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18560 @:>=_}{\.{>=} primitive@>
18561 mp_primitive(mp, "=",equals,equal_to);
18562 @:= }{\.{=} primitive@>
18563 mp_primitive(mp, "<>",expression_binary,unequal_to);
18564 @:<>_}{\.{<>} primitive@>
18565 mp_primitive(mp, "substring",primary_binary,substring_of);
18566 @:substring_}{\&{substring} primitive@>
18567 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18568 @:subpath_}{\&{subpath} primitive@>
18569 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18570 @:direction_time_}{\&{directiontime} primitive@>
18571 mp_primitive(mp, "point",primary_binary,point_of);
18572 @:point_}{\&{point} primitive@>
18573 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18574 @:precontrol_}{\&{precontrol} primitive@>
18575 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18576 @:postcontrol_}{\&{postcontrol} primitive@>
18577 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18578 @:pen_offset_}{\&{penoffset} primitive@>
18579 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18580 @:arc_time_of_}{\&{arctime} primitive@>
18581 mp_primitive(mp, "mpversion",nullary,mp_version);
18582 @:mp_verison_}{\&{mpversion} primitive@>
18583 mp_primitive(mp, "&",ampersand,concatenate);
18584 @:!!!}{\.{\&} primitive@>
18585 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18586 @:rotated_}{\&{rotated} primitive@>
18587 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18588 @:slanted_}{\&{slanted} primitive@>
18589 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18590 @:scaled_}{\&{scaled} primitive@>
18591 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18592 @:shifted_}{\&{shifted} primitive@>
18593 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18594 @:transformed_}{\&{transformed} primitive@>
18595 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18596 @:x_scaled_}{\&{xscaled} primitive@>
18597 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18598 @:y_scaled_}{\&{yscaled} primitive@>
18599 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18600 @:z_scaled_}{\&{zscaled} primitive@>
18601 mp_primitive(mp, "infont",secondary_binary,in_font);
18602 @:in_font_}{\&{infont} primitive@>
18603 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18604 @:intersection_times_}{\&{intersectiontimes} primitive@>
18605 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18606 @:envelope_}{\&{envelope} primitive@>
18607
18608 @ @<Cases of |print_cmd...@>=
18609 case nullary:
18610 case unary:
18611 case primary_binary:
18612 case secondary_binary:
18613 case tertiary_binary:
18614 case expression_binary:
18615 case cycle:
18616 case plus_or_minus:
18617 case slash:
18618 case ampersand:
18619 case equals:
18620 case and_command:
18621   mp_print_op(mp, m);
18622   break;
18623
18624 @ OK, let's look at the simplest \\{do} procedure first.
18625
18626 @c @<Declare nullary action procedure@>
18627 void mp_do_nullary (MP mp,quarterword c) { 
18628   check_arith;
18629   if ( mp->internal[mp_tracing_commands]>two )
18630     mp_show_cmd_mod(mp, nullary,c);
18631   switch (c) {
18632   case true_code: case false_code: 
18633     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18634     break;
18635   case null_picture_code: 
18636     mp->cur_type=mp_picture_type;
18637     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18638     mp_init_edges(mp, mp->cur_exp);
18639     break;
18640   case null_pen_code: 
18641     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18642     break;
18643   case normal_deviate: 
18644     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18645     break;
18646   case pen_circle: 
18647     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18648     break;
18649   case job_name_op:  
18650     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18651     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18652     break;
18653   case mp_version: 
18654     mp->cur_type=mp_string_type; 
18655     mp->cur_exp=intern(metapost_version) ;
18656     break;
18657   case read_string_op:
18658     @<Read a string from the terminal@>;
18659     break;
18660   } /* there are no other cases */
18661   check_arith;
18662 }
18663
18664 @ @<Read a string...@>=
18665
18666   if ( mp->interaction<=mp_nonstop_mode )
18667     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18668   mp_begin_file_reading(mp); name=is_read;
18669   limit=start; prompt_input("");
18670   mp_finish_read(mp);
18671 }
18672
18673 @ @<Declare nullary action procedure@>=
18674 void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18675   size_t k;
18676   str_room((int)mp->last-start);
18677   for (k=start;k<=mp->last-1;k++) {
18678    append_char(mp->buffer[k]);
18679   }
18680   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18681   mp->cur_exp=mp_make_string(mp);
18682 }
18683
18684 @ Things get a bit more interesting when there's an operand. The
18685 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18686
18687 @c @<Declare unary action procedures@>
18688 void mp_do_unary (MP mp,quarterword c) {
18689   pointer p,q,r; /* for list manipulation */
18690   integer x; /* a temporary register */
18691   check_arith;
18692   if ( mp->internal[mp_tracing_commands]>two )
18693     @<Trace the current unary operation@>;
18694   switch (c) {
18695   case plus:
18696     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18697     break;
18698   case minus:
18699     @<Negate the current expression@>;
18700     break;
18701   @<Additional cases of unary operators@>;
18702   } /* there are no other cases */
18703   check_arith;
18704 }
18705
18706 @ The |nice_pair| function returns |true| if both components of a pair
18707 are known.
18708
18709 @<Declare unary action procedures@>=
18710 boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18711   if ( t==mp_pair_type ) {
18712     p=value(p);
18713     if ( type(x_part_loc(p))==mp_known )
18714       if ( type(y_part_loc(p))==mp_known )
18715         return true;
18716   }
18717   return false;
18718 }
18719
18720 @ The |nice_color_or_pair| function is analogous except that it also accepts
18721 fully known colors.
18722
18723 @<Declare unary action procedures@>=
18724 boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18725   pointer q,r; /* for scanning the big node */
18726   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18727     return false;
18728   } else { 
18729     q=value(p);
18730     r=q+mp->big_node_size[type(p)];
18731     do {  
18732       r=r-2;
18733       if ( type(r)!=mp_known )
18734         return false;
18735     } while (r!=q);
18736     return true;
18737   }
18738 }
18739
18740 @ @<Declare unary action...@>=
18741 void mp_print_known_or_unknown_type (MP mp,small_number t, integer v) { 
18742   mp_print_char(mp, '(');
18743   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18744   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18745     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18746     mp_print_type(mp, t);
18747   }
18748   mp_print_char(mp, ')');
18749 }
18750
18751 @ @<Declare unary action...@>=
18752 void mp_bad_unary (MP mp,quarterword c) { 
18753   exp_err("Not implemented: "); mp_print_op(mp, c);
18754 @.Not implemented...@>
18755   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18756   help3("I'm afraid I don't know how to apply that operation to that")
18757     ("particular type. Continue, and I'll simply return the")
18758     ("argument (shown above) as the result of the operation.");
18759   mp_put_get_error(mp);
18760 }
18761
18762 @ @<Trace the current unary operation@>=
18763
18764   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18765   mp_print_op(mp, c); mp_print_char(mp, '(');
18766   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18767   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18768 }
18769
18770 @ Negation is easy except when the current expression
18771 is of type |independent|, or when it is a pair with one or more
18772 |independent| components.
18773
18774 It is tempting to argue that the negative of an independent variable
18775 is an independent variable, hence we don't have to do anything when
18776 negating it. The fallacy is that other dependent variables pointing
18777 to the current expression must change the sign of their
18778 coefficients if we make no change to the current expression.
18779
18780 Instead, we work around the problem by copying the current expression
18781 and recycling it afterwards (cf.~the |stash_in| routine).
18782
18783 @<Negate the current expression@>=
18784 switch (mp->cur_type) {
18785 case mp_color_type:
18786 case mp_cmykcolor_type:
18787 case mp_pair_type:
18788 case mp_independent: 
18789   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18790   if ( mp->cur_type==mp_dependent ) {
18791     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18792   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18793     p=value(mp->cur_exp);
18794     r=p+mp->big_node_size[mp->cur_type];
18795     do {  
18796       r=r-2;
18797       if ( type(r)==mp_known ) negate(value(r));
18798       else mp_negate_dep_list(mp, dep_list(r));
18799     } while (r!=p);
18800   } /* if |cur_type=mp_known| then |cur_exp=0| */
18801   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18802   break;
18803 case mp_dependent:
18804 case mp_proto_dependent:
18805   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18806   break;
18807 case mp_known:
18808   negate(mp->cur_exp);
18809   break;
18810 default:
18811   mp_bad_unary(mp, minus);
18812   break;
18813 }
18814
18815 @ @<Declare unary action...@>=
18816 void mp_negate_dep_list (MP mp,pointer p) { 
18817   while (1) { 
18818     negate(value(p));
18819     if ( info(p)==null ) return;
18820     p=link(p);
18821   }
18822 }
18823
18824 @ @<Additional cases of unary operators@>=
18825 case not_op: 
18826   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
18827   else mp->cur_exp=true_code+false_code-mp->cur_exp;
18828   break;
18829
18830 @ @d three_sixty_units 23592960 /* that's |360*unity| */
18831 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
18832
18833 @<Additional cases of unary operators@>=
18834 case sqrt_op:
18835 case m_exp_op:
18836 case m_log_op:
18837 case sin_d_op:
18838 case cos_d_op:
18839 case floor_op:
18840 case  uniform_deviate:
18841 case odd_op:
18842 case char_exists_op:
18843   if ( mp->cur_type!=mp_known ) {
18844     mp_bad_unary(mp, c);
18845   } else {
18846     switch (c) {
18847     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
18848     case m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
18849     case m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
18850     case sin_d_op:
18851     case cos_d_op:
18852       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
18853       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
18854       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
18855       break;
18856     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
18857     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
18858     case odd_op: 
18859       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
18860       mp->cur_type=mp_boolean_type;
18861       break;
18862     case char_exists_op:
18863       @<Determine if a character has been shipped out@>;
18864       break;
18865     } /* there are no other cases */
18866   }
18867   break;
18868
18869 @ @<Additional cases of unary operators@>=
18870 case angle_op:
18871   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
18872     p=value(mp->cur_exp);
18873     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
18874     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
18875     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
18876   } else {
18877     mp_bad_unary(mp, angle_op);
18878   }
18879   break;
18880
18881 @ If the current expression is a pair, but the context wants it to
18882 be a path, we call |pair_to_path|.
18883
18884 @<Declare unary action...@>=
18885 void mp_pair_to_path (MP mp) { 
18886   mp->cur_exp=mp_new_knot(mp); 
18887   mp->cur_type=mp_path_type;
18888 }
18889
18890
18891 @d pict_color_type(A) ((link(dummy_loc(mp->cur_exp))!=null) &&
18892                        (has_color(link(dummy_loc(mp->cur_exp)))) &&
18893                        (color_model(link(dummy_loc(mp->cur_exp)))==A))
18894
18895 @<Additional cases of unary operators@>=
18896 case x_part:
18897 case y_part:
18898   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
18899     mp_take_part(mp, c);
18900   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18901   else mp_bad_unary(mp, c);
18902   break;
18903 case xx_part:
18904 case xy_part:
18905 case yx_part:
18906 case yy_part: 
18907   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
18908   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18909   else mp_bad_unary(mp, c);
18910   break;
18911 case red_part:
18912 case green_part:
18913 case blue_part: 
18914   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
18915   else if ( mp->cur_type==mp_picture_type ) {
18916     if pict_color_type(mp_rgb_model) mp_take_pict_part(mp, c);
18917     else mp_bad_color_part(mp, c);
18918   }
18919   else mp_bad_unary(mp, c);
18920   break;
18921 case cyan_part:
18922 case magenta_part:
18923 case yellow_part:
18924 case black_part: 
18925   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
18926   else if ( mp->cur_type==mp_picture_type ) {
18927     if pict_color_type(mp_cmyk_model) mp_take_pict_part(mp, c);
18928     else mp_bad_color_part(mp, c);
18929   }
18930   else mp_bad_unary(mp, c);
18931   break;
18932 case grey_part: 
18933   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
18934   else if ( mp->cur_type==mp_picture_type ) {
18935     if pict_color_type(mp_grey_model) mp_take_pict_part(mp, c);
18936     else mp_bad_color_part(mp, c);
18937   }
18938   else mp_bad_unary(mp, c);
18939   break;
18940 case color_model_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_bad_color_part(MP mp, quarterword c);
18947
18948 @ @c
18949 void mp_bad_color_part(MP mp, quarterword c) {
18950   pointer p; /* the big node */
18951   p=link(dummy_loc(mp->cur_exp));
18952   exp_err("Wrong picture color model: "); mp_print_op(mp, c);
18953 @.Wrong picture color model...@>
18954   if (color_model(p)==mp_grey_model)
18955     mp_print(mp, " of grey object");
18956   else if (color_model(p)==mp_cmyk_model)
18957     mp_print(mp, " of cmyk object");
18958   else if (color_model(p)==mp_rgb_model)
18959     mp_print(mp, " of rgb object");
18960   else if (color_model(p)==mp_no_model) 
18961     mp_print(mp, " of marking object");
18962   else 
18963     mp_print(mp," of defaulted object");
18964   help3("You can only ask for the redpart, greenpart, bluepart of a rgb object,")
18965     ("the cyanpart, magentapart, yellowpart or blackpart of a cmyk object, ")
18966     ("or the greypart of a grey object. No mixing and matching, please.");
18967   mp_error(mp);
18968   if (c==black_part)
18969     mp_flush_cur_exp(mp,unity);
18970   else
18971     mp_flush_cur_exp(mp,0);
18972 }
18973
18974 @ In the following procedure, |cur_exp| points to a capsule, which points to
18975 a big node. We want to delete all but one part of the big node.
18976
18977 @<Declare unary action...@>=
18978 void mp_take_part (MP mp,quarterword c) {
18979   pointer p; /* the big node */
18980   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
18981   link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
18982   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
18983   mp_recycle_value(mp, temp_val);
18984 }
18985
18986 @ @<Initialize table entries...@>=
18987 name_type(temp_val)=mp_capsule;
18988
18989 @ @<Additional cases of unary operators@>=
18990 case font_part:
18991 case text_part:
18992 case path_part:
18993 case pen_part:
18994 case dash_part:
18995   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
18996   else mp_bad_unary(mp, c);
18997   break;
18998
18999 @ @<Declarations@>=
19000 void mp_scale_edges (MP mp);
19001
19002 @ @<Declare unary action...@>=
19003 void mp_take_pict_part (MP mp,quarterword c) {
19004   pointer p; /* first graphical object in |cur_exp| */
19005   p=link(dummy_loc(mp->cur_exp));
19006   if ( p!=null ) {
19007     switch (c) {
19008     case x_part: case y_part: case xx_part:
19009     case xy_part: case yx_part: case yy_part:
19010       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19011       else goto NOT_FOUND;
19012       break;
19013     case red_part: case green_part: case blue_part:
19014       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19015       else goto NOT_FOUND;
19016       break;
19017     case cyan_part: case magenta_part: case yellow_part:
19018     case black_part:
19019       if ( has_color(p) ) {
19020         if ( color_model(p)==mp_uninitialized_model )
19021           mp_flush_cur_exp(mp, unity);
19022         else
19023           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19024       } else goto NOT_FOUND;
19025       break;
19026     case grey_part:
19027       if ( has_color(p) )
19028           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19029       else goto NOT_FOUND;
19030       break;
19031     case color_model_part:
19032       if ( has_color(p) ) {
19033         if ( color_model(p)==mp_uninitialized_model )
19034           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19035         else
19036           mp_flush_cur_exp(mp, color_model(p)*unity);
19037       } else goto NOT_FOUND;
19038       break;
19039     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19040     } /* all cases have been enumerated */
19041     return;
19042   };
19043 NOT_FOUND:
19044   @<Convert the current expression to a null value appropriate
19045     for |c|@>;
19046 }
19047
19048 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19049 case text_part: 
19050   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19051   else { 
19052     mp_flush_cur_exp(mp, text_p(p));
19053     add_str_ref(mp->cur_exp);
19054     mp->cur_type=mp_string_type;
19055     };
19056   break;
19057 case font_part: 
19058   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19059   else { 
19060     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
19061     add_str_ref(mp->cur_exp);
19062     mp->cur_type=mp_string_type;
19063   };
19064   break;
19065 case path_part:
19066   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19067   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19068 @:this can't happen pict}{\quad pict@>
19069   else { 
19070     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19071     mp->cur_type=mp_path_type;
19072   }
19073   break;
19074 case pen_part: 
19075   if ( ! has_pen(p) ) goto NOT_FOUND;
19076   else {
19077     if ( pen_p(p)==null ) goto NOT_FOUND;
19078     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19079       mp->cur_type=mp_pen_type;
19080     };
19081   }
19082   break;
19083 case dash_part: 
19084   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19085   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19086     else { add_edge_ref(dash_p(p));
19087     mp->se_sf=dash_scale(p);
19088     mp->se_pic=dash_p(p);
19089     mp_scale_edges(mp);
19090     mp_flush_cur_exp(mp, mp->se_pic);
19091     mp->cur_type=mp_picture_type;
19092     };
19093   }
19094   break;
19095
19096 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19097 parameterless procedure even though it really takes two arguments and updates
19098 one of them.  Hence the following globals are needed.
19099
19100 @<Global...@>=
19101 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19102 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19103
19104 @ @<Convert the current expression to a null value appropriate...@>=
19105 switch (c) {
19106 case text_part: case font_part: 
19107   mp_flush_cur_exp(mp, rts(""));
19108   mp->cur_type=mp_string_type;
19109   break;
19110 case path_part: 
19111   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19112   left_type(mp->cur_exp)=mp_endpoint;
19113   right_type(mp->cur_exp)=mp_endpoint;
19114   link(mp->cur_exp)=mp->cur_exp;
19115   x_coord(mp->cur_exp)=0;
19116   y_coord(mp->cur_exp)=0;
19117   originator(mp->cur_exp)=mp_metapost_user;
19118   mp->cur_type=mp_path_type;
19119   break;
19120 case pen_part: 
19121   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19122   mp->cur_type=mp_pen_type;
19123   break;
19124 case dash_part: 
19125   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19126   mp_init_edges(mp, mp->cur_exp);
19127   mp->cur_type=mp_picture_type;
19128   break;
19129 default: 
19130    mp_flush_cur_exp(mp, 0);
19131   break;
19132 }
19133
19134 @ @<Additional cases of unary...@>=
19135 case char_op: 
19136   if ( mp->cur_type!=mp_known ) { 
19137     mp_bad_unary(mp, char_op);
19138   } else { 
19139     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19140     mp->cur_type=mp_string_type;
19141     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19142   }
19143   break;
19144 case decimal: 
19145   if ( mp->cur_type!=mp_known ) {
19146      mp_bad_unary(mp, decimal);
19147   } else { 
19148     mp->old_setting=mp->selector; mp->selector=new_string;
19149     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19150     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19151   }
19152   break;
19153 case oct_op:
19154 case hex_op:
19155 case ASCII_op: 
19156   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19157   else mp_str_to_num(mp, c);
19158   break;
19159 case font_size: 
19160   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19161   else @<Find the design size of the font whose name is |cur_exp|@>;
19162   break;
19163
19164 @ @<Declare unary action...@>=
19165 void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19166   integer n; /* accumulator */
19167   ASCII_code m; /* current character */
19168   pool_pointer k; /* index into |str_pool| */
19169   int b; /* radix of conversion */
19170   boolean bad_char; /* did the string contain an invalid digit? */
19171   if ( c==ASCII_op ) {
19172     if ( length(mp->cur_exp)==0 ) n=-1;
19173     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19174   } else { 
19175     if ( c==oct_op ) b=8; else b=16;
19176     n=0; bad_char=false;
19177     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19178       m=mp->str_pool[k];
19179       if ( (m>='0')&&(m<='9') ) m=m-'0';
19180       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19181       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19182       else  { bad_char=true; m=0; };
19183       if ( m>=b ) { bad_char=true; m=0; };
19184       if ( n<32768 / b ) n=n*b+m; else n=32767;
19185     }
19186     @<Give error messages if |bad_char| or |n>=4096|@>;
19187   }
19188   mp_flush_cur_exp(mp, n*unity);
19189 }
19190
19191 @ @<Give error messages if |bad_char|...@>=
19192 if ( bad_char ) { 
19193   exp_err("String contains illegal digits");
19194 @.String contains illegal digits@>
19195   if ( c==oct_op ) {
19196     help1("I zeroed out characters that weren't in the range 0..7.");
19197   } else  {
19198     help1("I zeroed out characters that weren't hex digits.");
19199   }
19200   mp_put_get_error(mp);
19201 }
19202 if ( (n>4095) ) {
19203   if ( mp->internal[mp_warning_check]>0 ) {
19204     print_err("Number too large ("); 
19205     mp_print_int(mp, n); mp_print_char(mp, ')');
19206 @.Number too large@>
19207     help2("I have trouble with numbers greater than 4095; watch out.")
19208       ("(Set warningcheck:=0 to suppress this message.)");
19209     mp_put_get_error(mp);
19210   }
19211 }
19212
19213 @ The length operation is somewhat unusual in that it applies to a variety
19214 of different types of operands.
19215
19216 @<Additional cases of unary...@>=
19217 case length_op: 
19218   switch (mp->cur_type) {
19219   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19220   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19221   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19222   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19223   default: 
19224     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19225       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19226         value(x_part_loc(value(mp->cur_exp))),
19227         value(y_part_loc(value(mp->cur_exp)))));
19228     else mp_bad_unary(mp, c);
19229     break;
19230   }
19231   break;
19232
19233 @ @<Declare unary action...@>=
19234 scaled mp_path_length (MP mp) { /* computes the length of the current path */
19235   scaled n; /* the path length so far */
19236   pointer p; /* traverser */
19237   p=mp->cur_exp;
19238   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
19239   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
19240   return n;
19241 }
19242
19243 @ @<Declare unary action...@>=
19244 scaled mp_pict_length (MP mp) { 
19245   /* counts interior components in picture |cur_exp| */
19246   scaled n; /* the count so far */
19247   pointer p; /* traverser */
19248   n=0;
19249   p=link(dummy_loc(mp->cur_exp));
19250   if ( p!=null ) {
19251     if ( is_start_or_stop(p) )
19252       if ( mp_skip_1component(mp, p)==null ) p=link(p);
19253     while ( p!=null )  { 
19254       skip_component(p) return n; 
19255       n=n+unity;   
19256     }
19257   }
19258   return n;
19259 }
19260
19261 @ Implement |turningnumber|
19262
19263 @<Additional cases of unary...@>=
19264 case turning_op:
19265   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19266   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19267   else if ( left_type(mp->cur_exp)==mp_endpoint )
19268      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19269   else
19270     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19271   break;
19272
19273 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19274 argument is |origin|.
19275
19276 @<Declare unary action...@>=
19277 angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19278   if ( (! ((xpar==0) && (ypar==0))) )
19279     return mp_n_arg(mp, xpar,ypar);
19280   return 0;
19281 }
19282
19283
19284 @ The actual turning number is (for the moment) computed in a C function
19285 that receives eight integers corresponding to the four controlling points,
19286 and returns a single angle.  Besides those, we have to account for discrete
19287 moves at the actual points.
19288
19289 @d floor(a) (a>=0 ? a : -(int)(-a))
19290 @d bezier_error (720<<20)+1
19291 @d sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19292 @d print_roots(a) 
19293 @d out ((double)(xo>>20))
19294 @d mid ((double)(xm>>20))
19295 @d in  ((double)(xi>>20))
19296 @d divisor (256*256)
19297 @d double2angle(a) (int)floor(a*256.0*256.0*16.0)
19298
19299 @<Declare unary action...@>=
19300 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19301             integer CX,integer CY,integer DX,integer DY);
19302
19303 @ @c 
19304 angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19305             integer CX,integer CY,integer DX,integer DY) {
19306   double a, b, c;
19307   integer deltax,deltay;
19308   double ax,ay,bx,by,cx,cy,dx,dy;
19309   angle xi = 0, xo = 0, xm = 0;
19310   double res = 0;
19311   ax=AX/divisor;  ay=AY/divisor;
19312   bx=BX/divisor;  by=BY/divisor;
19313   cx=CX/divisor;  cy=CY/divisor;
19314   dx=DX/divisor;  dy=DY/divisor;
19315
19316   deltax = (BX-AX); deltay = (BY-AY);
19317   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19318   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19319   xi = mp_an_angle(mp,deltax,deltay);
19320
19321   deltax = (CX-BX); deltay = (CY-BY);
19322   xm = mp_an_angle(mp,deltax,deltay);
19323
19324   deltax = (DX-CX); deltay = (DY-CY);
19325   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19326   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19327   xo = mp_an_angle(mp,deltax,deltay);
19328
19329   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19330   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19331   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19332
19333   if ((a==0)&&(c==0)) {
19334     res = (b==0 ?  0 :  (out-in)); 
19335     print_roots("no roots (a)");
19336   } else if ((a==0)||(c==0)) {
19337     if ((sign(b) == sign(a)) || (sign(b) == sign(c))) {
19338       res = out-in; /* ? */
19339       if (res<-180.0) 
19340         res += 360.0;
19341       else if (res>180.0)
19342         res -= 360.0;
19343       print_roots("no roots (b)");
19344     } else {
19345       res = out-in; /* ? */
19346       print_roots("one root (a)");
19347     }
19348   } else if ((sign(a)*sign(c))<0) {
19349     res = out-in; /* ? */
19350       if (res<-180.0) 
19351         res += 360.0;
19352       else if (res>180.0)
19353         res -= 360.0;
19354     print_roots("one root (b)");
19355   } else {
19356     if (sign(a) == sign(b)) {
19357       res = out-in; /* ? */
19358       if (res<-180.0) 
19359         res += 360.0;
19360       else if (res>180.0)
19361         res -= 360.0;
19362       print_roots("no roots (d)");
19363     } else {
19364       if ((b*b) == (4*a*c)) {
19365         res = bezier_error;
19366         print_roots("double root"); /* cusp */
19367       } else if ((b*b) < (4*a*c)) {
19368         res = out-in; /* ? */
19369         if (res<=0.0 &&res>-180.0) 
19370           res += 360.0;
19371         else if (res>=0.0 && res<180.0)
19372           res -= 360.0;
19373         print_roots("no roots (e)");
19374       } else {
19375         res = out-in;
19376         if (res<-180.0) 
19377           res += 360.0;
19378         else if (res>180.0)
19379           res -= 360.0;
19380         print_roots("two roots"); /* two inflections */
19381       }
19382     }
19383   }
19384   return double2angle(res);
19385 }
19386
19387 @
19388 @d p_nextnext link(link(p))
19389 @d p_next link(p)
19390 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19391
19392 @<Declare unary action...@>=
19393 scaled mp_new_turn_cycles (MP mp,pointer c) {
19394   angle res,ang; /*  the angles of intermediate results  */
19395   scaled turns;  /*  the turn counter  */
19396   pointer p;     /*  for running around the path  */
19397   integer xp,yp;   /*  coordinates of next point  */
19398   integer x,y;   /*  helper coordinates  */
19399   angle in_angle,out_angle;     /*  helper angles */
19400   int old_setting; /* saved |selector| setting */
19401   res=0;
19402   turns= 0;
19403   p=c;
19404   old_setting = mp->selector; mp->selector=term_only;
19405   if ( mp->internal[mp_tracing_commands]>unity ) {
19406     mp_begin_diagnostic(mp);
19407     mp_print_nl(mp, "");
19408     mp_end_diagnostic(mp, false);
19409   }
19410   do { 
19411     xp = x_coord(p_next); yp = y_coord(p_next);
19412     ang  = mp_bezier_slope(mp,x_coord(p), y_coord(p), right_x(p), right_y(p),
19413              left_x(p_next), left_y(p_next), xp, yp);
19414     if ( ang>seven_twenty_deg ) {
19415       print_err("Strange path");
19416       mp_error(mp);
19417       mp->selector=old_setting;
19418       return 0;
19419     }
19420     res  = res + ang;
19421     if ( res > one_eighty_deg ) {
19422       res = res - three_sixty_deg;
19423       turns = turns + unity;
19424     }
19425     if ( res <= -one_eighty_deg ) {
19426       res = res + three_sixty_deg;
19427       turns = turns - unity;
19428     }
19429     /*  incoming angle at next point  */
19430     x = left_x(p_next);  y = left_y(p_next);
19431     if ( (xp==x)&&(yp==y) ) { x = right_x(p);  y = right_y(p);  };
19432     if ( (xp==x)&&(yp==y) ) { x = x_coord(p);  y = y_coord(p);  };
19433     in_angle = mp_an_angle(mp, xp - x, yp - y);
19434     /*  outgoing angle at next point  */
19435     x = right_x(p_next);  y = right_y(p_next);
19436     if ( (xp==x)&&(yp==y) ) { x = left_x(p_nextnext);  y = left_y(p_nextnext);  };
19437     if ( (xp==x)&&(yp==y) ) { x = x_coord(p_nextnext); y = y_coord(p_nextnext); };
19438     out_angle = mp_an_angle(mp, x - xp, y- yp);
19439     ang  = (out_angle - in_angle);
19440     reduce_angle(ang);
19441     if ( ang!=0 ) {
19442       res  = res + ang;
19443       if ( res >= one_eighty_deg ) {
19444         res = res - three_sixty_deg;
19445         turns = turns + unity;
19446       };
19447       if ( res <= -one_eighty_deg ) {
19448         res = res + three_sixty_deg;
19449         turns = turns - unity;
19450       };
19451     };
19452     p = link(p);
19453   } while (p!=c);
19454   mp->selector=old_setting;
19455   return turns;
19456 }
19457
19458
19459 @ This code is based on Bogus\l{}av Jackowski's
19460 |emergency_turningnumber| macro, with some minor changes by Taco
19461 Hoekwater. The macro code looked more like this:
19462 {\obeylines
19463 vardef turning\_number primary p =
19464 ~~save res, ang, turns;
19465 ~~res := 0;
19466 ~~if length p <= 2:
19467 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19468 ~~else:
19469 ~~~~for t = 0 upto length p-1 :
19470 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19471 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19472 ~~~~~~if angc > 180: angc := angc - 360; fi;
19473 ~~~~~~if angc < -180: angc := angc + 360; fi;
19474 ~~~~~~res  := res + angc;
19475 ~~~~endfor;
19476 ~~res/360
19477 ~~fi
19478 enddef;}
19479 The general idea is to calculate only the sum of the angles of
19480 straight lines between the points, of a path, not worrying about cusps
19481 or self-intersections in the segments at all. If the segment is not
19482 well-behaved, the result is not necesarily correct. But the old code
19483 was not always correct either, and worse, it sometimes failed for
19484 well-behaved paths as well. All known bugs that were triggered by the
19485 original code no longer occur with this code, and it runs roughly 3
19486 times as fast because the algorithm is much simpler.
19487
19488 @ It is possible to overflow the return value of the |turn_cycles|
19489 function when the path is sufficiently long and winding, but I am not
19490 going to bother testing for that. In any case, it would only return
19491 the looped result value, which is not a big problem.
19492
19493 The macro code for the repeat loop was a bit nicer to look
19494 at than the pascal code, because it could use |point -1 of p|. In
19495 pascal, the fastest way to loop around the path is not to look
19496 backward once, but forward twice. These defines help hide the trick.
19497
19498 @d p_to link(link(p))
19499 @d p_here link(p)
19500 @d p_from p
19501
19502 @<Declare unary action...@>=
19503 scaled mp_turn_cycles (MP mp,pointer c) {
19504   angle res,ang; /*  the angles of intermediate results  */
19505   scaled turns;  /*  the turn counter  */
19506   pointer p;     /*  for running around the path  */
19507   res=0;  turns= 0; p=c;
19508   do { 
19509     ang  = mp_an_angle (mp, x_coord(p_to) - x_coord(p_here), 
19510                             y_coord(p_to) - y_coord(p_here))
19511         - mp_an_angle (mp, x_coord(p_here) - x_coord(p_from), 
19512                            y_coord(p_here) - y_coord(p_from));
19513     reduce_angle(ang);
19514     res  = res + ang;
19515     if ( res >= three_sixty_deg )  {
19516       res = res - three_sixty_deg;
19517       turns = turns + unity;
19518     };
19519     if ( res <= -three_sixty_deg ) {
19520       res = res + three_sixty_deg;
19521       turns = turns - unity;
19522     };
19523     p = link(p);
19524   } while (p!=c);
19525   return turns;
19526 }
19527
19528 @ @<Declare unary action...@>=
19529 scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19530   scaled nval,oval;
19531   scaled saved_t_o; /* tracing\_online saved  */
19532   if ( (link(c)==c)||(link(link(c))==c) ) {
19533     if ( mp_an_angle (mp, x_coord(c) - right_x(c),  y_coord(c) - right_y(c)) > 0 )
19534       return unity;
19535     else
19536       return -unity;
19537   } else {
19538     nval = mp_new_turn_cycles(mp, c);
19539     oval = mp_turn_cycles(mp, c);
19540     if ( nval!=oval ) {
19541       saved_t_o=mp->internal[mp_tracing_online];
19542       mp->internal[mp_tracing_online]=unity;
19543       mp_begin_diagnostic(mp);
19544       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19545                        " The current computed value is ");
19546       mp_print_scaled(mp, nval);
19547       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19548       mp_print_scaled(mp, oval);
19549       mp_end_diagnostic(mp, false);
19550       mp->internal[mp_tracing_online]=saved_t_o;
19551     }
19552     return nval;
19553   }
19554 }
19555
19556 @ @<Declare unary action...@>=
19557 scaled mp_count_turns (MP mp,pointer c) {
19558   pointer p; /* a knot in envelope spec |c| */
19559   integer t; /* total pen offset changes counted */
19560   t=0; p=c;
19561   do {  
19562     t=t+info(p)-zero_off;
19563     p=link(p);
19564   } while (p!=c);
19565   return ((t / 3)*unity);
19566 }
19567
19568 @ @d type_range(A,B) { 
19569   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19570     mp_flush_cur_exp(mp, true_code);
19571   else mp_flush_cur_exp(mp, false_code);
19572   mp->cur_type=mp_boolean_type;
19573   }
19574 @d type_test(A) { 
19575   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19576   else mp_flush_cur_exp(mp, false_code);
19577   mp->cur_type=mp_boolean_type;
19578   }
19579
19580 @<Additional cases of unary operators@>=
19581 case mp_boolean_type: 
19582   type_range(mp_boolean_type,mp_unknown_boolean); break;
19583 case mp_string_type: 
19584   type_range(mp_string_type,mp_unknown_string); break;
19585 case mp_pen_type: 
19586   type_range(mp_pen_type,mp_unknown_pen); break;
19587 case mp_path_type: 
19588   type_range(mp_path_type,mp_unknown_path); break;
19589 case mp_picture_type: 
19590   type_range(mp_picture_type,mp_unknown_picture); break;
19591 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19592 case mp_pair_type: 
19593   type_test(c); break;
19594 case mp_numeric_type: 
19595   type_range(mp_known,mp_independent); break;
19596 case known_op: case unknown_op: 
19597   mp_test_known(mp, c); break;
19598
19599 @ @<Declare unary action procedures@>=
19600 void mp_test_known (MP mp,quarterword c) {
19601   int b; /* is the current expression known? */
19602   pointer p,q; /* locations in a big node */
19603   b=false_code;
19604   switch (mp->cur_type) {
19605   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19606   case mp_pen_type: case mp_path_type: case mp_picture_type:
19607   case mp_known: 
19608     b=true_code;
19609     break;
19610   case mp_transform_type:
19611   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19612     p=value(mp->cur_exp);
19613     q=p+mp->big_node_size[mp->cur_type];
19614     do {  
19615       q=q-2;
19616       if ( type(q)!=mp_known ) 
19617        goto DONE;
19618     } while (q!=p);
19619     b=true_code;
19620   DONE:  
19621     break;
19622   default: 
19623     break;
19624   }
19625   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19626   else mp_flush_cur_exp(mp, true_code+false_code-b);
19627   mp->cur_type=mp_boolean_type;
19628 }
19629
19630 @ @<Additional cases of unary operators@>=
19631 case cycle_op: 
19632   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19633   else if ( left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19634   else mp_flush_cur_exp(mp, false_code);
19635   mp->cur_type=mp_boolean_type;
19636   break;
19637
19638 @ @<Additional cases of unary operators@>=
19639 case arc_length: 
19640   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19641   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19642   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19643   break;
19644
19645 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19646 object |type|.
19647 @^data structure assumptions@>
19648
19649 @<Additional cases of unary operators@>=
19650 case filled_op:
19651 case stroked_op:
19652 case textual_op:
19653 case clipped_op:
19654 case bounded_op:
19655   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19656   else if ( link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19657   else if ( type(link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19658     mp_flush_cur_exp(mp, true_code);
19659   else mp_flush_cur_exp(mp, false_code);
19660   mp->cur_type=mp_boolean_type;
19661   break;
19662
19663 @ @<Additional cases of unary operators@>=
19664 case make_pen_op: 
19665   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19666   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19667   else { 
19668     mp->cur_type=mp_pen_type;
19669     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19670   };
19671   break;
19672 case make_path_op: 
19673   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19674   else  { 
19675     mp->cur_type=mp_path_type;
19676     mp_make_path(mp, mp->cur_exp);
19677   };
19678   break;
19679 case reverse: 
19680   if ( mp->cur_type==mp_path_type ) {
19681     p=mp_htap_ypoc(mp, mp->cur_exp);
19682     if ( right_type(p)==mp_endpoint ) p=link(p);
19683     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19684   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19685   else mp_bad_unary(mp, reverse);
19686   break;
19687
19688 @ The |pair_value| routine changes the current expression to a
19689 given ordered pair of values.
19690
19691 @<Declare unary action procedures@>=
19692 void mp_pair_value (MP mp,scaled x, scaled y) {
19693   pointer p; /* a pair node */
19694   p=mp_get_node(mp, value_node_size); 
19695   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19696   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19697   p=value(p);
19698   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19699   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19700 }
19701
19702 @ @<Additional cases of unary operators@>=
19703 case ll_corner_op: 
19704   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19705   else mp_pair_value(mp, minx,miny);
19706   break;
19707 case lr_corner_op: 
19708   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19709   else mp_pair_value(mp, maxx,miny);
19710   break;
19711 case ul_corner_op: 
19712   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19713   else mp_pair_value(mp, minx,maxy);
19714   break;
19715 case ur_corner_op: 
19716   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19717   else mp_pair_value(mp, maxx,maxy);
19718   break;
19719
19720 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19721 box of the current expression.  The boolean result is |false| if the expression
19722 has the wrong type.
19723
19724 @<Declare unary action procedures@>=
19725 boolean mp_get_cur_bbox (MP mp) { 
19726   switch (mp->cur_type) {
19727   case mp_picture_type: 
19728     mp_set_bbox(mp, mp->cur_exp,true);
19729     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19730       minx=0; maxx=0; miny=0; maxy=0;
19731     } else { 
19732       minx=minx_val(mp->cur_exp);
19733       maxx=maxx_val(mp->cur_exp);
19734       miny=miny_val(mp->cur_exp);
19735       maxy=maxy_val(mp->cur_exp);
19736     }
19737     break;
19738   case mp_path_type: 
19739     mp_path_bbox(mp, mp->cur_exp);
19740     break;
19741   case mp_pen_type: 
19742     mp_pen_bbox(mp, mp->cur_exp);
19743     break;
19744   default: 
19745     return false;
19746   }
19747   return true;
19748 }
19749
19750 @ @<Additional cases of unary operators@>=
19751 case read_from_op:
19752 case close_from_op: 
19753   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19754   else mp_do_read_or_close(mp,c);
19755   break;
19756
19757 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19758 a line from the file or to close the file.
19759
19760 @<Declare unary action procedures@>=
19761 void mp_do_read_or_close (MP mp,quarterword c) {
19762   readf_index n,n0; /* indices for searching |rd_fname| */
19763   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19764     call |start_read_input| and |goto found| or |not_found|@>;
19765   mp_begin_file_reading(mp);
19766   name=is_read;
19767   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19768     goto FOUND;
19769   mp_end_file_reading(mp);
19770 NOT_FOUND:
19771   @<Record the end of file and set |cur_exp| to a dummy value@>;
19772   return;
19773 CLOSE_FILE:
19774   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19775   return;
19776 FOUND:
19777   mp_flush_cur_exp(mp, 0);
19778   mp_finish_read(mp);
19779 }
19780
19781 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19782 |rd_fname|.
19783
19784 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19785 {   
19786   char *fn;
19787   n=mp->read_files;
19788   n0=mp->read_files;
19789   fn = str(mp->cur_exp);
19790   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19791     if ( n>0 ) {
19792       decr(n);
19793     } else if ( c==close_from_op ) {
19794       goto CLOSE_FILE;
19795     } else {
19796       if ( n0==mp->read_files ) {
19797         if ( mp->read_files<mp->max_read_files ) {
19798           incr(mp->read_files);
19799         } else {
19800           void **rd_file;
19801           char **rd_fname;
19802               readf_index l,k;
19803           l = mp->max_read_files + (mp->max_read_files>>2);
19804           rd_file = xmalloc((l+1), sizeof(void *));
19805           rd_fname = xmalloc((l+1), sizeof(char *));
19806               for (k=0;k<=l;k++) {
19807             if (k<=mp->max_read_files) {
19808                   rd_file[k]=mp->rd_file[k]; 
19809               rd_fname[k]=mp->rd_fname[k];
19810             } else {
19811               rd_file[k]=0; 
19812               rd_fname[k]=NULL;
19813             }
19814           }
19815               xfree(mp->rd_file); xfree(mp->rd_fname);
19816           mp->max_read_files = l;
19817           mp->rd_file = rd_file;
19818           mp->rd_fname = rd_fname;
19819         }
19820       }
19821       n=n0;
19822       if ( mp_start_read_input(mp,fn,n) ) 
19823         goto FOUND;
19824       else 
19825         goto NOT_FOUND;
19826     }
19827     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19828   } 
19829   if ( c==close_from_op ) { 
19830     (mp->close_file)(mp,mp->rd_file[n]); 
19831     goto NOT_FOUND; 
19832   }
19833 }
19834
19835 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19836 xfree(mp->rd_fname[n]);
19837 mp->rd_fname[n]=NULL;
19838 if ( n==mp->read_files-1 ) mp->read_files=n;
19839 if ( c==close_from_op ) 
19840   goto CLOSE_FILE;
19841 mp_flush_cur_exp(mp, mp->eof_line);
19842 mp->cur_type=mp_string_type
19843
19844 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19845
19846 @<Glob...@>=
19847 str_number eof_line;
19848
19849 @ @<Set init...@>=
19850 mp->eof_line=0;
19851
19852 @ Finally, we have the operations that combine a capsule~|p|
19853 with the current expression.
19854
19855 @d binary_return  { mp_finish_binary(mp, old_p, old_exp); return; }
19856
19857 @c @<Declare binary action procedures@>
19858 void mp_finish_binary (MP mp, pointer old_p, pointer old_exp ){
19859   check_arith; 
19860   @<Recycle any sidestepped |independent| capsules@>;
19861 }
19862 void mp_do_binary (MP mp,pointer p, quarterword c) {
19863   pointer q,r,rr; /* for list manipulation */
19864   pointer old_p,old_exp; /* capsules to recycle */
19865   integer v; /* for numeric manipulation */
19866   check_arith;
19867   if ( mp->internal[mp_tracing_commands]>two ) {
19868     @<Trace the current binary operation@>;
19869   }
19870   @<Sidestep |independent| cases in capsule |p|@>;
19871   @<Sidestep |independent| cases in the current expression@>;
19872   switch (c) {
19873   case plus: case minus:
19874     @<Add or subtract the current expression from |p|@>;
19875     break;
19876   @<Additional cases of binary operators@>;
19877   }; /* there are no other cases */
19878   mp_recycle_value(mp, p); 
19879   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
19880   mp_finish_binary(mp, old_p, old_exp);
19881 }
19882
19883 @ @<Declare binary action...@>=
19884 void mp_bad_binary (MP mp,pointer p, quarterword c) { 
19885   mp_disp_err(mp, p,"");
19886   exp_err("Not implemented: ");
19887 @.Not implemented...@>
19888   if ( c>=min_of ) mp_print_op(mp, c);
19889   mp_print_known_or_unknown_type(mp, type(p),p);
19890   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
19891   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
19892   help3("I'm afraid I don't know how to apply that operation to that")
19893        ("combination of types. Continue, and I'll return the second")
19894       ("argument (see above) as the result of the operation.");
19895   mp_put_get_error(mp);
19896 }
19897 void mp_bad_envelope_pen (MP mp) {
19898   mp_disp_err(mp, null,"");
19899   exp_err("Not implemented: envelope(elliptical pen)of(path)");
19900 @.Not implemented...@>
19901   help3("I'm afraid I don't know how to apply that operation to that")
19902        ("combination of types. Continue, and I'll return the second")
19903       ("argument (see above) as the result of the operation.");
19904   mp_put_get_error(mp);
19905 }
19906
19907 @ @<Trace the current binary operation@>=
19908
19909   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
19910   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
19911   mp_print_char(mp,')'); mp_print_op(mp,c); mp_print_char(mp,'(');
19912   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
19913   mp_end_diagnostic(mp, false);
19914 }
19915
19916 @ Several of the binary operations are potentially complicated by the
19917 fact that |independent| values can sneak into capsules. For example,
19918 we've seen an instance of this difficulty in the unary operation
19919 of negation. In order to reduce the number of cases that need to be
19920 handled, we first change the two operands (if necessary)
19921 to rid them of |independent| components. The original operands are
19922 put into capsules called |old_p| and |old_exp|, which will be
19923 recycled after the binary operation has been safely carried out.
19924
19925 @<Recycle any sidestepped |independent| capsules@>=
19926 if ( old_p!=null ) { 
19927   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
19928 }
19929 if ( old_exp!=null ) {
19930   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
19931 }
19932
19933 @ A big node is considered to be ``tarnished'' if it contains at least one
19934 independent component. We will define a simple function called `|tarnished|'
19935 that returns |null| if and only if its argument is not tarnished.
19936
19937 @<Sidestep |independent| cases in capsule |p|@>=
19938 switch (type(p)) {
19939 case mp_transform_type:
19940 case mp_color_type:
19941 case mp_cmykcolor_type:
19942 case mp_pair_type: 
19943   old_p=mp_tarnished(mp, p);
19944   break;
19945 case mp_independent: old_p=mp_void; break;
19946 default: old_p=null; break;
19947 }
19948 if ( old_p!=null ) {
19949   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
19950   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
19951 }
19952
19953 @ @<Sidestep |independent| cases in the current expression@>=
19954 switch (mp->cur_type) {
19955 case mp_transform_type:
19956 case mp_color_type:
19957 case mp_cmykcolor_type:
19958 case mp_pair_type: 
19959   old_exp=mp_tarnished(mp, mp->cur_exp);
19960   break;
19961 case mp_independent:old_exp=mp_void; break;
19962 default: old_exp=null; break;
19963 }
19964 if ( old_exp!=null ) {
19965   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
19966 }
19967
19968 @ @<Declare binary action...@>=
19969 pointer mp_tarnished (MP mp,pointer p) {
19970   pointer q; /* beginning of the big node */
19971   pointer r; /* current position in the big node */
19972   q=value(p); r=q+mp->big_node_size[type(p)];
19973   do {  
19974    r=r-2;
19975    if ( type(r)==mp_independent ) return mp_void; 
19976   } while (r!=q);
19977   return null;
19978 }
19979
19980 @ @<Add or subtract the current expression from |p|@>=
19981 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
19982   mp_bad_binary(mp, p,c);
19983 } else  {
19984   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
19985     mp_add_or_subtract(mp, p,null,c);
19986   } else {
19987     if ( mp->cur_type!=type(p) )  {
19988       mp_bad_binary(mp, p,c);
19989     } else { 
19990       q=value(p); r=value(mp->cur_exp);
19991       rr=r+mp->big_node_size[mp->cur_type];
19992       while ( r<rr ) { 
19993         mp_add_or_subtract(mp, q,r,c);
19994         q=q+2; r=r+2;
19995       }
19996     }
19997   }
19998 }
19999
20000 @ The first argument to |add_or_subtract| is the location of a value node
20001 in a capsule or pair node that will soon be recycled. The second argument
20002 is either a location within a pair or transform node of |cur_exp|,
20003 or it is null (which means that |cur_exp| itself should be the second
20004 argument).  The third argument is either |plus| or |minus|.
20005
20006 The sum or difference of the numeric quantities will replace the second
20007 operand.  Arithmetic overflow may go undetected; users aren't supposed to
20008 be monkeying around with really big values.
20009 @^overflow in arithmetic@>
20010
20011 @<Declare binary action...@>=
20012 @<Declare the procedure called |dep_finish|@>
20013 void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20014   small_number s,t; /* operand types */
20015   pointer r; /* list traverser */
20016   integer v; /* second operand value */
20017   if ( q==null ) { 
20018     t=mp->cur_type;
20019     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20020   } else { 
20021     t=type(q);
20022     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20023   }
20024   if ( t==mp_known ) {
20025     if ( c==minus ) negate(v);
20026     if ( type(p)==mp_known ) {
20027       v=mp_slow_add(mp, value(p),v);
20028       if ( q==null ) mp->cur_exp=v; else value(q)=v;
20029       return;
20030     }
20031     @<Add a known value to the constant term of |dep_list(p)|@>;
20032   } else  { 
20033     if ( c==minus ) mp_negate_dep_list(mp, v);
20034     @<Add operand |p| to the dependency list |v|@>;
20035   }
20036 }
20037
20038 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20039 r=dep_list(p);
20040 while ( info(r)!=null ) r=link(r);
20041 value(r)=mp_slow_add(mp, value(r),v);
20042 if ( q==null ) {
20043   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
20044   name_type(q)=mp_capsule;
20045 }
20046 dep_list(q)=dep_list(p); type(q)=type(p);
20047 prev_dep(q)=prev_dep(p); link(prev_dep(p))=q;
20048 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20049
20050 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20051 nice to retain the extra accuracy of |fraction| coefficients.
20052 But we have to handle both kinds, and mixtures too.
20053
20054 @<Add operand |p| to the dependency list |v|@>=
20055 if ( type(p)==mp_known ) {
20056   @<Add the known |value(p)| to the constant term of |v|@>;
20057 } else { 
20058   s=type(p); r=dep_list(p);
20059   if ( t==mp_dependent ) {
20060     if ( s==mp_dependent ) {
20061       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20062         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20063       } /* |fix_needed| will necessarily be false */
20064       t=mp_proto_dependent; 
20065       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20066     }
20067     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20068     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20069  DONE:  
20070     @<Output the answer, |v| (which might have become |known|)@>;
20071   }
20072
20073 @ @<Add the known |value(p)| to the constant term of |v|@>=
20074
20075   while ( info(v)!=null ) v=link(v);
20076   value(v)=mp_slow_add(mp, value(p),value(v));
20077 }
20078
20079 @ @<Output the answer, |v| (which might have become |known|)@>=
20080 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20081 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20082
20083 @ Here's the current situation: The dependency list |v| of type |t|
20084 should either be put into the current expression (if |q=null|) or
20085 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20086 or |q|) formerly held a dependency list with the same
20087 final pointer as the list |v|.
20088
20089 @<Declare the procedure called |dep_finish|@>=
20090 void mp_dep_finish (MP mp, pointer v, pointer q, small_number t) {
20091   pointer p; /* the destination */
20092   scaled vv; /* the value, if it is |known| */
20093   if ( q==null ) p=mp->cur_exp; else p=q;
20094   dep_list(p)=v; type(p)=t;
20095   if ( info(v)==null ) { 
20096     vv=value(v);
20097     if ( q==null ) { 
20098       mp_flush_cur_exp(mp, vv);
20099     } else  { 
20100       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20101     }
20102   } else if ( q==null ) {
20103     mp->cur_type=t;
20104   }
20105   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20106 }
20107
20108 @ Let's turn now to the six basic relations of comparison.
20109
20110 @<Additional cases of binary operators@>=
20111 case less_than: case less_or_equal: case greater_than:
20112 case greater_or_equal: case equal_to: case unequal_to:
20113   check_arith; /* at this point |arith_error| should be |false|? */
20114   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20115     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20116   } else if ( mp->cur_type!=type(p) ) {
20117     mp_bad_binary(mp, p,c); goto DONE; 
20118   } else if ( mp->cur_type==mp_string_type ) {
20119     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20120   } else if ((mp->cur_type==mp_unknown_string)||
20121            (mp->cur_type==mp_unknown_boolean) ) {
20122     @<Check if unknowns have been equated@>;
20123   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20124     @<Reduce comparison of big nodes to comparison of scalars@>;
20125   } else if ( mp->cur_type==mp_boolean_type ) {
20126     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20127   } else { 
20128     mp_bad_binary(mp, p,c); goto DONE;
20129   }
20130   @<Compare the current expression with zero@>;
20131 DONE:  
20132   mp->arith_error=false; /* ignore overflow in comparisons */
20133   break;
20134
20135 @ @<Compare the current expression with zero@>=
20136 if ( mp->cur_type!=mp_known ) {
20137   if ( mp->cur_type<mp_known ) {
20138     mp_disp_err(mp, p,"");
20139     help1("The quantities shown above have not been equated.")
20140   } else  {
20141     help2("Oh dear. I can\'t decide if the expression above is positive,")
20142      ("negative, or zero. So this comparison test won't be `true'.");
20143   }
20144   exp_err("Unknown relation will be considered false");
20145 @.Unknown relation...@>
20146   mp_put_get_flush_error(mp, false_code);
20147 } else {
20148   switch (c) {
20149   case less_than: boolean_reset(mp->cur_exp<0); break;
20150   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20151   case greater_than: boolean_reset(mp->cur_exp>0); break;
20152   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20153   case equal_to: boolean_reset(mp->cur_exp==0); break;
20154   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20155   }; /* there are no other cases */
20156 }
20157 mp->cur_type=mp_boolean_type
20158
20159 @ When two unknown strings are in the same ring, we know that they are
20160 equal. Otherwise, we don't know whether they are equal or not, so we
20161 make no change.
20162
20163 @<Check if unknowns have been equated@>=
20164
20165   q=value(mp->cur_exp);
20166   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20167   if ( q==p ) mp_flush_cur_exp(mp, 0);
20168 }
20169
20170 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20171
20172   q=value(p); r=value(mp->cur_exp);
20173   rr=r+mp->big_node_size[mp->cur_type]-2;
20174   while (1) { mp_add_or_subtract(mp, q,r,minus);
20175     if ( type(r)!=mp_known ) break;
20176     if ( value(r)!=0 ) break;
20177     if ( r==rr ) break;
20178     q=q+2; r=r+2;
20179   }
20180   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20181 }
20182
20183 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20184
20185 @<Additional cases of binary operators@>=
20186 case and_op:
20187 case or_op: 
20188   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20189     mp_bad_binary(mp, p,c);
20190   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20191   break;
20192
20193 @ @<Additional cases of binary operators@>=
20194 case times: 
20195   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20196    mp_bad_binary(mp, p,times);
20197   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20198     @<Multiply when at least one operand is known@>;
20199   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20200       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20201           (type(p)>mp_pair_type)) ) {
20202     mp_hard_times(mp, p); 
20203     binary_return;
20204   } else {
20205     mp_bad_binary(mp, p,times);
20206   }
20207   break;
20208
20209 @ @<Multiply when at least one operand is known@>=
20210
20211   if ( type(p)==mp_known ) {
20212     v=value(p); mp_free_node(mp, p,value_node_size); 
20213   } else {
20214     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20215   }
20216   if ( mp->cur_type==mp_known ) {
20217     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20218   } else if ( (mp->cur_type==mp_pair_type)||
20219               (mp->cur_type==mp_color_type)||
20220               (mp->cur_type==mp_cmykcolor_type) ) {
20221     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20222     do {  
20223        p=p-2; mp_dep_mult(mp, p,v,true);
20224     } while (p!=value(mp->cur_exp));
20225   } else {
20226     mp_dep_mult(mp, null,v,true);
20227   }
20228   binary_return;
20229 }
20230
20231 @ @<Declare binary action...@>=
20232 void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20233   pointer q; /* the dependency list being multiplied by |v| */
20234   small_number s,t; /* its type, before and after */
20235   if ( p==null ) {
20236     q=mp->cur_exp;
20237   } else if ( type(p)!=mp_known ) {
20238     q=p;
20239   } else { 
20240     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20241     else value(p)=mp_take_fraction(mp, value(p),v);
20242     return;
20243   };
20244   t=type(q); q=dep_list(q); s=t;
20245   if ( t==mp_dependent ) if ( v_is_scaled )
20246     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20247       t=mp_proto_dependent;
20248   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20249   mp_dep_finish(mp, q,p,t);
20250 }
20251
20252 @ Here is a routine that is similar to |times|; but it is invoked only
20253 internally, when |v| is a |fraction| whose magnitude is at most~1,
20254 and when |cur_type>=mp_color_type|.
20255
20256 @c void mp_frac_mult (MP mp,scaled n, scaled d) {
20257   /* multiplies |cur_exp| by |n/d| */
20258   pointer p; /* a pair node */
20259   pointer old_exp; /* a capsule to recycle */
20260   fraction v; /* |n/d| */
20261   if ( mp->internal[mp_tracing_commands]>two ) {
20262     @<Trace the fraction multiplication@>;
20263   }
20264   switch (mp->cur_type) {
20265   case mp_transform_type:
20266   case mp_color_type:
20267   case mp_cmykcolor_type:
20268   case mp_pair_type:
20269    old_exp=mp_tarnished(mp, mp->cur_exp);
20270    break;
20271   case mp_independent: old_exp=mp_void; break;
20272   default: old_exp=null; break;
20273   }
20274   if ( old_exp!=null ) { 
20275      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20276   }
20277   v=mp_make_fraction(mp, n,d);
20278   if ( mp->cur_type==mp_known ) {
20279     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20280   } else if ( mp->cur_type<=mp_pair_type ) { 
20281     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20282     do {  
20283       p=p-2;
20284       mp_dep_mult(mp, p,v,false);
20285     } while (p!=value(mp->cur_exp));
20286   } else {
20287     mp_dep_mult(mp, null,v,false);
20288   }
20289   if ( old_exp!=null ) {
20290     mp_recycle_value(mp, old_exp); 
20291     mp_free_node(mp, old_exp,value_node_size);
20292   }
20293 }
20294
20295 @ @<Trace the fraction multiplication@>=
20296
20297   mp_begin_diagnostic(mp); 
20298   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,'/');
20299   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20300   mp_print(mp,")}");
20301   mp_end_diagnostic(mp, false);
20302 }
20303
20304 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20305
20306 @<Declare binary action procedures@>=
20307 void mp_hard_times (MP mp,pointer p) {
20308   pointer q; /* a copy of the dependent variable |p| */
20309   pointer r; /* a component of the big node for the nice color or pair */
20310   scaled v; /* the known value for |r| */
20311   if ( type(p)<=mp_pair_type ) { 
20312      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20313   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20314   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20315   while (1) { 
20316     r=r-2;
20317     v=value(r);
20318     type(r)=type(p);
20319     if ( r==value(mp->cur_exp) ) 
20320       break;
20321     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20322     mp_dep_mult(mp, r,v,true);
20323   }
20324   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20325   link(prev_dep(p))=r;
20326   mp_free_node(mp, p,value_node_size);
20327   mp_dep_mult(mp, r,v,true);
20328 }
20329
20330 @ @<Additional cases of binary operators@>=
20331 case over: 
20332   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20333     mp_bad_binary(mp, p,over);
20334   } else { 
20335     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20336     if ( v==0 ) {
20337       @<Squeal about division by zero@>;
20338     } else { 
20339       if ( mp->cur_type==mp_known ) {
20340         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20341       } else if ( mp->cur_type<=mp_pair_type ) { 
20342         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20343         do {  
20344           p=p-2;  mp_dep_div(mp, p,v);
20345         } while (p!=value(mp->cur_exp));
20346       } else {
20347         mp_dep_div(mp, null,v);
20348       }
20349     }
20350     binary_return;
20351   }
20352   break;
20353
20354 @ @<Declare binary action...@>=
20355 void mp_dep_div (MP mp,pointer p, scaled v) {
20356   pointer q; /* the dependency list being divided by |v| */
20357   small_number s,t; /* its type, before and after */
20358   if ( p==null ) q=mp->cur_exp;
20359   else if ( type(p)!=mp_known ) q=p;
20360   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20361   t=type(q); q=dep_list(q); s=t;
20362   if ( t==mp_dependent )
20363     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20364       t=mp_proto_dependent;
20365   q=mp_p_over_v(mp, q,v,s,t); 
20366   mp_dep_finish(mp, q,p,t);
20367 }
20368
20369 @ @<Squeal about division by zero@>=
20370
20371   exp_err("Division by zero");
20372 @.Division by zero@>
20373   help2("You're trying to divide the quantity shown above the error")
20374     ("message by zero. I'm going to divide it by one instead.");
20375   mp_put_get_error(mp);
20376 }
20377
20378 @ @<Additional cases of binary operators@>=
20379 case pythag_add:
20380 case pythag_sub: 
20381    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20382      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20383      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20384    } else mp_bad_binary(mp, p,c);
20385    break;
20386
20387 @ The next few sections of the program deal with affine transformations
20388 of coordinate data.
20389
20390 @<Additional cases of binary operators@>=
20391 case rotated_by: case slanted_by:
20392 case scaled_by: case shifted_by: case transformed_by:
20393 case x_scaled: case y_scaled: case z_scaled:
20394   if ( type(p)==mp_path_type ) { 
20395     path_trans(c,p); binary_return;
20396   } else if ( type(p)==mp_pen_type ) { 
20397     pen_trans(c,p);
20398     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20399       /* rounding error could destroy convexity */
20400     binary_return;
20401   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20402     mp_big_trans(mp, p,c);
20403   } else if ( type(p)==mp_picture_type ) {
20404     mp_do_edges_trans(mp, p,c); binary_return;
20405   } else {
20406     mp_bad_binary(mp, p,c);
20407   }
20408   break;
20409
20410 @ Let |c| be one of the eight transform operators. The procedure call
20411 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20412 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20413 change at all if |c=transformed_by|.)
20414
20415 Then, if all components of the resulting transform are |known|, they are
20416 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20417 and |cur_exp| is changed to the known value zero.
20418
20419 @<Declare binary action...@>=
20420 void mp_set_up_trans (MP mp,quarterword c) {
20421   pointer p,q,r; /* list manipulation registers */
20422   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20423     @<Put the current transform into |cur_exp|@>;
20424   }
20425   @<If the current transform is entirely known, stash it in global variables;
20426     otherwise |return|@>;
20427 }
20428
20429 @ @<Glob...@>=
20430 scaled txx;
20431 scaled txy;
20432 scaled tyx;
20433 scaled tyy;
20434 scaled tx;
20435 scaled ty; /* current transform coefficients */
20436
20437 @ @<Put the current transform...@>=
20438
20439   p=mp_stash_cur_exp(mp); 
20440   mp->cur_exp=mp_id_transform(mp); 
20441   mp->cur_type=mp_transform_type;
20442   q=value(mp->cur_exp);
20443   switch (c) {
20444   @<For each of the eight cases, change the relevant fields of |cur_exp|
20445     and |goto done|;
20446     but do nothing if capsule |p| doesn't have the appropriate type@>;
20447   }; /* there are no other cases */
20448   mp_disp_err(mp, p,"Improper transformation argument");
20449 @.Improper transformation argument@>
20450   help3("The expression shown above has the wrong type,")
20451        ("so I can\'t transform anything using it.")
20452        ("Proceed, and I'll omit the transformation.");
20453   mp_put_get_error(mp);
20454 DONE: 
20455   mp_recycle_value(mp, p); 
20456   mp_free_node(mp, p,value_node_size);
20457 }
20458
20459 @ @<If the current transform is entirely known, ...@>=
20460 q=value(mp->cur_exp); r=q+transform_node_size;
20461 do {  
20462   r=r-2;
20463   if ( type(r)!=mp_known ) return;
20464 } while (r!=q);
20465 mp->txx=value(xx_part_loc(q));
20466 mp->txy=value(xy_part_loc(q));
20467 mp->tyx=value(yx_part_loc(q));
20468 mp->tyy=value(yy_part_loc(q));
20469 mp->tx=value(x_part_loc(q));
20470 mp->ty=value(y_part_loc(q));
20471 mp_flush_cur_exp(mp, 0)
20472
20473 @ @<For each of the eight cases...@>=
20474 case rotated_by:
20475   if ( type(p)==mp_known )
20476     @<Install sines and cosines, then |goto done|@>;
20477   break;
20478 case slanted_by:
20479   if ( type(p)>mp_pair_type ) { 
20480    mp_install(mp, xy_part_loc(q),p); goto DONE;
20481   };
20482   break;
20483 case scaled_by:
20484   if ( type(p)>mp_pair_type ) { 
20485     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20486     goto DONE;
20487   };
20488   break;
20489 case shifted_by:
20490   if ( type(p)==mp_pair_type ) {
20491     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20492     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20493   };
20494   break;
20495 case x_scaled:
20496   if ( type(p)>mp_pair_type ) {
20497     mp_install(mp, xx_part_loc(q),p); goto DONE;
20498   };
20499   break;
20500 case y_scaled:
20501   if ( type(p)>mp_pair_type ) {
20502     mp_install(mp, yy_part_loc(q),p); goto DONE;
20503   };
20504   break;
20505 case z_scaled:
20506   if ( type(p)==mp_pair_type )
20507     @<Install a complex multiplier, then |goto done|@>;
20508   break;
20509 case transformed_by:
20510   break;
20511   
20512
20513 @ @<Install sines and cosines, then |goto done|@>=
20514 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20515   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20516   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20517   value(xy_part_loc(q))=-value(yx_part_loc(q));
20518   value(yy_part_loc(q))=value(xx_part_loc(q));
20519   goto DONE;
20520 }
20521
20522 @ @<Install a complex multiplier, then |goto done|@>=
20523
20524   r=value(p);
20525   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20526   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20527   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20528   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20529   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20530   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20531   goto DONE;
20532 }
20533
20534 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20535 insists that the transformation be entirely known.
20536
20537 @<Declare binary action...@>=
20538 void mp_set_up_known_trans (MP mp,quarterword c) { 
20539   mp_set_up_trans(mp, c);
20540   if ( mp->cur_type!=mp_known ) {
20541     exp_err("Transform components aren't all known");
20542 @.Transform components...@>
20543     help3("I'm unable to apply a partially specified transformation")
20544       ("except to a fully known pair or transform.")
20545       ("Proceed, and I'll omit the transformation.");
20546     mp_put_get_flush_error(mp, 0);
20547     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20548     mp->tx=0; mp->ty=0;
20549   }
20550 }
20551
20552 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20553 coordinates in locations |p| and~|q|.
20554
20555 @<Declare binary action...@>= 
20556 void mp_trans (MP mp,pointer p, pointer q) {
20557   scaled v; /* the new |x| value */
20558   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20559   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20560   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20561   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20562   mp->mem[p].sc=v;
20563 }
20564
20565 @ The simplest transformation procedure applies a transform to all
20566 coordinates of a path.  The |path_trans(c)(p)| macro applies
20567 a transformation defined by |cur_exp| and the transform operator |c|
20568 to the path~|p|.
20569
20570 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20571                      mp_unstash_cur_exp(mp, (B)); 
20572                      mp_do_path_trans(mp, mp->cur_exp); }
20573
20574 @<Declare binary action...@>=
20575 void mp_do_path_trans (MP mp,pointer p) {
20576   pointer q; /* list traverser */
20577   q=p;
20578   do { 
20579     if ( left_type(q)!=mp_endpoint ) 
20580       mp_trans(mp, q+3,q+4); /* that's |left_x| and |left_y| */
20581     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20582     if ( right_type(q)!=mp_endpoint ) 
20583       mp_trans(mp, q+5,q+6); /* that's |right_x| and |right_y| */
20584 @^data structure assumptions@>
20585     q=link(q);
20586   } while (q!=p);
20587 }
20588
20589 @ Transforming a pen is very similar, except that there are no |left_type|
20590 and |right_type| fields.
20591
20592 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20593                     mp_unstash_cur_exp(mp, (B)); 
20594                     mp_do_pen_trans(mp, mp->cur_exp); }
20595
20596 @<Declare binary action...@>=
20597 void mp_do_pen_trans (MP mp,pointer p) {
20598   pointer q; /* list traverser */
20599   if ( pen_is_elliptical(p) ) {
20600     mp_trans(mp, p+3,p+4); /* that's |left_x| and |left_y| */
20601     mp_trans(mp, p+5,p+6); /* that's |right_x| and |right_y| */
20602   };
20603   q=p;
20604   do { 
20605     mp_trans(mp, q+1,q+2); /* that's |x_coord| and |y_coord| */
20606 @^data structure assumptions@>
20607     q=link(q);
20608   } while (q!=p);
20609 }
20610
20611 @ The next transformation procedure applies to edge structures. It will do
20612 any transformation, but the results may be substandard if the picture contains
20613 text that uses downloaded bitmap fonts.  The binary action procedure is
20614 |do_edges_trans|, but we also need a function that just scales a picture.
20615 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20616 should be thought of as procedures that update an edge structure |h|, except
20617 that they have to return a (possibly new) structure because of the need to call
20618 |private_edges|.
20619
20620 @<Declare binary action...@>=
20621 pointer mp_edges_trans (MP mp, pointer h) {
20622   pointer q; /* the object being transformed */
20623   pointer r,s; /* for list manipulation */
20624   scaled sx,sy; /* saved transformation parameters */
20625   scaled sqdet; /* square root of determinant for |dash_scale| */
20626   integer sgndet; /* sign of the determinant */
20627   scaled v; /* a temporary value */
20628   h=mp_private_edges(mp, h);
20629   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20630   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20631   if ( dash_list(h)!=null_dash ) {
20632     @<Try to transform the dash list of |h|@>;
20633   }
20634   @<Make the bounding box of |h| unknown if it can't be updated properly
20635     without scanning the whole structure@>;  
20636   q=link(dummy_loc(h));
20637   while ( q!=null ) { 
20638     @<Transform graphical object |q|@>;
20639     q=link(q);
20640   }
20641   return h;
20642 }
20643 void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20644   mp_set_up_known_trans(mp, c);
20645   value(p)=mp_edges_trans(mp, value(p));
20646   mp_unstash_cur_exp(mp, p);
20647 }
20648 void mp_scale_edges (MP mp) { 
20649   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20650   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20651   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20652 }
20653
20654 @ @<Try to transform the dash list of |h|@>=
20655 if ( (mp->txy!=0)||(mp->tyx!=0)||
20656      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20657   mp_flush_dash_list(mp, h);
20658 } else { 
20659   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20660   @<Scale the dash list by |txx| and shift it by |tx|@>;
20661   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20662 }
20663
20664 @ @<Reverse the dash list of |h|@>=
20665
20666   r=dash_list(h);
20667   dash_list(h)=null_dash;
20668   while ( r!=null_dash ) {
20669     s=r; r=link(r);
20670     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20671     link(s)=dash_list(h);
20672     dash_list(h)=s;
20673   }
20674 }
20675
20676 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20677 r=dash_list(h);
20678 while ( r!=null_dash ) {
20679   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20680   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20681   r=link(r);
20682 }
20683
20684 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20685 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20686   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20687 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20688   mp_init_bbox(mp, h);
20689   goto DONE1;
20690 }
20691 if ( minx_val(h)<=maxx_val(h) ) {
20692   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20693    |(tx,ty)|@>;
20694 }
20695 DONE1:
20696
20697
20698
20699 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20700
20701   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20702   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20703 }
20704
20705 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20706 sum is similar.
20707
20708 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20709
20710   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20711   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20712   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20713   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20714   if ( mp->txx+mp->txy<0 ) {
20715     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20716   }
20717   if ( mp->tyx+mp->tyy<0 ) {
20718     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20719   }
20720 }
20721
20722 @ Now we ready for the main task of transforming the graphical objects in edge
20723 structure~|h|.
20724
20725 @<Transform graphical object |q|@>=
20726 switch (type(q)) {
20727 case mp_fill_code: case mp_stroked_code: 
20728   mp_do_path_trans(mp, path_p(q));
20729   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20730   break;
20731 case mp_start_clip_code: case mp_start_bounds_code: 
20732   mp_do_path_trans(mp, path_p(q));
20733   break;
20734 case mp_text_code: 
20735   r=text_tx_loc(q);
20736   @<Transform the compact transformation starting at |r|@>;
20737   break;
20738 case mp_stop_clip_code: case mp_stop_bounds_code: 
20739   break;
20740 } /* there are no other cases */
20741
20742 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20743 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20744 since the \ps\ output procedures will try to compensate for the transformation
20745 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20746 root of the determinant, |sqdet| is the appropriate factor.
20747
20748 @<Transform |pen_p(q)|, making sure...@>=
20749 if ( pen_p(q)!=null ) {
20750   sx=mp->tx; sy=mp->ty;
20751   mp->tx=0; mp->ty=0;
20752   mp_do_pen_trans(mp, pen_p(q));
20753   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20754     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20755   if ( ! pen_is_elliptical(pen_p(q)) )
20756     if ( sgndet<0 )
20757       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20758          /* this unreverses the pen */
20759   mp->tx=sx; mp->ty=sy;
20760 }
20761
20762 @ This uses the fact that transformations are stored in the order
20763 |(tx,ty,txx,txy,tyx,tyy)|.
20764 @^data structure assumptions@>
20765
20766 @<Transform the compact transformation starting at |r|@>=
20767 mp_trans(mp, r,r+1);
20768 sx=mp->tx; sy=mp->ty;
20769 mp->tx=0; mp->ty=0;
20770 mp_trans(mp, r+2,r+4);
20771 mp_trans(mp, r+3,r+5);
20772 mp->tx=sx; mp->ty=sy
20773
20774 @ The hard cases of transformation occur when big nodes are involved,
20775 and when some of their components are unknown.
20776
20777 @<Declare binary action...@>=
20778 @<Declare subroutines needed by |big_trans|@>
20779 void mp_big_trans (MP mp,pointer p, quarterword c) {
20780   pointer q,r,pp,qq; /* list manipulation registers */
20781   small_number s; /* size of a big node */
20782   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20783   do {  
20784     r=r-2;
20785     if ( type(r)!=mp_known ) {
20786       @<Transform an unknown big node and |return|@>;
20787     }
20788   } while (r!=q);
20789   @<Transform a known big node@>;
20790 } /* node |p| will now be recycled by |do_binary| */
20791
20792 @ @<Transform an unknown big node and |return|@>=
20793
20794   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20795   r=value(mp->cur_exp);
20796   if ( mp->cur_type==mp_transform_type ) {
20797     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20798     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20799     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20800     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20801   }
20802   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20803   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20804   return;
20805 }
20806
20807 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20808 and let |q| point to a another value field. The |bilin1| procedure
20809 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20810
20811 @<Declare subroutines needed by |big_trans|@>=
20812 void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20813                 scaled u, scaled delta) {
20814   pointer r; /* list traverser */
20815   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20816   if ( u!=0 ) {
20817     if ( type(q)==mp_known ) {
20818       delta+=mp_take_scaled(mp, value(q),u);
20819     } else { 
20820       @<Ensure that |type(p)=mp_proto_dependent|@>;
20821       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20822                                mp_proto_dependent,type(q));
20823     }
20824   }
20825   if ( type(p)==mp_known ) {
20826     value(p)+=delta;
20827   } else {
20828     r=dep_list(p);
20829     while ( info(r)!=null ) r=link(r);
20830     delta+=value(r);
20831     if ( r!=dep_list(p) ) value(r)=delta;
20832     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20833   }
20834   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20835 }
20836
20837 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20838 if ( type(p)!=mp_proto_dependent ) {
20839   if ( type(p)==mp_known ) 
20840     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20841   else 
20842     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20843                              mp_proto_dependent,true);
20844   type(p)=mp_proto_dependent;
20845 }
20846
20847 @ @<Transform a known big node@>=
20848 mp_set_up_trans(mp, c);
20849 if ( mp->cur_type==mp_known ) {
20850   @<Transform known by known@>;
20851 } else { 
20852   pp=mp_stash_cur_exp(mp); qq=value(pp);
20853   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20854   if ( mp->cur_type==mp_transform_type ) {
20855     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
20856       value(xy_part_loc(q)),yx_part_loc(qq),null);
20857     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
20858       value(xx_part_loc(q)),yx_part_loc(qq),null);
20859     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
20860       value(yy_part_loc(q)),xy_part_loc(qq),null);
20861     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
20862       value(yx_part_loc(q)),xy_part_loc(qq),null);
20863   };
20864   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
20865     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
20866   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
20867     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
20868   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
20869 }
20870
20871 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
20872 at |dep_final|. The following procedure adds |v| times another
20873 numeric quantity to~|p|.
20874
20875 @<Declare subroutines needed by |big_trans|@>=
20876 void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
20877   if ( type(r)==mp_known ) {
20878     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
20879   } else  { 
20880     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
20881                                                          mp_proto_dependent,type(r));
20882     if ( mp->fix_needed ) mp_fix_dependencies(mp);
20883   }
20884 }
20885
20886 @ The |bilin2| procedure is something like |bilin1|, but with known
20887 and unknown quantities reversed. Parameter |p| points to a value field
20888 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
20889 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
20890 unless it is |null| (which stands for zero). Location~|p| will be
20891 replaced by $p\cdot t+v\cdot u+q$.
20892
20893 @<Declare subroutines needed by |big_trans|@>=
20894 void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
20895                 pointer u, pointer q) {
20896   scaled vv; /* temporary storage for |value(p)| */
20897   vv=value(p); type(p)=mp_proto_dependent;
20898   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
20899   if ( vv!=0 ) 
20900     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
20901   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
20902   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
20903   if ( dep_list(p)==mp->dep_final ) {
20904     vv=value(mp->dep_final); mp_recycle_value(mp, p);
20905     type(p)=mp_known; value(p)=vv;
20906   }
20907 }
20908
20909 @ @<Transform known by known@>=
20910
20911   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
20912   if ( mp->cur_type==mp_transform_type ) {
20913     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
20914     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
20915     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
20916     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
20917   }
20918   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
20919   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
20920 }
20921
20922 @ Finally, in |bilin3| everything is |known|.
20923
20924 @<Declare subroutines needed by |big_trans|@>=
20925 void mp_bilin3 (MP mp,pointer p, scaled t, 
20926                scaled v, scaled u, scaled delta) { 
20927   if ( t!=unity )
20928     delta+=mp_take_scaled(mp, value(p),t);
20929   else 
20930     delta+=value(p);
20931   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
20932   else value(p)=delta;
20933 }
20934
20935 @ @<Additional cases of binary operators@>=
20936 case concatenate: 
20937   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
20938   else mp_bad_binary(mp, p,concatenate);
20939   break;
20940 case substring_of: 
20941   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
20942     mp_chop_string(mp, value(p));
20943   else mp_bad_binary(mp, p,substring_of);
20944   break;
20945 case subpath_of: 
20946   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
20947   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
20948     mp_chop_path(mp, value(p));
20949   else mp_bad_binary(mp, p,subpath_of);
20950   break;
20951
20952 @ @<Declare binary action...@>=
20953 void mp_cat (MP mp,pointer p) {
20954   str_number a,b; /* the strings being concatenated */
20955   pool_pointer k; /* index into |str_pool| */
20956   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
20957   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
20958     append_char(mp->str_pool[k]);
20959   }
20960   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
20961     append_char(mp->str_pool[k]);
20962   }
20963   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
20964 }
20965
20966 @ @<Declare binary action...@>=
20967 void mp_chop_string (MP mp,pointer p) {
20968   integer a, b; /* start and stop points */
20969   integer l; /* length of the original string */
20970   integer k; /* runs from |a| to |b| */
20971   str_number s; /* the original string */
20972   boolean reversed; /* was |a>b|? */
20973   a=mp_round_unscaled(mp, value(x_part_loc(p)));
20974   b=mp_round_unscaled(mp, value(y_part_loc(p)));
20975   if ( a<=b ) reversed=false;
20976   else  { reversed=true; k=a; a=b; b=k; };
20977   s=mp->cur_exp; l=length(s);
20978   if ( a<0 ) { 
20979     a=0;
20980     if ( b<0 ) b=0;
20981   }
20982   if ( b>l ) { 
20983     b=l;
20984     if ( a>l ) a=l;
20985   }
20986   str_room(b-a);
20987   if ( reversed ) {
20988     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
20989       append_char(mp->str_pool[k]);
20990     }
20991   } else  {
20992     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
20993       append_char(mp->str_pool[k]);
20994     }
20995   }
20996   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
20997 }
20998
20999 @ @<Declare binary action...@>=
21000 void mp_chop_path (MP mp,pointer p) {
21001   pointer q; /* a knot in the original path */
21002   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21003   scaled a,b,k,l; /* indices for chopping */
21004   boolean reversed; /* was |a>b|? */
21005   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21006   if ( a<=b ) reversed=false;
21007   else  { reversed=true; k=a; a=b; b=k; };
21008   @<Dispense with the cases |a<0| and/or |b>l|@>;
21009   q=mp->cur_exp;
21010   while ( a>=unity ) {
21011     q=link(q); a=a-unity; b=b-unity;
21012   }
21013   if ( b==a ) {
21014     @<Construct a path from |pp| to |qq| of length zero@>; 
21015   } else { 
21016     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
21017   }
21018   left_type(pp)=mp_endpoint; right_type(qq)=mp_endpoint; link(qq)=pp;
21019   mp_toss_knot_list(mp, mp->cur_exp);
21020   if ( reversed ) {
21021     mp->cur_exp=link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21022   } else {
21023     mp->cur_exp=pp;
21024   }
21025 }
21026
21027 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21028 if ( a<0 ) {
21029   if ( left_type(mp->cur_exp)==mp_endpoint ) {
21030     a=0; if ( b<0 ) b=0;
21031   } else  {
21032     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21033   }
21034 }
21035 if ( b>l ) {
21036   if ( left_type(mp->cur_exp)==mp_endpoint ) {
21037     b=l; if ( a>l ) a=l;
21038   } else {
21039     while ( a>=l ) { 
21040       a=a-l; b=b-l;
21041     }
21042   }
21043 }
21044
21045 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21046
21047   pp=mp_copy_knot(mp, q); qq=pp;
21048   do {  
21049     q=link(q); rr=qq; qq=mp_copy_knot(mp, q); link(rr)=qq; b=b-unity;
21050   } while (b>0);
21051   if ( a>0 ) {
21052     ss=pp; pp=link(pp);
21053     mp_split_cubic(mp, ss,a*010000); pp=link(ss);
21054     mp_free_node(mp, ss,knot_node_size);
21055     if ( rr==ss ) {
21056       b=mp_make_scaled(mp, b,unity-a); rr=pp;
21057     }
21058   }
21059   if ( b<0 ) {
21060     mp_split_cubic(mp, rr,(b+unity)*010000);
21061     mp_free_node(mp, qq,knot_node_size);
21062     qq=link(rr);
21063   }
21064 }
21065
21066 @ @<Construct a path from |pp| to |qq| of length zero@>=
21067
21068   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=link(q); };
21069   pp=mp_copy_knot(mp, q); qq=pp;
21070 }
21071
21072 @ @<Additional cases of binary operators@>=
21073 case point_of: case precontrol_of: case postcontrol_of: 
21074   if ( mp->cur_type==mp_pair_type )
21075      mp_pair_to_path(mp);
21076   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21077     mp_find_point(mp, value(p),c);
21078   else 
21079     mp_bad_binary(mp, p,c);
21080   break;
21081 case pen_offset_of: 
21082   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21083     mp_set_up_offset(mp, value(p));
21084   else 
21085     mp_bad_binary(mp, p,pen_offset_of);
21086   break;
21087 case direction_time_of: 
21088   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21089   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21090     mp_set_up_direction_time(mp, value(p));
21091   else 
21092     mp_bad_binary(mp, p,direction_time_of);
21093   break;
21094 case envelope_of:
21095   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21096     mp_bad_binary(mp, p,envelope_of);
21097   else
21098     mp_set_up_envelope(mp, p);
21099   break;
21100
21101 @ @<Declare binary action...@>=
21102 void mp_set_up_offset (MP mp,pointer p) { 
21103   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21104   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21105 }
21106 void mp_set_up_direction_time (MP mp,pointer p) { 
21107   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21108   value(y_part_loc(p)),mp->cur_exp));
21109 }
21110 void mp_set_up_envelope (MP mp,pointer p) {
21111   small_number ljoin, lcap;
21112   scaled miterlim;
21113   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21114   /* TODO: accept elliptical pens for straight paths */
21115   if (pen_is_elliptical(value(p))) {
21116     mp_bad_envelope_pen(mp);
21117     mp->cur_exp = q;
21118     mp->cur_type = mp_path_type;
21119     return;
21120   }
21121   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21122   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21123   else ljoin=0;
21124   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21125   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21126   else lcap=0;
21127   if ( mp->internal[mp_miterlimit]<unity )
21128     miterlim=unity;
21129   else
21130     miterlim=mp->internal[mp_miterlimit];
21131   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21132   mp->cur_type = mp_path_type;
21133 }
21134
21135 @ @<Declare binary action...@>=
21136 void mp_find_point (MP mp,scaled v, quarterword c) {
21137   pointer p; /* the path */
21138   scaled n; /* its length */
21139   p=mp->cur_exp;
21140   if ( left_type(p)==mp_endpoint ) n=-unity; else n=0;
21141   do {  p=link(p); n=n+unity; } while (p!=mp->cur_exp);
21142   if ( n==0 ) { 
21143     v=0; 
21144   } else if ( v<0 ) {
21145     if ( left_type(p)==mp_endpoint ) v=0;
21146     else v=n-1-((-v-1) % n);
21147   } else if ( v>n ) {
21148     if ( left_type(p)==mp_endpoint ) v=n;
21149     else v=v % n;
21150   }
21151   p=mp->cur_exp;
21152   while ( v>=unity ) { p=link(p); v=v-unity;  };
21153   if ( v!=0 ) {
21154      @<Insert a fractional node by splitting the cubic@>;
21155   }
21156   @<Set the current expression to the desired path coordinates@>;
21157 }
21158
21159 @ @<Insert a fractional node...@>=
21160 { mp_split_cubic(mp, p,v*010000); p=link(p); }
21161
21162 @ @<Set the current expression to the desired path coordinates...@>=
21163 switch (c) {
21164 case point_of: 
21165   mp_pair_value(mp, x_coord(p),y_coord(p));
21166   break;
21167 case precontrol_of: 
21168   if ( left_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21169   else mp_pair_value(mp, left_x(p),left_y(p));
21170   break;
21171 case postcontrol_of: 
21172   if ( right_type(p)==mp_endpoint ) mp_pair_value(mp, x_coord(p),y_coord(p));
21173   else mp_pair_value(mp, right_x(p),right_y(p));
21174   break;
21175 } /* there are no other cases */
21176
21177 @ @<Additional cases of binary operators@>=
21178 case arc_time_of: 
21179   if ( mp->cur_type==mp_pair_type )
21180      mp_pair_to_path(mp);
21181   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21182     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21183   else 
21184     mp_bad_binary(mp, p,c);
21185   break;
21186
21187 @ @<Additional cases of bin...@>=
21188 case intersect: 
21189   if ( type(p)==mp_pair_type ) {
21190     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21191     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21192   };
21193   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21194   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21195     mp_path_intersection(mp, value(p),mp->cur_exp);
21196     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21197   } else {
21198     mp_bad_binary(mp, p,intersect);
21199   }
21200   break;
21201
21202 @ @<Additional cases of bin...@>=
21203 case in_font:
21204   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21205     mp_bad_binary(mp, p,in_font);
21206   else { mp_do_infont(mp, p); binary_return; }
21207   break;
21208
21209 @ Function |new_text_node| owns the reference count for its second argument
21210 (the text string) but not its first (the font name).
21211
21212 @<Declare binary action...@>=
21213 void mp_do_infont (MP mp,pointer p) {
21214   pointer q;
21215   q=mp_get_node(mp, edge_header_size);
21216   mp_init_edges(mp, q);
21217   link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21218   obj_tail(q)=link(obj_tail(q));
21219   mp_free_node(mp, p,value_node_size);
21220   mp_flush_cur_exp(mp, q);
21221   mp->cur_type=mp_picture_type;
21222 }
21223
21224 @* \[40] Statements and commands.
21225 The chief executive of \MP\ is the |do_statement| routine, which
21226 contains the master switch that causes all the various pieces of \MP\
21227 to do their things, in the right order.
21228
21229 In a sense, this is the grand climax of the program: It applies all the
21230 tools that we have worked so hard to construct. In another sense, this is
21231 the messiest part of the program: It necessarily refers to other pieces
21232 of code all over the place, so that a person can't fully understand what is
21233 going on without paging back and forth to be reminded of conventions that
21234 are defined elsewhere. We are now at the hub of the web.
21235
21236 The structure of |do_statement| itself is quite simple.  The first token
21237 of the statement is fetched using |get_x_next|.  If it can be the first
21238 token of an expression, we look for an equation, an assignment, or a
21239 title. Otherwise we use a \&{case} construction to branch at high speed to
21240 the appropriate routine for various and sundry other types of commands,
21241 each of which has an ``action procedure'' that does the necessary work.
21242
21243 The program uses the fact that
21244 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21245 to interpret a statement that starts with, e.g., `\&{string}',
21246 as a type declaration rather than a boolean expression.
21247
21248 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21249   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21250   if ( mp->cur_cmd>max_primary_command ) {
21251     @<Worry about bad statement@>;
21252   } else if ( mp->cur_cmd>max_statement_command ) {
21253     @<Do an equation, assignment, title, or
21254      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21255   } else {
21256     @<Do a statement that doesn't begin with an expression@>;
21257   }
21258   if ( mp->cur_cmd<semicolon )
21259     @<Flush unparsable junk that was found after the statement@>;
21260   mp->error_count=0;
21261 }
21262
21263 @ @<Declarations@>=
21264 @<Declare action procedures for use by |do_statement|@>
21265
21266 @ The only command codes |>max_primary_command| that can be present
21267 at the beginning of a statement are |semicolon| and higher; these
21268 occur when the statement is null.
21269
21270 @<Worry about bad statement@>=
21271
21272   if ( mp->cur_cmd<semicolon ) {
21273     print_err("A statement can't begin with `");
21274 @.A statement can't begin with x@>
21275     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, '\'');
21276     help5("I was looking for the beginning of a new statement.")
21277       ("If you just proceed without changing anything, I'll ignore")
21278       ("everything up to the next `;'. Please insert a semicolon")
21279       ("now in front of anything that you don't want me to delete.")
21280       ("(See Chapter 27 of The METAFONTbook for an example.)");
21281 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21282     mp_back_error(mp); mp_get_x_next(mp);
21283   }
21284 }
21285
21286 @ The help message printed here says that everything is flushed up to
21287 a semicolon, but actually the commands |end_group| and |stop| will
21288 also terminate a statement.
21289
21290 @<Flush unparsable junk that was found after the statement@>=
21291
21292   print_err("Extra tokens will be flushed");
21293 @.Extra tokens will be flushed@>
21294   help6("I've just read as much of that statement as I could fathom,")
21295        ("so a semicolon should have been next. It's very puzzling...")
21296        ("but I'll try to get myself back together, by ignoring")
21297        ("everything up to the next `;'. Please insert a semicolon")
21298        ("now in front of anything that you don't want me to delete.")
21299        ("(See Chapter 27 of The METAFONTbook for an example.)");
21300 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21301   mp_back_error(mp); mp->scanner_status=flushing;
21302   do {  
21303     get_t_next;
21304     @<Decrease the string reference count...@>;
21305   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21306   mp->scanner_status=normal;
21307 }
21308
21309 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21310 |cur_type=mp_vacuous| unless the statement was simply an expression;
21311 in the latter case, |cur_type| and |cur_exp| should represent that
21312 expression.
21313
21314 @<Do a statement that doesn't...@>=
21315
21316   if ( mp->internal[mp_tracing_commands]>0 ) 
21317     show_cur_cmd_mod;
21318   switch (mp->cur_cmd ) {
21319   case type_name:mp_do_type_declaration(mp); break;
21320   case macro_def:
21321     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21322     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21323      break;
21324   @<Cases of |do_statement| that invoke particular commands@>;
21325   } /* there are no other cases */
21326   mp->cur_type=mp_vacuous;
21327 }
21328
21329 @ The most important statements begin with expressions.
21330
21331 @<Do an equation, assignment, title, or...@>=
21332
21333   mp->var_flag=assignment; mp_scan_expression(mp);
21334   if ( mp->cur_cmd<end_group ) {
21335     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21336     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21337     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21338     else if ( mp->cur_type!=mp_vacuous ){ 
21339       exp_err("Isolated expression");
21340 @.Isolated expression@>
21341       help3("I couldn't find an `=' or `:=' after the")
21342         ("expression that is shown above this error message,")
21343         ("so I guess I'll just ignore it and carry on.");
21344       mp_put_get_error(mp);
21345     }
21346     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21347   }
21348 }
21349
21350 @ @<Do a title@>=
21351
21352   if ( mp->internal[mp_tracing_titles]>0 ) {
21353     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21354   }
21355 }
21356
21357 @ Equations and assignments are performed by the pair of mutually recursive
21358 @^recursion@>
21359 routines |do_equation| and |do_assignment|. These routines are called when
21360 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21361 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21362 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21363 will be equal to the right-hand side (which will normally be equal
21364 to the left-hand side).
21365
21366 @<Declare action procedures for use by |do_statement|@>=
21367 @<Declare the procedure called |try_eq|@>
21368 @<Declare the procedure called |make_eq|@>
21369 void mp_do_equation (MP mp) ;
21370
21371 @ @c
21372 void mp_do_equation (MP mp) {
21373   pointer lhs; /* capsule for the left-hand side */
21374   pointer p; /* temporary register */
21375   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21376   mp->var_flag=assignment; mp_scan_expression(mp);
21377   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21378   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21379   if ( mp->internal[mp_tracing_commands]>two ) 
21380     @<Trace the current equation@>;
21381   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21382     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21383   }; /* in this case |make_eq| will change the pair to a path */
21384   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21385 }
21386
21387 @ And |do_assignment| is similar to |do_equation|:
21388
21389 @<Declarations@>=
21390 void mp_do_assignment (MP mp);
21391
21392 @ @<Declare action procedures for use by |do_statement|@>=
21393 void mp_do_assignment (MP mp) ;
21394
21395 @ @c
21396 void mp_do_assignment (MP mp) {
21397   pointer lhs; /* token list for the left-hand side */
21398   pointer p; /* where the left-hand value is stored */
21399   pointer q; /* temporary capsule for the right-hand value */
21400   if ( mp->cur_type!=mp_token_list ) { 
21401     exp_err("Improper `:=' will be changed to `='");
21402 @.Improper `:='@>
21403     help2("I didn't find a variable name at the left of the `:=',")
21404       ("so I'm going to pretend that you said `=' instead.");
21405     mp_error(mp); mp_do_equation(mp);
21406   } else { 
21407     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21408     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21409     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21410     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21411     if ( mp->internal[mp_tracing_commands]>two ) 
21412       @<Trace the current assignment@>;
21413     if ( info(lhs)>hash_end ) {
21414       @<Assign the current expression to an internal variable@>;
21415     } else  {
21416       @<Assign the current expression to the variable |lhs|@>;
21417     }
21418     mp_flush_node_list(mp, lhs);
21419   }
21420 }
21421
21422 @ @<Trace the current equation@>=
21423
21424   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21425   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21426   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21427 }
21428
21429 @ @<Trace the current assignment@>=
21430
21431   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21432   if ( info(lhs)>hash_end ) 
21433      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21434   else 
21435      mp_show_token_list(mp, lhs,null,1000,0);
21436   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21437   mp_print_char(mp, '}'); mp_end_diagnostic(mp, false);
21438 }
21439
21440 @ @<Assign the current expression to an internal variable@>=
21441 if ( mp->cur_type==mp_known )  {
21442   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21443 } else { 
21444   exp_err("Internal quantity `");
21445 @.Internal quantity...@>
21446   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21447   mp_print(mp, "' must receive a known value");
21448   help2("I can\'t set an internal quantity to anything but a known")
21449     ("numeric value, so I'll have to ignore this assignment.");
21450   mp_put_get_error(mp);
21451 }
21452
21453 @ @<Assign the current expression to the variable |lhs|@>=
21454
21455   p=mp_find_variable(mp, lhs);
21456   if ( p!=null ) {
21457     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21458     mp_recycle_value(mp, p);
21459     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21460     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21461   } else  { 
21462     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21463   }
21464 }
21465
21466
21467 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21468 a pointer to a capsule that is to be equated to the current expression.
21469
21470 @<Declare the procedure called |make_eq|@>=
21471 void mp_make_eq (MP mp,pointer lhs) ;
21472
21473
21474
21475 @c void mp_make_eq (MP mp,pointer lhs) {
21476   small_number t; /* type of the left-hand side */
21477   pointer p,q; /* pointers inside of big nodes */
21478   integer v=0; /* value of the left-hand side */
21479 RESTART: 
21480   t=type(lhs);
21481   if ( t<=mp_pair_type ) v=value(lhs);
21482   switch (t) {
21483   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21484     is incompatible with~|t|@>;
21485   } /* all cases have been listed */
21486   @<Announce that the equation cannot be performed@>;
21487 DONE:
21488   check_arith; mp_recycle_value(mp, lhs); 
21489   mp_free_node(mp, lhs,value_node_size);
21490 }
21491
21492 @ @<Announce that the equation cannot be performed@>=
21493 mp_disp_err(mp, lhs,""); 
21494 exp_err("Equation cannot be performed (");
21495 @.Equation cannot be performed@>
21496 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21497 else mp_print(mp, "numeric");
21498 mp_print_char(mp, '=');
21499 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21500 else mp_print(mp, "numeric");
21501 mp_print_char(mp, ')');
21502 help2("I'm sorry, but I don't know how to make such things equal.")
21503      ("(See the two expressions just above the error message.)");
21504 mp_put_get_error(mp)
21505
21506 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21507 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21508 case mp_path_type: case mp_picture_type:
21509   if ( mp->cur_type==t+unknown_tag ) { 
21510     mp_nonlinear_eq(mp, v,mp->cur_exp,false); 
21511     mp_unstash_cur_exp(mp, mp->cur_exp); goto DONE;
21512   } else if ( mp->cur_type==t ) {
21513     @<Report redundant or inconsistent equation and |goto done|@>;
21514   }
21515   break;
21516 case unknown_types:
21517   if ( mp->cur_type==t-unknown_tag ) { 
21518     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21519   } else if ( mp->cur_type==t ) { 
21520     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21521   } else if ( mp->cur_type==mp_pair_type ) {
21522     if ( t==mp_unknown_path ) { 
21523      mp_pair_to_path(mp); goto RESTART;
21524     };
21525   }
21526   break;
21527 case mp_transform_type: case mp_color_type:
21528 case mp_cmykcolor_type: case mp_pair_type:
21529   if ( mp->cur_type==t ) {
21530     @<Do multiple equations and |goto done|@>;
21531   }
21532   break;
21533 case mp_known: case mp_dependent:
21534 case mp_proto_dependent: case mp_independent:
21535   if ( mp->cur_type>=mp_known ) { 
21536     mp_try_eq(mp, lhs,null); goto DONE;
21537   };
21538   break;
21539 case mp_vacuous:
21540   break;
21541
21542 @ @<Report redundant or inconsistent equation and |goto done|@>=
21543
21544   if ( mp->cur_type<=mp_string_type ) {
21545     if ( mp->cur_type==mp_string_type ) {
21546       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21547         goto NOT_FOUND;
21548       }
21549     } else if ( v!=mp->cur_exp ) {
21550       goto NOT_FOUND;
21551     }
21552     @<Exclaim about a redundant equation@>; goto DONE;
21553   }
21554   print_err("Redundant or inconsistent equation");
21555 @.Redundant or inconsistent equation@>
21556   help2("An equation between already-known quantities can't help.")
21557        ("But don't worry; continue and I'll just ignore it.");
21558   mp_put_get_error(mp); goto DONE;
21559 NOT_FOUND: 
21560   print_err("Inconsistent equation");
21561 @.Inconsistent equation@>
21562   help2("The equation I just read contradicts what was said before.")
21563        ("But don't worry; continue and I'll just ignore it.");
21564   mp_put_get_error(mp); goto DONE;
21565 }
21566
21567 @ @<Do multiple equations and |goto done|@>=
21568
21569   p=v+mp->big_node_size[t]; 
21570   q=value(mp->cur_exp)+mp->big_node_size[t];
21571   do {  
21572     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21573   } while (p!=v);
21574   goto DONE;
21575 }
21576
21577 @ The first argument to |try_eq| is the location of a value node
21578 in a capsule that will soon be recycled. The second argument is
21579 either a location within a pair or transform node pointed to by
21580 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21581 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21582 but to equate the two operands.
21583
21584 @<Declare the procedure called |try_eq|@>=
21585 void mp_try_eq (MP mp,pointer l, pointer r) ;
21586
21587
21588 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21589   pointer p; /* dependency list for right operand minus left operand */
21590   int t; /* the type of list |p| */
21591   pointer q; /* the constant term of |p| is here */
21592   pointer pp; /* dependency list for right operand */
21593   int tt; /* the type of list |pp| */
21594   boolean copied; /* have we copied a list that ought to be recycled? */
21595   @<Remove the left operand from its container, negate it, and
21596     put it into dependency list~|p| with constant term~|q|@>;
21597   @<Add the right operand to list |p|@>;
21598   if ( info(p)==null ) {
21599     @<Deal with redundant or inconsistent equation@>;
21600   } else { 
21601     mp_linear_eq(mp, p,t);
21602     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21603       if ( type(mp->cur_exp)==mp_known ) {
21604         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21605         mp_free_node(mp, pp,value_node_size);
21606       }
21607     }
21608   }
21609 }
21610
21611 @ @<Remove the left operand from its container, negate it, and...@>=
21612 t=type(l);
21613 if ( t==mp_known ) { 
21614   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21615 } else if ( t==mp_independent ) {
21616   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21617   q=mp->dep_final;
21618 } else { 
21619   p=dep_list(l); q=p;
21620   while (1) { 
21621     negate(value(q));
21622     if ( info(q)==null ) break;
21623     q=link(q);
21624   }
21625   link(prev_dep(l))=link(q); prev_dep(link(q))=prev_dep(l);
21626   type(l)=mp_known;
21627 }
21628
21629 @ @<Deal with redundant or inconsistent equation@>=
21630
21631   if ( abs(value(p))>64 ) { /* off by .001 or more */
21632     print_err("Inconsistent equation");
21633 @.Inconsistent equation@>
21634     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21635     mp_print_char(mp, ')');
21636     help2("The equation I just read contradicts what was said before.")
21637       ("But don't worry; continue and I'll just ignore it.");
21638     mp_put_get_error(mp);
21639   } else if ( r==null ) {
21640     @<Exclaim about a redundant equation@>;
21641   }
21642   mp_free_node(mp, p,dep_node_size);
21643 }
21644
21645 @ @<Add the right operand to list |p|@>=
21646 if ( r==null ) {
21647   if ( mp->cur_type==mp_known ) {
21648     value(q)=value(q)+mp->cur_exp; goto DONE1;
21649   } else { 
21650     tt=mp->cur_type;
21651     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21652     else pp=dep_list(mp->cur_exp);
21653   } 
21654 } else {
21655   if ( type(r)==mp_known ) {
21656     value(q)=value(q)+value(r); goto DONE1;
21657   } else { 
21658     tt=type(r);
21659     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21660     else pp=dep_list(r);
21661   }
21662 }
21663 if ( tt!=mp_independent ) copied=false;
21664 else  { copied=true; tt=mp_dependent; };
21665 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21666 if ( copied ) mp_flush_node_list(mp, pp);
21667 DONE1:
21668
21669 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21670 mp->watch_coefs=false;
21671 if ( t==tt ) {
21672   p=mp_p_plus_q(mp, p,pp,t);
21673 } else if ( t==mp_proto_dependent ) {
21674   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21675 } else { 
21676   q=p;
21677   while ( info(q)!=null ) {
21678     value(q)=mp_round_fraction(mp, value(q)); q=link(q);
21679   }
21680   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21681 }
21682 mp->watch_coefs=true;
21683
21684 @ Our next goal is to process type declarations. For this purpose it's
21685 convenient to have a procedure that scans a $\langle\,$declared
21686 variable$\,\rangle$ and returns the corresponding token list. After the
21687 following procedure has acted, the token after the declared variable
21688 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21689 and~|cur_sym|.
21690
21691 @<Declare the function called |scan_declared_variable|@>=
21692 pointer mp_scan_declared_variable (MP mp) {
21693   pointer x; /* hash address of the variable's root */
21694   pointer h,t; /* head and tail of the token list to be returned */
21695   pointer l; /* hash address of left bracket */
21696   mp_get_symbol(mp); x=mp->cur_sym;
21697   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21698   h=mp_get_avail(mp); info(h)=x; t=h;
21699   while (1) { 
21700     mp_get_x_next(mp);
21701     if ( mp->cur_sym==0 ) break;
21702     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21703       if ( mp->cur_cmd==left_bracket ) {
21704         @<Descend past a collective subscript@>;
21705       } else {
21706         break;
21707       }
21708     }
21709     link(t)=mp_get_avail(mp); t=link(t); info(t)=mp->cur_sym;
21710   }
21711   if ( (eq_type(x)%outer_tag)!=tag_token ) mp_clear_symbol(mp, x,false);
21712   if ( equiv(x)==null ) mp_new_root(mp, x);
21713   return h;
21714 }
21715
21716 @ If the subscript isn't collective, we don't accept it as part of the
21717 declared variable.
21718
21719 @<Descend past a collective subscript@>=
21720
21721   l=mp->cur_sym; mp_get_x_next(mp);
21722   if ( mp->cur_cmd!=right_bracket ) {
21723     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21724   } else {
21725     mp->cur_sym=collective_subscript;
21726   }
21727 }
21728
21729 @ Type declarations are introduced by the following primitive operations.
21730
21731 @<Put each...@>=
21732 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21733 @:numeric_}{\&{numeric} primitive@>
21734 mp_primitive(mp, "string",type_name,mp_string_type);
21735 @:string_}{\&{string} primitive@>
21736 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21737 @:boolean_}{\&{boolean} primitive@>
21738 mp_primitive(mp, "path",type_name,mp_path_type);
21739 @:path_}{\&{path} primitive@>
21740 mp_primitive(mp, "pen",type_name,mp_pen_type);
21741 @:pen_}{\&{pen} primitive@>
21742 mp_primitive(mp, "picture",type_name,mp_picture_type);
21743 @:picture_}{\&{picture} primitive@>
21744 mp_primitive(mp, "transform",type_name,mp_transform_type);
21745 @:transform_}{\&{transform} primitive@>
21746 mp_primitive(mp, "color",type_name,mp_color_type);
21747 @:color_}{\&{color} primitive@>
21748 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21749 @:color_}{\&{rgbcolor} primitive@>
21750 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21751 @:color_}{\&{cmykcolor} primitive@>
21752 mp_primitive(mp, "pair",type_name,mp_pair_type);
21753 @:pair_}{\&{pair} primitive@>
21754
21755 @ @<Cases of |print_cmd...@>=
21756 case type_name: mp_print_type(mp, m); break;
21757
21758 @ Now we are ready to handle type declarations, assuming that a
21759 |type_name| has just been scanned.
21760
21761 @<Declare action procedures for use by |do_statement|@>=
21762 void mp_do_type_declaration (MP mp) ;
21763
21764 @ @c
21765 void mp_do_type_declaration (MP mp) {
21766   small_number t; /* the type being declared */
21767   pointer p; /* token list for a declared variable */
21768   pointer q; /* value node for the variable */
21769   if ( mp->cur_mod>=mp_transform_type ) 
21770     t=mp->cur_mod;
21771   else 
21772     t=mp->cur_mod+unknown_tag;
21773   do {  
21774     p=mp_scan_declared_variable(mp);
21775     mp_flush_variable(mp, equiv(info(p)),link(p),false);
21776     q=mp_find_variable(mp, p);
21777     if ( q!=null ) { 
21778       type(q)=t; value(q)=null; 
21779     } else  { 
21780       print_err("Declared variable conflicts with previous vardef");
21781 @.Declared variable conflicts...@>
21782       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.")
21783            ("Proceed, and I'll ignore the illegal redeclaration.");
21784       mp_put_get_error(mp);
21785     }
21786     mp_flush_list(mp, p);
21787     if ( mp->cur_cmd<comma ) {
21788       @<Flush spurious symbols after the declared variable@>;
21789     }
21790   } while (! end_of_statement);
21791 }
21792
21793 @ @<Flush spurious symbols after the declared variable@>=
21794
21795   print_err("Illegal suffix of declared variable will be flushed");
21796 @.Illegal suffix...flushed@>
21797   help5("Variables in declarations must consist entirely of")
21798     ("names and collective subscripts, e.g., `x[]a'.")
21799     ("Are you trying to use a reserved word in a variable name?")
21800     ("I'm going to discard the junk I found here,")
21801     ("up to the next comma or the end of the declaration.");
21802   if ( mp->cur_cmd==numeric_token )
21803     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21804   mp_put_get_error(mp); mp->scanner_status=flushing;
21805   do {  
21806     get_t_next;
21807     @<Decrease the string reference count...@>;
21808   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21809   mp->scanner_status=normal;
21810 }
21811
21812 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21813 until coming to the end of the user's program.
21814 Each execution of |do_statement| concludes with
21815 |cur_cmd=semicolon|, |end_group|, or |stop|.
21816
21817 @c void mp_main_control (MP mp) { 
21818   do {  
21819     mp_do_statement(mp);
21820     if ( mp->cur_cmd==end_group ) {
21821       print_err("Extra `endgroup'");
21822 @.Extra `endgroup'@>
21823       help2("I'm not currently working on a `begingroup',")
21824         ("so I had better not try to end anything.");
21825       mp_flush_error(mp, 0);
21826     }
21827   } while (mp->cur_cmd!=stop);
21828 }
21829 int __attribute__((noinline)) 
21830 mp_run (MP mp) {
21831   if (mp->history < mp_fatal_error_stop ) {
21832     @<Install and test the non-local jump buffer@>;
21833     mp_main_control(mp); /* come to life */
21834     mp_final_cleanup(mp); /* prepare for death */
21835     mp_close_files_and_terminate(mp);
21836   }
21837   return mp->history;
21838 }
21839 int __attribute__((noinline)) 
21840 mp_execute (MP mp) {
21841   if (mp->history < mp_fatal_error_stop ) {
21842     mp->history = mp_spotless;
21843     mp->file_offset = 0;
21844     mp->term_offset = 0;
21845     mp->tally = 0; 
21846     @<Install and test the non-local jump buffer@>;
21847         if (mp->run_state==0) {
21848       mp->run_state = 1;
21849     } else {
21850       mp_input_ln(mp,mp->term_in);
21851       mp_firm_up_the_line(mp);  
21852       mp->buffer[limit]='%';
21853       mp->first=limit+1; 
21854       loc=start;
21855     }
21856         do {  
21857       mp_do_statement(mp);
21858     } while (mp->cur_cmd!=stop);
21859   }
21860   return mp->history;
21861 }
21862 int __attribute__((noinline)) 
21863 mp_finish (MP mp) {
21864   if (mp->history < mp_fatal_error_stop ) {
21865     @<Install and test the non-local jump buffer@>;
21866     mp_final_cleanup(mp); /* prepare for death */
21867     mp_close_files_and_terminate(mp);
21868   }
21869   return mp->history;
21870 }
21871 const char * mp_mplib_version (MP mp) {
21872   (void)mp;
21873   return mplib_version;
21874 }
21875 const char * mp_metapost_version (MP mp) {
21876   (void)mp;
21877   return metapost_version;
21878 }
21879
21880 @ @<Exported function headers@>=
21881 int mp_run (MP mp);
21882 int mp_execute (MP mp);
21883 int mp_finish (MP mp);
21884 const char * mp_mplib_version (MP mp);
21885 const char * mp_metapost_version (MP mp);
21886
21887 @ @<Put each...@>=
21888 mp_primitive(mp, "end",stop,0);
21889 @:end_}{\&{end} primitive@>
21890 mp_primitive(mp, "dump",stop,1);
21891 @:dump_}{\&{dump} primitive@>
21892
21893 @ @<Cases of |print_cmd...@>=
21894 case stop:
21895   if ( m==0 ) mp_print(mp, "end");
21896   else mp_print(mp, "dump");
21897   break;
21898
21899 @* \[41] Commands.
21900 Let's turn now to statements that are classified as ``commands'' because
21901 of their imperative nature. We'll begin with simple ones, so that it
21902 will be clear how to hook command processing into the |do_statement| routine;
21903 then we'll tackle the tougher commands.
21904
21905 Here's one of the simplest:
21906
21907 @<Cases of |do_statement|...@>=
21908 case mp_random_seed: mp_do_random_seed(mp);  break;
21909
21910 @ @<Declare action procedures for use by |do_statement|@>=
21911 void mp_do_random_seed (MP mp) ;
21912
21913 @ @c void mp_do_random_seed (MP mp) { 
21914   mp_get_x_next(mp);
21915   if ( mp->cur_cmd!=assignment ) {
21916     mp_missing_err(mp, ":=");
21917 @.Missing `:='@>
21918     help1("Always say `randomseed:=<numeric expression>'.");
21919     mp_back_error(mp);
21920   };
21921   mp_get_x_next(mp); mp_scan_expression(mp);
21922   if ( mp->cur_type!=mp_known ) {
21923     exp_err("Unknown value will be ignored");
21924 @.Unknown value...ignored@>
21925     help2("Your expression was too random for me to handle,")
21926       ("so I won't change the random seed just now.");
21927     mp_put_get_flush_error(mp, 0);
21928   } else {
21929    @<Initialize the random seed to |cur_exp|@>;
21930   }
21931 }
21932
21933 @ @<Initialize the random seed to |cur_exp|@>=
21934
21935   mp_init_randoms(mp, mp->cur_exp);
21936   if ( mp->selector>=log_only && mp->selector<write_file) {
21937     mp->old_setting=mp->selector; mp->selector=log_only;
21938     mp_print_nl(mp, "{randomseed:="); 
21939     mp_print_scaled(mp, mp->cur_exp); 
21940     mp_print_char(mp, '}');
21941     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
21942   }
21943 }
21944
21945 @ And here's another simple one (somewhat different in flavor):
21946
21947 @<Cases of |do_statement|...@>=
21948 case mode_command: 
21949   mp_print_ln(mp); mp->interaction=mp->cur_mod;
21950   @<Initialize the print |selector| based on |interaction|@>;
21951   if ( mp->log_opened ) mp->selector=mp->selector+2;
21952   mp_get_x_next(mp);
21953   break;
21954
21955 @ @<Put each...@>=
21956 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
21957 @:mp_batch_mode_}{\&{batchmode} primitive@>
21958 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
21959 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
21960 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
21961 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
21962 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
21963 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
21964
21965 @ @<Cases of |print_cmd_mod|...@>=
21966 case mode_command: 
21967   switch (m) {
21968   case mp_batch_mode: mp_print(mp, "batchmode"); break;
21969   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
21970   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
21971   default: mp_print(mp, "errorstopmode"); break;
21972   }
21973   break;
21974
21975 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
21976
21977 @<Cases of |do_statement|...@>=
21978 case protection_command: mp_do_protection(mp); break;
21979
21980 @ @<Put each...@>=
21981 mp_primitive(mp, "inner",protection_command,0);
21982 @:inner_}{\&{inner} primitive@>
21983 mp_primitive(mp, "outer",protection_command,1);
21984 @:outer_}{\&{outer} primitive@>
21985
21986 @ @<Cases of |print_cmd...@>=
21987 case protection_command: 
21988   if ( m==0 ) mp_print(mp, "inner");
21989   else mp_print(mp, "outer");
21990   break;
21991
21992 @ @<Declare action procedures for use by |do_statement|@>=
21993 void mp_do_protection (MP mp) ;
21994
21995 @ @c void mp_do_protection (MP mp) {
21996   int m; /* 0 to unprotect, 1 to protect */
21997   halfword t; /* the |eq_type| before we change it */
21998   m=mp->cur_mod;
21999   do {  
22000     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
22001     if ( m==0 ) { 
22002       if ( t>=outer_tag ) 
22003         eq_type(mp->cur_sym)=t-outer_tag;
22004     } else if ( t<outer_tag ) {
22005       eq_type(mp->cur_sym)=t+outer_tag;
22006     }
22007     mp_get_x_next(mp);
22008   } while (mp->cur_cmd==comma);
22009 }
22010
22011 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
22012 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
22013 declaration assigns the command code |left_delimiter| to `\.{(}' and
22014 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
22015 hash address of its mate.
22016
22017 @<Cases of |do_statement|...@>=
22018 case delimiters: mp_def_delims(mp); break;
22019
22020 @ @<Declare action procedures for use by |do_statement|@>=
22021 void mp_def_delims (MP mp) ;
22022
22023 @ @c void mp_def_delims (MP mp) {
22024   pointer l_delim,r_delim; /* the new delimiter pair */
22025   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
22026   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
22027   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
22028   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
22029   mp_get_x_next(mp);
22030 }
22031
22032 @ Here is a procedure that is called when \MP\ has reached a point
22033 where some right delimiter is mandatory.
22034
22035 @<Declare the procedure called |check_delimiter|@>=
22036 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
22037   if ( mp->cur_cmd==right_delimiter ) 
22038     if ( mp->cur_mod==l_delim ) 
22039       return;
22040   if ( mp->cur_sym!=r_delim ) {
22041      mp_missing_err(mp, str(text(r_delim)));
22042 @.Missing `)'@>
22043     help2("I found no right delimiter to match a left one. So I've")
22044       ("put one in, behind the scenes; this may fix the problem.");
22045     mp_back_error(mp);
22046   } else { 
22047     print_err("The token `"); mp_print_text(r_delim);
22048 @.The token...delimiter@>
22049     mp_print(mp, "' is no longer a right delimiter");
22050     help3("Strange: This token has lost its former meaning!")
22051       ("I'll read it as a right delimiter this time;")
22052       ("but watch out, I'll probably miss it later.");
22053     mp_error(mp);
22054   }
22055 }
22056
22057 @ The next four commands save or change the values associated with tokens.
22058
22059 @<Cases of |do_statement|...@>=
22060 case save_command: 
22061   do {  
22062     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22063   } while (mp->cur_cmd==comma);
22064   break;
22065 case interim_command: mp_do_interim(mp); break;
22066 case let_command: mp_do_let(mp); break;
22067 case new_internal: mp_do_new_internal(mp); break;
22068
22069 @ @<Declare action procedures for use by |do_statement|@>=
22070 void mp_do_statement (MP mp);
22071 void mp_do_interim (MP mp);
22072
22073 @ @c void mp_do_interim (MP mp) { 
22074   mp_get_x_next(mp);
22075   if ( mp->cur_cmd!=internal_quantity ) {
22076      print_err("The token `");
22077 @.The token...quantity@>
22078     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22079     else mp_print_text(mp->cur_sym);
22080     mp_print(mp, "' isn't an internal quantity");
22081     help1("Something like `tracingonline' should follow `interim'.");
22082     mp_back_error(mp);
22083   } else { 
22084     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22085   }
22086   mp_do_statement(mp);
22087 }
22088
22089 @ The following procedure is careful not to undefine the left-hand symbol
22090 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22091
22092 @<Declare action procedures for use by |do_statement|@>=
22093 void mp_do_let (MP mp) ;
22094
22095 @ @c void mp_do_let (MP mp) {
22096   pointer l; /* hash location of the left-hand symbol */
22097   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22098   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22099      mp_missing_err(mp, "=");
22100 @.Missing `='@>
22101     help3("You should have said `let symbol = something'.")
22102       ("But don't worry; I'll pretend that an equals sign")
22103       ("was present. The next token I read will be `something'.");
22104     mp_back_error(mp);
22105   }
22106   mp_get_symbol(mp);
22107   switch (mp->cur_cmd) {
22108   case defined_macro: case secondary_primary_macro:
22109   case tertiary_secondary_macro: case expression_tertiary_macro: 
22110     add_mac_ref(mp->cur_mod);
22111     break;
22112   default: 
22113     break;
22114   }
22115   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22116   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22117   else equiv(l)=mp->cur_mod;
22118   mp_get_x_next(mp);
22119 }
22120
22121 @ @<Declarations@>=
22122 void mp_grow_internals (MP mp, int l);
22123 void mp_do_new_internal (MP mp) ;
22124
22125 @ @c
22126 void mp_grow_internals (MP mp, int l) {
22127   scaled *internal;
22128   char * *int_name; 
22129   int k;
22130   if ( hash_end+l>max_halfword ) {
22131     mp_confusion(mp, "out of memory space"); /* can't be reached */
22132   }
22133   int_name = xmalloc ((l+1),sizeof(char *));
22134   internal = xmalloc ((l+1),sizeof(scaled));
22135   for (k=0;k<=l; k++ ) { 
22136     if (k<=mp->max_internal) {
22137       internal[k]=mp->internal[k]; 
22138       int_name[k]=mp->int_name[k]; 
22139     } else {
22140       internal[k]=0; 
22141       int_name[k]=NULL; 
22142     }
22143   }
22144   xfree(mp->internal); xfree(mp->int_name);
22145   mp->int_name = int_name;
22146   mp->internal = internal;
22147   mp->max_internal = l;
22148 }
22149
22150
22151 void mp_do_new_internal (MP mp) { 
22152   do {  
22153     if ( mp->int_ptr==mp->max_internal ) {
22154       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal>>2)));
22155     }
22156     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22157     eq_type(mp->cur_sym)=internal_quantity; 
22158     equiv(mp->cur_sym)=mp->int_ptr;
22159     if(mp->int_name[mp->int_ptr]!=NULL)
22160       xfree(mp->int_name[mp->int_ptr]);
22161     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22162     mp->internal[mp->int_ptr]=0;
22163     mp_get_x_next(mp);
22164   } while (mp->cur_cmd==comma);
22165 }
22166
22167 @ @<Dealloc variables@>=
22168 for (k=0;k<=mp->max_internal;k++) {
22169    xfree(mp->int_name[k]);
22170 }
22171 xfree(mp->internal); 
22172 xfree(mp->int_name); 
22173
22174
22175 @ The various `\&{show}' commands are distinguished by modifier fields
22176 in the usual way.
22177
22178 @d show_token_code 0 /* show the meaning of a single token */
22179 @d show_stats_code 1 /* show current memory and string usage */
22180 @d show_code 2 /* show a list of expressions */
22181 @d show_var_code 3 /* show a variable and its descendents */
22182 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22183
22184 @<Put each...@>=
22185 mp_primitive(mp, "showtoken",show_command,show_token_code);
22186 @:show_token_}{\&{showtoken} primitive@>
22187 mp_primitive(mp, "showstats",show_command,show_stats_code);
22188 @:show_stats_}{\&{showstats} primitive@>
22189 mp_primitive(mp, "show",show_command,show_code);
22190 @:show_}{\&{show} primitive@>
22191 mp_primitive(mp, "showvariable",show_command,show_var_code);
22192 @:show_var_}{\&{showvariable} primitive@>
22193 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22194 @:show_dependencies_}{\&{showdependencies} primitive@>
22195
22196 @ @<Cases of |print_cmd...@>=
22197 case show_command: 
22198   switch (m) {
22199   case show_token_code:mp_print(mp, "showtoken"); break;
22200   case show_stats_code:mp_print(mp, "showstats"); break;
22201   case show_code:mp_print(mp, "show"); break;
22202   case show_var_code:mp_print(mp, "showvariable"); break;
22203   default: mp_print(mp, "showdependencies"); break;
22204   }
22205   break;
22206
22207 @ @<Cases of |do_statement|...@>=
22208 case show_command:mp_do_show_whatever(mp); break;
22209
22210 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22211 if it's |show_code|, complicated structures are abbreviated, otherwise
22212 they aren't.
22213
22214 @<Declare action procedures for use by |do_statement|@>=
22215 void mp_do_show (MP mp) ;
22216
22217 @ @c void mp_do_show (MP mp) { 
22218   do {  
22219     mp_get_x_next(mp); mp_scan_expression(mp);
22220     mp_print_nl(mp, ">> ");
22221 @.>>@>
22222     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22223   } while (mp->cur_cmd==comma);
22224 }
22225
22226 @ @<Declare action procedures for use by |do_statement|@>=
22227 void mp_disp_token (MP mp) ;
22228
22229 @ @c void mp_disp_token (MP mp) { 
22230   mp_print_nl(mp, "> ");
22231 @.>\relax@>
22232   if ( mp->cur_sym==0 ) {
22233     @<Show a numeric or string or capsule token@>;
22234   } else { 
22235     mp_print_text(mp->cur_sym); mp_print_char(mp, '=');
22236     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22237     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22238     if ( mp->cur_cmd==defined_macro ) {
22239       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22240     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22241 @^recursion@>
22242   }
22243 }
22244
22245 @ @<Show a numeric or string or capsule token@>=
22246
22247   if ( mp->cur_cmd==numeric_token ) {
22248     mp_print_scaled(mp, mp->cur_mod);
22249   } else if ( mp->cur_cmd==capsule_token ) {
22250     mp_print_capsule(mp,mp->cur_mod);
22251   } else  { 
22252     mp_print_char(mp, '"'); 
22253     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, '"');
22254     delete_str_ref(mp->cur_mod);
22255   }
22256 }
22257
22258 @ The following cases of |print_cmd_mod| might arise in connection
22259 with |disp_token|, although they don't necessarily correspond to
22260 primitive tokens.
22261
22262 @<Cases of |print_cmd_...@>=
22263 case left_delimiter:
22264 case right_delimiter: 
22265   if ( c==left_delimiter ) mp_print(mp, "left");
22266   else mp_print(mp, "right");
22267   mp_print(mp, " delimiter that matches "); 
22268   mp_print_text(m);
22269   break;
22270 case tag_token:
22271   if ( m==null ) mp_print(mp, "tag");
22272    else mp_print(mp, "variable");
22273    break;
22274 case defined_macro: 
22275    mp_print(mp, "macro:");
22276    break;
22277 case secondary_primary_macro:
22278 case tertiary_secondary_macro:
22279 case expression_tertiary_macro:
22280   mp_print_cmd_mod(mp, macro_def,c); 
22281   mp_print(mp, "'d macro:");
22282   mp_print_ln(mp); mp_show_token_list(mp, link(link(m)),null,1000,0);
22283   break;
22284 case repeat_loop:
22285   mp_print(mp, "[repeat the loop]");
22286   break;
22287 case internal_quantity:
22288   mp_print(mp, mp->int_name[m]);
22289   break;
22290
22291 @ @<Declare action procedures for use by |do_statement|@>=
22292 void mp_do_show_token (MP mp) ;
22293
22294 @ @c void mp_do_show_token (MP mp) { 
22295   do {  
22296     get_t_next; mp_disp_token(mp);
22297     mp_get_x_next(mp);
22298   } while (mp->cur_cmd==comma);
22299 }
22300
22301 @ @<Declare action procedures for use by |do_statement|@>=
22302 void mp_do_show_stats (MP mp) ;
22303
22304 @ @c void mp_do_show_stats (MP mp) { 
22305   mp_print_nl(mp, "Memory usage ");
22306 @.Memory usage...@>
22307   mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used);
22308   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22309   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22310   mp_print_nl(mp, "String usage ");
22311   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22312   mp_print_char(mp, '&'); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22313   mp_print(mp, " (");
22314   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, '&');
22315   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22316   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22317   mp_get_x_next(mp);
22318 }
22319
22320 @ Here's a recursive procedure that gives an abbreviated account
22321 of a variable, for use by |do_show_var|.
22322
22323 @<Declare action procedures for use by |do_statement|@>=
22324 void mp_disp_var (MP mp,pointer p) ;
22325
22326 @ @c void mp_disp_var (MP mp,pointer p) {
22327   pointer q; /* traverses attributes and subscripts */
22328   int n; /* amount of macro text to show */
22329   if ( type(p)==mp_structured )  {
22330     @<Descend the structure@>;
22331   } else if ( type(p)>=mp_unsuffixed_macro ) {
22332     @<Display a variable macro@>;
22333   } else if ( type(p)!=undefined ){ 
22334     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22335     mp_print_char(mp, '=');
22336     mp_print_exp(mp, p,0);
22337   }
22338 }
22339
22340 @ @<Descend the structure@>=
22341
22342   q=attr_head(p);
22343   do {  mp_disp_var(mp, q); q=link(q); } while (q!=end_attr);
22344   q=subscr_head(p);
22345   while ( name_type(q)==mp_subscr ) { 
22346     mp_disp_var(mp, q); q=link(q);
22347   }
22348 }
22349
22350 @ @<Display a variable macro@>=
22351
22352   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22353   if ( type(p)>mp_unsuffixed_macro ) 
22354     mp_print(mp, "@@#"); /* |suffixed_macro| */
22355   mp_print(mp, "=macro:");
22356   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22357   else n=mp->max_print_line-mp->file_offset-15;
22358   mp_show_macro(mp, value(p),null,n);
22359 }
22360
22361 @ @<Declare action procedures for use by |do_statement|@>=
22362 void mp_do_show_var (MP mp) ;
22363
22364 @ @c void mp_do_show_var (MP mp) { 
22365   do {  
22366     get_t_next;
22367     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22368       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22369       mp_disp_var(mp, mp->cur_mod); goto DONE;
22370     }
22371    mp_disp_token(mp);
22372   DONE:
22373    mp_get_x_next(mp);
22374   } while (mp->cur_cmd==comma);
22375 }
22376
22377 @ @<Declare action procedures for use by |do_statement|@>=
22378 void mp_do_show_dependencies (MP mp) ;
22379
22380 @ @c void mp_do_show_dependencies (MP mp) {
22381   pointer p; /* link that runs through all dependencies */
22382   p=link(dep_head);
22383   while ( p!=dep_head ) {
22384     if ( mp_interesting(mp, p) ) {
22385       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22386       if ( type(p)==mp_dependent ) mp_print_char(mp, '=');
22387       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22388       mp_print_dependency(mp, dep_list(p),type(p));
22389     }
22390     p=dep_list(p);
22391     while ( info(p)!=null ) p=link(p);
22392     p=link(p);
22393   }
22394   mp_get_x_next(mp);
22395 }
22396
22397 @ Finally we are ready for the procedure that governs all of the
22398 show commands.
22399
22400 @<Declare action procedures for use by |do_statement|@>=
22401 void mp_do_show_whatever (MP mp) ;
22402
22403 @ @c void mp_do_show_whatever (MP mp) { 
22404   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22405   switch (mp->cur_mod) {
22406   case show_token_code:mp_do_show_token(mp); break;
22407   case show_stats_code:mp_do_show_stats(mp); break;
22408   case show_code:mp_do_show(mp); break;
22409   case show_var_code:mp_do_show_var(mp); break;
22410   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22411   } /* there are no other cases */
22412   if ( mp->internal[mp_showstopping]>0 ){ 
22413     print_err("OK");
22414 @.OK@>
22415     if ( mp->interaction<mp_error_stop_mode ) { 
22416       help0; decr(mp->error_count);
22417     } else {
22418       help1("This isn't an error message; I'm just showing something.");
22419     }
22420     if ( mp->cur_cmd==semicolon ) mp_error(mp);
22421      else mp_put_get_error(mp);
22422   }
22423 }
22424
22425 @ The `\&{addto}' command needs the following additional primitives:
22426
22427 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
22428 @d contour_code 1 /* command modifier for `\&{contour}' */
22429 @d also_code 2 /* command modifier for `\&{also}' */
22430
22431 @ Pre and postscripts need two new identifiers:
22432
22433 @d with_pre_script 11
22434 @d with_post_script 13
22435
22436 @<Put each...@>=
22437 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
22438 @:double_path_}{\&{doublepath} primitive@>
22439 mp_primitive(mp, "contour",thing_to_add,contour_code);
22440 @:contour_}{\&{contour} primitive@>
22441 mp_primitive(mp, "also",thing_to_add,also_code);
22442 @:also_}{\&{also} primitive@>
22443 mp_primitive(mp, "withpen",with_option,mp_pen_type);
22444 @:with_pen_}{\&{withpen} primitive@>
22445 mp_primitive(mp, "dashed",with_option,mp_picture_type);
22446 @:dashed_}{\&{dashed} primitive@>
22447 mp_primitive(mp, "withprescript",with_option,with_pre_script);
22448 @:with_pre_script_}{\&{withprescript} primitive@>
22449 mp_primitive(mp, "withpostscript",with_option,with_post_script);
22450 @:with_post_script_}{\&{withpostscript} primitive@>
22451 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
22452 @:with_color_}{\&{withoutcolor} primitive@>
22453 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
22454 @:with_color_}{\&{withgreyscale} primitive@>
22455 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
22456 @:with_color_}{\&{withcolor} primitive@>
22457 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
22458 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
22459 @:with_color_}{\&{withrgbcolor} primitive@>
22460 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
22461 @:with_color_}{\&{withcmykcolor} primitive@>
22462
22463 @ @<Cases of |print_cmd...@>=
22464 case thing_to_add:
22465   if ( m==contour_code ) mp_print(mp, "contour");
22466   else if ( m==double_path_code ) mp_print(mp, "doublepath");
22467   else mp_print(mp, "also");
22468   break;
22469 case with_option:
22470   if ( m==mp_pen_type ) mp_print(mp, "withpen");
22471   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
22472   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
22473   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
22474   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
22475   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
22476   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
22477   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
22478   else mp_print(mp, "dashed");
22479   break;
22480
22481 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
22482 updates the list of graphical objects starting at |p|.  Each $\langle$with
22483 clause$\rangle$ updates all graphical objects whose |type| is compatible.
22484 Other objects are ignored.
22485
22486 @<Declare action procedures for use by |do_statement|@>=
22487 void mp_scan_with_list (MP mp,pointer p) ;
22488
22489 @ @c void mp_scan_with_list (MP mp,pointer p) {
22490   small_number t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
22491   pointer q; /* for list manipulation */
22492   int old_setting; /* saved |selector| setting */
22493   pointer k; /* for finding the near-last item in a list  */
22494   str_number s; /* for string cleanup after combining  */
22495   pointer cp,pp,dp,ap,bp;
22496     /* objects being updated; |void| initially; |null| to suppress update */
22497   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
22498   k=0;
22499   while ( mp->cur_cmd==with_option ){ 
22500     t=mp->cur_mod;
22501     mp_get_x_next(mp);
22502     if ( t!=mp_no_model ) mp_scan_expression(mp);
22503     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
22504      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
22505      ((t==mp_uninitialized_model)&&
22506         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
22507           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
22508      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
22509      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
22510      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
22511      ((t==mp_pen_type)&&(mp->cur_type!=t))||
22512      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
22513       @<Complain about improper type@>;
22514     } else if ( t==mp_uninitialized_model ) {
22515       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22516       if ( cp!=null )
22517         @<Transfer a color from the current expression to object~|cp|@>;
22518       mp_flush_cur_exp(mp, 0);
22519     } else if ( t==mp_rgb_model ) {
22520       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22521       if ( cp!=null )
22522         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
22523       mp_flush_cur_exp(mp, 0);
22524     } else if ( t==mp_cmyk_model ) {
22525       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22526       if ( cp!=null )
22527         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
22528       mp_flush_cur_exp(mp, 0);
22529     } else if ( t==mp_grey_model ) {
22530       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22531       if ( cp!=null )
22532         @<Transfer a greyscale from the current expression to object~|cp|@>;
22533       mp_flush_cur_exp(mp, 0);
22534     } else if ( t==mp_no_model ) {
22535       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
22536       if ( cp!=null )
22537         @<Transfer a noncolor from the current expression to object~|cp|@>;
22538     } else if ( t==mp_pen_type ) {
22539       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
22540       if ( pp!=null ) {
22541         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
22542         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
22543       }
22544     } else if ( t==with_pre_script ) {
22545       if ( ap==mp_void )
22546         ap=p;
22547       while ( (ap!=null)&&(! has_color(ap)) )
22548          ap=link(ap);
22549       if ( ap!=null ) {
22550         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
22551           s=pre_script(ap);
22552           old_setting=mp->selector;
22553               mp->selector=new_string;
22554           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
22555               mp_print_str(mp, mp->cur_exp);
22556           append_char(13);  /* a forced \ps\ newline  */
22557           mp_print_str(mp, pre_script(ap));
22558           pre_script(ap)=mp_make_string(mp);
22559           delete_str_ref(s);
22560           mp->selector=old_setting;
22561         } else {
22562           pre_script(ap)=mp->cur_exp;
22563         }
22564         mp->cur_type=mp_vacuous;
22565       }
22566     } else if ( t==with_post_script ) {
22567       if ( bp==mp_void )
22568         k=p; 
22569       bp=k;
22570       while ( link(k)!=null ) {
22571         k=link(k);
22572         if ( has_color(k) ) bp=k;
22573       }
22574       if ( bp!=null ) {
22575          if ( post_script(bp)!=null ) {
22576            s=post_script(bp);
22577            old_setting=mp->selector;
22578                mp->selector=new_string;
22579            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
22580            mp_print_str(mp, post_script(bp));
22581            append_char(13); /* a forced \ps\ newline  */
22582            mp_print_str(mp, mp->cur_exp);
22583            post_script(bp)=mp_make_string(mp);
22584            delete_str_ref(s);
22585            mp->selector=old_setting;
22586          } else {
22587            post_script(bp)=mp->cur_exp;
22588          }
22589          mp->cur_type=mp_vacuous;
22590        }
22591     } else { 
22592       if ( dp==mp_void ) {
22593         @<Make |dp| a stroked node in list~|p|@>;
22594       }
22595       if ( dp!=null ) {
22596         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
22597         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
22598         dash_scale(dp)=unity;
22599         mp->cur_type=mp_vacuous;
22600       }
22601     }
22602   }
22603   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
22604     of the list@>;
22605 }
22606
22607 @ @<Complain about improper type@>=
22608 { exp_err("Improper type");
22609 @.Improper type@>
22610 help2("Next time say `withpen <known pen expression>';")
22611   ("I'll ignore the bad `with' clause and look for another.");
22612 if ( t==with_pre_script )
22613   mp->help_line[1]="Next time say `withprescript <known string expression>';";
22614 else if ( t==with_post_script )
22615   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
22616 else if ( t==mp_picture_type )
22617   mp->help_line[1]="Next time say `dashed <known picture expression>';";
22618 else if ( t==mp_uninitialized_model )
22619   mp->help_line[1]="Next time say `withcolor <known color expression>';";
22620 else if ( t==mp_rgb_model )
22621   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
22622 else if ( t==mp_cmyk_model )
22623   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
22624 else if ( t==mp_grey_model )
22625   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
22626 mp_put_get_flush_error(mp, 0);
22627 }
22628
22629 @ Forcing the color to be between |0| and |unity| here guarantees that no
22630 picture will ever contain a color outside the legal range for \ps\ graphics.
22631
22632 @<Transfer a color from the current expression to object~|cp|@>=
22633 { if ( mp->cur_type==mp_color_type )
22634    @<Transfer a rgbcolor from the current expression to object~|cp|@>
22635 else if ( mp->cur_type==mp_cmykcolor_type )
22636    @<Transfer a cmykcolor from the current expression to object~|cp|@>
22637 else if ( mp->cur_type==mp_known )
22638    @<Transfer a greyscale from the current expression to object~|cp|@>
22639 else if ( mp->cur_exp==false_code )
22640    @<Transfer a noncolor from the current expression to object~|cp|@>;
22641 }
22642
22643 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
22644 { q=value(mp->cur_exp);
22645 cyan_val(cp)=0;
22646 magenta_val(cp)=0;
22647 yellow_val(cp)=0;
22648 black_val(cp)=0;
22649 red_val(cp)=value(red_part_loc(q));
22650 green_val(cp)=value(green_part_loc(q));
22651 blue_val(cp)=value(blue_part_loc(q));
22652 color_model(cp)=mp_rgb_model;
22653 if ( red_val(cp)<0 ) red_val(cp)=0;
22654 if ( green_val(cp)<0 ) green_val(cp)=0;
22655 if ( blue_val(cp)<0 ) blue_val(cp)=0;
22656 if ( red_val(cp)>unity ) red_val(cp)=unity;
22657 if ( green_val(cp)>unity ) green_val(cp)=unity;
22658 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
22659 }
22660
22661 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
22662 { q=value(mp->cur_exp);
22663 cyan_val(cp)=value(cyan_part_loc(q));
22664 magenta_val(cp)=value(magenta_part_loc(q));
22665 yellow_val(cp)=value(yellow_part_loc(q));
22666 black_val(cp)=value(black_part_loc(q));
22667 color_model(cp)=mp_cmyk_model;
22668 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
22669 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
22670 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
22671 if ( black_val(cp)<0 ) black_val(cp)=0;
22672 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
22673 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
22674 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
22675 if ( black_val(cp)>unity ) black_val(cp)=unity;
22676 }
22677
22678 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
22679 { q=mp->cur_exp;
22680 cyan_val(cp)=0;
22681 magenta_val(cp)=0;
22682 yellow_val(cp)=0;
22683 black_val(cp)=0;
22684 grey_val(cp)=q;
22685 color_model(cp)=mp_grey_model;
22686 if ( grey_val(cp)<0 ) grey_val(cp)=0;
22687 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
22688 }
22689
22690 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
22691 {
22692 cyan_val(cp)=0;
22693 magenta_val(cp)=0;
22694 yellow_val(cp)=0;
22695 black_val(cp)=0;
22696 grey_val(cp)=0;
22697 color_model(cp)=mp_no_model;
22698 }
22699
22700 @ @<Make |cp| a colored object in object list~|p|@>=
22701 { cp=p;
22702   while ( cp!=null ){ 
22703     if ( has_color(cp) ) break;
22704     cp=link(cp);
22705   }
22706 }
22707
22708 @ @<Make |pp| an object in list~|p| that needs a pen@>=
22709 { pp=p;
22710   while ( pp!=null ) {
22711     if ( has_pen(pp) ) break;
22712     pp=link(pp);
22713   }
22714 }
22715
22716 @ @<Make |dp| a stroked node in list~|p|@>=
22717 { dp=p;
22718   while ( dp!=null ) {
22719     if ( type(dp)==mp_stroked_code ) break;
22720     dp=link(dp);
22721   }
22722 }
22723
22724 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
22725 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
22726 if ( pp>mp_void ) {
22727   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
22728 }
22729 if ( dp>mp_void ) {
22730   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
22731 }
22732
22733
22734 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
22735 { q=link(cp);
22736   while ( q!=null ) { 
22737     if ( has_color(q) ) {
22738       red_val(q)=red_val(cp);
22739       green_val(q)=green_val(cp);
22740       blue_val(q)=blue_val(cp);
22741       black_val(q)=black_val(cp);
22742       color_model(q)=color_model(cp);
22743     }
22744     q=link(q);
22745   }
22746 }
22747
22748 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
22749 { q=link(pp);
22750   while ( q!=null ) {
22751     if ( has_pen(q) ) {
22752       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
22753       pen_p(q)=copy_pen(pen_p(pp));
22754     }
22755     q=link(q);
22756   }
22757 }
22758
22759 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
22760 { q=link(dp);
22761   while ( q!=null ) {
22762     if ( type(q)==mp_stroked_code ) {
22763       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
22764       dash_p(q)=dash_p(dp);
22765       dash_scale(q)=unity;
22766       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
22767     }
22768     q=link(q);
22769   }
22770 }
22771
22772 @ One of the things we need to do when we've parsed an \&{addto} or
22773 similar command is find the header of a supposed \&{picture} variable, given
22774 a token list for that variable.  Since the edge structure is about to be
22775 updated, we use |private_edges| to make sure that this is possible.
22776
22777 @<Declare action procedures for use by |do_statement|@>=
22778 pointer mp_find_edges_var (MP mp, pointer t) ;
22779
22780 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
22781   pointer p;
22782   pointer cur_edges; /* the return value */
22783   p=mp_find_variable(mp, t); cur_edges=null;
22784   if ( p==null ) { 
22785     mp_obliterated(mp, t); mp_put_get_error(mp);
22786   } else if ( type(p)!=mp_picture_type )  { 
22787     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
22788 @.Variable x is the wrong type@>
22789     mp_print(mp, " is the wrong type ("); 
22790     mp_print_type(mp, type(p)); mp_print_char(mp, ')');
22791     help2("I was looking for a \"known\" picture variable.")
22792          ("So I'll not change anything just now."); 
22793     mp_put_get_error(mp);
22794   } else { 
22795     value(p)=mp_private_edges(mp, value(p));
22796     cur_edges=value(p);
22797   }
22798   mp_flush_node_list(mp, t);
22799   return cur_edges;
22800 }
22801
22802 @ @<Cases of |do_statement|...@>=
22803 case add_to_command: mp_do_add_to(mp); break;
22804 case bounds_command:mp_do_bounds(mp); break;
22805
22806 @ @<Put each...@>=
22807 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
22808 @:clip_}{\&{clip} primitive@>
22809 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
22810 @:set_bounds_}{\&{setbounds} primitive@>
22811
22812 @ @<Cases of |print_cmd...@>=
22813 case bounds_command: 
22814   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
22815   else mp_print(mp, "setbounds");
22816   break;
22817
22818 @ The following function parses the beginning of an \&{addto} or \&{clip}
22819 command: it expects a variable name followed by a token with |cur_cmd=sep|
22820 and then an expression.  The function returns the token list for the variable
22821 and stores the command modifier for the separator token in the global variable
22822 |last_add_type|.  We must be careful because this variable might get overwritten
22823 any time we call |get_x_next|.
22824
22825 @<Glob...@>=
22826 quarterword last_add_type;
22827   /* command modifier that identifies the last \&{addto} command */
22828
22829 @ @<Declare action procedures for use by |do_statement|@>=
22830 pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
22831
22832 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
22833   pointer lhv; /* variable to add to left */
22834   quarterword add_type=0; /* value to be returned in |last_add_type| */
22835   lhv=null;
22836   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
22837   if ( mp->cur_type!=mp_token_list ) {
22838     @<Abandon edges command because there's no variable@>;
22839   } else  { 
22840     lhv=mp->cur_exp; add_type=mp->cur_mod;
22841     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
22842   }
22843   mp->last_add_type=add_type;
22844   return lhv;
22845 }
22846
22847 @ @<Abandon edges command because there's no variable@>=
22848 { exp_err("Not a suitable variable");
22849 @.Not a suitable variable@>
22850   help4("At this point I needed to see the name of a picture variable.")
22851     ("(Or perhaps you have indeed presented me with one; I might")
22852     ("have missed it, if it wasn't followed by the proper token.)")
22853     ("So I'll not change anything just now.");
22854   mp_put_get_flush_error(mp, 0);
22855 }
22856
22857 @ Here is an example of how to use |start_draw_cmd|.
22858
22859 @<Declare action procedures for use by |do_statement|@>=
22860 void mp_do_bounds (MP mp) ;
22861
22862 @ @c void mp_do_bounds (MP mp) {
22863   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22864   pointer p; /* for list manipulation */
22865   integer m; /* initial value of |cur_mod| */
22866   m=mp->cur_mod;
22867   lhv=mp_start_draw_cmd(mp, to_token);
22868   if ( lhv!=null ) {
22869     lhe=mp_find_edges_var(mp, lhv);
22870     if ( lhe==null ) {
22871       mp_flush_cur_exp(mp, 0);
22872     } else if ( mp->cur_type!=mp_path_type ) {
22873       exp_err("Improper `clip'");
22874 @.Improper `addto'@>
22875       help2("This expression should have specified a known path.")
22876         ("So I'll not change anything just now."); 
22877       mp_put_get_flush_error(mp, 0);
22878     } else if ( left_type(mp->cur_exp)==mp_endpoint ) {
22879       @<Complain about a non-cycle@>;
22880     } else {
22881       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
22882     }
22883   }
22884 }
22885
22886 @ @<Complain about a non-cycle@>=
22887 { print_err("Not a cycle");
22888 @.Not a cycle@>
22889   help2("That contour should have ended with `..cycle' or `&cycle'.")
22890     ("So I'll not change anything just now."); mp_put_get_error(mp);
22891 }
22892
22893 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
22894 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
22895   link(p)=link(dummy_loc(lhe));
22896   link(dummy_loc(lhe))=p;
22897   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
22898   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
22899   type(p)=stop_type(m);
22900   link(obj_tail(lhe))=p;
22901   obj_tail(lhe)=p;
22902   mp_init_bbox(mp, lhe);
22903 }
22904
22905 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
22906 cases to deal with.
22907
22908 @<Declare action procedures for use by |do_statement|@>=
22909 void mp_do_add_to (MP mp) ;
22910
22911 @ @c void mp_do_add_to (MP mp) {
22912   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
22913   pointer p; /* the graphical object or list for |scan_with_list| to update */
22914   pointer e; /* an edge structure to be merged */
22915   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
22916   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
22917   if ( lhv!=null ) {
22918     if ( add_type==also_code ) {
22919       @<Make sure the current expression is a suitable picture and set |e| and |p|
22920        appropriately@>;
22921     } else {
22922       @<Create a graphical object |p| based on |add_type| and the current
22923         expression@>;
22924     }
22925     mp_scan_with_list(mp, p);
22926     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
22927   }
22928 }
22929
22930 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
22931 setting |e:=null| prevents anything from being added to |lhe|.
22932
22933 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
22934
22935   p=null; e=null;
22936   if ( mp->cur_type!=mp_picture_type ) {
22937     exp_err("Improper `addto'");
22938 @.Improper `addto'@>
22939     help2("This expression should have specified a known picture.")
22940       ("So I'll not change anything just now."); mp_put_get_flush_error(mp, 0);
22941   } else { 
22942     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
22943     p=link(dummy_loc(e));
22944   }
22945 }
22946
22947 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
22948 attempts to add to the edge structure.
22949
22950 @<Create a graphical object |p| based on |add_type| and the current...@>=
22951 { e=null; p=null;
22952   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
22953   if ( mp->cur_type!=mp_path_type ) {
22954     exp_err("Improper `addto'");
22955 @.Improper `addto'@>
22956     help2("This expression should have specified a known path.")
22957       ("So I'll not change anything just now."); 
22958     mp_put_get_flush_error(mp, 0);
22959   } else if ( add_type==contour_code ) {
22960     if ( left_type(mp->cur_exp)==mp_endpoint ) {
22961       @<Complain about a non-cycle@>;
22962     } else { 
22963       p=mp_new_fill_node(mp, mp->cur_exp);
22964       mp->cur_type=mp_vacuous;
22965     }
22966   } else { 
22967     p=mp_new_stroked_node(mp, mp->cur_exp);
22968     mp->cur_type=mp_vacuous;
22969   }
22970 }
22971
22972 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
22973 lhe=mp_find_edges_var(mp, lhv);
22974 if ( lhe==null ) {
22975   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
22976   if ( e!=null ) delete_edge_ref(e);
22977 } else if ( add_type==also_code ) {
22978   if ( e!=null ) {
22979     @<Merge |e| into |lhe| and delete |e|@>;
22980   } else { 
22981     do_nothing;
22982   }
22983 } else if ( p!=null ) {
22984   link(obj_tail(lhe))=p;
22985   obj_tail(lhe)=p;
22986   if ( add_type==double_path_code )
22987     if ( pen_p(p)==null ) 
22988       pen_p(p)=mp_get_pen_circle(mp, 0);
22989 }
22990
22991 @ @<Merge |e| into |lhe| and delete |e|@>=
22992 { if ( link(dummy_loc(e))!=null ) {
22993     link(obj_tail(lhe))=link(dummy_loc(e));
22994     obj_tail(lhe)=obj_tail(e);
22995     obj_tail(e)=dummy_loc(e);
22996     link(dummy_loc(e))=null;
22997     mp_flush_dash_list(mp, lhe);
22998   }
22999   mp_toss_edges(mp, e);
23000 }
23001
23002 @ @<Cases of |do_statement|...@>=
23003 case ship_out_command: mp_do_ship_out(mp); break;
23004
23005 @ @<Declare action procedures for use by |do_statement|@>=
23006 @<Declare the function called |tfm_check|@>
23007 @<Declare the \ps\ output procedures@>
23008 void mp_do_ship_out (MP mp) ;
23009
23010 @ @c void mp_do_ship_out (MP mp) {
23011   integer c; /* the character code */
23012   mp_get_x_next(mp); mp_scan_expression(mp);
23013   if ( mp->cur_type!=mp_picture_type ) {
23014     @<Complain that it's not a known picture@>;
23015   } else { 
23016     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
23017     if ( c<0 ) c=c+256;
23018     @<Store the width information for character code~|c|@>;
23019     mp_ship_out(mp, mp->cur_exp);
23020     mp_flush_cur_exp(mp, 0);
23021   }
23022 }
23023
23024 @ @<Complain that it's not a known picture@>=
23025
23026   exp_err("Not a known picture");
23027   help1("I can only output known pictures.");
23028   mp_put_get_flush_error(mp, 0);
23029 }
23030
23031 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
23032 |start_sym|.
23033
23034 @<Cases of |do_statement|...@>=
23035 case every_job_command: 
23036   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
23037   break;
23038
23039 @ @<Glob...@>=
23040 halfword start_sym; /* a symbolic token to insert at beginning of job */
23041
23042 @ @<Set init...@>=
23043 mp->start_sym=0;
23044
23045 @ Finally, we have only the ``message'' commands remaining.
23046
23047 @d message_code 0
23048 @d err_message_code 1
23049 @d err_help_code 2
23050 @d filename_template_code 3
23051 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
23052               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
23053               if ( f>g ) {
23054                 mp->pool_ptr = mp->pool_ptr - g;
23055                 while ( f>g ) {
23056                   mp_print_char(mp, '0');
23057                   decr(f);
23058                   };
23059                 mp_print_int(mp, (A));
23060               };
23061               f = 0
23062
23063 @<Put each...@>=
23064 mp_primitive(mp, "message",message_command,message_code);
23065 @:message_}{\&{message} primitive@>
23066 mp_primitive(mp, "errmessage",message_command,err_message_code);
23067 @:err_message_}{\&{errmessage} primitive@>
23068 mp_primitive(mp, "errhelp",message_command,err_help_code);
23069 @:err_help_}{\&{errhelp} primitive@>
23070 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23071 @:filename_template_}{\&{filenametemplate} primitive@>
23072
23073 @ @<Cases of |print_cmd...@>=
23074 case message_command: 
23075   if ( m<err_message_code ) mp_print(mp, "message");
23076   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23077   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23078   else mp_print(mp, "errhelp");
23079   break;
23080
23081 @ @<Cases of |do_statement|...@>=
23082 case message_command: mp_do_message(mp); break;
23083
23084 @ @<Declare action procedures for use by |do_statement|@>=
23085 @<Declare a procedure called |no_string_err|@>
23086 void mp_do_message (MP mp) ;
23087
23088
23089 @c void mp_do_message (MP mp) {
23090   int m; /* the type of message */
23091   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23092   if ( mp->cur_type!=mp_string_type )
23093     mp_no_string_err(mp, "A message should be a known string expression.");
23094   else {
23095     switch (m) {
23096     case message_code: 
23097       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23098       break;
23099     case err_message_code:
23100       @<Print string |cur_exp| as an error message@>;
23101       break;
23102     case err_help_code:
23103       @<Save string |cur_exp| as the |err_help|@>;
23104       break;
23105     case filename_template_code:
23106       @<Save the filename template@>;
23107       break;
23108     } /* there are no other cases */
23109   }
23110   mp_flush_cur_exp(mp, 0);
23111 }
23112
23113 @ @<Declare a procedure called |no_string_err|@>=
23114 void mp_no_string_err (MP mp, const char *s) { 
23115    exp_err("Not a string");
23116 @.Not a string@>
23117   help1(s);
23118   mp_put_get_error(mp);
23119 }
23120
23121 @ The global variable |err_help| is zero when the user has most recently
23122 given an empty help string, or if none has ever been given.
23123
23124 @<Save string |cur_exp| as the |err_help|@>=
23125
23126   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23127   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23128   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23129 }
23130
23131 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23132 \&{errhelp}, we don't want to give a long help message each time. So we
23133 give a verbose explanation only once.
23134
23135 @<Glob...@>=
23136 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23137
23138 @ @<Set init...@>=mp->long_help_seen=false;
23139
23140 @ @<Print string |cur_exp| as an error message@>=
23141
23142   print_err(""); mp_print_str(mp, mp->cur_exp);
23143   if ( mp->err_help!=0 ) {
23144     mp->use_err_help=true;
23145   } else if ( mp->long_help_seen ) { 
23146     help1("(That was another `errmessage'.)") ; 
23147   } else  { 
23148    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23149     help4("This error message was generated by an `errmessage'")
23150      ("command, so I can\'t give any explicit help.")
23151      ("Pretend that you're Miss Marple: Examine all clues,")
23152 @^Marple, Jane@>
23153      ("and deduce the truth by inspired guesses.");
23154   }
23155   mp_put_get_error(mp); mp->use_err_help=false;
23156 }
23157
23158 @ @<Cases of |do_statement|...@>=
23159 case write_command: mp_do_write(mp); break;
23160
23161 @ @<Declare action procedures for use by |do_statement|@>=
23162 void mp_do_write (MP mp) ;
23163
23164 @ @c void mp_do_write (MP mp) {
23165   str_number t; /* the line of text to be written */
23166   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23167   int old_setting; /* for saving |selector| during output */
23168   mp_get_x_next(mp);
23169   mp_scan_expression(mp);
23170   if ( mp->cur_type!=mp_string_type ) {
23171     mp_no_string_err(mp, "The text to be written should be a known string expression");
23172   } else if ( mp->cur_cmd!=to_token ) { 
23173     print_err("Missing `to' clause");
23174     help1("A write command should end with `to <filename>'");
23175     mp_put_get_error(mp);
23176   } else { 
23177     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23178     mp_get_x_next(mp);
23179     mp_scan_expression(mp);
23180     if ( mp->cur_type!=mp_string_type )
23181       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23182     else {
23183       @<Write |t| to the file named by |cur_exp|@>;
23184     }
23185     delete_str_ref(t);
23186   }
23187   mp_flush_cur_exp(mp, 0);
23188 }
23189
23190 @ @<Write |t| to the file named by |cur_exp|@>=
23191
23192   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23193     |cur_exp| must be inserted@>;
23194   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23195     @<Record the end of file on |wr_file[n]|@>;
23196   } else { 
23197     old_setting=mp->selector;
23198     mp->selector=n+write_file;
23199     mp_print_str(mp, t); mp_print_ln(mp);
23200     mp->selector = old_setting;
23201   }
23202 }
23203
23204 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23205 {
23206   char *fn = str(mp->cur_exp);
23207   n=mp->write_files;
23208   n0=mp->write_files;
23209   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23210     if ( n==0 ) { /* bottom reached */
23211           if ( n0==mp->write_files ) {
23212         if ( mp->write_files<mp->max_write_files ) {
23213           incr(mp->write_files);
23214         } else {
23215           void **wr_file;
23216           char **wr_fname;
23217               write_index l,k;
23218           l = mp->max_write_files + (mp->max_write_files>>2);
23219           wr_file = xmalloc((l+1),sizeof(void *));
23220           wr_fname = xmalloc((l+1),sizeof(char *));
23221               for (k=0;k<=l;k++) {
23222             if (k<=mp->max_write_files) {
23223                   wr_file[k]=mp->wr_file[k]; 
23224               wr_fname[k]=mp->wr_fname[k];
23225             } else {
23226                   wr_file[k]=0; 
23227               wr_fname[k]=NULL;
23228             }
23229           }
23230               xfree(mp->wr_file); xfree(mp->wr_fname);
23231           mp->max_write_files = l;
23232           mp->wr_file = wr_file;
23233           mp->wr_fname = wr_fname;
23234         }
23235       }
23236       n=n0;
23237       mp_open_write_file(mp, fn ,n);
23238     } else { 
23239       decr(n);
23240           if ( mp->wr_fname[n]==NULL )  n0=n; 
23241     }
23242   }
23243 }
23244
23245 @ @<Record the end of file on |wr_file[n]|@>=
23246 { (mp->close_file)(mp,mp->wr_file[n]);
23247   xfree(mp->wr_fname[n]);
23248   mp->wr_fname[n]=NULL;
23249   if ( n==mp->write_files-1 ) mp->write_files=n;
23250 }
23251
23252
23253 @* \[42] Writing font metric data.
23254 \TeX\ gets its knowledge about fonts from font metric files, also called
23255 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23256 but other programs know about them too. One of \MP's duties is to
23257 write \.{TFM} files so that the user's fonts can readily be
23258 applied to typesetting.
23259 @:TFM files}{\.{TFM} files@>
23260 @^font metric files@>
23261
23262 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23263 Since the number of bytes is always a multiple of~4, we could
23264 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23265 byte interpretation. The format of \.{TFM} files was designed by
23266 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23267 @^Ramshaw, Lyle Harold@>
23268 of information in a compact but useful form.
23269
23270 @<Glob...@>=
23271 void * tfm_file; /* the font metric output goes here */
23272 char * metric_file_name; /* full name of the font metric file */
23273
23274 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23275 integers that give the lengths of the various subsequent portions
23276 of the file. These twelve integers are, in order:
23277 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23278 |lf|&length of the entire file, in words;\cr
23279 |lh|&length of the header data, in words;\cr
23280 |bc|&smallest character code in the font;\cr
23281 |ec|&largest character code in the font;\cr
23282 |nw|&number of words in the width table;\cr
23283 |nh|&number of words in the height table;\cr
23284 |nd|&number of words in the depth table;\cr
23285 |ni|&number of words in the italic correction table;\cr
23286 |nl|&number of words in the lig/kern table;\cr
23287 |nk|&number of words in the kern table;\cr
23288 |ne|&number of words in the extensible character table;\cr
23289 |np|&number of font parameter words.\cr}}$$
23290 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23291 |ne<=256|, and
23292 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23293 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23294 and as few as 0 characters (if |bc=ec+1|).
23295
23296 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23297 16 or more bits, the most significant bytes appear first in the file.
23298 This is called BigEndian order.
23299 @^BigEndian order@>
23300
23301 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23302 arrays.
23303
23304 The most important data type used here is a |fix_word|, which is
23305 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23306 quantity, with the two's complement of the entire word used to represent
23307 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23308 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23309 the smallest is $-2048$. We will see below, however, that all but two of
23310 the |fix_word| values must lie between $-16$ and $+16$.
23311
23312 @ The first data array is a block of header information, which contains
23313 general facts about the font. The header must contain at least two words,
23314 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23315 header information of use to other software routines might also be
23316 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23317 For example, 16 more words of header information are in use at the Xerox
23318 Palo Alto Research Center; the first ten specify the character coding
23319 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23320 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23321 last gives the ``face byte.''
23322
23323 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23324 the \.{GF} output file. This helps ensure consistency between files,
23325 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23326 should match the check sums on actual fonts that are used.  The actual
23327 relation between this check sum and the rest of the \.{TFM} file is not
23328 important; the check sum is simply an identification number with the
23329 property that incompatible fonts almost always have distinct check sums.
23330 @^check sum@>
23331
23332 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23333 font, in units of \TeX\ points. This number must be at least 1.0; it is
23334 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23335 font, i.e., a font that was designed to look best at a 10-point size,
23336 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23337 $\delta$ \.{pt}', the effect is to override the design size and replace it
23338 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23339 the font image by a factor of $\delta$ divided by the design size.  {\sl
23340 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23341 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23342 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23343 since many fonts have a design size equal to one em.  The other dimensions
23344 must be less than 16 design-size units in absolute value; thus,
23345 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23346 \.{TFM} file whose first byte might be something besides 0 or 255.
23347 @^design size@>
23348
23349 @ Next comes the |char_info| array, which contains one |char_info_word|
23350 per character. Each word in this part of the file contains six fields
23351 packed into four bytes as follows.
23352
23353 \yskip\hang first byte: |width_index| (8 bits)\par
23354 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23355   (4~bits)\par
23356 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23357   (2~bits)\par
23358 \hang fourth byte: |remainder| (8 bits)\par
23359 \yskip\noindent
23360 The actual width of a character is \\{width}|[width_index]|, in design-size
23361 units; this is a device for compressing information, since many characters
23362 have the same width. Since it is quite common for many characters
23363 to have the same height, depth, or italic correction, the \.{TFM} format
23364 imposes a limit of 16 different heights, 16 different depths, and
23365 64 different italic corrections.
23366
23367 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23368 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23369 value of zero.  The |width_index| should never be zero unless the
23370 character does not exist in the font, since a character is valid if and
23371 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23372
23373 @ The |tag| field in a |char_info_word| has four values that explain how to
23374 interpret the |remainder| field.
23375
23376 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23377 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23378 program starting at location |remainder| in the |lig_kern| array.\par
23379 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23380 characters of ascending sizes, and not the largest in the chain.  The
23381 |remainder| field gives the character code of the next larger character.\par
23382 \hang|tag=3| (|ext_tag|) means that this character code represents an
23383 extensible character, i.e., a character that is built up of smaller pieces
23384 so that it can be made arbitrarily large. The pieces are specified in
23385 |exten[remainder]|.\par
23386 \yskip\noindent
23387 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23388 unless they are used in special circumstances in math formulas. For example,
23389 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23390 operation looks for both |list_tag| and |ext_tag|.
23391
23392 @d no_tag 0 /* vanilla character */
23393 @d lig_tag 1 /* character has a ligature/kerning program */
23394 @d list_tag 2 /* character has a successor in a charlist */
23395 @d ext_tag 3 /* character is extensible */
23396
23397 @ The |lig_kern| array contains instructions in a simple programming language
23398 that explains what to do for special letter pairs. Each word in this array is a
23399 |lig_kern_command| of four bytes.
23400
23401 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23402   step if the byte is 128 or more, otherwise the next step is obtained by
23403   skipping this number of intervening steps.\par
23404 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23405   then perform the operation and stop, otherwise continue.''\par
23406 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23407   a kern step otherwise.\par
23408 \hang fourth byte: |remainder|.\par
23409 \yskip\noindent
23410 In a kern step, an
23411 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23412 between the current character and |next_char|. This amount is
23413 often negative, so that the characters are brought closer together
23414 by kerning; but it might be positive.
23415
23416 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
23417 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
23418 |remainder| is inserted between the current character and |next_char|;
23419 then the current character is deleted if $b=0$, and |next_char| is
23420 deleted if $c=0$; then we pass over $a$~characters to reach the next
23421 current character (which may have a ligature/kerning program of its own).
23422
23423 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
23424 the |next_char| byte is the so-called right boundary character of this font;
23425 the value of |next_char| need not lie between |bc| and~|ec|.
23426 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
23427 there is a special ligature/kerning program for a left boundary character,
23428 beginning at location |256*op_byte+remainder|.
23429 The interpretation is that \TeX\ puts implicit boundary characters
23430 before and after each consecutive string of characters from the same font.
23431 These implicit characters do not appear in the output, but they can affect
23432 ligatures and kerning.
23433
23434 If the very first instruction of a character's |lig_kern| program has
23435 |skip_byte>128|, the program actually begins in location
23436 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
23437 arrays, because the first instruction must otherwise
23438 appear in a location |<=255|.
23439
23440 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
23441 the condition
23442 $$\hbox{|256*op_byte+remainder<nl|.}$$
23443 If such an instruction is encountered during
23444 normal program execution, it denotes an unconditional halt; no ligature
23445 command is performed.
23446
23447 @d stop_flag (128)
23448   /* value indicating `\.{STOP}' in a lig/kern program */
23449 @d kern_flag (128) /* op code for a kern step */
23450 @d skip_byte(A) mp->lig_kern[(A)].b0
23451 @d next_char(A) mp->lig_kern[(A)].b1
23452 @d op_byte(A) mp->lig_kern[(A)].b2
23453 @d rem_byte(A) mp->lig_kern[(A)].b3
23454
23455 @ Extensible characters are specified by an |extensible_recipe|, which
23456 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
23457 order). These bytes are the character codes of individual pieces used to
23458 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
23459 present in the built-up result. For example, an extensible vertical line is
23460 like an extensible bracket, except that the top and bottom pieces are missing.
23461
23462 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
23463 if the piece isn't present. Then the extensible characters have the form
23464 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
23465 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
23466 The width of the extensible character is the width of $R$; and the
23467 height-plus-depth is the sum of the individual height-plus-depths of the
23468 components used, since the pieces are butted together in a vertical list.
23469
23470 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
23471 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
23472 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
23473 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
23474
23475 @ The final portion of a \.{TFM} file is the |param| array, which is another
23476 sequence of |fix_word| values.
23477
23478 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
23479 to help position accents. For example, |slant=.25| means that when you go
23480 up one unit, you also go .25 units to the right. The |slant| is a pure
23481 number; it is the only |fix_word| other than the design size itself that is
23482 not scaled by the design size.
23483 @^design size@>
23484
23485 \hang|param[2]=space| is the normal spacing between words in text.
23486 Note that character 040 in the font need not have anything to do with
23487 blank spaces.
23488
23489 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
23490
23491 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
23492
23493 \hang|param[5]=x_height| is the size of one ex in the font; it is also
23494 the height of letters for which accents don't have to be raised or lowered.
23495
23496 \hang|param[6]=quad| is the size of one em in the font.
23497
23498 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
23499 ends of sentences.
23500
23501 \yskip\noindent
23502 If fewer than seven parameters are present, \TeX\ sets the missing parameters
23503 to zero.
23504
23505 @d slant_code 1
23506 @d space_code 2
23507 @d space_stretch_code 3
23508 @d space_shrink_code 4
23509 @d x_height_code 5
23510 @d quad_code 6
23511 @d extra_space_code 7
23512
23513 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
23514 information, and it does this all at once at the end of a job.
23515 In order to prepare for such frenetic activity, it squirrels away the
23516 necessary facts in various arrays as information becomes available.
23517
23518 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
23519 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
23520 |tfm_ital_corr|. Other information about a character (e.g., about
23521 its ligatures or successors) is accessible via the |char_tag| and
23522 |char_remainder| arrays. Other information about the font as a whole
23523 is kept in additional arrays called |header_byte|, |lig_kern|,
23524 |kern|, |exten|, and |param|.
23525
23526 @d max_tfm_int 32510
23527 @d undefined_label max_tfm_int /* an undefined local label */
23528
23529 @<Glob...@>=
23530 #define TFM_ITEMS 257
23531 eight_bits bc;
23532 eight_bits ec; /* smallest and largest character codes shipped out */
23533 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
23534 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
23535 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
23536 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
23537 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
23538 int char_tag[TFM_ITEMS]; /* |remainder| category */
23539 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
23540 char *header_byte; /* bytes of the \.{TFM} header */
23541 int header_last; /* last initialized \.{TFM} header byte */
23542 int header_size; /* size of the \.{TFM} header */
23543 four_quarters *lig_kern; /* the ligature/kern table */
23544 short nl; /* the number of ligature/kern steps so far */
23545 scaled *kern; /* distinct kerning amounts */
23546 short nk; /* the number of distinct kerns so far */
23547 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
23548 short ne; /* the number of extensible characters so far */
23549 scaled *param; /* \&{fontinfo} parameters */
23550 short np; /* the largest \&{fontinfo} parameter specified so far */
23551 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
23552 short skip_table[TFM_ITEMS]; /* local label status */
23553 boolean lk_started; /* has there been a lig/kern step in this command yet? */
23554 integer bchar; /* right boundary character */
23555 short bch_label; /* left boundary starting location */
23556 short ll;short lll; /* registers used for lig/kern processing */
23557 short label_loc[257]; /* lig/kern starting addresses */
23558 eight_bits label_char[257]; /* characters for |label_loc| */
23559 short label_ptr; /* highest position occupied in |label_loc| */
23560
23561 @ @<Allocate or initialize ...@>=
23562 mp->header_last = 0; mp->header_size = 128; /* just for init */
23563 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
23564 mp->lig_kern = NULL; /* allocated when needed */
23565 mp->kern = NULL; /* allocated when needed */ 
23566 mp->param = NULL; /* allocated when needed */
23567
23568 @ @<Dealloc variables@>=
23569 xfree(mp->header_byte);
23570 xfree(mp->lig_kern);
23571 xfree(mp->kern);
23572 xfree(mp->param);
23573
23574 @ @<Set init...@>=
23575 for (k=0;k<= 255;k++ ) {
23576   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
23577   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
23578   mp->skip_table[k]=undefined_label;
23579 }
23580 memset(mp->header_byte,0,mp->header_size);
23581 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
23582 mp->internal[mp_boundary_char]=-unity;
23583 mp->bch_label=undefined_label;
23584 mp->label_loc[0]=-1; mp->label_ptr=0;
23585
23586 @ @<Declarations@>=
23587 scaled mp_tfm_check (MP mp,small_number m) ;
23588
23589 @ @<Declare the function called |tfm_check|@>=
23590 scaled mp_tfm_check (MP mp,small_number m) {
23591   if ( abs(mp->internal[m])>=fraction_half ) {
23592     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
23593 @.Enormous charwd...@>
23594 @.Enormous chardp...@>
23595 @.Enormous charht...@>
23596 @.Enormous charic...@>
23597 @.Enormous designsize...@>
23598     mp_print(mp, " has been reduced");
23599     help1("Font metric dimensions must be less than 2048pt.");
23600     mp_put_get_error(mp);
23601     if ( mp->internal[m]>0 ) return (fraction_half-1);
23602     else return (1-fraction_half);
23603   } else {
23604     return mp->internal[m];
23605   }
23606 }
23607
23608 @ @<Store the width information for character code~|c|@>=
23609 if ( c<mp->bc ) mp->bc=c;
23610 if ( c>mp->ec ) mp->ec=c;
23611 mp->char_exists[c]=true;
23612 mp->tfm_width[c]=mp_tfm_check(mp, mp_char_wd);
23613 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
23614 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
23615 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
23616
23617 @ Now let's consider \MP's special \.{TFM}-oriented commands.
23618
23619 @<Cases of |do_statement|...@>=
23620 case tfm_command: mp_do_tfm_command(mp); break;
23621
23622 @ @d char_list_code 0
23623 @d lig_table_code 1
23624 @d extensible_code 2
23625 @d header_byte_code 3
23626 @d font_dimen_code 4
23627
23628 @<Put each...@>=
23629 mp_primitive(mp, "charlist",tfm_command,char_list_code);
23630 @:char_list_}{\&{charlist} primitive@>
23631 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
23632 @:lig_table_}{\&{ligtable} primitive@>
23633 mp_primitive(mp, "extensible",tfm_command,extensible_code);
23634 @:extensible_}{\&{extensible} primitive@>
23635 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
23636 @:header_byte_}{\&{headerbyte} primitive@>
23637 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
23638 @:font_dimen_}{\&{fontdimen} primitive@>
23639
23640 @ @<Cases of |print_cmd...@>=
23641 case tfm_command: 
23642   switch (m) {
23643   case char_list_code:mp_print(mp, "charlist"); break;
23644   case lig_table_code:mp_print(mp, "ligtable"); break;
23645   case extensible_code:mp_print(mp, "extensible"); break;
23646   case header_byte_code:mp_print(mp, "headerbyte"); break;
23647   default: mp_print(mp, "fontdimen"); break;
23648   }
23649   break;
23650
23651 @ @<Declare action procedures for use by |do_statement|@>=
23652 eight_bits mp_get_code (MP mp) ;
23653
23654 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
23655   integer c; /* the code value found */
23656   mp_get_x_next(mp); mp_scan_expression(mp);
23657   if ( mp->cur_type==mp_known ) { 
23658     c=mp_round_unscaled(mp, mp->cur_exp);
23659     if ( c>=0 ) if ( c<256 ) return c;
23660   } else if ( mp->cur_type==mp_string_type ) {
23661     if ( length(mp->cur_exp)==1 )  { 
23662       c=mp->str_pool[mp->str_start[mp->cur_exp]];
23663       return c;
23664     }
23665   }
23666   exp_err("Invalid code has been replaced by 0");
23667 @.Invalid code...@>
23668   help2("I was looking for a number between 0 and 255, or for a")
23669        ("string of length 1. Didn't find it; will use 0 instead.");
23670   mp_put_get_flush_error(mp, 0); c=0;
23671   return c;
23672 }
23673
23674 @ @<Declare action procedures for use by |do_statement|@>=
23675 void mp_set_tag (MP mp,halfword c, small_number t, halfword r) ;
23676
23677 @ @c void mp_set_tag (MP mp,halfword c, small_number t, halfword r) { 
23678   if ( mp->char_tag[c]==no_tag ) {
23679     mp->char_tag[c]=t; mp->char_remainder[c]=r;
23680     if ( t==lig_tag ){ 
23681       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
23682       mp->label_char[mp->label_ptr]=c;
23683     }
23684   } else {
23685     @<Complain about a character tag conflict@>;
23686   }
23687 }
23688
23689 @ @<Complain about a character tag conflict@>=
23690
23691   print_err("Character ");
23692   if ( (c>' ')&&(c<127) ) mp_print_char(mp,c);
23693   else if ( c==256 ) mp_print(mp, "||");
23694   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
23695   mp_print(mp, " is already ");
23696 @.Character c is already...@>
23697   switch (mp->char_tag[c]) {
23698   case lig_tag: mp_print(mp, "in a ligtable"); break;
23699   case list_tag: mp_print(mp, "in a charlist"); break;
23700   case ext_tag: mp_print(mp, "extensible"); break;
23701   } /* there are no other cases */
23702   help2("It's not legal to label a character more than once.")
23703     ("So I'll not change anything just now.");
23704   mp_put_get_error(mp); 
23705 }
23706
23707 @ @<Declare action procedures for use by |do_statement|@>=
23708 void mp_do_tfm_command (MP mp) ;
23709
23710 @ @c void mp_do_tfm_command (MP mp) {
23711   int c,cc; /* character codes */
23712   int k; /* index into the |kern| array */
23713   int j; /* index into |header_byte| or |param| */
23714   switch (mp->cur_mod) {
23715   case char_list_code: 
23716     c=mp_get_code(mp);
23717      /* we will store a list of character successors */
23718     while ( mp->cur_cmd==colon )   { 
23719       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
23720     };
23721     break;
23722   case lig_table_code: 
23723     if (mp->lig_kern==NULL) 
23724        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
23725     if (mp->kern==NULL) 
23726        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
23727     @<Store a list of ligature/kern steps@>;
23728     break;
23729   case extensible_code: 
23730     @<Define an extensible recipe@>;
23731     break;
23732   case header_byte_code: 
23733   case font_dimen_code: 
23734     c=mp->cur_mod; mp_get_x_next(mp);
23735     mp_scan_expression(mp);
23736     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
23737       exp_err("Improper location");
23738 @.Improper location@>
23739       help2("I was looking for a known, positive number.")
23740        ("For safety's sake I'll ignore the present command.");
23741       mp_put_get_error(mp);
23742     } else  { 
23743       j=mp_round_unscaled(mp, mp->cur_exp);
23744       if ( mp->cur_cmd!=colon ) {
23745         mp_missing_err(mp, ":");
23746 @.Missing `:'@>
23747         help1("A colon should follow a headerbyte or fontinfo location.");
23748         mp_back_error(mp);
23749       }
23750       if ( c==header_byte_code ) { 
23751         @<Store a list of header bytes@>;
23752       } else {     
23753         if (mp->param==NULL) 
23754           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
23755         @<Store a list of font dimensions@>;
23756       }
23757     }
23758     break;
23759   } /* there are no other cases */
23760 }
23761
23762 @ @<Store a list of ligature/kern steps@>=
23763
23764   mp->lk_started=false;
23765 CONTINUE: 
23766   mp_get_x_next(mp);
23767   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
23768     @<Process a |skip_to| command and |goto done|@>;
23769   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
23770   else { mp_back_input(mp); c=mp_get_code(mp); };
23771   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
23772     @<Record a label in a lig/kern subprogram and |goto continue|@>;
23773   }
23774   if ( mp->cur_cmd==lig_kern_token ) { 
23775     @<Compile a ligature/kern command@>; 
23776   } else  { 
23777     print_err("Illegal ligtable step");
23778 @.Illegal ligtable step@>
23779     help1("I was looking for `=:' or `kern' here.");
23780     mp_back_error(mp); next_char(mp->nl)=qi(0); 
23781     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
23782     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
23783   }
23784   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
23785   incr(mp->nl);
23786   if ( mp->cur_cmd==comma ) goto CONTINUE;
23787   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
23788 }
23789 DONE:
23790
23791 @ @<Put each...@>=
23792 mp_primitive(mp, "=:",lig_kern_token,0);
23793 @:=:_}{\.{=:} primitive@>
23794 mp_primitive(mp, "=:|",lig_kern_token,1);
23795 @:=:/_}{\.{=:\char'174} primitive@>
23796 mp_primitive(mp, "=:|>",lig_kern_token,5);
23797 @:=:/>_}{\.{=:\char'174>} primitive@>
23798 mp_primitive(mp, "|=:",lig_kern_token,2);
23799 @:=:/_}{\.{\char'174=:} primitive@>
23800 mp_primitive(mp, "|=:>",lig_kern_token,6);
23801 @:=:/>_}{\.{\char'174=:>} primitive@>
23802 mp_primitive(mp, "|=:|",lig_kern_token,3);
23803 @:=:/_}{\.{\char'174=:\char'174} primitive@>
23804 mp_primitive(mp, "|=:|>",lig_kern_token,7);
23805 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
23806 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
23807 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
23808 mp_primitive(mp, "kern",lig_kern_token,128);
23809 @:kern_}{\&{kern} primitive@>
23810
23811 @ @<Cases of |print_cmd...@>=
23812 case lig_kern_token: 
23813   switch (m) {
23814   case 0:mp_print(mp, "=:"); break;
23815   case 1:mp_print(mp, "=:|"); break;
23816   case 2:mp_print(mp, "|=:"); break;
23817   case 3:mp_print(mp, "|=:|"); break;
23818   case 5:mp_print(mp, "=:|>"); break;
23819   case 6:mp_print(mp, "|=:>"); break;
23820   case 7:mp_print(mp, "|=:|>"); break;
23821   case 11:mp_print(mp, "|=:|>>"); break;
23822   default: mp_print(mp, "kern"); break;
23823   }
23824   break;
23825
23826 @ Local labels are implemented by maintaining the |skip_table| array,
23827 where |skip_table[c]| is either |undefined_label| or the address of the
23828 most recent lig/kern instruction that skips to local label~|c|. In the
23829 latter case, the |skip_byte| in that instruction will (temporarily)
23830 be zero if there were no prior skips to this label, or it will be the
23831 distance to the prior skip.
23832
23833 We may need to cancel skips that span more than 127 lig/kern steps.
23834
23835 @d cancel_skips(A) mp->ll=(A);
23836   do {  
23837     mp->lll=qo(skip_byte(mp->ll)); 
23838     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
23839   } while (mp->lll!=0)
23840 @d skip_error(A) { print_err("Too far to skip");
23841 @.Too far to skip@>
23842   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
23843   mp_error(mp); cancel_skips((A));
23844   }
23845
23846 @<Process a |skip_to| command and |goto done|@>=
23847
23848   c=mp_get_code(mp);
23849   if ( mp->nl-mp->skip_table[c]>128 ) {
23850     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
23851   }
23852   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
23853   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
23854   mp->skip_table[c]=mp->nl-1; goto DONE;
23855 }
23856
23857 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
23858
23859   if ( mp->cur_cmd==colon ) {
23860     if ( c==256 ) mp->bch_label=mp->nl;
23861     else mp_set_tag(mp, c,lig_tag,mp->nl);
23862   } else if ( mp->skip_table[c]<undefined_label ) {
23863     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
23864     do {  
23865       mp->lll=qo(skip_byte(mp->ll));
23866       if ( mp->nl-mp->ll>128 ) {
23867         skip_error(mp->ll); goto CONTINUE;
23868       }
23869       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
23870     } while (mp->lll!=0);
23871   }
23872   goto CONTINUE;
23873 }
23874
23875 @ @<Compile a ligature/kern...@>=
23876
23877   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
23878   if ( mp->cur_mod<128 ) { /* ligature op */
23879     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
23880   } else { 
23881     mp_get_x_next(mp); mp_scan_expression(mp);
23882     if ( mp->cur_type!=mp_known ) {
23883       exp_err("Improper kern");
23884 @.Improper kern@>
23885       help2("The amount of kern should be a known numeric value.")
23886         ("I'm zeroing this one. Proceed, with fingers crossed.");
23887       mp_put_get_flush_error(mp, 0);
23888     }
23889     mp->kern[mp->nk]=mp->cur_exp;
23890     k=0; 
23891     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
23892     if ( k==mp->nk ) {
23893       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
23894       incr(mp->nk);
23895     }
23896     op_byte(mp->nl)=kern_flag+(k / 256);
23897     rem_byte(mp->nl)=qi((k % 256));
23898   }
23899   mp->lk_started=true;
23900 }
23901
23902 @ @d missing_extensible_punctuation(A) 
23903   { mp_missing_err(mp, (A));
23904 @.Missing `\char`\#'@>
23905   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
23906   }
23907
23908 @<Define an extensible recipe@>=
23909
23910   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
23911   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
23912   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
23913   ext_top(mp->ne)=qi(mp_get_code(mp));
23914   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23915   ext_mid(mp->ne)=qi(mp_get_code(mp));
23916   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23917   ext_bot(mp->ne)=qi(mp_get_code(mp));
23918   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
23919   ext_rep(mp->ne)=qi(mp_get_code(mp));
23920   incr(mp->ne);
23921 }
23922
23923 @ The header could contain ASCII zeroes, so can't use |strdup|.
23924
23925 @<Store a list of header bytes@>=
23926 do {  
23927   if ( j>=mp->header_size ) {
23928     int l = mp->header_size + (mp->header_size >> 2);
23929     char *t = xmalloc(l,sizeof(char));
23930     memset(t,0,l); 
23931     memcpy(t,mp->header_byte,mp->header_size);
23932     xfree (mp->header_byte);
23933     mp->header_byte = t;
23934     mp->header_size = l;
23935   }
23936   mp->header_byte[j]=mp_get_code(mp); 
23937   incr(j); incr(mp->header_last);
23938 } while (mp->cur_cmd==comma)
23939
23940 @ @<Store a list of font dimensions@>=
23941 do {  
23942   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
23943   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
23944   mp_get_x_next(mp); mp_scan_expression(mp);
23945   if ( mp->cur_type!=mp_known ){ 
23946     exp_err("Improper font parameter");
23947 @.Improper font parameter@>
23948     help1("I'm zeroing this one. Proceed, with fingers crossed.");
23949     mp_put_get_flush_error(mp, 0);
23950   }
23951   mp->param[j]=mp->cur_exp; incr(j);
23952 } while (mp->cur_cmd==comma)
23953
23954 @ OK: We've stored all the data that is needed for the \.{TFM} file.
23955 All that remains is to output it in the correct format.
23956
23957 An interesting problem needs to be solved in this connection, because
23958 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
23959 and 64~italic corrections. If the data has more distinct values than
23960 this, we want to meet the necessary restrictions by perturbing the
23961 given values as little as possible.
23962
23963 \MP\ solves this problem in two steps. First the values of a given
23964 kind (widths, heights, depths, or italic corrections) are sorted;
23965 then the list of sorted values is perturbed, if necessary.
23966
23967 The sorting operation is facilitated by having a special node of
23968 essentially infinite |value| at the end of the current list.
23969
23970 @<Initialize table entries...@>=
23971 value(inf_val)=fraction_four;
23972
23973 @ Straight linear insertion is good enough for sorting, since the lists
23974 are usually not terribly long. As we work on the data, the current list
23975 will start at |link(temp_head)| and end at |inf_val|; the nodes in this
23976 list will be in increasing order of their |value| fields.
23977
23978 Given such a list, the |sort_in| function takes a value and returns a pointer
23979 to where that value can be found in the list. The value is inserted in
23980 the proper place, if necessary.
23981
23982 At the time we need to do these operations, most of \MP's work has been
23983 completed, so we will have plenty of memory to play with. The value nodes
23984 that are allocated for sorting will never be returned to free storage.
23985
23986 @d clear_the_list link(temp_head)=inf_val
23987
23988 @c pointer mp_sort_in (MP mp,scaled v) {
23989   pointer p,q,r; /* list manipulation registers */
23990   p=temp_head;
23991   while (1) { 
23992     q=link(p);
23993     if ( v<=value(q) ) break;
23994     p=q;
23995   }
23996   if ( v<value(q) ) {
23997     r=mp_get_node(mp, value_node_size); value(r)=v; link(r)=q; link(p)=r;
23998   }
23999   return link(p);
24000 }
24001
24002 @ Now we come to the interesting part, where we reduce the list if necessary
24003 until it has the required size. The |min_cover| routine is basic to this
24004 process; it computes the minimum number~|m| such that the values of the
24005 current sorted list can be covered by |m|~intervals of width~|d|. It
24006 also sets the global value |perturbation| to the smallest value $d'>d$
24007 such that the covering found by this algorithm would be different.
24008
24009 In particular, |min_cover(0)| returns the number of distinct values in the
24010 current list and sets |perturbation| to the minimum distance between
24011 adjacent values.
24012
24013 @c integer mp_min_cover (MP mp,scaled d) {
24014   pointer p; /* runs through the current list */
24015   scaled l; /* the least element covered by the current interval */
24016   integer m; /* lower bound on the size of the minimum cover */
24017   m=0; p=link(temp_head); mp->perturbation=el_gordo;
24018   while ( p!=inf_val ){ 
24019     incr(m); l=value(p);
24020     do {  p=link(p); } while (value(p)<=l+d);
24021     if ( value(p)-l<mp->perturbation ) 
24022       mp->perturbation=value(p)-l;
24023   }
24024   return m;
24025 }
24026
24027 @ @<Glob...@>=
24028 scaled perturbation; /* quantity related to \.{TFM} rounding */
24029 integer excess; /* the list is this much too long */
24030
24031 @ The smallest |d| such that a given list can be covered with |m| intervals
24032 is determined by the |threshold| routine, which is sort of an inverse
24033 to |min_cover|. The idea is to increase the interval size rapidly until
24034 finding the range, then to go sequentially until the exact borderline has
24035 been discovered.
24036
24037 @c scaled mp_threshold (MP mp,integer m) {
24038   scaled d; /* lower bound on the smallest interval size */
24039   mp->excess=mp_min_cover(mp, 0)-m;
24040   if ( mp->excess<=0 ) {
24041     return 0;
24042   } else  { 
24043     do {  
24044       d=mp->perturbation;
24045     } while (mp_min_cover(mp, d+d)>m);
24046     while ( mp_min_cover(mp, d)>m ) 
24047       d=mp->perturbation;
24048     return d;
24049   }
24050 }
24051
24052 @ The |skimp| procedure reduces the current list to at most |m| entries,
24053 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
24054 is the |k|th distinct value on the resulting list, and it sets
24055 |perturbation| to the maximum amount by which a |value| field has
24056 been changed. The size of the resulting list is returned as the
24057 value of |skimp|.
24058
24059 @c integer mp_skimp (MP mp,integer m) {
24060   scaled d; /* the size of intervals being coalesced */
24061   pointer p,q,r; /* list manipulation registers */
24062   scaled l; /* the least value in the current interval */
24063   scaled v; /* a compromise value */
24064   d=mp_threshold(mp, m); mp->perturbation=0;
24065   q=temp_head; m=0; p=link(temp_head);
24066   while ( p!=inf_val ) {
24067     incr(m); l=value(p); info(p)=m;
24068     if ( value(link(p))<=l+d ) {
24069       @<Replace an interval of values by its midpoint@>;
24070     }
24071     q=p; p=link(p);
24072   }
24073   return m;
24074 }
24075
24076 @ @<Replace an interval...@>=
24077
24078   do {  
24079     p=link(p); info(p)=m;
24080     decr(mp->excess); if ( mp->excess==0 ) d=0;
24081   } while (value(link(p))<=l+d);
24082   v=l+halfp(value(p)-l);
24083   if ( value(p)-v>mp->perturbation ) 
24084     mp->perturbation=value(p)-v;
24085   r=q;
24086   do {  
24087     r=link(r); value(r)=v;
24088   } while (r!=p);
24089   link(q)=p; /* remove duplicate values from the current list */
24090 }
24091
24092 @ A warning message is issued whenever something is perturbed by
24093 more than 1/16\thinspace pt.
24094
24095 @c void mp_tfm_warning (MP mp,small_number m) { 
24096   mp_print_nl(mp, "(some "); 
24097   mp_print(mp, mp->int_name[m]);
24098 @.some charwds...@>
24099 @.some chardps...@>
24100 @.some charhts...@>
24101 @.some charics...@>
24102   mp_print(mp, " values had to be adjusted by as much as ");
24103   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24104 }
24105
24106 @ Here's an example of how we use these routines.
24107 The width data needs to be perturbed only if there are 256 distinct
24108 widths, but \MP\ must check for this case even though it is
24109 highly unusual.
24110
24111 An integer variable |k| will be defined when we use this code.
24112 The |dimen_head| array will contain pointers to the sorted
24113 lists of dimensions.
24114
24115 @<Massage the \.{TFM} widths@>=
24116 clear_the_list;
24117 for (k=mp->bc;k<=mp->ec;k++)  {
24118   if ( mp->char_exists[k] )
24119     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24120 }
24121 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=link(temp_head);
24122 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24123
24124 @ @<Glob...@>=
24125 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24126
24127 @ Heights, depths, and italic corrections are different from widths
24128 not only because their list length is more severely restricted, but
24129 also because zero values do not need to be put into the lists.
24130
24131 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24132 clear_the_list;
24133 for (k=mp->bc;k<=mp->ec;k++) {
24134   if ( mp->char_exists[k] ) {
24135     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24136     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24137   }
24138 }
24139 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=link(temp_head);
24140 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24141 clear_the_list;
24142 for (k=mp->bc;k<=mp->ec;k++) {
24143   if ( mp->char_exists[k] ) {
24144     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24145     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24146   }
24147 }
24148 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=link(temp_head);
24149 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24150 clear_the_list;
24151 for (k=mp->bc;k<=mp->ec;k++) {
24152   if ( mp->char_exists[k] ) {
24153     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24154     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24155   }
24156 }
24157 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=link(temp_head);
24158 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24159
24160 @ @<Initialize table entries...@>=
24161 value(zero_val)=0; info(zero_val)=0;
24162
24163 @ Bytes 5--8 of the header are set to the design size, unless the user has
24164 some crazy reason for specifying them differently.
24165 @^design size@>
24166
24167 Error messages are not allowed at the time this procedure is called,
24168 so a warning is printed instead.
24169
24170 The value of |max_tfm_dimen| is calculated so that
24171 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24172  < \\{three\_bytes}.$$
24173
24174 @d three_bytes 0100000000 /* $2^{24}$ */
24175
24176 @c 
24177 void mp_fix_design_size (MP mp) {
24178   scaled d; /* the design size */
24179   d=mp->internal[mp_design_size];
24180   if ( (d<unity)||(d>=fraction_half) ) {
24181     if ( d!=0 )
24182       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24183 @.illegal design size...@>
24184     d=040000000; mp->internal[mp_design_size]=d;
24185   }
24186   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24187     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24188      mp->header_byte[4]=d / 04000000;
24189      mp->header_byte[5]=(d / 4096) % 256;
24190      mp->header_byte[6]=(d / 16) % 256;
24191      mp->header_byte[7]=(d % 16)*16;
24192   };
24193   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-1-mp->internal[mp_design_size] / 010000000;
24194   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24195 }
24196
24197 @ The |dimen_out| procedure computes a |fix_word| relative to the
24198 design size. If the data was out of range, it is corrected and the
24199 global variable |tfm_changed| is increased by~one.
24200
24201 @c integer mp_dimen_out (MP mp,scaled x) { 
24202   if ( abs(x)>mp->max_tfm_dimen ) {
24203     incr(mp->tfm_changed);
24204     if ( x>0 ) x=mp->max_tfm_dimen; else x=-mp->max_tfm_dimen;
24205   }
24206   x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24207   return x;
24208 }
24209
24210 @ @<Glob...@>=
24211 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24212 integer tfm_changed; /* the number of data entries that were out of bounds */
24213
24214 @ If the user has not specified any of the first four header bytes,
24215 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24216 from the |tfm_width| data relative to the design size.
24217 @^check sum@>
24218
24219 @c void mp_fix_check_sum (MP mp) {
24220   eight_bits k; /* runs through character codes */
24221   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24222   integer x;  /* hash value used in check sum computation */
24223   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24224        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24225     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24226     mp->header_byte[0]=B1; mp->header_byte[1]=B2;
24227     mp->header_byte[2]=B3; mp->header_byte[3]=B4; 
24228     return;
24229   }
24230 }
24231
24232 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24233 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24234 for (k=mp->bc;k<=mp->ec;k++) { 
24235   if ( mp->char_exists[k] ) {
24236     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24237     B1=(B1+B1+x) % 255;
24238     B2=(B2+B2+x) % 253;
24239     B3=(B3+B3+x) % 251;
24240     B4=(B4+B4+x) % 247;
24241   }
24242 }
24243
24244 @ Finally we're ready to actually write the \.{TFM} information.
24245 Here are some utility routines for this purpose.
24246
24247 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24248   unsigned char s=(A); 
24249   (mp->write_binary_file)(mp,mp->tfm_file,(void *)&s,1); 
24250   } while (0)
24251
24252 @c void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24253   tfm_out(x / 256); tfm_out(x % 256);
24254 }
24255 void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24256   if ( x>=0 ) tfm_out(x / three_bytes);
24257   else { 
24258     x=x+010000000000; /* use two's complement for negative values */
24259     x=x+010000000000;
24260     tfm_out((x / three_bytes) + 128);
24261   };
24262   x=x % three_bytes; tfm_out(x / unity);
24263   x=x % unity; tfm_out(x / 0400);
24264   tfm_out(x % 0400);
24265 }
24266 void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24267   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24268   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24269 }
24270
24271 @ @<Finish the \.{TFM} file@>=
24272 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24273 mp_pack_job_name(mp, ".tfm");
24274 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24275   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24276 mp->metric_file_name=xstrdup(mp->name_of_file);
24277 @<Output the subfile sizes and header bytes@>;
24278 @<Output the character information bytes, then
24279   output the dimensions themselves@>;
24280 @<Output the ligature/kern program@>;
24281 @<Output the extensible character recipes and the font metric parameters@>;
24282   if ( mp->internal[mp_tracing_stats]>0 )
24283   @<Log the subfile sizes of the \.{TFM} file@>;
24284 mp_print_nl(mp, "Font metrics written on "); 
24285 mp_print(mp, mp->metric_file_name); mp_print_char(mp, '.');
24286 @.Font metrics written...@>
24287 (mp->close_file)(mp,mp->tfm_file)
24288
24289 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24290 this code.
24291
24292 @<Output the subfile sizes and header bytes@>=
24293 k=mp->header_last;
24294 LH=(k+3) / 4; /* this is the number of header words */
24295 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24296 @<Compute the ligature/kern program offset and implant the
24297   left boundary label@>;
24298 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24299      +lk_offset+mp->nk+mp->ne+mp->np);
24300   /* this is the total number of file words that will be output */
24301 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24302 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24303 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24304 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24305 mp_tfm_two(mp, mp->np);
24306 for (k=0;k< 4*LH;k++)   { 
24307   tfm_out(mp->header_byte[k]);
24308 }
24309
24310 @ @<Output the character information bytes...@>=
24311 for (k=mp->bc;k<=mp->ec;k++) {
24312   if ( ! mp->char_exists[k] ) {
24313     mp_tfm_four(mp, 0);
24314   } else { 
24315     tfm_out(info(mp->tfm_width[k])); /* the width index */
24316     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24317     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24318     tfm_out(mp->char_remainder[k]);
24319   };
24320 }
24321 mp->tfm_changed=0;
24322 for (k=1;k<=4;k++) { 
24323   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24324   while ( p!=inf_val ) {
24325     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=link(p);
24326   }
24327 }
24328
24329
24330 @ We need to output special instructions at the beginning of the
24331 |lig_kern| array in order to specify the right boundary character
24332 and/or to handle starting addresses that exceed 255. The |label_loc|
24333 and |label_char| arrays have been set up to record all the
24334 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24335 \le|label_loc|[|label_ptr]|$.
24336
24337 @<Compute the ligature/kern program offset...@>=
24338 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24339 if ((mp->bchar<0)||(mp->bchar>255))
24340   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24341 else { mp->lk_started=true; lk_offset=1; };
24342 @<Find the minimum |lk_offset| and adjust all remainders@>;
24343 if ( mp->bch_label<undefined_label )
24344   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24345   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24346   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24347   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24348   }
24349
24350 @ @<Find the minimum |lk_offset|...@>=
24351 k=mp->label_ptr; /* pointer to the largest unallocated label */
24352 if ( mp->label_loc[k]+lk_offset>255 ) {
24353   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24354   do {  
24355     mp->char_remainder[mp->label_char[k]]=lk_offset;
24356     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24357        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24358     }
24359     incr(lk_offset); decr(k);
24360   } while (! (lk_offset+mp->label_loc[k]<256));
24361     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24362 }
24363 if ( lk_offset>0 ) {
24364   while ( k>0 ) {
24365     mp->char_remainder[mp->label_char[k]]
24366      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24367     decr(k);
24368   }
24369 }
24370
24371 @ @<Output the ligature/kern program@>=
24372 for (k=0;k<= 255;k++ ) {
24373   if ( mp->skip_table[k]<undefined_label ) {
24374      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24375 @.local label l:: was missing@>
24376     cancel_skips(mp->skip_table[k]);
24377   }
24378 }
24379 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24380   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24381 } else {
24382   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24383     mp->ll=mp->label_loc[mp->label_ptr];
24384     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24385     else { tfm_out(255); tfm_out(mp->bchar);   };
24386     mp_tfm_two(mp, mp->ll+lk_offset);
24387     do {  
24388       decr(mp->label_ptr);
24389     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24390   }
24391 }
24392 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24393 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24394
24395 @ @<Output the extensible character recipes...@>=
24396 for (k=0;k<=mp->ne-1;k++) 
24397   mp_tfm_qqqq(mp, mp->exten[k]);
24398 for (k=1;k<=mp->np;k++) {
24399   if ( k==1 ) {
24400     if ( abs(mp->param[1])<fraction_half ) {
24401       mp_tfm_four(mp, mp->param[1]*16);
24402     } else  { 
24403       incr(mp->tfm_changed);
24404       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24405       else mp_tfm_four(mp, -el_gordo);
24406     }
24407   } else {
24408     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
24409   }
24410 }
24411 if ( mp->tfm_changed>0 )  { 
24412   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
24413 @.a font metric dimension...@>
24414   else  { 
24415     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
24416 @.font metric dimensions...@>
24417     mp_print(mp, " font metric dimensions");
24418   }
24419   mp_print(mp, " had to be decreased)");
24420 }
24421
24422 @ @<Log the subfile sizes of the \.{TFM} file@>=
24423
24424   char s[200];
24425   wlog_ln(" ");
24426   if ( mp->bch_label<undefined_label ) decr(mp->nl);
24427   snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
24428                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
24429   wlog_ln(s);
24430 }
24431
24432 @* \[43] Reading font metric data.
24433
24434 \MP\ isn't a typesetting program but it does need to find the bounding box
24435 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
24436 well as write them.
24437
24438 @<Glob...@>=
24439 void * tfm_infile;
24440
24441 @ All the width, height, and depth information is stored in an array called
24442 |font_info|.  This array is allocated sequentially and each font is stored
24443 as a series of |char_info| words followed by the width, height, and depth
24444 tables.  Since |font_name| entries are permanent, their |str_ref| values are
24445 set to |max_str_ref|.
24446
24447 @<Types...@>=
24448 typedef unsigned int font_number; /* |0..font_max| */
24449
24450 @ The |font_info| array is indexed via a group directory arrays.
24451 For example, the |char_info| data for character~|c| in font~|f| will be
24452 in |font_info[char_base[f]+c].qqqq|.
24453
24454 @<Glob...@>=
24455 font_number font_max; /* maximum font number for included text fonts */
24456 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
24457 memory_word *font_info; /* height, width, and depth data */
24458 char        **font_enc_name; /* encoding names, if any */
24459 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
24460 int         next_fmem; /* next unused entry in |font_info| */
24461 font_number last_fnum; /* last font number used so far */
24462 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
24463 char        **font_name;  /* name as specified in the \&{infont} command */
24464 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
24465 font_number last_ps_fnum; /* last valid |font_ps_name| index */
24466 eight_bits  *font_bc;
24467 eight_bits  *font_ec;  /* first and last character code */
24468 int         *char_base;  /* base address for |char_info| */
24469 int         *width_base; /* index for zeroth character width */
24470 int         *height_base; /* index for zeroth character height */
24471 int         *depth_base; /* index for zeroth character depth */
24472 pointer     *font_sizes;
24473
24474 @ @<Allocate or initialize ...@>=
24475 mp->font_mem_size = 10000; 
24476 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
24477 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
24478 mp->font_enc_name = NULL;
24479 mp->font_ps_name_fixed = NULL;
24480 mp->font_dsize = NULL;
24481 mp->font_name = NULL;
24482 mp->font_ps_name = NULL;
24483 mp->font_bc = NULL;
24484 mp->font_ec = NULL;
24485 mp->last_fnum = null_font;
24486 mp->char_base = NULL;
24487 mp->width_base = NULL;
24488 mp->height_base = NULL;
24489 mp->depth_base = NULL;
24490 mp->font_sizes = null;
24491
24492 @ @<Dealloc variables@>=
24493 for (k=1;k<=(int)mp->last_fnum;k++) {
24494   xfree(mp->font_enc_name[k]);
24495   xfree(mp->font_name[k]);
24496   xfree(mp->font_ps_name[k]);
24497 }
24498 xfree(mp->font_info);
24499 xfree(mp->font_enc_name);
24500 xfree(mp->font_ps_name_fixed);
24501 xfree(mp->font_dsize);
24502 xfree(mp->font_name);
24503 xfree(mp->font_ps_name);
24504 xfree(mp->font_bc);
24505 xfree(mp->font_ec);
24506 xfree(mp->char_base);
24507 xfree(mp->width_base);
24508 xfree(mp->height_base);
24509 xfree(mp->depth_base);
24510 xfree(mp->font_sizes);
24511
24512
24513 @c 
24514 void mp_reallocate_fonts (MP mp, font_number l) {
24515   font_number f;
24516   XREALLOC(mp->font_enc_name,      l, char *);
24517   XREALLOC(mp->font_ps_name_fixed, l, boolean);
24518   XREALLOC(mp->font_dsize,         l, scaled);
24519   XREALLOC(mp->font_name,          l, char *);
24520   XREALLOC(mp->font_ps_name,       l, char *);
24521   XREALLOC(mp->font_bc,            l, eight_bits);
24522   XREALLOC(mp->font_ec,            l, eight_bits);
24523   XREALLOC(mp->char_base,          l, int);
24524   XREALLOC(mp->width_base,         l, int);
24525   XREALLOC(mp->height_base,        l, int);
24526   XREALLOC(mp->depth_base,         l, int);
24527   XREALLOC(mp->font_sizes,         l, pointer);
24528   for (f=(mp->last_fnum+1);f<=l;f++) {
24529     mp->font_enc_name[f]=NULL;
24530     mp->font_ps_name_fixed[f] = false;
24531     mp->font_name[f]=NULL;
24532     mp->font_ps_name[f]=NULL;
24533     mp->font_sizes[f]=null;
24534   }
24535   mp->font_max = l;
24536 }
24537
24538 @ @<Declare |mp_reallocate| functions@>=
24539 void mp_reallocate_fonts (MP mp, font_number l);
24540
24541
24542 @ A |null_font| containing no characters is useful for error recovery.  Its
24543 |font_name| entry starts out empty but is reset each time an erroneous font is
24544 found.  This helps to cut down on the number of duplicate error messages without
24545 wasting a lot of space.
24546
24547 @d null_font 0 /* the |font_number| for an empty font */
24548
24549 @<Set initial...@>=
24550 mp->font_dsize[null_font]=0;
24551 mp->font_bc[null_font]=1;
24552 mp->font_ec[null_font]=0;
24553 mp->char_base[null_font]=0;
24554 mp->width_base[null_font]=0;
24555 mp->height_base[null_font]=0;
24556 mp->depth_base[null_font]=0;
24557 mp->next_fmem=0;
24558 mp->last_fnum=null_font;
24559 mp->last_ps_fnum=null_font;
24560 mp->font_name[null_font]=(char *)"nullfont";
24561 mp->font_ps_name[null_font]=(char *)"";
24562 mp->font_ps_name_fixed[null_font] = false;
24563 mp->font_enc_name[null_font]=NULL;
24564 mp->font_sizes[null_font]=null;
24565
24566 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
24567 the |width index|; the |b1| field contains the height
24568 index; the |b2| fields contains the depth index, and the |b3| field used only
24569 for temporary storage. (It is used to keep track of which characters occur in
24570 an edge structure that is being shipped out.)
24571 The corresponding words in the width, height, and depth tables are stored as
24572 |scaled| values in units of \ps\ points.
24573
24574 With the macros below, the |char_info| word for character~|c| in font~|f| is
24575 |char_info(f)(c)| and the width is
24576 $$\hbox{|char_width(f)(char_info(f)(c)).sc|.}$$
24577
24578 @d char_info_end(A) (A)].qqqq
24579 @d char_info(A) mp->font_info[mp->char_base[(A)]+char_info_end
24580 @d char_width_end(A) (A).b0].sc
24581 @d char_width(A) mp->font_info[mp->width_base[(A)]+char_width_end
24582 @d char_height_end(A) (A).b1].sc
24583 @d char_height(A) mp->font_info[mp->height_base[(A)]+char_height_end
24584 @d char_depth_end(A) (A).b2].sc
24585 @d char_depth(A) mp->font_info[mp->depth_base[(A)]+char_depth_end
24586 @d ichar_exists(A) ((A).b0>0)
24587
24588 @ The |font_ps_name| for a built-in font should be what PostScript expects.
24589 A preliminary name is obtained here from the \.{TFM} name as given in the
24590 |fname| argument.  This gets updated later from an external table if necessary.
24591
24592 @<Declare text measuring subroutines@>=
24593 @<Declare subroutines for parsing file names@>
24594 font_number mp_read_font_info (MP mp, char *fname) {
24595   boolean file_opened; /* has |tfm_infile| been opened? */
24596   font_number n; /* the number to return */
24597   halfword lf,tfm_lh,bc,ec,nw,nh,nd; /* subfile size parameters */
24598   size_t whd_size; /* words needed for heights, widths, and depths */
24599   int i,ii; /* |font_info| indices */
24600   int jj; /* counts bytes to be ignored */
24601   scaled z; /* used to compute the design size */
24602   fraction d;
24603   /* height, width, or depth as a fraction of design size times $2^{-8}$ */
24604   eight_bits h_and_d; /* height and depth indices being unpacked */
24605   unsigned char tfbyte; /* a byte read from the file */
24606   n=null_font;
24607   @<Open |tfm_infile| for input@>;
24608   @<Read data from |tfm_infile|; if there is no room, say so and |goto done|;
24609     otherwise |goto bad_tfm| or |goto done| as appropriate@>;
24610 BAD_TFM:
24611   @<Complain that the \.{TFM} file is bad@>;
24612 DONE:
24613   if ( file_opened ) (mp->close_file)(mp,mp->tfm_infile);
24614   if ( n!=null_font ) { 
24615     mp->font_ps_name[n]=mp_xstrdup(mp,fname);
24616     mp->font_name[n]=mp_xstrdup(mp,fname);
24617   }
24618   return n;
24619 }
24620
24621 @ \MP\ doesn't bother to check the entire \.{TFM} file for errors or explain
24622 precisely what is wrong if it does find a problem.  Programs called \.{TFtoPL}
24623 @.TFtoPL@> @.PLtoTF@>
24624 and \.{PLtoTF} can be used to debug \.{TFM} files.
24625
24626 @<Complain that the \.{TFM} file is bad@>=
24627 print_err("Font ");
24628 mp_print(mp, fname);
24629 if ( file_opened ) mp_print(mp, " not usable: TFM file is bad");
24630 else mp_print(mp, " not usable: TFM file not found");
24631 help3("I wasn't able to read the size data for this font so this")
24632   ("`infont' operation won't produce anything. If the font name")
24633   ("is right, you might ask an expert to make a TFM file");
24634 if ( file_opened )
24635   mp->help_line[0]="is right, try asking an expert to fix the TFM file";
24636 mp_error(mp)
24637
24638 @ @<Read data from |tfm_infile|; if there is no room, say so...@>=
24639 @<Read the \.{TFM} size fields@>;
24640 @<Use the size fields to allocate space in |font_info|@>;
24641 @<Read the \.{TFM} header@>;
24642 @<Read the character data and the width, height, and depth tables and
24643   |goto done|@>
24644
24645 @ A bad \.{TFM} file can be shorter than it claims to be.  The code given here
24646 might try to read past the end of the file if this happens.  Changes will be
24647 needed if it causes a system error to refer to |tfm_infile^| or call
24648 |get_tfm_infile| when |eof(tfm_infile)| is true.  For example, the definition
24649 @^system dependencies@>
24650 of |tfget| could be changed to
24651 ``|begin get(tfm_infile); if eof(tfm_infile) then goto bad_tfm; end|.''
24652
24653 @d tfget do { 
24654   size_t wanted=1; 
24655   void *tfbyte_ptr = &tfbyte;
24656   (mp->read_binary_file)(mp,mp->tfm_infile,&tfbyte_ptr,&wanted); 
24657   if (wanted==0) goto BAD_TFM; 
24658 } while (0)
24659 @d read_two(A) { (A)=tfbyte;
24660   if ( (A)>127 ) goto BAD_TFM;
24661   tfget; (A)=(A)*0400+tfbyte;
24662 }
24663 @d tf_ignore(A) { for (jj=(A);jj>=1;jj--) tfget; }
24664
24665 @<Read the \.{TFM} size fields@>=
24666 tfget; read_two(lf);
24667 tfget; read_two(tfm_lh);
24668 tfget; read_two(bc);
24669 tfget; read_two(ec);
24670 if ( (bc>1+ec)||(ec>255) ) goto BAD_TFM;
24671 tfget; read_two(nw);
24672 tfget; read_two(nh);
24673 tfget; read_two(nd);
24674 whd_size=(ec+1-bc)+nw+nh+nd;
24675 if ( lf<(int)(6+tfm_lh+whd_size) ) goto BAD_TFM;
24676 tf_ignore(10)
24677
24678 @ Offsets are added to |char_base[n]| and |width_base[n]| so that is not
24679 necessary to apply the |so|  and |qo| macros when looking up the width of a
24680 character in the string pool.  In order to ensure nonnegative |char_base|
24681 values when |bc>0|, it may be necessary to reserve a few unused |font_info|
24682 elements.
24683
24684 @<Use the size fields to allocate space in |font_info|@>=
24685 if ( mp->next_fmem<bc) mp->next_fmem=bc;  /* ensure nonnegative |char_base| */
24686 if (mp->last_fnum==mp->font_max)
24687   mp_reallocate_fonts(mp,(mp->font_max+(mp->font_max>>2)));
24688 while (mp->next_fmem+whd_size>=mp->font_mem_size) {
24689   size_t l = mp->font_mem_size+(mp->font_mem_size>>2);
24690   memory_word *font_info;
24691   font_info = xmalloc ((l+1),sizeof(memory_word));
24692   memset (font_info,0,sizeof(memory_word)*(l+1));
24693   memcpy (font_info,mp->font_info,sizeof(memory_word)*(mp->font_mem_size+1));
24694   xfree(mp->font_info);
24695   mp->font_info = font_info;
24696   mp->font_mem_size = l;
24697 }
24698 incr(mp->last_fnum);
24699 n=mp->last_fnum;
24700 mp->font_bc[n]=bc;
24701 mp->font_ec[n]=ec;
24702 mp->char_base[n]=mp->next_fmem-bc;
24703 mp->width_base[n]=mp->next_fmem+ec-bc+1;
24704 mp->height_base[n]=mp->width_base[n]+nw;
24705 mp->depth_base[n]=mp->height_base[n]+nh;
24706 mp->next_fmem=mp->next_fmem+whd_size;
24707
24708
24709 @ @<Read the \.{TFM} header@>=
24710 if ( tfm_lh<2 ) goto BAD_TFM;
24711 tf_ignore(4);
24712 tfget; read_two(z);
24713 tfget; z=z*0400+tfbyte;
24714 tfget; z=z*0400+tfbyte; /* now |z| is 16 times the design size */
24715 mp->font_dsize[n]=mp_take_fraction(mp, z,267432584);
24716   /* times ${72\over72.27}2^{28}$ to convert from \TeX\ points */
24717 tf_ignore(4*(tfm_lh-2))
24718
24719 @ @<Read the character data and the width, height, and depth tables...@>=
24720 ii=mp->width_base[n];
24721 i=mp->char_base[n]+bc;
24722 while ( i<ii ) { 
24723   tfget; mp->font_info[i].qqqq.b0=qi(tfbyte);
24724   tfget; h_and_d=tfbyte;
24725   mp->font_info[i].qqqq.b1=h_and_d / 16;
24726   mp->font_info[i].qqqq.b2=h_and_d % 16;
24727   tfget; tfget;
24728   incr(i);
24729 }
24730 while ( i<mp->next_fmem ) {
24731   @<Read a four byte dimension, scale it by the design size, store it in
24732     |font_info[i]|, and increment |i|@>;
24733 }
24734 goto DONE
24735
24736 @ The raw dimension read into |d| should have magnitude at most $2^{24}$ when
24737 interpreted as an integer, and this includes a scale factor of $2^{20}$.  Thus
24738 we can multiply it by sixteen and think of it as a |fraction| that has been
24739 divided by sixteen.  This cancels the extra scale factor contained in
24740 |font_dsize[n|.
24741
24742 @<Read a four byte dimension, scale it by the design size, store it in...@>=
24743
24744 tfget; d=tfbyte;
24745 if ( d>=0200 ) d=d-0400;
24746 tfget; d=d*0400+tfbyte;
24747 tfget; d=d*0400+tfbyte;
24748 tfget; d=d*0400+tfbyte;
24749 mp->font_info[i].sc=mp_take_fraction(mp, d*16,mp->font_dsize[n]);
24750 incr(i);
24751 }
24752
24753 @ This function does no longer use the file name parser, because |fname| is
24754 a C string already.
24755 @<Open |tfm_infile| for input@>=
24756 file_opened=false;
24757 mp_ptr_scan_file(mp, fname);
24758 if ( strlen(mp->cur_area)==0 ) { xfree(mp->cur_area); }
24759 if ( strlen(mp->cur_ext)==0 )  { xfree(mp->cur_ext); mp->cur_ext=xstrdup(".tfm"); }
24760 pack_cur_name;
24761 mp->tfm_infile = (mp->open_file)(mp, mp->name_of_file, "r",mp_filetype_metrics);
24762 if ( !mp->tfm_infile  ) goto BAD_TFM;
24763 file_opened=true
24764
24765 @ When we have a font name and we don't know whether it has been loaded yet,
24766 we scan the |font_name| array before calling |read_font_info|.
24767
24768 @<Declare text measuring subroutines@>=
24769 font_number mp_find_font (MP mp, char *f) {
24770   font_number n;
24771   for (n=0;n<=mp->last_fnum;n++) {
24772     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
24773       mp_xfree(f);
24774       return n;
24775     }
24776   }
24777   n = mp_read_font_info(mp, f);
24778   mp_xfree(f);
24779   return n;
24780 }
24781
24782 @ One simple application of |find_font| is the implementation of the |font_size|
24783 operator that gets the design size for a given font name.
24784
24785 @<Find the design size of the font whose name is |cur_exp|@>=
24786 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
24787
24788 @ If we discover that the font doesn't have a requested character, we omit it
24789 from the bounding box computation and expect the \ps\ interpreter to drop it.
24790 This routine issues a warning message if the user has asked for it.
24791
24792 @<Declare text measuring subroutines@>=
24793 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
24794   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
24795     mp_begin_diagnostic(mp);
24796     if ( mp->selector==log_only ) incr(mp->selector);
24797     mp_print_nl(mp, "Missing character: There is no ");
24798 @.Missing character@>
24799     mp_print_str(mp, mp->str_pool[k]); 
24800     mp_print(mp, " in font ");
24801     mp_print(mp, mp->font_name[f]); mp_print_char(mp, '!'); 
24802     mp_end_diagnostic(mp, false);
24803   }
24804 }
24805
24806 @ The whole purpose of saving the height, width, and depth information is to be
24807 able to find the bounding box of an item of text in an edge structure.  The
24808 |set_text_box| procedure takes a text node and adds this information.
24809
24810 @<Declare text measuring subroutines@>=
24811 void mp_set_text_box (MP mp,pointer p) {
24812   font_number f; /* |font_n(p)| */
24813   ASCII_code bc,ec; /* range of valid characters for font |f| */
24814   pool_pointer k,kk; /* current character and character to stop at */
24815   four_quarters cc; /* the |char_info| for the current character */
24816   scaled h,d; /* dimensions of the current character */
24817   width_val(p)=0;
24818   height_val(p)=-el_gordo;
24819   depth_val(p)=-el_gordo;
24820   f=font_n(p);
24821   bc=mp->font_bc[f];
24822   ec=mp->font_ec[f];
24823   kk=str_stop(text_p(p));
24824   k=mp->str_start[text_p(p)];
24825   while ( k<kk ) {
24826     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
24827   }
24828   @<Set the height and depth to zero if the bounding box is empty@>;
24829 }
24830
24831 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
24832
24833   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
24834     mp_lost_warning(mp, f,k);
24835   } else { 
24836     cc=char_info(f)(mp->str_pool[k]);
24837     if ( ! ichar_exists(cc) ) {
24838       mp_lost_warning(mp, f,k);
24839     } else { 
24840       width_val(p)=width_val(p)+char_width(f)(cc);
24841       h=char_height(f)(cc);
24842       d=char_depth(f)(cc);
24843       if ( h>height_val(p) ) height_val(p)=h;
24844       if ( d>depth_val(p) ) depth_val(p)=d;
24845     }
24846   }
24847   incr(k);
24848 }
24849
24850 @ Let's hope modern compilers do comparisons correctly when the difference would
24851 overflow.
24852
24853 @<Set the height and depth to zero if the bounding box is empty@>=
24854 if ( height_val(p)<-depth_val(p) ) { 
24855   height_val(p)=0;
24856   depth_val(p)=0;
24857 }
24858
24859 @ The new primitives fontmapfile and fontmapline.
24860
24861 @<Declare action procedures for use by |do_statement|@>=
24862 void mp_do_mapfile (MP mp) ;
24863 void mp_do_mapline (MP mp) ;
24864
24865 @ @c void mp_do_mapfile (MP mp) { 
24866   mp_get_x_next(mp); mp_scan_expression(mp);
24867   if ( mp->cur_type!=mp_string_type ) {
24868     @<Complain about improper map operation@>;
24869   } else {
24870     mp_map_file(mp,mp->cur_exp);
24871   }
24872 }
24873 void mp_do_mapline (MP mp) { 
24874   mp_get_x_next(mp); mp_scan_expression(mp);
24875   if ( mp->cur_type!=mp_string_type ) {
24876      @<Complain about improper map operation@>;
24877   } else { 
24878      mp_map_line(mp,mp->cur_exp);
24879   }
24880 }
24881
24882 @ @<Complain about improper map operation@>=
24883
24884   exp_err("Unsuitable expression");
24885   help1("Only known strings can be map files or map lines.");
24886   mp_put_get_error(mp);
24887 }
24888
24889 @ To print |scaled| value to PDF output we need some subroutines to ensure
24890 accurary.
24891
24892 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
24893
24894 @<Glob...@>=
24895 scaled one_bp; /* scaled value corresponds to 1bp */
24896 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
24897 scaled one_hundred_inch; /* scaled value corresponds to 100in */
24898 integer ten_pow[10]; /* $10^0..10^9$ */
24899 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
24900
24901 @ @<Set init...@>=
24902 mp->one_bp = 65782; /* 65781.76 */
24903 mp->one_hundred_bp = 6578176;
24904 mp->one_hundred_inch = 473628672;
24905 mp->ten_pow[0] = 1;
24906 for (i = 1;i<= 9; i++ ) {
24907   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
24908 }
24909
24910 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
24911
24912 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
24913   scaled q,r;
24914   integer sign,i;
24915   sign = 1;
24916   if ( s < 0 ) { sign = -sign; s = -s; }
24917   if ( m < 0 ) { sign = -sign; m = -m; }
24918   if ( m == 0 )
24919     mp_confusion(mp, "arithmetic: divided by zero");
24920   else if ( m >= (max_integer / 10) )
24921     mp_confusion(mp, "arithmetic: number too big");
24922   q = s / m;
24923   r = s % m;
24924   for (i = 1;i<=dd;i++) {
24925     q = 10*q + (10*r) / m;
24926     r = (10*r) % m;
24927   }
24928   if ( 2*r >= m ) { incr(q); r = r - m; }
24929   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
24930   return (sign*q);
24931 }
24932
24933 @* \[44] Shipping pictures out.
24934 The |ship_out| procedure, to be described below, is given a pointer to
24935 an edge structure. Its mission is to output a file containing the \ps\
24936 description of an edge structure.
24937
24938 @ Each time an edge structure is shipped out we write a new \ps\ output
24939 file named according to the current \&{charcode}.
24940 @:char_code_}{\&{charcode} primitive@>
24941
24942 This is the only backend function that remains in the main |mpost.w| file. 
24943 There are just too many variable accesses needed for status reporting 
24944 etcetera to make it worthwile to move the code to |psout.w|.
24945
24946 @<Internal library declarations@>=
24947 void mp_open_output_file (MP mp) ;
24948
24949 @ @c 
24950 char *mp_set_output_file_name (MP mp, integer c) {
24951   char *ss = NULL; /* filename extension proposal */  
24952   int old_setting; /* previous |selector| setting */
24953   pool_pointer i; /*  indexes into |filename_template|  */
24954   integer cc; /* a temporary integer for template building  */
24955   integer f,g=0; /* field widths */
24956   if ( mp->job_name==NULL ) mp_open_log_file(mp);
24957   if ( mp->filename_template==0 ) {
24958     char *s; /* a file extension derived from |c| */
24959     if ( c<0 ) 
24960       s=xstrdup(".ps");
24961     else 
24962       @<Use |c| to compute the file extension |s|@>;
24963     mp_pack_job_name(mp, s);
24964     ss = s ;
24965   } else { /* initializations */
24966     str_number s, n; /* a file extension derived from |c| */
24967     old_setting=mp->selector; 
24968     mp->selector=new_string;
24969     f = 0;
24970     i = mp->str_start[mp->filename_template];
24971     n = rts(""); /* initialize */
24972     while ( i<str_stop(mp->filename_template) ) {
24973        if ( mp->str_pool[i]=='%' ) {
24974       CONTINUE:
24975         incr(i);
24976         if ( i<str_stop(mp->filename_template) ) {
24977           if ( mp->str_pool[i]=='j' ) {
24978             mp_print(mp, mp->job_name);
24979           } else if ( mp->str_pool[i]=='d' ) {
24980              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
24981              print_with_leading_zeroes(cc);
24982           } else if ( mp->str_pool[i]=='m' ) {
24983              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
24984              print_with_leading_zeroes(cc);
24985           } else if ( mp->str_pool[i]=='y' ) {
24986              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
24987              print_with_leading_zeroes(cc);
24988           } else if ( mp->str_pool[i]=='H' ) {
24989              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
24990              print_with_leading_zeroes(cc);
24991           }  else if ( mp->str_pool[i]=='M' ) {
24992              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
24993              print_with_leading_zeroes(cc);
24994           } else if ( mp->str_pool[i]=='c' ) {
24995             if ( c<0 ) mp_print(mp, "ps");
24996             else print_with_leading_zeroes(c);
24997           } else if ( (mp->str_pool[i]>='0') && 
24998                       (mp->str_pool[i]<='9') ) {
24999             if ( (f<10)  )
25000               f = (f*10) + mp->str_pool[i]-'0';
25001             goto CONTINUE;
25002           } else {
25003             mp_print_str(mp, mp->str_pool[i]);
25004           }
25005         }
25006       } else {
25007         if ( mp->str_pool[i]=='.' )
25008           if (length(n)==0)
25009             n = mp_make_string(mp);
25010         mp_print_str(mp, mp->str_pool[i]);
25011       };
25012       incr(i);
25013     };
25014     s = mp_make_string(mp);
25015     mp->selector= old_setting;
25016     if (length(n)==0) {
25017        n=s;
25018        s=rts("");
25019     };
25020     mp_pack_file_name(mp, str(n),"",str(s));
25021     delete_str_ref(n);
25022         ss = str(s);
25023     delete_str_ref(s);
25024   }
25025   return ss;
25026 }
25027
25028 char * mp_get_output_file_name (MP mp) {
25029   char *fname; /* return value */
25030   char *saved_name;  /* saved |name_of_file| */
25031   saved_name = mp_xstrdup(mp, mp->name_of_file);
25032   (void)mp_set_output_file_name(mp, mp_round_unscaled(mp, mp->internal[mp_char_code]));
25033   fname = mp_xstrdup(mp, mp->name_of_file);
25034   mp_pack_file_name(mp, saved_name,NULL,NULL);
25035   return fname;
25036 }
25037
25038 void mp_open_output_file (MP mp) {
25039   char *ss; /* filename extension proposal */
25040   integer c; /* \&{charcode} rounded to the nearest integer */
25041   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25042   ss = mp_set_output_file_name(mp, c);
25043   while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
25044     mp_prompt_file_name(mp, "file name for output",ss);
25045   xfree(ss);
25046   @<Store the true output file name if appropriate@>;
25047 }
25048
25049 @ The file extension created here could be up to five characters long in
25050 extreme cases so it may have to be shortened on some systems.
25051 @^system dependencies@>
25052
25053 @<Use |c| to compute the file extension |s|@>=
25054
25055   s = xmalloc(7,1);
25056   snprintf(s,7,".%i",(int)c);
25057 }
25058
25059 @ The user won't want to see all the output file names so we only save the
25060 first and last ones and a count of how many there were.  For this purpose
25061 files are ordered primarily by \&{charcode} and secondarily by order of
25062 creation.
25063 @:char_code_}{\&{charcode} primitive@>
25064
25065 @<Store the true output file name if appropriate@>=
25066 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
25067   mp->first_output_code=c;
25068   xfree(mp->first_file_name);
25069   mp->first_file_name=xstrdup(mp->name_of_file);
25070 }
25071 if ( c>=mp->last_output_code ) {
25072   mp->last_output_code=c;
25073   xfree(mp->last_file_name);
25074   mp->last_file_name=xstrdup(mp->name_of_file);
25075 }
25076
25077 @ @<Glob...@>=
25078 char * first_file_name;
25079 char * last_file_name; /* full file names */
25080 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25081 @:char_code_}{\&{charcode} primitive@>
25082 integer total_shipped; /* total number of |ship_out| operations completed */
25083
25084 @ @<Set init...@>=
25085 mp->first_file_name=xstrdup("");
25086 mp->last_file_name=xstrdup("");
25087 mp->first_output_code=32768;
25088 mp->last_output_code=-32768;
25089 mp->total_shipped=0;
25090
25091 @ @<Dealloc variables@>=
25092 xfree(mp->first_file_name);
25093 xfree(mp->last_file_name);
25094
25095 @ @<Begin the progress report for the output of picture~|c|@>=
25096 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25097 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, ' ');
25098 mp_print_char(mp, '[');
25099 if ( c>=0 ) mp_print_int(mp, c)
25100
25101 @ @<End progress report@>=
25102 mp_print_char(mp, ']');
25103 update_terminal;
25104 incr(mp->total_shipped)
25105
25106 @ @<Explain what output files were written@>=
25107 if ( mp->total_shipped>0 ) { 
25108   mp_print_nl(mp, "");
25109   mp_print_int(mp, mp->total_shipped);
25110   mp_print(mp, " output file");
25111   if ( mp->total_shipped>1 ) mp_print_char(mp, 's');
25112   mp_print(mp, " written: ");
25113   mp_print(mp, mp->first_file_name);
25114   if ( mp->total_shipped>1 ) {
25115     if ( 31+strlen(mp->first_file_name)+
25116          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25117       mp_print_ln(mp);
25118     mp_print(mp, " .. ");
25119     mp_print(mp, mp->last_file_name);
25120   }
25121 }
25122
25123 @ @<Internal library declarations@>=
25124 boolean mp_has_font_size(MP mp, font_number f );
25125
25126 @ @c 
25127 boolean mp_has_font_size(MP mp, font_number f ) {
25128   return (mp->font_sizes[f]!=null);
25129 }
25130
25131 @ The \&{special} command saves up lines of text to be printed during the next
25132 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25133
25134 @<Glob...@>=
25135 pointer last_pending; /* the last token in a list of pending specials */
25136
25137 @ @<Set init...@>=
25138 mp->last_pending=spec_head;
25139
25140 @ @<Cases of |do_statement|...@>=
25141 case special_command: 
25142   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25143   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25144   mp_do_mapline(mp);
25145   break;
25146
25147 @ @<Declare action procedures for use by |do_statement|@>=
25148 void mp_do_special (MP mp) ;
25149
25150 @ @c void mp_do_special (MP mp) { 
25151   mp_get_x_next(mp); mp_scan_expression(mp);
25152   if ( mp->cur_type!=mp_string_type ) {
25153     @<Complain about improper special operation@>;
25154   } else { 
25155     link(mp->last_pending)=mp_stash_cur_exp(mp);
25156     mp->last_pending=link(mp->last_pending);
25157     link(mp->last_pending)=null;
25158   }
25159 }
25160
25161 @ @<Complain about improper special operation@>=
25162
25163   exp_err("Unsuitable expression");
25164   help1("Only known strings are allowed for output as specials.");
25165   mp_put_get_error(mp);
25166 }
25167
25168 @ On the export side, we need an extra object type for special strings.
25169
25170 @<Graphical object codes@>=
25171 mp_special_code=8, 
25172
25173 @ @<Export pending specials@>=
25174 p=link(spec_head);
25175 while ( p!=null ) {
25176   mp_special_object *tp;
25177   tp = (mp_special_object *)mp_new_graphic_object(mp,mp_special_code);  
25178   gr_pre_script(tp)  = str(value(p));
25179   if (hh->body==NULL) hh->body = (mp_graphic_object *)tp; 
25180   else gr_link(hp) = (mp_graphic_object *)tp;
25181   hp = (mp_graphic_object *)tp;
25182   p=link(p);
25183 }
25184 mp_flush_token_list(mp, link(spec_head));
25185 link(spec_head)=null;
25186 mp->last_pending=spec_head
25187
25188 @ We are now ready for the main output procedure.  Note that the |selector|
25189 setting is saved in a global variable so that |begin_diagnostic| can access it.
25190
25191 @<Declare the \ps\ output procedures@>=
25192 void mp_ship_out (MP mp, pointer h) ;
25193
25194 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25195
25196 @d export_color(q,p) 
25197   if ( color_model(p)==mp_uninitialized_model ) {
25198     gr_color_model(q)  = (mp->internal[mp_default_color_model]>>16);
25199     gr_cyan_val(q)     = 0;
25200         gr_magenta_val(q)  = 0;
25201         gr_yellow_val(q)   = 0;
25202         gr_black_val(q)    = (gr_color_model(q)==mp_cmyk_model ? unity : 0);
25203   } else {
25204     gr_color_model(q)  = color_model(p);
25205     gr_cyan_val(q)     = cyan_val(p);
25206     gr_magenta_val(q)  = magenta_val(p);
25207     gr_yellow_val(q)   = yellow_val(p);
25208     gr_black_val(q)    = black_val(p);
25209   }
25210
25211 @d export_scripts(q,p)
25212   if (pre_script(p)!=null)  gr_pre_script(q)   = str(pre_script(p));
25213   if (post_script(p)!=null) gr_post_script(q)  = str(post_script(p));
25214
25215 @c
25216 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25217   pointer p; /* the current graphical object */
25218   integer t; /* a temporary value */
25219   mp_edge_object *hh; /* the first graphical object */
25220   struct mp_graphic_object *hq; /* something |hp| points to  */
25221   struct mp_text_object    *tt;
25222   struct mp_fill_object    *tf;
25223   struct mp_stroked_object *ts;
25224   struct mp_clip_object    *tc;
25225   struct mp_bounds_object  *tb;
25226   struct mp_graphic_object *hp = NULL; /* the current graphical object */
25227   mp_set_bbox(mp, h, true);
25228   hh = mp_xmalloc(mp,1,sizeof(mp_edge_object));
25229   hh->body = NULL;
25230   hh->_next = NULL;
25231   hh->_parent = mp;
25232   hh->_minx = minx_val(h);
25233   hh->_miny = miny_val(h);
25234   hh->_maxx = maxx_val(h);
25235   hh->_maxy = maxy_val(h);
25236   hh->_filename = mp_get_output_file_name(mp);
25237   @<Export pending specials@>;
25238   p=link(dummy_loc(h));
25239   while ( p!=null ) { 
25240     hq = mp_new_graphic_object(mp,type(p));
25241     switch (type(p)) {
25242     case mp_fill_code:
25243       tf = (mp_fill_object *)hq;
25244       gr_pen_p(tf)        = mp_export_knot_list(mp,pen_p(p));
25245       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25246             gr_path_p(tf)       = mp_export_knot_list(mp,path_p(p));
25247       } else {
25248         pointer pc, pp;
25249         pc = mp_copy_path(mp, path_p(p));
25250         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25251         gr_path_p(tf)       = mp_export_knot_list(mp,pp);
25252         mp_toss_knot_list(mp, pp);
25253         pc = mp_htap_ypoc(mp, path_p(p));
25254         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25255         gr_htap_p(tf)       = mp_export_knot_list(mp,pp);
25256         mp_toss_knot_list(mp, pp);
25257       }
25258       export_color(tf,p) ;
25259       export_scripts(tf,p);
25260       gr_ljoin_val(tf)    = ljoin_val(p);
25261       gr_miterlim_val(tf) = miterlim_val(p);
25262       break;
25263     case mp_stroked_code:
25264       ts = (mp_stroked_object *)hq;
25265       gr_pen_p(ts)        = mp_export_knot_list(mp,pen_p(p));
25266       if (pen_is_elliptical(pen_p(p)))  {
25267               gr_path_p(ts)       = mp_export_knot_list(mp,path_p(p));
25268       } else {
25269         pointer pc;
25270         pc=mp_copy_path(mp, path_p(p));
25271         t=lcap_val(p);
25272         if ( left_type(pc)!=mp_endpoint ) { 
25273           left_type(mp_insert_knot(mp, pc,x_coord(pc),y_coord(pc)))=mp_endpoint;
25274           right_type(pc)=mp_endpoint;
25275           pc=link(pc);
25276           t=1;
25277         }
25278         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25279         gr_path_p(ts)       = mp_export_knot_list(mp,pc);
25280         mp_toss_knot_list(mp, pc);
25281       }
25282       export_color(ts,p) ;
25283       export_scripts(ts,p);
25284       gr_ljoin_val(ts)    = ljoin_val(p);
25285       gr_miterlim_val(ts) = miterlim_val(p);
25286       gr_lcap_val(ts)     = lcap_val(p);
25287       gr_dash_p(ts)       = mp_export_dashes(mp,dash_p(p));
25288       break;
25289     case mp_text_code:
25290       tt = (mp_text_object *)hq;
25291       gr_text_p(tt)       = str(text_p(p));
25292       gr_font_n(tt)       = font_n(p);
25293       gr_font_name(tt)    = mp_xstrdup(mp,mp->font_name[font_n(p)]);
25294       gr_font_dsize(tt)   = mp->font_dsize[font_n(p)];
25295       export_color(tt,p) ;
25296       export_scripts(tt,p);
25297       gr_width_val(tt)    = width_val(p);
25298       gr_height_val(tt)   = height_val(p);
25299       gr_depth_val(tt)    = depth_val(p);
25300       gr_tx_val(tt)       = tx_val(p);
25301       gr_ty_val(tt)       = ty_val(p);
25302       gr_txx_val(tt)      = txx_val(p);
25303       gr_txy_val(tt)      = txy_val(p);
25304       gr_tyx_val(tt)      = tyx_val(p);
25305       gr_tyy_val(tt)      = tyy_val(p);
25306       break;
25307     case mp_start_clip_code: 
25308       tc = (mp_clip_object *)hq;
25309       gr_path_p(tc) = mp_export_knot_list(mp,path_p(p));
25310       break;
25311     case mp_start_bounds_code:
25312       tb = (mp_bounds_object *)hq;
25313       gr_path_p(tb) = mp_export_knot_list(mp,path_p(p));
25314       break;
25315     case mp_stop_clip_code: 
25316     case mp_stop_bounds_code:
25317       /* nothing to do here */
25318       break;
25319     } 
25320     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25321     hp = hq;
25322     p=link(p);
25323   }
25324   return hh;
25325 }
25326
25327 @ @<Exported function ...@>=
25328 struct mp_edge_object *mp_gr_export(MP mp, int h);
25329
25330 @ This function is now nearly trivial.
25331
25332 @c
25333 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25334   integer c; /* \&{charcode} rounded to the nearest integer */
25335   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25336   @<Begin the progress report for the output of picture~|c|@>;
25337   (mp->shipout_backend) (mp, h);
25338   @<End progress report@>;
25339   if ( mp->internal[mp_tracing_output]>0 ) 
25340    mp_print_edges(mp, h," (just shipped out)",true);
25341 }
25342
25343 @ @<Declarations@>=
25344 void mp_shipout_backend (MP mp, pointer h);
25345
25346 @ @c
25347 void mp_shipout_backend (MP mp, pointer h) {
25348   mp_edge_object *hh; /* the first graphical object */
25349   hh = mp_gr_export(mp,h);
25350   mp_gr_ship_out (hh,
25351                  (mp->internal[mp_prologues]>>16),
25352                  (mp->internal[mp_procset]>>16));
25353   mp_gr_toss_objects(hh);
25354 }
25355
25356 @ @<Exported types@>=
25357 typedef void (*mp_backend_writer)(MP, int);
25358
25359 @ @<Option variables@>=
25360 mp_backend_writer shipout_backend;
25361
25362 @ @<Allocate or initialize ...@>=
25363 set_callback_option(shipout_backend);
25364
25365 @ Now that we've finished |ship_out|, let's look at the other commands
25366 by which a user can send things to the \.{GF} file.
25367
25368 @ @<Determine if a character has been shipped out@>=
25369
25370   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25371   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25372   boolean_reset(mp->char_exists[mp->cur_exp]);
25373   mp->cur_type=mp_boolean_type;
25374 }
25375
25376 @ @<Glob...@>=
25377 psout_data ps;
25378
25379 @ @<Allocate or initialize ...@>=
25380 mp_backend_initialize(mp);
25381
25382 @ @<Dealloc...@>=
25383 mp_backend_free(mp);
25384
25385
25386 @* \[45] Dumping and undumping the tables.
25387 After \.{INIMP} has seen a collection of macros, it
25388 can write all the necessary information on an auxiliary file so
25389 that production versions of \MP\ are able to initialize their
25390 memory at high speed. The present section of the program takes
25391 care of such output and input. We shall consider simultaneously
25392 the processes of storing and restoring,
25393 so that the inverse relation between them is clear.
25394 @.INIMP@>
25395
25396 The global variable |mem_ident| is a string that is printed right
25397 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25398 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25399 for example, `\.{(mem=plain 1990.4.14)}', showing the year,
25400 month, and day that the mem file was created. We have |mem_ident=0|
25401 before \MP's tables are loaded.
25402
25403 @<Glob...@>=
25404 char * mem_ident;
25405
25406 @ @<Set init...@>=
25407 mp->mem_ident=NULL;
25408
25409 @ @<Initialize table entries...@>=
25410 mp->mem_ident=xstrdup(" (INIMP)");
25411
25412 @ @<Declare act...@>=
25413 void mp_store_mem_file (MP mp) ;
25414
25415 @ @c void mp_store_mem_file (MP mp) {
25416   integer k;  /* all-purpose index */
25417   pointer p,q; /* all-purpose pointers */
25418   integer x; /* something to dump */
25419   four_quarters w; /* four ASCII codes */
25420   memory_word WW;
25421   @<Create the |mem_ident|, open the mem file,
25422     and inform the user that dumping has begun@>;
25423   @<Dump constants for consistency check@>;
25424   @<Dump the string pool@>;
25425   @<Dump the dynamic memory@>;
25426   @<Dump the table of equivalents and the hash table@>;
25427   @<Dump a few more things and the closing check word@>;
25428   @<Close the mem file@>;
25429 }
25430
25431 @ Corresponding to the procedure that dumps a mem file, we also have a function
25432 that reads~one~in. The function returns |false| if the dumped mem is
25433 incompatible with the present \MP\ table sizes, etc.
25434
25435 @d off_base 6666 /* go here if the mem file is unacceptable */
25436 @d too_small(A) { wake_up_terminal;
25437   wterm_ln("---! Must increase the "); wterm((A));
25438 @.Must increase the x@>
25439   goto OFF_BASE;
25440   }
25441
25442 @c 
25443 boolean mp_load_mem_file (MP mp) {
25444   integer k; /* all-purpose index */
25445   pointer p,q; /* all-purpose pointers */
25446   integer x; /* something undumped */
25447   str_number s; /* some temporary string */
25448   four_quarters w; /* four ASCII codes */
25449   memory_word WW;
25450   @<Undump constants for consistency check@>;
25451   @<Undump the string pool@>;
25452   @<Undump the dynamic memory@>;
25453   @<Undump the table of equivalents and the hash table@>;
25454   @<Undump a few more things and the closing check word@>;
25455   return true; /* it worked! */
25456 OFF_BASE: 
25457   wake_up_terminal;
25458   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25459 @.Fatal mem file error@>
25460    return false;
25461 }
25462
25463 @ @<Declarations@>=
25464 boolean mp_load_mem_file (MP mp) ;
25465
25466 @ Mem files consist of |memory_word| items, and we use the following
25467 macros to dump words of different types:
25468
25469 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp,mp->mem_file,&WW,sizeof(WW)); }
25470 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp,mp->mem_file,&cint,sizeof(cint)); }
25471 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp,mp->mem_file,&WW,sizeof(WW)); }
25472 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp,mp->mem_file,&WW,sizeof(WW)); }
25473 @d dump_string(A) { dump_int(strlen(A)+1);
25474                     (mp->write_binary_file)(mp,mp->mem_file,A,strlen(A)+1); }
25475
25476 @<Glob...@>=
25477 void * mem_file; /* for input or output of mem information */
25478
25479 @ The inverse macros are slightly more complicated, since we need to check
25480 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25481 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25482
25483 @d mgeti(A) do {
25484   size_t wanted = sizeof(A);
25485   void *A_ptr = &A;
25486   (mp->read_binary_file)(mp, mp->mem_file,&A_ptr,&wanted);
25487   if (wanted!=sizeof(A)) goto OFF_BASE;
25488 } while (0)
25489
25490 @d mgetw(A) do {
25491   size_t wanted = sizeof(A);
25492   void *A_ptr = &A;
25493   (mp->read_binary_file)(mp, mp->mem_file,&A_ptr,&wanted);
25494   if (wanted!=sizeof(A)) goto OFF_BASE;
25495 } while (0)
25496
25497 @d undump_wd(A)   { mgetw(WW); A=WW; }
25498 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25499 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25500 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25501 @d undump_strings(A,B,C) { 
25502    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25503 @d undump(A,B,C) { undump_int(x); if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25504 @d undump_size(A,B,C,D) { undump_int(x);
25505                           if (x<(A)) goto OFF_BASE; 
25506                           if (x>(B)) { too_small((C)); } else { D=x;} }
25507 @d undump_string(A) do { 
25508   size_t the_wanted; 
25509   void *the_string;
25510   integer XX=0; 
25511   undump_int(XX);
25512   the_wanted = XX;
25513   the_string = xmalloc(XX,sizeof(char));
25514   (mp->read_binary_file)(mp,mp->mem_file,&the_string,&the_wanted);
25515   A = (char *)the_string;
25516   if (the_wanted!=(size_t)XX) goto OFF_BASE;
25517 } while (0)
25518
25519 @ The next few sections of the program should make it clear how we use the
25520 dump/undump macros.
25521
25522 @<Dump constants for consistency check@>=
25523 dump_int(mp->mem_top);
25524 dump_int(mp->hash_size);
25525 dump_int(mp->hash_prime)
25526 dump_int(mp->param_size);
25527 dump_int(mp->max_in_open);
25528
25529 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25530 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25531 the same strings. (And it is, of course, a good thing that they do.)
25532 @.WEB@>
25533 @^string pool@>
25534
25535 @<Undump constants for consistency check@>=
25536 undump_int(x); mp->mem_top = x;
25537 undump_int(x); if (mp->hash_size != x) goto OFF_BASE;
25538 undump_int(x); if (mp->hash_prime != x) goto OFF_BASE;
25539 undump_int(x); if (mp->param_size != x) goto OFF_BASE;
25540 undump_int(x); if (mp->max_in_open != x) goto OFF_BASE
25541
25542 @ We do string pool compaction to avoid dumping unused strings.
25543
25544 @d dump_four_ASCII 
25545   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
25546   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
25547   dump_qqqq(w)
25548
25549 @<Dump the string pool@>=
25550 mp_do_compaction(mp, mp->pool_size);
25551 dump_int(mp->pool_ptr);
25552 dump_int(mp->max_str_ptr);
25553 dump_int(mp->str_ptr);
25554 k=0;
25555 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
25556   incr(k);
25557 dump_int(k);
25558 while ( k<=mp->max_str_ptr ) { 
25559   dump_int(mp->next_str[k]); incr(k);
25560 }
25561 k=0;
25562 while (1)  { 
25563   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
25564   if ( k==mp->str_ptr ) {
25565     break;
25566   } else { 
25567     k=mp->next_str[k]; 
25568   }
25569 }
25570 k=0;
25571 while (k+4<mp->pool_ptr ) { 
25572   dump_four_ASCII; k=k+4; 
25573 }
25574 k=mp->pool_ptr-4; dump_four_ASCII;
25575 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
25576 mp_print(mp, " strings of total length ");
25577 mp_print_int(mp, mp->pool_ptr)
25578
25579 @ @d undump_four_ASCII 
25580   undump_qqqq(w);
25581   mp->str_pool[k]=qo(w.b0); mp->str_pool[k+1]=qo(w.b1);
25582   mp->str_pool[k+2]=qo(w.b2); mp->str_pool[k+3]=qo(w.b3)
25583
25584 @<Undump the string pool@>=
25585 undump_int(mp->pool_ptr);
25586 mp_reallocate_pool(mp, mp->pool_ptr) ;
25587 undump_int(mp->max_str_ptr);
25588 mp_reallocate_strings (mp,mp->max_str_ptr) ;
25589 undump(0,mp->max_str_ptr,mp->str_ptr);
25590 undump(0,mp->max_str_ptr+1,s);
25591 for (k=0;k<=s-1;k++) 
25592   mp->next_str[k]=k+1;
25593 for (k=s;k<=mp->max_str_ptr;k++) 
25594   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
25595 mp->fixed_str_use=0;
25596 k=0;
25597 while (1) { 
25598   undump(0,mp->pool_ptr,mp->str_start[k]);
25599   if ( k==mp->str_ptr ) break;
25600   mp->str_ref[k]=max_str_ref;
25601   incr(mp->fixed_str_use);
25602   mp->last_fixed_str=k; k=mp->next_str[k];
25603 }
25604 k=0;
25605 while ( k+4<mp->pool_ptr ) { 
25606   undump_four_ASCII; k=k+4;
25607 }
25608 k=mp->pool_ptr-4; undump_four_ASCII;
25609 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
25610 mp->max_pool_ptr=mp->pool_ptr;
25611 mp->strs_used_up=mp->fixed_str_use;
25612 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
25613 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
25614 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
25615
25616 @ By sorting the list of available spaces in the variable-size portion of
25617 |mem|, we are usually able to get by without having to dump very much
25618 of the dynamic memory.
25619
25620 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
25621 information even when it has not been gathering statistics.
25622
25623 @<Dump the dynamic memory@>=
25624 mp_sort_avail(mp); mp->var_used=0;
25625 dump_int(mp->lo_mem_max); dump_int(mp->rover);
25626 p=0; q=mp->rover; x=0;
25627 do {  
25628   for (k=p;k<= q+1;k++) 
25629     dump_wd(mp->mem[k]);
25630   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
25631   p=q+node_size(q); q=rlink(q);
25632 } while (q!=mp->rover);
25633 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
25634 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
25635 for (k=p;k<= mp->lo_mem_max;k++ ) 
25636   dump_wd(mp->mem[k]);
25637 x=x+mp->lo_mem_max+1-p;
25638 dump_int(mp->hi_mem_min); dump_int(mp->avail);
25639 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
25640   dump_wd(mp->mem[k]);
25641 x=x+mp->mem_end+1-mp->hi_mem_min;
25642 p=mp->avail;
25643 while ( p!=null ) { 
25644   decr(mp->dyn_used); p=link(p);
25645 }
25646 dump_int(mp->var_used); dump_int(mp->dyn_used);
25647 mp_print_ln(mp); mp_print_int(mp, x);
25648 mp_print(mp, " memory locations dumped; current usage is ");
25649 mp_print_int(mp, mp->var_used); mp_print_char(mp, '&'); mp_print_int(mp, mp->dyn_used)
25650
25651 @ @<Undump the dynamic memory@>=
25652 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
25653 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
25654 p=0; q=mp->rover;
25655 do {  
25656   for (k=p;k<= q+1; k++) 
25657     undump_wd(mp->mem[k]);
25658   p=q+node_size(q);
25659   if ( (p>mp->lo_mem_max)||((q>=rlink(q))&&(rlink(q)!=mp->rover)) ) 
25660     goto OFF_BASE;
25661   q=rlink(q);
25662 } while (q!=mp->rover);
25663 for (k=p;k<=mp->lo_mem_max;k++ ) 
25664   undump_wd(mp->mem[k]);
25665 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
25666 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
25667 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
25668   undump_wd(mp->mem[k]);
25669 undump_int(mp->var_used); undump_int(mp->dyn_used)
25670
25671 @ A different scheme is used to compress the hash table, since its lower region
25672 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
25673 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
25674 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
25675
25676 @<Dump the table of equivalents and the hash table@>=
25677 dump_int(mp->hash_used); 
25678 mp->st_count=frozen_inaccessible-1-mp->hash_used;
25679 for (p=1;p<=mp->hash_used;p++) {
25680   if ( text(p)!=0 ) {
25681      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
25682   }
25683 }
25684 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
25685   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
25686 }
25687 dump_int(mp->st_count);
25688 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
25689
25690 @ @<Undump the table of equivalents and the hash table@>=
25691 undump(1,frozen_inaccessible,mp->hash_used); 
25692 p=0;
25693 do {  
25694   undump(p+1,mp->hash_used,p); 
25695   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25696 } while (p!=mp->hash_used);
25697 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
25698   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
25699 }
25700 undump_int(mp->st_count)
25701
25702 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
25703 to prevent them appearing again.
25704
25705 @<Dump a few more things and the closing check word@>=
25706 dump_int(mp->max_internal);
25707 dump_int(mp->int_ptr);
25708 for (k=1;k<= mp->int_ptr;k++ ) { 
25709   dump_int(mp->internal[k]); 
25710   dump_string(mp->int_name[k]);
25711 }
25712 dump_int(mp->start_sym); 
25713 dump_int(mp->interaction); 
25714 dump_string(mp->mem_ident);
25715 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
25716 mp->internal[mp_tracing_stats]=0
25717
25718 @ @<Undump a few more things and the closing check word@>=
25719 undump_int(x);
25720 if (x>mp->max_internal) mp_grow_internals(mp,x);
25721 undump_int(mp->int_ptr);
25722 for (k=1;k<= mp->int_ptr;k++) { 
25723   undump_int(mp->internal[k]);
25724   undump_string(mp->int_name[k]);
25725 }
25726 undump(0,frozen_inaccessible,mp->start_sym);
25727 if (mp->interaction==mp_unspecified_mode) {
25728   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
25729 } else {
25730   undump(mp_unspecified_mode,mp_error_stop_mode,x);
25731 }
25732 undump_string(mp->mem_ident);
25733 undump(1,hash_end,mp->bg_loc);
25734 undump(1,hash_end,mp->eg_loc);
25735 undump_int(mp->serial_no);
25736 undump_int(x); 
25737 if (x!=69073) goto OFF_BASE
25738
25739 @ @<Create the |mem_ident|...@>=
25740
25741   xfree(mp->mem_ident);
25742   mp->mem_ident = xmalloc(256,1);
25743   snprintf(mp->mem_ident,256," (mem=%s %i.%i.%i)", 
25744            mp->job_name,
25745            (int)(mp_round_unscaled(mp, mp->internal[mp_year]) % 100),
25746            (int)mp_round_unscaled(mp, mp->internal[mp_month]),
25747            (int)mp_round_unscaled(mp, mp->internal[mp_day]));
25748   mp_pack_job_name(mp, mem_extension);
25749   while (! mp_w_open_out(mp, &mp->mem_file) )
25750     mp_prompt_file_name(mp, "mem file name", mem_extension);
25751   mp_print_nl(mp, "Beginning to dump on file ");
25752 @.Beginning to dump...@>
25753   mp_print(mp, mp->name_of_file); 
25754   mp_print_nl(mp, mp->mem_ident);
25755 }
25756
25757 @ @<Dealloc variables@>=
25758 xfree(mp->mem_ident);
25759
25760 @ @<Close the mem file@>=
25761 (mp->close_file)(mp,mp->mem_file)
25762
25763 @* \[46] The main program.
25764 This is it: the part of \MP\ that executes all those procedures we have
25765 written.
25766
25767 Well---almost. We haven't put the parsing subroutines into the
25768 program yet; and we'd better leave space for a few more routines that may
25769 have been forgotten.
25770
25771 @c @<Declare the basic parsing subroutines@>
25772 @<Declare miscellaneous procedures that were declared |forward|@>
25773 @<Last-minute procedures@>
25774
25775 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25776 @.INIMP@>
25777 has to be run first; it initializes everything from scratch, without
25778 reading a mem file, and it has the capability of dumping a mem file.
25779 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25780 @.VIRMP@>
25781 to input a mem file in order to get started. \.{VIRMP} typically has
25782 a bit more memory capacity than \.{INIMP}, because it does not need the
25783 space consumed by the dumping/undumping routines and the numerous calls on
25784 |primitive|, etc.
25785
25786 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25787 the best implementations therefore allow for production versions of \MP\ that
25788 not only avoid the loading routine for object code, they also have
25789 a mem file pre-loaded. 
25790
25791 @ @<Option variables@>=
25792 int ini_version; /* are we iniMP? */
25793
25794 @ @<Set |ini_version|@>=
25795 mp->ini_version = (opt->ini_version ? true : false);
25796
25797 @ Here we do whatever is needed to complete \MP's job gracefully on the
25798 local operating system. The code here might come into play after a fatal
25799 error; it must therefore consist entirely of ``safe'' operations that
25800 cannot produce error messages. For example, it would be a mistake to call
25801 |str_room| or |make_string| at this time, because a call on |overflow|
25802 might lead to an infinite loop.
25803 @^system dependencies@>
25804
25805 This program doesn't bother to close the input files that may still be open.
25806
25807 @<Last-minute...@>=
25808 void mp_close_files_and_terminate (MP mp) {
25809   integer k; /* all-purpose index */
25810   integer LH; /* the length of the \.{TFM} header, in words */
25811   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25812   pointer p; /* runs through a list of \.{TFM} dimensions */
25813   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25814   if ( mp->internal[mp_tracing_stats]>0 )
25815     @<Output statistics about this job@>;
25816   wake_up_terminal; 
25817   @<Do all the finishing work on the \.{TFM} file@>;
25818   @<Explain what output files were written@>;
25819   if ( mp->log_opened ){ 
25820     wlog_cr;
25821     (mp->close_file)(mp,mp->log_file); 
25822     mp->selector=mp->selector-2;
25823     if ( mp->selector==term_only ) {
25824       mp_print_nl(mp, "Transcript written on ");
25825 @.Transcript written...@>
25826       mp_print(mp, mp->log_name); mp_print_char(mp, '.');
25827     }
25828   }
25829   mp_print_ln(mp);
25830   t_close_out;
25831   t_close_in;
25832 }
25833
25834 @ @<Declarations@>=
25835 void mp_close_files_and_terminate (MP mp) ;
25836
25837 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
25838 if (mp->rd_fname!=NULL) {
25839   for (k=0;k<=(int)mp->read_files-1;k++ ) {
25840     if ( mp->rd_fname[k]!=NULL ) {
25841       (mp->close_file)(mp,mp->rd_file[k]);
25842    }
25843  }
25844 }
25845 if (mp->wr_fname!=NULL) {
25846   for (k=0;k<=(int)mp->write_files-1;k++) {
25847     if ( mp->wr_fname[k]!=NULL ) {
25848      (mp->close_file)(mp,mp->wr_file[k]);
25849     }
25850   }
25851 }
25852
25853 @ @<Dealloc ...@>=
25854 for (k=0;k<(int)mp->max_read_files;k++ ) {
25855   if ( mp->rd_fname[k]!=NULL ) {
25856     (mp->close_file)(mp,mp->rd_file[k]);
25857     mp_xfree(mp->rd_fname[k]); 
25858   }
25859 }
25860 mp_xfree(mp->rd_file);
25861 mp_xfree(mp->rd_fname);
25862 for (k=0;k<(int)mp->max_write_files;k++) {
25863   if ( mp->wr_fname[k]!=NULL ) {
25864     (mp->close_file)(mp,mp->wr_file[k]);
25865     mp_xfree(mp->wr_fname[k]); 
25866   }
25867 }
25868 mp_xfree(mp->wr_file);
25869 mp_xfree(mp->wr_fname);
25870
25871
25872 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
25873
25874 We reclaim all of the variable-size memory at this point, so that
25875 there is no chance of another memory overflow after the memory capacity
25876 has already been exceeded.
25877
25878 @<Do all the finishing work on the \.{TFM} file@>=
25879 if ( mp->internal[mp_fontmaking]>0 ) {
25880   @<Make the dynamic memory into one big available node@>;
25881   @<Massage the \.{TFM} widths@>;
25882   mp_fix_design_size(mp); mp_fix_check_sum(mp);
25883   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
25884   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
25885   @<Finish the \.{TFM} file@>;
25886 }
25887
25888 @ @<Make the dynamic memory into one big available node@>=
25889 mp->rover=lo_mem_stat_max+1; link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
25890 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
25891 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
25892 llink(mp->rover)=mp->rover; rlink(mp->rover)=mp->rover;
25893 link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
25894
25895 @ The present section goes directly to the log file instead of using
25896 |print| commands, because there's no need for these strings to take
25897 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
25898
25899 @<Output statistics...@>=
25900 if ( mp->log_opened ) { 
25901   char s[128];
25902   wlog_ln(" ");
25903   wlog_ln("Here is how much of MetaPost's memory you used:");
25904 @.Here is how much...@>
25905   snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
25906           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
25907           (int)(mp->max_strings-1-mp->init_str_use));
25908   wlog_ln(s);
25909   snprintf(s,128," %i string characters out of %i",
25910            (int)mp->max_pl_used-mp->init_pool_ptr,
25911            (int)mp->pool_size-mp->init_pool_ptr);
25912   wlog_ln(s);
25913   snprintf(s,128," %i words of memory out of %i",
25914            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
25915            (int)mp->mem_end);
25916   wlog_ln(s);
25917   snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
25918   wlog_ln(s);
25919   snprintf(s,128," %ii,%in,%ip,%ib stack positions out of %ii,%in,%ip,%ib",
25920            (int)mp->max_in_stack,(int)mp->int_ptr,
25921            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
25922            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
25923   wlog_ln(s);
25924   snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
25925           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
25926   wlog_ln(s);
25927 }
25928
25929 @ It is nice to have have some of the stats available from the API.
25930
25931 @<Exported function ...@>=
25932 int mp_memory_usage (MP mp );
25933 int mp_hash_usage (MP mp );
25934 int mp_param_usage (MP mp );
25935 int mp_open_usage (MP mp );
25936
25937 @ @c
25938 int mp_memory_usage (MP mp ) {
25939         return (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2;
25940 }
25941 int mp_hash_usage (MP mp ) {
25942   return (int)mp->st_count;
25943 }
25944 int mp_param_usage (MP mp ) {
25945         return (int)mp->max_param_stack;
25946 }
25947 int mp_open_usage (MP mp ) {
25948         return (int)mp->max_in_stack;
25949 }
25950
25951 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
25952 been scanned.
25953
25954 @<Last-minute...@>=
25955 void mp_final_cleanup (MP mp) {
25956   small_number c; /* 0 for \&{end}, 1 for \&{dump} */
25957   c=mp->cur_mod;
25958   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25959   while ( mp->input_ptr>0 ) {
25960     if ( token_state ) mp_end_token_list(mp);
25961     else  mp_end_file_reading(mp);
25962   }
25963   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
25964   while ( mp->open_parens>0 ) { 
25965     mp_print(mp, " )"); decr(mp->open_parens);
25966   };
25967   while ( mp->cond_ptr!=null ) {
25968     mp_print_nl(mp, "(end occurred when ");
25969 @.end occurred...@>
25970     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
25971     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
25972     if ( mp->if_line!=0 ) {
25973       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
25974     }
25975     mp_print(mp, " was incomplete)");
25976     mp->if_line=if_line_field(mp->cond_ptr);
25977     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=link(mp->cond_ptr);
25978   }
25979   if ( mp->history!=mp_spotless )
25980     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
25981       if ( mp->selector==term_and_log ) {
25982     mp->selector=term_only;
25983     mp_print_nl(mp, "(see the transcript file for additional information)");
25984 @.see the transcript file...@>
25985     mp->selector=term_and_log;
25986   }
25987   if ( c==1 ) {
25988     if (mp->ini_version) {
25989       mp_store_mem_file(mp); return;
25990     }
25991     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
25992 @.dump...only by INIMP@>
25993   }
25994 }
25995
25996 @ @<Declarations@>=
25997 void mp_final_cleanup (MP mp) ;
25998 void mp_init_prim (MP mp) ;
25999 void mp_init_tab (MP mp) ;
26000
26001 @ @<Last-minute...@>=
26002 void mp_init_prim (MP mp) { /* initialize all the primitives */
26003   @<Put each...@>;
26004 }
26005 @#
26006 void mp_init_tab (MP mp) { /* initialize other tables */
26007   integer k; /* all-purpose index */
26008   @<Initialize table entries (done by \.{INIMP} only)@>;
26009 }
26010
26011
26012 @ When we begin the following code, \MP's tables may still contain garbage;
26013 the strings might not even be present. Thus we must proceed cautiously to get
26014 bootstrapped in.
26015
26016 But when we finish this part of the program, \MP\ is ready to call on the
26017 |main_control| routine to do its work.
26018
26019 @<Get the first line...@>=
26020
26021   @<Initialize the input routines@>;
26022   if ( (mp->mem_ident==NULL)||(mp->buffer[loc]=='&') ) {
26023     if ( mp->mem_ident!=NULL ) {
26024       mp_do_initialize(mp); /* erase preloaded mem */
26025     }
26026     if ( ! mp_open_mem_file(mp) ) return mp_fatal_error_stop;
26027     if ( ! mp_load_mem_file(mp) ) {
26028       (mp->close_file)(mp, mp->mem_file); 
26029       return mp_fatal_error_stop;
26030     }
26031     (mp->close_file)(mp, mp->mem_file);
26032     while ( (loc<limit)&&(mp->buffer[loc]==' ') ) incr(loc);
26033   }
26034   mp->buffer[limit]='%';
26035   mp_fix_date_and_time(mp);
26036   if (mp->random_seed==0)
26037     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
26038   mp_init_randoms(mp, mp->random_seed);
26039   @<Initialize the print |selector|...@>;
26040   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26041     mp_start_input(mp); /* \&{input} assumed */
26042 }
26043
26044 @ @<Run inimpost commands@>=
26045 {
26046   mp_get_strings_started(mp);
26047   mp_init_tab(mp); /* initialize the tables */
26048   mp_init_prim(mp); /* call |primitive| for each primitive */
26049   mp->init_str_use=mp->str_ptr; mp->init_pool_ptr=mp->pool_ptr;
26050   mp->max_str_ptr=mp->str_ptr; mp->max_pool_ptr=mp->pool_ptr;
26051   mp_fix_date_and_time(mp);
26052 }
26053
26054
26055 @* \[47] Debugging.
26056 Once \MP\ is working, you should be able to diagnose most errors with
26057 the \.{show} commands and other diagnostic features. But for the initial
26058 stages of debugging, and for the revelation of really deep mysteries, you
26059 can compile \MP\ with a few more aids. An additional routine called |debug_help|
26060 will also come into play when you type `\.D' after an error message;
26061 |debug_help| also occurs just before a fatal error causes \MP\ to succumb.
26062 @^debugging@>
26063 @^system dependencies@>
26064
26065 The interface to |debug_help| is primitive, but it is good enough when used
26066 with a debugger that allows you to set breakpoints and to read
26067 variables and change their values. After getting the prompt `\.{debug \#}', you
26068 type either a negative number (this exits |debug_help|), or zero (this
26069 goes to a location where you can set a breakpoint, thereby entering into
26070 dialog with the debugger), or a positive number |m| followed by
26071 an argument |n|. The meaning of |m| and |n| will be clear from the
26072 program below. (If |m=13|, there is an additional argument, |l|.)
26073 @.debug \#@>
26074
26075 @<Last-minute...@>=
26076 void mp_debug_help (MP mp) { /* routine to display various things */
26077   integer k;
26078   int l,m,n;
26079   char *aline;
26080   size_t len;
26081   while (1) { 
26082     wake_up_terminal;
26083     mp_print_nl(mp, "debug # (-1 to exit):"); update_terminal;
26084 @.debug \#@>
26085     m = 0;
26086     aline = (mp->read_ascii_file)(mp,mp->term_in, &len);
26087     if (len) { sscanf(aline,"%i",&m); xfree(aline); }
26088     if ( m<=0 )
26089       return;
26090     n = 0 ;
26091     aline = (mp->read_ascii_file)(mp,mp->term_in, &len);
26092     if (len) { sscanf(aline,"%i",&n); xfree(aline); }
26093     switch (m) {
26094     @<Numbered cases for |debug_help|@>;
26095     default: mp_print(mp, "?"); break;
26096     }
26097   }
26098 }
26099
26100 @ @<Numbered cases...@>=
26101 case 1: mp_print_word(mp, mp->mem[n]); /* display |mem[n]| in all forms */
26102   break;
26103 case 2: mp_print_int(mp, info(n));
26104   break;
26105 case 3: mp_print_int(mp, link(n));
26106   break;
26107 case 4: mp_print_int(mp, eq_type(n)); mp_print_char(mp, ':'); mp_print_int(mp, equiv(n));
26108   break;
26109 case 5: mp_print_variable_name(mp, n);
26110   break;
26111 case 6: mp_print_int(mp, mp->internal[n]);
26112   break;
26113 case 7: mp_do_show_dependencies(mp);
26114   break;
26115 case 9: mp_show_token_list(mp, n,null,100000,0);
26116   break;
26117 case 10: mp_print_str(mp, n);
26118   break;
26119 case 11: mp_check_mem(mp, n>0); /* check wellformedness; print new busy locations if |n>0| */
26120   break;
26121 case 12: mp_search_mem(mp, n); /* look for pointers to |n| */
26122   break;
26123 case 13: 
26124   l = 0;  
26125   aline = (mp->read_ascii_file)(mp,mp->term_in, &len);
26126   if (len) { sscanf(aline,"%i",&l); xfree(aline); }
26127   mp_print_cmd_mod(mp, n,l); 
26128   break;
26129 case 14: for (k=0;k<=n;k++) mp_print_str(mp, mp->buffer[k]);
26130   break;
26131 case 15: mp->panicking=! mp->panicking;
26132   break;
26133
26134
26135 @ Saving the filename template
26136
26137 @<Save the filename template@>=
26138
26139   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26140   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26141   else { 
26142     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26143   }
26144 }
26145
26146 @* \[48] System-dependent changes.
26147 This section should be replaced, if necessary, by any special
26148 modification of the program
26149 that are necessary to make \MP\ work at a particular installation.
26150 It is usually best to design your change file so that all changes to
26151 previous sections preserve the section numbering; then everybody's version
26152 will be consistent with the published program. More extensive changes,
26153 which introduce new sections, can be inserted here; then only the index
26154 itself will get a new section number.
26155 @^system dependencies@>
26156
26157 @* \[49] Index.
26158 Here is where you can find all uses of each identifier in the program,
26159 with underlined entries pointing to where the identifier was defined.
26160 If the identifier is only one letter long, however, you get to see only
26161 the underlined entries. {\sl All references are to section numbers instead of
26162 page numbers.}
26163
26164 This index also lists error messages and other aspects of the program
26165 that you might want to look up some day. For example, the entry
26166 for ``system dependencies'' lists all sections that should receive
26167 special attention from people who are installing \MP\ in a new
26168 operating environment. A list of various things that can't happen appears
26169 under ``this can't happen''.
26170 Approximately 25 sections are listed under ``inner loop''; these account
26171 for more than 60\pct! of \MP's running time, exclusive of input and output.