Cleanup all field names for mp_knot as well as mp_edge_object._next
[mplib] / src / texk / web2c / mpdir / mp.w
1 % $Id$
2 %
3 % Copyright 2008 Taco Hoekwater.
4 %
5 % This program is free software: you can redistribute it and/or modify
6 % it under the terms of the GNU General Public License as published by
7 % the Free Software Foundation, either version 2 of the License, or
8 % (at your option) any later version.
9 %
10 % This program is distributed in the hope that it will be useful,
11 % but WITHOUT ANY WARRANTY; without even the implied warranty of
12 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 % GNU General Public License for more details.
14 %
15 % You should have received a copy of the GNU General Public License
16 % along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 %
18 % TeX is a trademark of the American Mathematical Society.
19 % METAFONT is a trademark of Addison-Wesley Publishing Company.
20 % PostScript is a trademark of Adobe Systems Incorporated.
21
22 % Here is TeX material that gets inserted after \input webmac
23 \def\hang{\hangindent 3em\noindent\ignorespaces}
24 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
25 \def\ps{PostScript}
26 \def\psqrt#1{\sqrt{\mathstrut#1}}
27 \def\k{_{k+1}}
28 \def\pct!{{\char`\%}} % percent sign in ordinary text
29 \font\tenlogo=logo10 % font used for the METAFONT logo
30 \font\logos=logosl10
31 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
32 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
33 \def\[#1]{\ignorespaces} % left over from pascal web
34 \def\<#1>{$\langle#1\rangle$}
35 \def\section{\mathhexbox278}
36 \let\swap=\leftrightarrow
37 \def\round{\mathop{\rm round}\nolimits}
38 \mathchardef\vb="026A % synonym for `\|'
39
40 \def\(#1){} % this is used to make section names sort themselves better
41 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
42 \def\title{MetaPost}
43 \pdfoutput=1
44 \pageno=3
45
46 @* \[1] Introduction.
47
48 This is \MP\ by John Hobby, a graphics-language processor based on D. E. Knuth's \MF.
49
50 Much of the original Pascal version of this program was copied with
51 permission from MF.web Version 1.9. It interprets a language very
52 similar to D.E. Knuth's METAFONT, but with changes designed to make it
53 more suitable for PostScript output.
54
55 The main purpose of the following program is to explain the algorithms of \MP\
56 as clearly as possible. However, the program has been written so that it
57 can be tuned to run efficiently in a wide variety of operating environments
58 by making comparatively few changes. Such flexibility is possible because
59 the documentation that follows is written in the \.{WEB} language, which is
60 at a higher level than C.
61
62 A large piece of software like \MP\ has inherent complexity that cannot
63 be reduced below a certain level of difficulty, although each individual
64 part is fairly simple by itself. The \.{WEB} language is intended to make
65 the algorithms as readable as possible, by reflecting the way the
66 individual program pieces fit together and by providing the
67 cross-references that connect different parts. Detailed comments about
68 what is going on, and about why things were done in certain ways, have
69 been liberally sprinkled throughout the program.  These comments explain
70 features of the implementation, but they rarely attempt to explain the
71 \MP\ language itself, since the reader is supposed to be familiar with
72 {\sl The {\logos METAFONT\/}book} as well as the manual
73 @.WEB@>
74 @:METAFONTbook}{\sl The {\logos METAFONT\/}book}@>
75 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
76 AT\AM T Bell Laboratories.
77
78 @ The present implementation is a preliminary version, but the possibilities
79 for new features are limited by the desire to remain as nearly compatible
80 with \MF\ as possible.
81
82 On the other hand, the \.{WEB} description can be extended without changing
83 the core of the program, and it has been designed so that such
84 extensions are not extremely difficult to make.
85 The |banner| string defined here should be changed whenever \MP\
86 undergoes any modifications, so that it will be clear which version of
87 \MP\ might be the guilty party when a problem arises.
88 @^extensions to \MP@>
89 @^system dependencies@>
90
91 @d default_banner "This is MetaPost, Version 1.085" /* printed when \MP\ starts */
92 @d metapost_version "1.085"
93 @d metapost_magic (('M'*256) + 'P')*65536 + 1085
94
95 @d true 1
96 @d false 0
97
98 @ The external library header for \MP\ is |mplib.h|. It contains a
99 few typedefs and the header defintions for the externally used
100 fuctions.
101
102 The most important of the typedefs is the definition of the structure 
103 |MP_options|, that acts as a small, configurable front-end to the fairly 
104 large |MP_instance| structure.
105  
106 @(mplib.h@>=
107 typedef struct MP_instance * MP;
108 @<Exported types@>
109 typedef struct MP_options {
110   @<Option variables@>
111 } MP_options;
112 @<Exported function headers@>
113
114 @ The internal header file is much longer: it not only lists the complete
115 |MP_instance|, but also a lot of functions that have to be available to
116 the \ps\ backend, that is defined in a separate \.{WEB} file. 
117
118 The variables from |MP_options| are included inside the |MP_instance| 
119 wholesale.
120
121 @(mpmp.h@>=
122 #include <setjmp.h>
123 typedef struct psout_data_struct * psout_data;
124 #ifndef HAVE_BOOLEAN
125 typedef int boolean;
126 #endif
127 #ifndef INTEGER_TYPE
128 typedef int integer;
129 #endif
130 @<Declare helpers@>
131 @<Types in the outer block@>
132 @<Constants in the outer block@>
133 #  ifndef LIBAVL_ALLOCATOR
134 #    define LIBAVL_ALLOCATOR
135     struct libavl_allocator {
136         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
137         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
138     };
139 #  endif
140 typedef struct MP_instance {
141   @<Option variables@>
142   @<Global variables@>
143 } MP_instance;
144 @<Internal library declarations@>
145
146 @ @c 
147 #include "config.h"
148 #include <stdio.h>
149 #include <stdlib.h>
150 #include <string.h>
151 #include <stdarg.h>
152 #include <assert.h>
153 #ifdef HAVE_UNISTD_H
154 #include <unistd.h> /* for access() */
155 #endif
156 #include <time.h> /* for struct tm \& co */
157 #include "mplib.h"
158 #include "psout.h" /* external header */
159 #include "mpmp.h" /* internal header */
160 #include "mppsout.h" /* internal header */
161 #include "mptfmin.h" /* mp_read_font_info */
162 @h
163 @<Declarations@>
164 @<Basic printing procedures@>
165 @<Error handling procedures@>
166
167 @ Here are the functions that set up the \MP\ instance.
168
169 @<Declarations@> =
170 MP_options *mp_options (void);
171 MP mp_initialize (MP_options *opt);
172
173 @ @c
174 MP_options *mp_options (void) {
175   MP_options *opt;
176   size_t l = sizeof(MP_options);
177   opt = malloc(l);
178   if (opt!=NULL) {
179     memset (opt,0,l);
180     opt->ini_version = true;
181   }
182   return opt;
183
184
185 @ @<Internal library declarations@>=
186 @<Declare subroutines for parsing file names@>
187
188 @ The whole instance structure is initialized with zeroes,
189 this greatly reduces the number of statements needed in 
190 the |Allocate or initialize variables| block.
191
192 @d set_callback_option(A) do { mp->A = mp_##A;
193   if (opt->A!=NULL) mp->A = opt->A;
194 } while (0)
195
196 @c
197 static MP mp_do_new (jmp_buf *buf) {
198   MP mp = malloc(sizeof(MP_instance));
199   if (mp==NULL) {
200     xfree(buf);
201         return NULL;
202   }
203   memset(mp,0,sizeof(MP_instance));
204   mp->jump_buf = buf;
205   return mp;
206 }
207
208 @ @c
209 static void mp_free (MP mp) {
210   int k; /* loop variable */
211   @<Dealloc variables@>
212   if (mp->noninteractive) {
213     @<Finish non-interactive use@>;
214   }
215   xfree(mp->jump_buf);
216   xfree(mp);
217 }
218
219 @ @c
220 static void mp_do_initialize ( MP mp) {
221   @<Local variables for initialization@>
222   @<Set initial values of key variables@>
223 }
224
225 @ This procedure gets things started properly.
226 @c
227 MP mp_initialize (MP_options *opt) { 
228   MP mp;
229   jmp_buf *buf = malloc(sizeof(jmp_buf));
230   if (buf == NULL || setjmp(*buf) != 0) 
231     return NULL;
232   mp = mp_do_new(buf);
233   if (mp == NULL)
234     return NULL;
235   mp->userdata=opt->userdata;
236   @<Set |ini_version|@>;
237   mp->noninteractive=opt->noninteractive;
238   set_callback_option(find_file);
239   set_callback_option(open_file);
240   set_callback_option(read_ascii_file);
241   set_callback_option(read_binary_file);
242   set_callback_option(close_file);
243   set_callback_option(eof_file);
244   set_callback_option(flush_file);
245   set_callback_option(write_ascii_file);
246   set_callback_option(write_binary_file);
247   set_callback_option(shipout_backend);
248   if (opt->banner && *(opt->banner)) {
249     mp->banner = xstrdup(opt->banner);
250   } else {
251     mp->banner = xstrdup(default_banner);
252   }
253   if (opt->command_line && *(opt->command_line))
254     mp->command_line = xstrdup(opt->command_line);
255   if (mp->noninteractive) {
256     @<Prepare function pointers for non-interactive use@>;
257   } 
258   /* open the terminal for output */
259   t_open_out; 
260   @<Find constant sizes@>;
261   @<Allocate or initialize variables@>
262   mp_reallocate_memory(mp,mp->mem_max);
263   mp_reallocate_paths(mp,1000);
264   mp_reallocate_fonts(mp,8);
265   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
266   @<Check the ``constant'' values...@>;
267   if ( mp->bad>0 ) {
268         char ss[256];
269     mp_snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
270                    "---case %i",(int)mp->bad);
271     do_fprintf(mp->err_out,(char *)ss);
272 @.Ouch...clobbered@>
273     return mp;
274   }
275   mp_do_initialize(mp); /* erase preloaded mem */
276   if (mp->ini_version) {
277     @<Run inimpost commands@>;
278   }
279   if (!mp->noninteractive) {
280     @<Initialize the output routines@>;
281     @<Get the first line of input and prepare to start@>;
282     @<Initializations after first line is read@>;
283   } else {
284     mp->history=mp_spotless;
285   }
286   return mp;
287 }
288
289 @ @<Initializations after first line is read@>=
290 mp_set_job_id(mp);
291 mp_init_map_file(mp, mp->troff_mode);
292 mp->history=mp_spotless; /* ready to go! */
293 if (mp->troff_mode) {
294   mp->internal[mp_gtroffmode]=unity; 
295   mp->internal[mp_prologues]=unity; 
296 }
297 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
298   mp->cur_sym=mp->start_sym; mp_back_input(mp);
299 }
300
301 @ @<Exported function headers@>=
302 extern MP_options *mp_options (void);
303 extern MP mp_initialize (MP_options *opt) ;
304 extern int mp_status(MP mp);
305 extern void *mp_userdata(MP mp);
306
307 @ @c
308 int mp_status(MP mp) { return mp->history; }
309
310 @ @c
311 void *mp_userdata(MP mp) { return mp->userdata; }
312
313 @ The overall \MP\ program begins with the heading just shown, after which
314 comes a bunch of procedure declarations and function declarations.
315 Finally we will get to the main program, which begins with the
316 comment `|start_here|'. If you want to skip down to the
317 main program now, you can look up `|start_here|' in the index.
318 But the author suggests that the best way to understand this program
319 is to follow pretty much the order of \MP's components as they appear in the
320 \.{WEB} description you are now reading, since the present ordering is
321 intended to combine the advantages of the ``bottom up'' and ``top down''
322 approaches to the problem of understanding a somewhat complicated system.
323
324 @ Some of the code below is intended to be used only when diagnosing the
325 strange behavior that sometimes occurs when \MP\ is being installed or
326 when system wizards are fooling around with \MP\ without quite knowing
327 what they are doing. Such code will not normally be compiled; it is
328 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
329
330 @ This program has two important variations: (1) There is a long and slow
331 version called \.{INIMP}, which does the extra calculations needed to
332 @.INIMP@>
333 initialize \MP's internal tables; and (2)~there is a shorter and faster
334 production version, which cuts the initialization to a bare minimum.
335
336 Which is which is decided at runtime.
337
338 @ The following parameters can be changed at compile time to extend or
339 reduce \MP's capacity. They may have different values in \.{INIMP} and
340 in production versions of \MP.
341 @.INIMP@>
342 @^system dependencies@>
343
344 @<Constants...@>=
345 #define file_name_size 255 /* file names shouldn't be longer than this */
346 #define bistack_size 1500 /* size of stack for bisection algorithms;
347   should probably be left at this value */
348
349 @ Like the preceding parameters, the following quantities can be changed
350 to extend or reduce \MP's capacity. But if they are changed,
351 it is necessary to rerun the initialization program \.{INIMP}
352 @.INIMP@>
353 to generate new tables for the production \MP\ program.
354 One can't simply make helter-skelter changes to the following constants,
355 since certain rather complex initialization
356 numbers are computed from them. 
357
358 @ @<Glob...@>=
359 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
360 int pool_size; /* maximum number of characters in strings, including all
361   error messages and help texts, and the names of all identifiers */
362 int mem_max; /* greatest index in \MP's internal |mem| array;
363   must be strictly less than |max_halfword|;
364   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
365 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
366   must not be greater than |mem_max| */
367 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
368
369 @ @<Option variables@>=
370 int error_line; /* width of context lines on terminal error messages */
371 int half_error_line; /* width of first lines of contexts in terminal
372   error messages; should be between 30 and |error_line-15| */
373 int max_print_line; /* width of longest text lines output; should be at least 60 */
374 unsigned hash_size; /* maximum number of symbolic tokens,
375   must be less than |max_halfword-3*param_size| */
376 int param_size; /* maximum number of simultaneous macro parameters */
377 int max_in_open; /* maximum number of input files and error insertions that
378   can be going on simultaneously */
379 int main_memory; /* only for options, to set up |mem_max| and |mem_top| */
380 void *userdata; /* this allows the calling application to setup local */
381 char *banner; /* the banner that is printed to the screen and log */
382
383 @ @<Dealloc variables@>=
384 xfree(mp->banner);
385
386
387 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
388
389 @<Allocate or ...@>=
390 mp->max_strings=500;
391 mp->pool_size=10000;
392 set_value(mp->error_line,opt->error_line,79);
393 set_value(mp->half_error_line,opt->half_error_line,50);
394 if (mp->half_error_line>mp->error_line-15 ) 
395   mp->half_error_line = mp->error_line-15;
396 set_value(mp->max_print_line,opt->max_print_line,100);
397
398 @ In case somebody has inadvertently made bad settings of the ``constants,''
399 \MP\ checks them using a global variable called |bad|.
400
401 This is the second of many sections of \MP\ where global variables are
402 defined.
403
404 @<Glob...@>=
405 integer bad; /* is some ``constant'' wrong? */
406
407 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
408 or something similar. (We can't do that until |max_halfword| has been defined.)
409
410 In case you are wondering about the non-consequtive values of |bad|: some
411 of the things that used to be WEB constants are now runtime variables
412 with checking at assignment time.
413
414 @<Check the ``constant'' values for consistency@>=
415 mp->bad=0;
416 if ( mp->mem_top<=1100 ) mp->bad=4;
417
418 @ Some |goto| labels are used by the following definitions. The label
419 `|restart|' is occasionally used at the very beginning of a procedure; and
420 the label `|reswitch|' is occasionally used just prior to a |case|
421 statement in which some cases change the conditions and we wish to branch
422 to the newly applicable case.  Loops that are set up with the |loop|
423 construction defined below are commonly exited by going to `|done|' or to
424 `|found|' or to `|not_found|', and they are sometimes repeated by going to
425 `|continue|'.  If two or more parts of a subroutine start differently but
426 end up the same, the shared code may be gathered together at
427 `|common_ending|'.
428
429 @ Here are some macros for common programming idioms.
430
431 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
432 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
433 @d negate(A) (A)=-(A) /* change the sign of a variable */
434 @d double(A) (A)=(A)+(A)
435 @d odd(A)   ((A)%2==1)
436 @d do_nothing   /* empty statement */
437
438 @* \[2] The character set.
439 In order to make \MP\ readily portable to a wide variety of
440 computers, all of its input text is converted to an internal eight-bit
441 code that includes standard ASCII, the ``American Standard Code for
442 Information Interchange.''  This conversion is done immediately when each
443 character is read in. Conversely, characters are converted from ASCII to
444 the user's external representation just before they are output to a
445 text file.
446 @^ASCII code@>
447
448 Such an internal code is relevant to users of \MP\ only with respect to
449 the \&{char} and \&{ASCII} operations, and the comparison of strings.
450
451 @ Characters of text that have been converted to \MP's internal form
452 are said to be of type |ASCII_code|, which is a subrange of the integers.
453
454 @<Types...@>=
455 typedef unsigned char ASCII_code; /* eight-bit numbers */
456
457 @ The present specification of \MP\ has been written under the assumption
458 that the character set contains at least the letters and symbols associated
459 with ASCII codes 040 through 0176; all of these characters are now
460 available on most computer terminals.
461
462 @<Types...@>=
463 typedef unsigned char text_char; /* the data type of characters in text files */
464
465 @ @<Local variables for init...@>=
466 integer i;
467
468 @ The \MP\ processor converts between ASCII code and
469 the user's external character set by means of arrays |xord| and |xchr|
470 that are analogous to Pascal's |ord| and |chr| functions.
471
472 @d xchr(A) mp->xchr[(A)]
473 @d xord(A) mp->xord[(A)]
474
475 @<Glob...@>=
476 ASCII_code xord[256];  /* specifies conversion of input characters */
477 text_char xchr[256];  /* specifies conversion of output characters */
478
479 @ The core system assumes all 8-bit is acceptable.  If it is not,
480 a change file has to alter the below section.
481 @^system dependencies@>
482
483 Additionally, people with extended character sets can
484 assign codes arbitrarily, giving an |xchr| equivalent to whatever
485 characters the users of \MP\ are allowed to have in their input files.
486 Appropriate changes to \MP's |char_class| table should then be made.
487 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
488 codes, called the |char_class|.) Such changes make portability of programs
489 more difficult, so they should be introduced cautiously if at all.
490 @^character set dependencies@>
491 @^system dependencies@>
492
493 @<Set initial ...@>=
494 for (i=0;i<=0377;i++) { xchr(i)=(text_char)i; }
495
496 @ The following system-independent code makes the |xord| array contain a
497 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
498 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
499 |j| or more; hence, standard ASCII code numbers will be used instead of
500 codes below 040 in case there is a coincidence.
501
502 @<Set initial ...@>=
503 for (i=0;i<=255;i++) { 
504    xord(xchr(i))=0177;
505 }
506 for (i=0200;i<=0377;i++) { xord(xchr(i))=(ASCII_code)i;}
507 for (i=0;i<=0176;i++) { xord(xchr(i))=(ASCII_code)i;}
508
509 @* \[3] Input and output.
510 The bane of portability is the fact that different operating systems treat
511 input and output quite differently, perhaps because computer scientists
512 have not given sufficient attention to this problem. People have felt somehow
513 that input and output are not part of ``real'' programming. Well, it is true
514 that some kinds of programming are more fun than others. With existing
515 input/output conventions being so diverse and so messy, the only sources of
516 joy in such parts of the code are the rare occasions when one can find a
517 way to make the program a little less bad than it might have been. We have
518 two choices, either to attack I/O now and get it over with, or to postpone
519 I/O until near the end. Neither prospect is very attractive, so let's
520 get it over with.
521
522 The basic operations we need to do are (1)~inputting and outputting of
523 text, to or from a file or the user's terminal; (2)~inputting and
524 outputting of eight-bit bytes, to or from a file; (3)~instructing the
525 operating system to initiate (``open'') or to terminate (``close'') input or
526 output from a specified file; (4)~testing whether the end of an input
527 file has been reached; (5)~display of bits on the user's screen.
528 The bit-display operation will be discussed in a later section; we shall
529 deal here only with more traditional kinds of I/O.
530
531 @ Finding files happens in a slightly roundabout fashion: the \MP\
532 instance object contains a field that holds a function pointer that finds a
533 file, and returns its name, or NULL. For this, it receives three
534 parameters: the non-qualified name |fname|, the intended |fopen|
535 operation type |fmode|, and the type of the file |ftype|.
536
537 The file types that are passed on in |ftype| can be  used to 
538 differentiate file searches if a library like kpathsea is used,
539 the fopen mode is passed along for the same reason.
540
541 @<Types...@>=
542 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
543
544 @ @<Exported types@>=
545 enum mp_filetype {
546   mp_filetype_terminal = 0, /* the terminal */
547   mp_filetype_error, /* the terminal */
548   mp_filetype_program , /* \MP\ language input */
549   mp_filetype_log,  /* the log file */
550   mp_filetype_postscript, /* the postscript output */
551   mp_filetype_memfile, /* memory dumps */
552   mp_filetype_metrics, /* TeX font metric files */
553   mp_filetype_fontmap, /* PostScript font mapping files */
554   mp_filetype_font, /*  PostScript type1 font programs */
555   mp_filetype_encoding, /*  PostScript font encoding files */
556   mp_filetype_text  /* first text file for readfrom and writeto primitives */
557 };
558 typedef char *(*mp_file_finder)(MP, const char *, const char *, int);
559 typedef void *(*mp_file_opener)(MP, const char *, const char *, int);
560 typedef char *(*mp_file_reader)(MP, void *, size_t *);
561 typedef void (*mp_binfile_reader)(MP, void *, void **, size_t *);
562 typedef void (*mp_file_closer)(MP, void *);
563 typedef int (*mp_file_eoftest)(MP, void *);
564 typedef void (*mp_file_flush)(MP, void *);
565 typedef void (*mp_file_writer)(MP, void *, const char *);
566 typedef void (*mp_binfile_writer)(MP, void *, void *, size_t);
567
568 @ @<Option variables@>=
569 mp_file_finder find_file;
570 mp_file_opener open_file;
571 mp_file_reader read_ascii_file;
572 mp_binfile_reader read_binary_file;
573 mp_file_closer close_file;
574 mp_file_eoftest eof_file;
575 mp_file_flush flush_file;
576 mp_file_writer write_ascii_file;
577 mp_binfile_writer write_binary_file;
578
579 @ The default function for finding files is |mp_find_file|. It is 
580 pretty stupid: it will only find files in the current directory.
581
582 This function may disappear altogether, it is currently only
583 used for the default font map file.
584
585 @c
586 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype)  {
587   (void) mp;
588   if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {  
589      return mp_strdup(fname);
590   }
591   return NULL;
592 }
593
594 @ Because |mp_find_file| is used so early, it has to be in the helpers
595 section.
596
597 @<Declarations@>=
598 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype) ;
599 static void *mp_open_file (MP mp , const char *fname, const char *fmode, int ftype) ;
600 static char *mp_read_ascii_file (MP mp, void *f, size_t *size) ;
601 static void mp_read_binary_file (MP mp, void *f, void **d, size_t *size) ;
602 static void mp_close_file (MP mp, void *f) ;
603 static int mp_eof_file (MP mp, void *f) ;
604 static void mp_flush_file (MP mp, void *f) ;
605 static void mp_write_ascii_file (MP mp, void *f, const char *s) ;
606 static void mp_write_binary_file (MP mp, void *f, void *s, size_t t) ;
607
608 @ The function to open files can now be very short.
609
610 @c
611 void *mp_open_file(MP mp, const char *fname, const char *fmode, int ftype)  {
612   char realmode[3];
613   (void) mp;
614   realmode[0] = *fmode;
615   realmode[1] = 'b';
616   realmode[2] = 0;
617   if (ftype==mp_filetype_terminal) {
618     return (fmode[0] == 'r' ? stdin : stdout);
619   } else if (ftype==mp_filetype_error) {
620     return stderr;
621   } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
622     return (void *)fopen(fname, realmode);
623   }
624   return NULL;
625 }
626
627 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
628
629 @<Glob...@>=
630 char name_of_file[file_name_size+1]; /* the name of a system file */
631 int name_length;/* this many characters are actually
632   relevant in |name_of_file| (the rest are blank) */
633
634 @ @<Option variables@>=
635 int print_found_names; /* configuration parameter */
636
637 @ If this parameter is true, the terminal and log will report the found
638 file names for input files instead of the requested ones. 
639 It is off by default because it creates an extra filename lookup.
640
641 @<Allocate or initialize ...@>=
642 mp->print_found_names = (opt->print_found_names>0 ? true : false);
643
644 @ \MP's file-opening procedures return |false| if no file identified by
645 |name_of_file| could be opened.
646
647 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
648 It is not used for opening a mem file for read, because that file name 
649 is never printed.
650
651 @d OPEN_FILE(A) do {
652   if (mp->print_found_names) {
653     char *s = (mp->find_file)(mp,mp->name_of_file,A,ftype);
654     if (s!=NULL) {
655       *f = (mp->open_file)(mp,mp->name_of_file,A, ftype); 
656       strncpy(mp->name_of_file,s,file_name_size);
657       xfree(s);
658     } else {
659       *f = NULL;
660     }
661   } else {
662     *f = (mp->open_file)(mp,mp->name_of_file,A, ftype); 
663   }
664 } while (0);
665 return (*f ? true : false)
666
667 @c 
668 static boolean mp_a_open_in (MP mp, void **f, int ftype) {
669   /* open a text file for input */
670   OPEN_FILE("r");
671 }
672 @#
673 boolean mp_w_open_in (MP mp, void **f) {
674   /* open a word file for input */
675   *f = (mp->open_file)(mp,mp->name_of_file,"r",mp_filetype_memfile); 
676   return (*f ? true : false);
677 }
678 @#
679 static boolean mp_a_open_out (MP mp, void **f, int ftype) {
680   /* open a text file for output */
681   OPEN_FILE("w");
682 }
683 @#
684 static boolean mp_b_open_out (MP mp, void **f, int ftype) {
685   /* open a binary file for output */
686   OPEN_FILE("w");
687 }
688 @#
689 static boolean mp_w_open_out (MP mp, void **f) {
690   /* open a word file for output */
691   int ftype = mp_filetype_memfile;
692   OPEN_FILE("w");
693 }
694
695 @ @c
696 static char *mp_read_ascii_file (MP mp, void *ff, size_t *size) {
697   int c;
698   size_t len = 0, lim = 128;
699   char *s = NULL;
700   FILE *f = (FILE *)ff;
701   *size = 0;
702   (void) mp; /* for -Wunused */
703   if (f==NULL)
704     return NULL;
705   c = fgetc(f);
706   if (c==EOF)
707     return NULL;
708   s = malloc(lim); 
709   if (s==NULL) return NULL;
710   while (c!=EOF && c!='\n' && c!='\r') { 
711     if (len==lim) {
712       s =realloc(s, (lim+(lim>>2)));
713       if (s==NULL) return NULL;
714       lim+=(lim>>2);
715     }
716         s[len++] = c;
717     c =fgetc(f);
718   }
719   if (c=='\r') {
720     c = fgetc(f);
721     if (c!=EOF && c!='\n')
722        ungetc(c,f);
723   }
724   s[len] = 0;
725   *size = len;
726   return s;
727 }
728
729 @ @c
730 void mp_write_ascii_file (MP mp, void *f, const char *s) {
731   (void) mp;
732   if (f!=NULL) {
733     fputs(s,(FILE *)f);
734   }
735 }
736
737 @ @c
738 void mp_read_binary_file (MP mp, void *f, void **data, size_t *size) {
739   size_t len = 0;
740   (void) mp;
741   if (f!=NULL)
742     len = fread(*data,1,*size,(FILE *)f);
743   *size = len;
744 }
745
746 @ @c
747 void mp_write_binary_file (MP mp, void *f, void *s, size_t size) {
748   (void) mp;
749   if (f!=NULL)
750     (void)fwrite(s,size,1,(FILE *)f);
751 }
752
753
754 @ @c
755 void mp_close_file (MP mp, void *f) {
756   (void) mp;
757   if (f!=NULL)
758     fclose((FILE *)f);
759 }
760
761 @ @c
762 int mp_eof_file (MP mp, void *f) {
763   (void) mp;
764   if (f!=NULL)
765     return feof((FILE *)f);
766    else 
767     return 1;
768 }
769
770 @ @c
771 void mp_flush_file (MP mp, void *f) {
772   (void) mp;
773   if (f!=NULL)
774     fflush((FILE *)f);
775 }
776
777 @ Input from text files is read one line at a time, using a routine called
778 |input_ln|. This function is defined in terms of global variables called
779 |buffer|, |first|, and |last| that will be described in detail later; for
780 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
781 values, and that |first| and |last| are indices into this array
782 representing the beginning and ending of a line of text.
783
784 @<Glob...@>=
785 size_t buf_size; /* maximum number of characters simultaneously present in
786                     current lines of open files */
787 ASCII_code *buffer; /* lines of characters being read */
788 size_t first; /* the first unused position in |buffer| */
789 size_t last; /* end of the line just input to |buffer| */
790 size_t max_buf_stack; /* largest index used in |buffer| */
791
792 @ @<Allocate or initialize ...@>=
793 mp->buf_size = 200;
794 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
795
796 @ @<Dealloc variables@>=
797 xfree(mp->buffer);
798
799 @ @c
800 static void mp_reallocate_buffer(MP mp, size_t l) {
801   ASCII_code *buffer;
802   if (l>max_halfword) {
803     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
804   }
805   buffer = xmalloc((l+1),sizeof(ASCII_code));
806   memcpy(buffer,mp->buffer,(mp->buf_size+1));
807   xfree(mp->buffer);
808   mp->buffer = buffer ;
809   mp->buf_size = l;
810 }
811
812 @ The |input_ln| function brings the next line of input from the specified
813 field into available positions of the buffer array and returns the value
814 |true|, unless the file has already been entirely read, in which case it
815 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
816 numbers that represent the next line of the file are input into
817 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
818 global variable |last| is set equal to |first| plus the length of the
819 line. Trailing blanks are removed from the line; thus, either |last=first|
820 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
821 @^inner loop@>
822
823 The variable |max_buf_stack|, which is used to keep track of how large
824 the |buf_size| parameter must be to accommodate the present job, is
825 also kept up to date by |input_ln|.
826
827 @c 
828 static boolean mp_input_ln (MP mp, void *f ) {
829   /* inputs the next line or returns |false| */
830   char *s;
831   size_t size = 0; 
832   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
833   s = (mp->read_ascii_file)(mp,f, &size);
834   if (s==NULL)
835         return false;
836   if (size>0) {
837     mp->last = mp->first+size;
838     if ( mp->last>=mp->max_buf_stack ) { 
839       mp->max_buf_stack=mp->last+1;
840       while ( mp->max_buf_stack>=mp->buf_size ) {
841         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
842       }
843     }
844     memcpy((mp->buffer+mp->first),s,size);
845     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
846   } 
847   free(s);
848   return true;
849 }
850
851 @ The user's terminal acts essentially like other files of text, except
852 that it is used both for input and for output. When the terminal is
853 considered an input file, the file variable is called |term_in|, and when it
854 is considered an output file the file variable is |term_out|.
855 @^system dependencies@>
856
857 @<Glob...@>=
858 void * term_in; /* the terminal as an input file */
859 void * term_out; /* the terminal as an output file */
860 void * err_out; /* the terminal as an output file */
861
862 @ Here is how to open the terminal files. In the default configuration,
863 nothing happens except that the command line (if there is one) is copied
864 to the input buffer.  The variable |command_line| will be filled by the 
865 |main| procedure. The copying can not be done earlier in the program 
866 logic because in the |INI| version, the |buffer| is also used for primitive 
867 initialization.
868
869 @d t_open_out  do {/* open the terminal for text output */
870     mp->term_out = (mp->open_file)(mp,"terminal", "w", mp_filetype_terminal);
871     mp->err_out = (mp->open_file)(mp,"error", "w", mp_filetype_error);
872 } while (0)
873 @d t_open_in  do { /* open the terminal for text input */
874     mp->term_in = (mp->open_file)(mp,"terminal", "r", mp_filetype_terminal);
875     if (mp->command_line!=NULL) {
876       mp->last = strlen(mp->command_line);
877       strncpy((char *)mp->buffer,mp->command_line,mp->last);
878       xfree(mp->command_line);
879     } else {
880           mp->last = 0;
881     }
882 } while (0)
883
884 @<Option variables@>=
885 char *command_line;
886
887 @ Sometimes it is necessary to synchronize the input/output mixture that
888 happens on the user's terminal, and three system-dependent
889 procedures are used for this
890 purpose. The first of these, |update_terminal|, is called when we want
891 to make sure that everything we have output to the terminal so far has
892 actually left the computer's internal buffers and been sent.
893 The second, |clear_terminal|, is called when we wish to cancel any
894 input that the user may have typed ahead (since we are about to
895 issue an unexpected error message). The third, |wake_up_terminal|,
896 is supposed to revive the terminal if the user has disabled it by
897 some instruction to the operating system.  The following macros show how
898 these operations can be specified:
899 @^system dependencies@>
900
901 @d update_terminal  (mp->flush_file)(mp,mp->term_out) /* empty the terminal output buffer */
902 @d clear_terminal   do_nothing /* clear the terminal input buffer */
903 @d wake_up_terminal (mp->flush_file)(mp,mp->term_out) 
904                     /* cancel the user's cancellation of output */
905
906 @ We need a special routine to read the first line of \MP\ input from
907 the user's terminal. This line is different because it is read before we
908 have opened the transcript file; there is sort of a ``chicken and
909 egg'' problem here. If the user types `\.{input cmr10}' on the first
910 line, or if some macro invoked by that line does such an \.{input},
911 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
912 commands are performed during the first line of terminal input, the transcript
913 file will acquire its default name `\.{mpout.log}'. (The transcript file
914 will not contain error messages generated by the first line before the
915 first \.{input} command.)
916
917 The first line is even more special. It's nice to let the user start
918 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
919 such a case, \MP\ will operate as if the first line of input were
920 `\.{cmr10}', i.e., the first line will consist of the remainder of the
921 command line, after the part that invoked \MP.
922
923 @ Different systems have different ways to get started. But regardless of
924 what conventions are adopted, the routine that initializes the terminal
925 should satisfy the following specifications:
926
927 \yskip\textindent{1)}It should open file |term_in| for input from the
928   terminal. (The file |term_out| will already be open for output to the
929   terminal.)
930
931 \textindent{2)}If the user has given a command line, this line should be
932   considered the first line of terminal input. Otherwise the
933   user should be prompted with `\.{**}', and the first line of input
934   should be whatever is typed in response.
935
936 \textindent{3)}The first line of input, which might or might not be a
937   command line, should appear in locations |first| to |last-1| of the
938   |buffer| array.
939
940 \textindent{4)}The global variable |loc| should be set so that the
941   character to be read next by \MP\ is in |buffer[loc]|. This
942   character should not be blank, and we should have |loc<last|.
943
944 \yskip\noindent(It may be necessary to prompt the user several times
945 before a non-blank line comes in. The prompt is `\.{**}' instead of the
946 later `\.*' because the meaning is slightly different: `\.{input}' need
947 not be typed immediately after~`\.{**}'.)
948
949 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
950
951 @c 
952 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
953   t_open_in; 
954   if (mp->last!=0) {
955     loc = 0; mp->first = 0;
956         return true;
957   }
958   while (1) { 
959     if (!mp->noninteractive) {
960           wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
961 @.**@>
962     }
963     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
964       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
965 @.End of file on the terminal@>
966       return false;
967     }
968     loc=(halfword)mp->first;
969     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
970       incr(loc);
971     if ( loc<(int)mp->last ) { 
972       return true; /* return unless the line was all blank */
973     }
974     if (!mp->noninteractive) {
975           do_fprintf(mp->term_out,"Please type the name of your input file.\n");
976     }
977   }
978 }
979
980 @ @<Declarations@>=
981 static boolean mp_init_terminal (MP mp) ;
982
983
984 @* \[4] String handling.
985 Symbolic token names and diagnostic messages are variable-length strings
986 of eight-bit characters. Many strings \MP\ uses are simply literals
987 in the compiled source, like the error messages and the names of the
988 internal parameters. Other strings are used or defined from the \MP\ input 
989 language, and these have to be interned.
990
991 \MP\ uses strings more extensively than \MF\ does, but the necessary
992 operations can still be handled with a fairly simple data structure.
993 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
994 of the strings, and the array |str_start| contains indices of the starting
995 points of each string. Strings are referred to by integer numbers, so that
996 string number |s| comprises the characters |str_pool[j]| for
997 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
998 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
999 location.  The first string number not currently in use is |str_ptr|
1000 and |next_str[str_ptr]| begins a list of free string numbers.  String
1001 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
1002 string currently being constructed.
1003
1004 String numbers 0 to 255 are reserved for strings that correspond to single
1005 ASCII characters. This is in accordance with the conventions of \.{WEB},
1006 @.WEB@>
1007 which converts single-character strings into the ASCII code number of the
1008 single character involved, while it converts other strings into integers
1009 and builds a string pool file. Thus, when the string constant \.{"."} appears
1010 in the program below, \.{WEB} converts it into the integer 46, which is the
1011 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1012 into some integer greater than~255. String number 46 will presumably be the
1013 single character `\..'\thinspace; but some ASCII codes have no standard visible
1014 representation, and \MP\ may need to be able to print an arbitrary
1015 ASCII character, so the first 256 strings are used to specify exactly what
1016 should be printed for each of the 256 possibilities.
1017
1018 @<Types...@>=
1019 typedef int pool_pointer; /* for variables that point into |str_pool| */
1020 typedef int str_number; /* for variables that point into |str_start| */
1021
1022 @ @<Glob...@>=
1023 ASCII_code *str_pool; /* the characters */
1024 pool_pointer *str_start; /* the starting pointers */
1025 str_number *next_str; /* for linking strings in order */
1026 pool_pointer pool_ptr; /* first unused position in |str_pool| */
1027 str_number str_ptr; /* number of the current string being created */
1028 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
1029 str_number init_str_use; /* the initial number of strings in use */
1030 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
1031 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
1032
1033 @ @<Allocate or initialize ...@>=
1034 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
1035 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1036 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1037
1038 @ @<Dealloc variables@>=
1039 xfree(mp->str_pool);
1040 xfree(mp->str_start);
1041 xfree(mp->next_str);
1042
1043 @ Most printing is done from |char *|s, but sometimes not. Here are
1044 functions that convert an internal string into a |char *| for use
1045 by the printing routines, and vice versa.
1046
1047 @d str(A) mp_str(mp,A)
1048 @d rts(A) mp_rts(mp,A)
1049 @d null_str rts("")
1050
1051 @<Internal ...@>=
1052 int mp_xstrcmp (const char *a, const char *b);
1053 char * mp_str (MP mp, str_number s);
1054
1055 @ @<Declarations@>=
1056 static str_number mp_rts (MP mp, const char *s);
1057 static str_number mp_make_string (MP mp);
1058
1059 @ @c 
1060 int mp_xstrcmp (const char *a, const char *b) {
1061         if (a==NULL && b==NULL) 
1062           return 0;
1063     if (a==NULL)
1064       return -1;
1065     if (b==NULL)
1066       return 1;
1067     return strcmp(a,b);
1068 }
1069
1070 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1071 very good: it does not handle nesting over more than one level.
1072
1073 @c
1074 char * mp_str (MP mp, str_number ss) {
1075   char *s;
1076   size_t len;
1077   if (ss==mp->str_ptr) {
1078     return NULL;
1079   } else {
1080     len = (size_t)length(ss);
1081     s = xmalloc(len+1,sizeof(char));
1082     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1083     s[len] = 0;
1084     return (char *)s;
1085   }
1086 }
1087 str_number mp_rts (MP mp, const char *s) {
1088   int r; /* the new string */ 
1089   int old; /* a possible string in progress */
1090   int i=0;
1091   if (strlen(s)==0) {
1092     return 256;
1093   } else if (strlen(s)==1) {
1094     return s[0];
1095   } else {
1096    old=0;
1097    str_room((integer)strlen(s));
1098    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1099      old = mp_make_string(mp);
1100    while (*s) {
1101      append_char(*s);
1102      s++;
1103    }
1104    r = mp_make_string(mp);
1105    if (old!=0) {
1106       str_room(length(old));
1107       while (i<length(old)) {
1108         append_char((mp->str_start[old]+i));
1109       } 
1110       mp_flush_string(mp,old);
1111     }
1112     return r;
1113   }
1114 }
1115
1116 @ Except for |strs_used_up|, the following string statistics are only
1117 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1118 commented out:
1119
1120 @<Glob...@>=
1121 integer strs_used_up; /* strings in use or unused but not reclaimed */
1122 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1123 integer strs_in_use; /* total number of strings actually in use */
1124 integer max_pl_used; /* maximum |pool_in_use| so far */
1125 integer max_strs_used; /* maximum |strs_in_use| so far */
1126
1127 @ Several of the elementary string operations are performed using \.{WEB}
1128 macros instead of functions, because many of the
1129 operations are done quite frequently and we want to avoid the
1130 overhead of procedure calls. For example, here is
1131 a simple macro that computes the length of a string.
1132 @.WEB@>
1133
1134 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string \# */
1135 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1136
1137 @ The length of the current string is called |cur_length|.  If we decide that
1138 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1139 |cur_length| becomes zero.
1140
1141 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1142 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1143
1144 @ Strings are created by appending character codes to |str_pool|.
1145 The |append_char| macro, defined here, does not check to see if the
1146 value of |pool_ptr| has gotten too high; this test is supposed to be
1147 made before |append_char| is used.
1148
1149 To test if there is room to append |l| more characters to |str_pool|,
1150 we shall write |str_room(l)|, which tries to make sure there is enough room
1151 by compacting the string pool if necessary.  If this does not work,
1152 |do_compaction| aborts \MP\ and gives an apologetic error message.
1153
1154 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1155 { mp->str_pool[mp->pool_ptr]=(ASCII_code)(A); incr(mp->pool_ptr);
1156 }
1157 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1158   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1159     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1160     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1161   }
1162
1163 @ The following routine is similar to |str_room(1)| but it uses the
1164 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1165 string space is exhausted.
1166
1167 @<Declarations@>=
1168 static void mp_unit_str_room (MP mp);
1169
1170 @ @c
1171 void mp_unit_str_room (MP mp) { 
1172   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1173   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1174 }
1175
1176 @ \MP's string expressions are implemented in a brute-force way: Every
1177 new string or substring that is needed is simply copied into the string pool.
1178 Space is eventually reclaimed by a procedure called |do_compaction| with
1179 the aid of a simple system system of reference counts.
1180 @^reference counts@>
1181
1182 The number of references to string number |s| will be |str_ref[s]|. The
1183 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1184 positive number of references; such strings will never be recycled. If
1185 a string is ever referred to more than 126 times, simultaneously, we
1186 put it in this category. Hence a single byte suffices to store each |str_ref|.
1187
1188 @d max_str_ref 127 /* ``infinite'' number of references */
1189 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]); }
1190
1191 @<Glob...@>=
1192 int *str_ref;
1193
1194 @ @<Allocate or initialize ...@>=
1195 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1196
1197 @ @<Dealloc variables@>=
1198 xfree(mp->str_ref);
1199
1200 @ Here's what we do when a string reference disappears:
1201
1202 @d delete_str_ref(A)  { 
1203     if ( mp->str_ref[(A)]<max_str_ref ) {
1204        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1205        else mp_flush_string(mp, (A));
1206     }
1207   }
1208
1209 @<Declarations@>=
1210 static void mp_flush_string (MP mp,str_number s) ;
1211
1212 @ We can't flush the first set of static strings at all, so there 
1213 is no point in trying
1214
1215 @c
1216 void mp_flush_string (MP mp,str_number s) { 
1217   if (length(s)>1) {
1218     mp->pool_in_use=mp->pool_in_use-length(s);
1219     decr(mp->strs_in_use);
1220     if ( mp->next_str[s]!=mp->str_ptr ) {
1221       mp->str_ref[s]=0;
1222     } else { 
1223       mp->str_ptr=s;
1224       decr(mp->strs_used_up);
1225     }
1226     mp->pool_ptr=mp->str_start[mp->str_ptr];
1227   }
1228 }
1229
1230 @ C literals cannot be simply added, they need to be set so they can't
1231 be flushed.
1232
1233 @d intern(A) mp_intern(mp,(A))
1234
1235 @c
1236 str_number mp_intern (MP mp, const char *s) {
1237   str_number r ;
1238   r = rts(s);
1239   mp->str_ref[r] = max_str_ref;
1240   return r;
1241 }
1242
1243 @ @<Declarations@>=
1244 static str_number mp_intern (MP mp, const char *s);
1245
1246
1247 @ Once a sequence of characters has been appended to |str_pool|, it
1248 officially becomes a string when the function |make_string| is called.
1249 This function returns the identification number of the new string as its
1250 value.
1251
1252 When getting the next unused string number from the linked list, we pretend
1253 that
1254 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1255 are linked sequentially even though the |next_str| entries have not been
1256 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1257 |do_compaction| is responsible for making sure of this.
1258
1259 @<Declarations@>=
1260 static str_number mp_make_string (MP mp);
1261
1262 @ @c 
1263 str_number mp_make_string (MP mp) { /* current string enters the pool */
1264   str_number s; /* the new string */
1265 RESTART: 
1266   s=mp->str_ptr;
1267   mp->str_ptr=mp->next_str[s];
1268   if ( mp->str_ptr>mp->max_str_ptr ) {
1269     if ( mp->str_ptr==mp->max_strings ) { 
1270       mp->str_ptr=s;
1271       mp_do_compaction(mp, 0);
1272       goto RESTART;
1273     } else {
1274       mp->max_str_ptr=mp->str_ptr;
1275       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1276     }
1277   }
1278   mp->str_ref[s]=1;
1279   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1280   incr(mp->strs_used_up);
1281   incr(mp->strs_in_use);
1282   mp->pool_in_use=mp->pool_in_use+length(s);
1283   if ( mp->pool_in_use>mp->max_pl_used ) 
1284     mp->max_pl_used=mp->pool_in_use;
1285   if ( mp->strs_in_use>mp->max_strs_used ) 
1286     mp->max_strs_used=mp->strs_in_use;
1287   return s;
1288 }
1289
1290 @ The most interesting string operation is string pool compaction.  The idea
1291 is to recover unused space in the |str_pool| array by recopying the strings
1292 to close the gaps created when some strings become unused.  All string
1293 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1294 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1295 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1296 with |needed=mp->pool_size| supresses all overflow tests.
1297
1298 The compaction process starts with |last_fixed_str| because all lower numbered
1299 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1300
1301 @<Glob...@>=
1302 str_number last_fixed_str; /* last permanently allocated string */
1303 str_number fixed_str_use; /* number of permanently allocated strings */
1304
1305 @ @<Declarations@>=
1306 static void mp_do_compaction (MP mp, pool_pointer needed) ;
1307
1308 @ @c
1309 void mp_do_compaction (MP mp, pool_pointer needed) {
1310   str_number str_use; /* a count of strings in use */
1311   str_number r,s,t; /* strings being manipulated */
1312   pool_pointer p,q; /* destination and source for copying string characters */
1313   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1314   r=mp->last_fixed_str;
1315   s=mp->next_str[r];
1316   p=mp->str_start[s];
1317   while ( s!=mp->str_ptr ) { 
1318     while ( mp->str_ref[s]==0 ) {
1319       @<Advance |s| and add the old |s| to the list of free string numbers;
1320         then |break| if |s=str_ptr|@>;
1321     }
1322     r=s; s=mp->next_str[s];
1323     incr(str_use);
1324     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1325      after the end of the string@>;
1326   }
1327 DONE:   
1328   @<Move the current string back so that it starts at |p|@>;
1329   if ( needed<mp->pool_size ) {
1330     @<Make sure that there is room for another string with |needed| characters@>;
1331   }
1332   @<Account for the compaction and make sure the statistics agree with the
1333      global versions@>;
1334   mp->strs_used_up=str_use;
1335 }
1336
1337 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1338 t=mp->next_str[mp->last_fixed_str];
1339 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1340   incr(mp->fixed_str_use);
1341   mp->last_fixed_str=t;
1342   t=mp->next_str[t];
1343 }
1344 str_use=mp->fixed_str_use
1345
1346 @ Because of the way |flush_string| has been written, it should never be
1347 necessary to |break| here.  The extra line of code seems worthwhile to
1348 preserve the generality of |do_compaction|.
1349
1350 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1351 {
1352 t=s;
1353 s=mp->next_str[s];
1354 mp->next_str[r]=s;
1355 mp->next_str[t]=mp->next_str[mp->str_ptr];
1356 mp->next_str[mp->str_ptr]=t;
1357 if ( s==mp->str_ptr ) goto DONE;
1358 }
1359
1360 @ The string currently starts at |str_start[r]| and ends just before
1361 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1362 to locate the next string.
1363
1364 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1365 q=mp->str_start[r];
1366 mp->str_start[r]=p;
1367 while ( q<mp->str_start[s] ) { 
1368   mp->str_pool[p]=mp->str_pool[q];
1369   incr(p); incr(q);
1370 }
1371
1372 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1373 we do this, anything between them should be moved.
1374
1375 @ @<Move the current string back so that it starts at |p|@>=
1376 q=mp->str_start[mp->str_ptr];
1377 mp->str_start[mp->str_ptr]=p;
1378 while ( q<mp->pool_ptr ) { 
1379   mp->str_pool[p]=mp->str_pool[q];
1380   incr(p); incr(q);
1381 }
1382 mp->pool_ptr=p
1383
1384 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1385
1386 @<Make sure that there is room for another string with |needed| char...@>=
1387 if ( str_use>=mp->max_strings-1 )
1388   mp_reallocate_strings (mp,str_use);
1389 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1390   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1391   mp->max_pool_ptr=mp->pool_ptr+needed;
1392 }
1393
1394 @ @<Declarations@>=
1395 static void mp_reallocate_strings (MP mp, str_number str_use) ;
1396 static void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1397
1398 @ @c 
1399 void mp_reallocate_strings (MP mp, str_number str_use) { 
1400   while ( str_use>=mp->max_strings-1 ) {
1401     int l = mp->max_strings + (mp->max_strings/4);
1402     XREALLOC (mp->str_ref,   l, int);
1403     XREALLOC (mp->str_start, l, pool_pointer);
1404     XREALLOC (mp->next_str,  l, str_number);
1405     mp->max_strings = l;
1406   }
1407 }
1408 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1409   while ( needed>mp->pool_size ) {
1410     int l = mp->pool_size + (mp->pool_size/4);
1411         XREALLOC (mp->str_pool, l, ASCII_code);
1412     mp->pool_size = l;
1413   }
1414 }
1415
1416 @ @<Account for the compaction and make sure the statistics agree with...@>=
1417 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1418   mp_confusion(mp, "string");
1419 @:this can't happen string}{\quad string@>
1420 incr(mp->pact_count);
1421 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1422 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1423
1424 @ A few more global variables are needed to keep track of statistics when
1425 |stat| $\ldots$ |tats| blocks are not commented out.
1426
1427 @<Glob...@>=
1428 integer pact_count; /* number of string pool compactions so far */
1429 integer pact_chars; /* total number of characters moved during compactions */
1430 integer pact_strs; /* total number of strings moved during compactions */
1431
1432 @ @<Initialize compaction statistics@>=
1433 mp->pact_count=0;
1434 mp->pact_chars=0;
1435 mp->pact_strs=0;
1436
1437 @ The following subroutine compares string |s| with another string of the
1438 same length that appears in |buffer| starting at position |k|;
1439 the result is |true| if and only if the strings are equal.
1440
1441 @c 
1442 static boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1443   /* test equality of strings */
1444   pool_pointer j; /* running index */
1445   j=mp->str_start[s];
1446   while ( j<str_stop(s) ) { 
1447     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1448       return false;
1449   }
1450   return true;
1451 }
1452
1453 @ Here is a similar routine, but it compares two strings in the string pool,
1454 and it does not assume that they have the same length. If the first string
1455 is lexicographically greater than, less than, or equal to the second,
1456 the result is respectively positive, negative, or zero.
1457
1458 @c 
1459 static integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1460   /* test equality of strings */
1461   pool_pointer j,k; /* running indices */
1462   integer ls,lt; /* lengths */
1463   integer l; /* length remaining to test */
1464   ls=length(s); lt=length(t);
1465   if ( ls<=lt ) l=ls; else l=lt;
1466   j=mp->str_start[s]; k=mp->str_start[t];
1467   while ( l-->0 ) { 
1468     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1469        return (mp->str_pool[j]-mp->str_pool[k]); 
1470     }
1471     j++; k++;
1472   }
1473   return (ls-lt);
1474 }
1475
1476 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1477 and |str_ptr| are computed by the \.{INIMP} program, based in part
1478 on the information that \.{WEB} has output while processing \MP.
1479 @.INIMP@>
1480 @^string pool@>
1481
1482 @c 
1483 void mp_get_strings_started (MP mp) { 
1484   /* initializes the string pool,
1485     but returns |false| if something goes wrong */
1486   int k; /* small indices or counters */
1487   str_number g; /* a new string */
1488   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1489   mp->str_start[0]=0;
1490   mp->next_str[0]=1;
1491   mp->pool_in_use=0; mp->strs_in_use=0;
1492   mp->max_pl_used=0; mp->max_strs_used=0;
1493   @<Initialize compaction statistics@>;
1494   mp->strs_used_up=0;
1495   @<Make the first 256 strings@>;
1496   g=mp_make_string(mp); /* string 256 == "" */
1497   mp->str_ref[g]=max_str_ref;
1498   mp->last_fixed_str=mp->str_ptr-1;
1499   mp->fixed_str_use=mp->str_ptr;
1500   return;
1501 }
1502
1503 @ @<Declarations@>=
1504 static void mp_get_strings_started (MP mp);
1505
1506 @ The first 256 strings will consist of a single character only.
1507
1508 @<Make the first 256...@>=
1509 for (k=0;k<=255;k++) { 
1510   append_char(k);
1511   g=mp_make_string(mp); 
1512   mp->str_ref[g]=max_str_ref;
1513 }
1514
1515 @ The first 128 strings will contain 95 standard ASCII characters, and the
1516 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1517 unless a system-dependent change is made here. Installations that have
1518 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1519 would like string 032 to be printed as the single character 032 instead
1520 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1521 even people with an extended character set will want to represent string
1522 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1523 to produce visible strings instead of tabs or line-feeds or carriage-returns
1524 or bell-rings or characters that are treated anomalously in text files.
1525
1526 The boolean expression defined here should be |true| unless \MP\ internal
1527 code number~|k| corresponds to a non-troublesome visible symbol in the
1528 local character set.
1529 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1530 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1531 must be printable.
1532 @^character set dependencies@>
1533 @^system dependencies@>
1534
1535 @<Character |k| cannot be printed@>=
1536   (k<' ')||(k==127)
1537
1538 @* \[5] On-line and off-line printing.
1539 Messages that are sent to a user's terminal and to the transcript-log file
1540 are produced by several `|print|' procedures. These procedures will
1541 direct their output to a variety of places, based on the setting of
1542 the global variable |selector|, which has the following possible
1543 values:
1544
1545 \yskip
1546 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1547   transcript file.
1548
1549 \hang |log_only|, prints only on the transcript file.
1550
1551 \hang |term_only|, prints only on the terminal.
1552
1553 \hang |no_print|, doesn't print at all. This is used only in rare cases
1554   before the transcript file is open.
1555
1556 \hang |pseudo|, puts output into a cyclic buffer that is used
1557   by the |show_context| routine; when we get to that routine we shall discuss
1558   the reasoning behind this curious mode.
1559
1560 \hang |new_string|, appends the output to the current string in the
1561   string pool.
1562
1563 \hang |>=write_file| prints on one of the files used for the \&{write}
1564 @:write_}{\&{write} primitive@>
1565   command.
1566
1567 \yskip
1568 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1569 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1570 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1571 relations are not used when |selector| could be |pseudo|, or |new_string|.
1572 We need not check for unprintable characters when |selector<pseudo|.
1573
1574 Three additional global variables, |tally|, |term_offset| and |file_offset|
1575 record the number of characters that have been printed
1576 since they were most recently cleared to zero. We use |tally| to record
1577 the length of (possibly very long) stretches of printing; |term_offset|,
1578 and |file_offset|, on the other hand, keep track of how many
1579 characters have appeared so far on the current line that has been output
1580 to the terminal, the transcript file, or the \ps\ output file, respectively.
1581
1582 @d new_string 0 /* printing is deflected to the string pool */
1583 @d pseudo 2 /* special |selector| setting for |show_context| */
1584 @d no_print 3 /* |selector| setting that makes data disappear */
1585 @d term_only 4 /* printing is destined for the terminal only */
1586 @d log_only 5 /* printing is destined for the transcript file only */
1587 @d term_and_log 6 /* normal |selector| setting */
1588 @d write_file 7 /* first write file selector */
1589
1590 @<Glob...@>=
1591 void * log_file; /* transcript of \MP\ session */
1592 void * ps_file; /* the generic font output goes here */
1593 unsigned int selector; /* where to print a message */
1594 unsigned char dig[23]; /* digits in a number, for rounding */
1595 integer tally; /* the number of characters recently printed */
1596 unsigned int term_offset;
1597   /* the number of characters on the current terminal line */
1598 unsigned int file_offset;
1599   /* the number of characters on the current file line */
1600 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1601 integer trick_count; /* threshold for pseudoprinting, explained later */
1602 integer first_count; /* another variable for pseudoprinting */
1603
1604 @ @<Allocate or initialize ...@>=
1605 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1606
1607 @ @<Dealloc variables@>=
1608 xfree(mp->trick_buf);
1609
1610 @ @<Initialize the output routines@>=
1611 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1612
1613 @ Macro abbreviations for output to the terminal and to the log file are
1614 defined here for convenience. Some systems need special conventions
1615 for terminal output, and it is possible to adhere to those conventions
1616 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1617 @^system dependencies@>
1618
1619 @d do_fprintf(f,b) (mp->write_ascii_file)(mp,f,b)
1620 @d wterm(A)     do_fprintf(mp->term_out,(A))
1621 @d wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; 
1622                   do_fprintf(mp->term_out,(char *)ss); }
1623 @d wterm_cr     do_fprintf(mp->term_out,"\n")
1624 @d wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1625 @d wlog(A)      do_fprintf(mp->log_file,(A))
1626 @d wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; 
1627                   do_fprintf(mp->log_file,(char *)ss); }
1628 @d wlog_cr      do_fprintf(mp->log_file, "\n")
1629 @d wlog_ln(A)   { wlog_cr; do_fprintf(mp->log_file,(A)); }
1630
1631
1632 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1633 use an array |wr_file| that will be declared later.
1634
1635 @d mp_print_text(A) mp_print_str(mp,text((A)))
1636
1637 @<Internal ...@>=
1638 void mp_print (MP mp, const char *s);
1639
1640 @ @<Declarations@>=
1641 static void mp_print_ln (MP mp);
1642 static void mp_print_visible_char (MP mp, ASCII_code s); 
1643 static void mp_print_char (MP mp, ASCII_code k);
1644 static void mp_print_str (MP mp, str_number s);
1645 static void mp_print_nl (MP mp, const char *s);
1646 static void mp_print_two (MP mp,scaled x, scaled y) ;
1647 static void mp_print_scaled (MP mp,scaled s);
1648
1649 @ @<Basic print...@>=
1650 static void mp_print_ln (MP mp) { /* prints an end-of-line */
1651  switch (mp->selector) {
1652   case term_and_log: 
1653     wterm_cr; wlog_cr;
1654     mp->term_offset=0;  mp->file_offset=0;
1655     break;
1656   case log_only: 
1657     wlog_cr; mp->file_offset=0;
1658     break;
1659   case term_only: 
1660     wterm_cr; mp->term_offset=0;
1661     break;
1662   case no_print:
1663   case pseudo: 
1664   case new_string: 
1665     break;
1666   default: 
1667     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1668   }
1669 } /* note that |tally| is not affected */
1670
1671 @ The |print_visible_char| procedure sends one character to the desired
1672 destination, using the |xchr| array to map it into an external character
1673 compatible with |input_ln|.  (It assumes that it is always called with
1674 a visible ASCII character.)  All printing comes through |print_ln| or
1675 |print_char|, which ultimately calls |print_visible_char|, hence these
1676 routines are the ones that limit lines to at most |max_print_line| characters.
1677 But we must make an exception for the \ps\ output file since it is not safe
1678 to cut up lines arbitrarily in \ps.
1679
1680 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1681 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1682 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1683
1684 @<Basic printing...@>=
1685 static void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1686   switch (mp->selector) {
1687   case term_and_log: 
1688     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1689     incr(mp->term_offset); incr(mp->file_offset);
1690     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1691        wterm_cr; mp->term_offset=0;
1692     };
1693     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1694        wlog_cr; mp->file_offset=0;
1695     };
1696     break;
1697   case log_only: 
1698     wlog_chr(xchr(s)); incr(mp->file_offset);
1699     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1700     break;
1701   case term_only: 
1702     wterm_chr(xchr(s)); incr(mp->term_offset);
1703     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1704     break;
1705   case no_print: 
1706     break;
1707   case pseudo: 
1708     if ( mp->tally<mp->trick_count ) 
1709       mp->trick_buf[mp->tally % mp->error_line]=s;
1710     break;
1711   case new_string: 
1712     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1713       mp_unit_str_room(mp);
1714       if ( mp->pool_ptr>=mp->pool_size ) 
1715         goto DONE; /* drop characters if string space is full */
1716     };
1717     append_char(s);
1718     break;
1719   default:
1720     { text_char ss[2]; ss[0] = xchr(s); ss[1]=0;
1721       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1722     }
1723   }
1724 DONE:
1725   incr(mp->tally);
1726 }
1727
1728 @ The |print_char| procedure sends one character to the desired destination.
1729 File names and string expressions might contain |ASCII_code| values that
1730 can't be printed using |print_visible_char|.  These characters will be
1731 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1732 (This procedure assumes that it is safe to bypass all checks for unprintable
1733 characters when |selector| is in the range |0..max_write_files-1|.
1734 The user might want to write unprintable characters.
1735
1736 @<Basic printing...@>=
1737 static void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1738   if ( mp->selector<pseudo || mp->selector>=write_file) {
1739     mp_print_visible_char(mp, k);
1740   } else if ( @<Character |k| cannot be printed@> ) { 
1741     mp_print(mp, "^^"); 
1742     if ( k<0100 ) { 
1743       mp_print_visible_char(mp, k+0100); 
1744     } else if ( k<0200 ) { 
1745       mp_print_visible_char(mp, k-0100); 
1746     } else {
1747       int l; /* small index or counter */
1748       l = (k / 16);
1749       mp_print_visible_char(mp, xord(l<10 ? l+'0' : l-10+'a'));
1750       l = (k % 16);
1751       mp_print_visible_char(mp, xord(l<10 ? l+'0' : l-10+'a'));
1752     }
1753   } else {
1754     mp_print_visible_char(mp, k);
1755   }
1756 }
1757
1758 @ An entire string is output by calling |print|. Note that if we are outputting
1759 the single standard ASCII character \.c, we could call |print("c")|, since
1760 |"c"=99| is the number of a single-character string, as explained above. But
1761 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1762 routine when it knows that this is safe. (The present implementation
1763 assumes that it is always safe to print a visible ASCII character.)
1764 @^system dependencies@>
1765
1766 @<Basic print...@>=
1767 static void mp_do_print (MP mp, const char *ss, size_t len) { /* prints string |s| */
1768   size_t j = 0;
1769   while ( j<len ){ 
1770     mp_print_char(mp, xord((int)ss[j])); j++;
1771   }
1772 }
1773
1774
1775 @<Basic print...@>=
1776 void mp_print (MP mp, const char *ss) {
1777   if (ss==NULL) return;
1778   mp_do_print(mp, ss,strlen(ss));
1779 }
1780 static void mp_print_str (MP mp, str_number s) {
1781   pool_pointer j; /* current character code position */
1782   if ( (s<0)||(s>mp->max_str_ptr) ) {
1783      mp_do_print(mp,"???",3); /* this can't happen */
1784 @.???@>
1785   }
1786   j=mp->str_start[s];
1787   mp_do_print(mp, (char *)(mp->str_pool+j), (size_t)(str_stop(s)-j));
1788 }
1789
1790
1791 @ Here is the very first thing that \MP\ prints: a headline that identifies
1792 the version number and base name. The |term_offset| variable is temporarily
1793 incorrect, but the discrepancy is not serious since we assume that the banner
1794 and mem identifier together will occupy at most |max_print_line|
1795 character positions.
1796
1797 @<Initialize the output...@>=
1798 wterm (mp->banner);
1799 if (mp->mem_ident!=NULL) 
1800   mp_print(mp,mp->mem_ident); 
1801 mp_print_ln(mp);
1802 update_terminal;
1803
1804 @ The procedure |print_nl| is like |print|, but it makes sure that the
1805 string appears at the beginning of a new line.
1806
1807 @<Basic print...@>=
1808 static void mp_print_nl (MP mp, const char *s) { /* prints string |s| at beginning of line */
1809   switch(mp->selector) {
1810   case term_and_log: 
1811     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1812     break;
1813   case log_only: 
1814     if ( mp->file_offset>0 ) mp_print_ln(mp);
1815     break;
1816   case term_only: 
1817     if ( mp->term_offset>0 ) mp_print_ln(mp);
1818     break;
1819   case no_print:
1820   case pseudo:
1821   case new_string: 
1822         break;
1823   } /* there are no other cases */
1824   mp_print(mp, s);
1825 }
1826
1827 @ The following procedure, which prints out the decimal representation of a
1828 given integer |n|, assumes that all integers fit nicely into a |int|.
1829 @^system dependencies@>
1830
1831 @<Basic print...@>=
1832 static void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1833   char s[12];
1834   mp_snprintf(s,12,"%d", (int)n);
1835   mp_print(mp,s);
1836 }
1837
1838 @ @<Declarations@>=
1839 static void mp_print_int (MP mp,integer n);
1840
1841 @ \MP\ also makes use of a trivial procedure to print two digits. The
1842 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1843
1844 @c 
1845 static void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1846   n=abs(n) % 100; 
1847   mp_print_char(mp, xord('0'+(n / 10)));
1848   mp_print_char(mp, xord('0'+(n % 10)));
1849 }
1850
1851
1852 @ @<Declarations@>=
1853 static void mp_print_dd (MP mp,integer n);
1854
1855 @ Here is a procedure that asks the user to type a line of input,
1856 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1857 The input is placed into locations |first| through |last-1| of the
1858 |buffer| array, and echoed on the transcript file if appropriate.
1859
1860 This procedure is never called when |interaction<mp_scroll_mode|.
1861
1862 @d prompt_input(A) do { 
1863     if (!mp->noninteractive) {
1864       wake_up_terminal; mp_print(mp, (A)); 
1865     }
1866     mp_term_input(mp);
1867   } while (0) /* prints a string and gets a line of input */
1868
1869 @c 
1870 void mp_term_input (MP mp) { /* gets a line from the terminal */
1871   size_t k; /* index into |buffer| */
1872   if (mp->noninteractive) {
1873     if (!mp_input_ln(mp, mp->term_in ))
1874           longjmp(*(mp->jump_buf),1);  /* chunk finished */
1875     mp->buffer[mp->last]=xord('%'); 
1876   } else {
1877     update_terminal; /* Now the user sees the prompt for sure */
1878     if (!mp_input_ln(mp, mp->term_in )) {
1879           mp_fatal_error(mp, "End of file on the terminal!");
1880 @.End of file on the terminal@>
1881     }
1882     mp->term_offset=0; /* the user's line ended with \<\rm return> */
1883     decr(mp->selector); /* prepare to echo the input */
1884     if ( mp->last!=mp->first ) {
1885       for (k=mp->first;k<=mp->last-1;k++) {
1886         mp_print_char(mp, mp->buffer[k]);
1887       }
1888     }
1889     mp_print_ln(mp); 
1890     mp->buffer[mp->last]=xord('%'); 
1891     incr(mp->selector); /* restore previous status */
1892   }
1893 }
1894
1895 @* \[6] Reporting errors.
1896 When something anomalous is detected, \MP\ typically does something like this:
1897 $$\vbox{\halign{#\hfil\cr
1898 |print_err("Something anomalous has been detected");|\cr
1899 |help3("This is the first line of my offer to help.")|\cr
1900 |("This is the second line. I'm trying to")|\cr
1901 |("explain the best way for you to proceed.");|\cr
1902 |error;|\cr}}$$
1903 A two-line help message would be given using |help2|, etc.; these informal
1904 helps should use simple vocabulary that complements the words used in the
1905 official error message that was printed. (Outside the U.S.A., the help
1906 messages should preferably be translated into the local vernacular. Each
1907 line of help is at most 60 characters long, in the present implementation,
1908 so that |max_print_line| will not be exceeded.)
1909
1910 The |print_err| procedure supplies a `\.!' before the official message,
1911 and makes sure that the terminal is awake if a stop is going to occur.
1912 The |error| procedure supplies a `\..' after the official message, then it
1913 shows the location of the error; and if |interaction=error_stop_mode|,
1914 it also enters into a dialog with the user, during which time the help
1915 message may be printed.
1916 @^system dependencies@>
1917
1918 @ The global variable |interaction| has four settings, representing increasing
1919 amounts of user interaction:
1920
1921 @<Exported types@>=
1922 enum mp_interaction_mode { 
1923  mp_unspecified_mode=0, /* extra value for command-line switch */
1924  mp_batch_mode, /* omits all stops and omits terminal output */
1925  mp_nonstop_mode, /* omits all stops */
1926  mp_scroll_mode, /* omits error stops */
1927  mp_error_stop_mode /* stops at every opportunity to interact */
1928 };
1929
1930 @ @<Option variables@>=
1931 int interaction; /* current level of interaction */
1932 int noninteractive; /* do we have a terminal? */
1933
1934 @ Set it here so it can be overwritten by the commandline
1935
1936 @<Allocate or initialize ...@>=
1937 mp->interaction=opt->interaction;
1938 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1939   mp->interaction=mp_error_stop_mode;
1940 if (mp->interaction<mp_unspecified_mode) 
1941   mp->interaction=mp_batch_mode;
1942
1943
1944
1945 @d print_err(A) mp_print_err(mp,(A))
1946
1947 @<Internal ...@>=
1948 void mp_print_err(MP mp, const char * A);
1949
1950 @ @c
1951 void mp_print_err(MP mp, const char * A) { 
1952   if ( mp->interaction==mp_error_stop_mode ) 
1953     wake_up_terminal;
1954   mp_print_nl(mp, "! "); 
1955   mp_print(mp, A);
1956 @.!\relax@>
1957 }
1958
1959
1960 @ \MP\ is careful not to call |error| when the print |selector| setting
1961 might be unusual. The only possible values of |selector| at the time of
1962 error messages are
1963
1964 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1965   and |log_file| not yet open);
1966
1967 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1968
1969 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1970
1971 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1972
1973 @<Initialize the print |selector| based on |interaction|@>=
1974 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1975
1976 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1977 routine is active when |error| is called; this ensures that |get_next|
1978 will never be called recursively.
1979 @^recursion@>
1980
1981 The global variable |history| records the worst level of error that
1982 has been detected. It has four possible values: |spotless|, |warning_issued|,
1983 |error_message_issued|, and |fatal_error_stop|.
1984
1985 Another global variable, |error_count|, is increased by one when an
1986 |error| occurs without an interactive dialog, and it is reset to zero at
1987 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1988 that there is no point in continuing further.
1989
1990 @<Exported types@>=
1991 enum mp_history_state {
1992   mp_spotless=0, /* |history| value when nothing has been amiss yet */
1993   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
1994   mp_error_message_issued, /* |history| value when |error| has been called */
1995   mp_fatal_error_stop, /* |history| value when termination was premature */
1996   mp_system_error_stop /* |history| value when termination was due to disaster */
1997 };
1998
1999 @ @<Glob...@>=
2000 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2001 int history; /* has the source input been clean so far? */
2002 int error_count; /* the number of scrolled errors since the last statement ended */
2003
2004 @ The value of |history| is initially |fatal_error_stop|, but it will
2005 be changed to |spotless| if \MP\ survives the initialization process.
2006
2007 @<Allocate or ...@>=
2008 mp->deletions_allowed=true; /* |history| is initialized elsewhere */
2009
2010 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2011 error procedures near the beginning of the program. But the error procedures
2012 in turn use some other procedures, which need to be declared |forward|
2013 before we get to |error| itself.
2014
2015 It is possible for |error| to be called recursively if some error arises
2016 when |get_next| is being used to delete a token, and/or if some fatal error
2017 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2018 @^recursion@>
2019 is never more than two levels deep.
2020
2021 @<Declarations@>=
2022 static void mp_get_next (MP mp);
2023 static void mp_term_input (MP mp);
2024 static void mp_show_context (MP mp);
2025 static void mp_begin_file_reading (MP mp);
2026 static void mp_open_log_file (MP mp);
2027 static void mp_clear_for_error_prompt (MP mp);
2028
2029 @ @<Internal ...@>=
2030 void mp_normalize_selector (MP mp);
2031
2032 @ Individual lines of help are recorded in the array |help_line|, which
2033 contains entries in positions |0..(help_ptr-1)|. They should be printed
2034 in reverse order, i.e., with |help_line[0]| appearing last.
2035
2036 @d hlp1(A) mp->help_line[0]=A; }
2037 @d hlp2(A,B) mp->help_line[1]=A; hlp1(B)
2038 @d hlp3(A,B,C) mp->help_line[2]=A; hlp2(B,C)
2039 @d hlp4(A,B,C,D) mp->help_line[3]=A; hlp3(B,C,D)
2040 @d hlp5(A,B,C,D,E) mp->help_line[4]=A; hlp4(B,C,D,E)
2041 @d hlp6(A,B,C,D,E,F) mp->help_line[5]=A; hlp5(B,C,D,E,F)
2042 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2043 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2044 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2045 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2046 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2047 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2048 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2049
2050 @<Glob...@>=
2051 const char * help_line[6]; /* helps for the next |error| */
2052 unsigned int help_ptr; /* the number of help lines present */
2053 boolean use_err_help; /* should the |err_help| string be shown? */
2054 str_number err_help; /* a string set up by \&{errhelp} */
2055 str_number filename_template; /* a string set up by \&{filenametemplate} */
2056
2057 @ @<Allocate or ...@>=
2058 mp->use_err_help=false;
2059
2060 @ The |jump_out| procedure just cuts across all active procedure levels and
2061 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2062 whole program. It is used when there is no recovery from a particular error.
2063
2064 The program uses a |jump_buf| to handle this, this is initialized at three
2065 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2066 of |mp_run|. Those are the only library enty points.
2067
2068 @^system dependencies@>
2069
2070 @<Glob...@>=
2071 jmp_buf *jump_buf;
2072
2073 @ If the array of internals is still |NULL| when |jump_out| is called, a
2074 crash occured during initialization, and it is not safe to run the normal
2075 cleanup routine.
2076
2077 @<Error hand...@>=
2078 static void mp_jump_out (MP mp) { 
2079   if (mp->internal!=NULL && mp->history < mp_system_error_stop) 
2080     mp_close_files_and_terminate(mp);
2081   longjmp(*(mp->jump_buf),1);
2082 }
2083
2084 @ Here now is the general |error| routine.
2085
2086 @<Error hand...@>=
2087 void mp_error (MP mp) { /* completes the job of error reporting */
2088   ASCII_code c; /* what the user types */
2089   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2090   pool_pointer j; /* character position being printed */
2091   if ( mp->history<mp_error_message_issued ) 
2092         mp->history=mp_error_message_issued;
2093   mp_print_char(mp, xord('.')); mp_show_context(mp);
2094   if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2095     @<Get user's advice and |return|@>;
2096   }
2097   incr(mp->error_count);
2098   if ( mp->error_count==100 ) { 
2099     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2100 @.That makes 100 errors...@>
2101     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2102   }
2103   @<Put help message on the transcript file@>;
2104 }
2105 void mp_warn (MP mp, const char *msg) {
2106   unsigned saved_selector = mp->selector;
2107   mp_normalize_selector(mp);
2108   mp_print_nl(mp,"Warning: ");
2109   mp_print(mp,msg);
2110   mp_print_ln(mp);
2111   mp->selector = saved_selector;
2112 }
2113
2114 @ @<Exported function ...@>=
2115 extern void mp_error (MP mp);
2116 extern void mp_warn (MP mp, const char *msg);
2117
2118
2119 @ @<Get user's advice...@>=
2120 while (true) { 
2121 CONTINUE:
2122   mp_clear_for_error_prompt(mp); prompt_input("? ");
2123 @.?\relax@>
2124   if ( mp->last==mp->first ) return;
2125   c=mp->buffer[mp->first];
2126   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2127   @<Interpret code |c| and |return| if done@>;
2128 }
2129
2130 @ It is desirable to provide an `\.E' option here that gives the user
2131 an easy way to return from \MP\ to the system editor, with the offending
2132 line ready to be edited. But such an extension requires some system
2133 wizardry, so the present implementation simply types out the name of the
2134 file that should be
2135 edited and the relevant line number.
2136 @^system dependencies@>
2137
2138 @<Exported types@>=
2139 typedef void (*mp_run_editor_command)(MP, char *, int);
2140
2141 @ @<Option variables@>=
2142 mp_run_editor_command run_editor;
2143
2144 @ @<Allocate or initialize ...@>=
2145 set_callback_option(run_editor);
2146
2147 @ @<Declarations@>=
2148 static void mp_run_editor (MP mp, char *fname, int fline);
2149
2150 @ @c 
2151 void mp_run_editor (MP mp, char *fname, int fline) {
2152     mp_print_nl(mp, "You want to edit file ");
2153 @.You want to edit file x@>
2154     mp_print(mp, fname);
2155     mp_print(mp, " at line "); 
2156     mp_print_int(mp, fline);
2157     mp->interaction=mp_scroll_mode; 
2158     mp_jump_out(mp);
2159 }
2160
2161
2162 There is a secret `\.D' option available when the debugging routines haven't
2163 been commented~out.
2164 @^debugging@>
2165
2166 @<Interpret code |c| and |return| if done@>=
2167 switch (c) {
2168 case '0': case '1': case '2': case '3': case '4':
2169 case '5': case '6': case '7': case '8': case '9': 
2170   if ( mp->deletions_allowed ) {
2171     @<Delete |c-"0"| tokens and |continue|@>;
2172   }
2173   break;
2174 case 'E': 
2175   if ( mp->file_ptr>0 ){ 
2176     (mp->run_editor)(mp, 
2177                      str(mp->input_stack[mp->file_ptr].name_field), 
2178                      mp_true_line(mp));
2179   }
2180   break;
2181 case 'H': 
2182   @<Print the help information and |continue|@>;
2183   /* |break;| */
2184 case 'I':
2185   @<Introduce new material from the terminal and |return|@>;
2186   /* |break;| */
2187 case 'Q': case 'R': case 'S':
2188   @<Change the interaction level and |return|@>;
2189   /* |break;| */
2190 case 'X':
2191   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2192   break;
2193 default:
2194   break;
2195 }
2196 @<Print the menu of available options@>
2197
2198 @ @<Print the menu...@>=
2199
2200   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2201 @.Type <return> to proceed...@>
2202   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2203   mp_print_nl(mp, "I to insert something, ");
2204   if ( mp->file_ptr>0 ) 
2205     mp_print(mp, "E to edit your file,");
2206   if ( mp->deletions_allowed )
2207     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2208   mp_print_nl(mp, "H for help, X to quit.");
2209 }
2210
2211 @ Here the author of \MP\ apologizes for making use of the numerical
2212 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2213 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2214 @^Knuth, Donald Ervin@>
2215
2216 @<Change the interaction...@>=
2217
2218   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2219   mp_print(mp, "OK, entering ");
2220   switch (c) {
2221   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2222   case 'R': mp_print(mp, "nonstopmode"); break;
2223   case 'S': mp_print(mp, "scrollmode"); break;
2224   } /* there are no other cases */
2225   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2226 }
2227
2228 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2229 contain the material inserted by the user; otherwise another prompt will
2230 be given. In order to understand this part of the program fully, you need
2231 to be familiar with \MP's input stacks.
2232
2233 @<Introduce new material...@>=
2234
2235   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2236   if ( mp->last>mp->first+1 ) { 
2237     loc=(halfword)(mp->first+1); mp->buffer[mp->first]=xord(' ');
2238   } else { 
2239    prompt_input("insert>"); loc=(halfword)mp->first;
2240 @.insert>@>
2241   };
2242   mp->first=mp->last+1; mp->cur_input.limit_field=(halfword)mp->last; return;
2243 }
2244
2245 @ We allow deletion of up to 99 tokens at a time.
2246
2247 @<Delete |c-"0"| tokens...@>=
2248
2249   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2250   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2251     c=xord(c*10+mp->buffer[mp->first+1]-'0'*11);
2252   else 
2253     c=c-'0';
2254   while ( c>0 ) { 
2255     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2256     @<Decrease the string reference count, if the current token is a string@>;
2257     decr(c);
2258   };
2259   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2260   help2("I have just deleted some text, as you asked.",
2261        "You can now delete more, or insert, or whatever.");
2262   mp_show_context(mp); 
2263   goto CONTINUE;
2264 }
2265
2266 @ @<Print the help info...@>=
2267
2268   if ( mp->use_err_help ) { 
2269     @<Print the string |err_help|, possibly on several lines@>;
2270     mp->use_err_help=false;
2271   } else { 
2272     if ( mp->help_ptr==0 ) {
2273       help2("Sorry, I don't know how to help in this situation.",
2274             "Maybe you should try asking a human?");
2275      }
2276     do { 
2277       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2278     } while (mp->help_ptr!=0);
2279   };
2280   help4("Sorry, I already gave what help I could...",
2281        "Maybe you should try asking a human?",
2282        "An error might have occurred before I noticed any problems.",
2283        "``If all else fails, read the instructions.''");
2284   goto CONTINUE;
2285 }
2286
2287 @ @<Print the string |err_help|, possibly on several lines@>=
2288 j=mp->str_start[mp->err_help];
2289 while ( j<str_stop(mp->err_help) ) { 
2290   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2291   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2292   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2293   else  { j++; mp_print_char(mp, xord('%')); };
2294   j++;
2295 }
2296
2297 @ @<Put help message on the transcript file@>=
2298 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2299 if ( mp->use_err_help ) { 
2300   mp_print_nl(mp, "");
2301   @<Print the string |err_help|, possibly on several lines@>;
2302 } else { 
2303   while ( mp->help_ptr>0 ){ 
2304     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2305   };
2306 }
2307 mp_print_ln(mp);
2308 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2309 mp_print_ln(mp)
2310
2311 @ In anomalous cases, the print selector might be in an unknown state;
2312 the following subroutine is called to fix things just enough to keep
2313 running a bit longer.
2314
2315 @c 
2316 void mp_normalize_selector (MP mp) { 
2317   if ( mp->log_opened ) mp->selector=term_and_log;
2318   else mp->selector=term_only;
2319   if ( mp->job_name==NULL) mp_open_log_file(mp);
2320   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2321 }
2322
2323 @ The following procedure prints \MP's last words before dying.
2324
2325 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2326     mp->interaction=mp_scroll_mode; /* no more interaction */
2327   if ( mp->log_opened ) mp_error(mp);
2328   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2329   }
2330
2331 @<Error hand...@>=
2332 void mp_fatal_error (MP mp, const char *s) { /* prints |s|, and that's it */
2333   mp_normalize_selector(mp);
2334   print_err("Emergency stop"); help1(s); succumb;
2335 @.Emergency stop@>
2336 }
2337
2338 @ @<Exported function ...@>=
2339 extern void mp_fatal_error (MP mp, const char *s);
2340
2341
2342 @ Here is the most dreaded error message.
2343
2344 @<Error hand...@>=
2345 void mp_overflow (MP mp, const char *s, integer n) { /* stop due to finiteness */
2346   char msg[256];
2347   mp_normalize_selector(mp);
2348   mp_snprintf(msg, 256, "MetaPost capacity exceeded, sorry [%s=%d]",s,(int)n);
2349 @.MetaPost capacity exceeded ...@>
2350   print_err(msg);
2351   help2("If you really absolutely need more capacity,",
2352         "you can ask a wizard to enlarge me.");
2353   succumb;
2354 }
2355
2356 @ @<Internal library declarations@>=
2357 void mp_overflow (MP mp, const char *s, integer n);
2358
2359 @ The program might sometime run completely amok, at which point there is
2360 no choice but to stop. If no previous error has been detected, that's bad
2361 news; a message is printed that is really intended for the \MP\
2362 maintenance person instead of the user (unless the user has been
2363 particularly diabolical).  The index entries for `this can't happen' may
2364 help to pinpoint the problem.
2365 @^dry rot@>
2366
2367 @<Internal library ...@>=
2368 void mp_confusion (MP mp, const char *s);
2369
2370 @ Consistency check violated; |s| tells where.
2371 @<Error hand...@>=
2372 void mp_confusion (MP mp, const char *s) {
2373   char msg[256];
2374   mp_normalize_selector(mp);
2375   if ( mp->history<mp_error_message_issued ) { 
2376     mp_snprintf(msg, 256, "This can't happen (%s)",s);
2377 @.This can't happen@>
2378     print_err(msg);
2379     help1("I'm broken. Please show this to someone who can fix can fix");
2380   } else { 
2381     print_err("I can\'t go on meeting you like this");
2382 @.I can't go on...@>
2383     help2("One of your faux pas seems to have wounded me deeply...",
2384           "in fact, I'm barely conscious. Please fix it and try again.");
2385   }
2386   succumb;
2387 }
2388
2389 @ Users occasionally want to interrupt \MP\ while it's running.
2390 If the runtime system allows this, one can implement
2391 a routine that sets the global variable |interrupt| to some nonzero value
2392 when such an interrupt is signaled. Otherwise there is probably at least
2393 a way to make |interrupt| nonzero using the C debugger.
2394 @^system dependencies@>
2395 @^debugging@>
2396
2397 @d check_interrupt { if ( mp->interrupt!=0 )
2398    mp_pause_for_instructions(mp); }
2399
2400 @<Global...@>=
2401 integer interrupt; /* should \MP\ pause for instructions? */
2402 boolean OK_to_interrupt; /* should interrupts be observed? */
2403 integer run_state; /* are we processing input ?*/
2404 boolean finished; /* set true by |close_files_and_terminate| */
2405
2406 @ @<Allocate or ...@>=
2407 mp->OK_to_interrupt=true;
2408 mp->finished=false;
2409
2410 @ When an interrupt has been detected, the program goes into its
2411 highest interaction level and lets the user have the full flexibility of
2412 the |error| routine.  \MP\ checks for interrupts only at times when it is
2413 safe to do this.
2414
2415 @c 
2416 static void mp_pause_for_instructions (MP mp) { 
2417   if ( mp->OK_to_interrupt ) { 
2418     mp->interaction=mp_error_stop_mode;
2419     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2420       incr(mp->selector);
2421     print_err("Interruption");
2422 @.Interruption@>
2423     help3("You rang?",
2424          "Try to insert some instructions for me (e.g.,`I show x'),",
2425          "unless you just want to quit by typing `X'.");
2426     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2427     mp->interrupt=0;
2428   }
2429 }
2430
2431 @ Many of \MP's error messages state that a missing token has been
2432 inserted behind the scenes. We can save string space and program space
2433 by putting this common code into a subroutine.
2434
2435 @c 
2436 static void mp_missing_err (MP mp, const char *s) { 
2437   char msg[256];
2438   mp_snprintf(msg, 256, "Missing `%s' has been inserted", s);
2439 @.Missing...inserted@>
2440   print_err(msg);
2441 }
2442
2443 @* \[7] Arithmetic with scaled numbers.
2444 The principal computations performed by \MP\ are done entirely in terms of
2445 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2446 program can be carried out in exactly the same way on a wide variety of
2447 computers, including some small ones.
2448 @^small computers@>
2449
2450 But C does not rigidly define the |/| operation in the case of negative
2451 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2452 computers and |-n| on others (is this true ?).  There are two principal
2453 types of arithmetic: ``translation-preserving,'' in which the identity
2454 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2455 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2456 different results, although the differences should be negligible when the
2457 language is being used properly.  The \TeX\ processor has been defined
2458 carefully so that both varieties of arithmetic will produce identical
2459 output, but it would be too inefficient to constrain \MP\ in a similar way.
2460
2461 @d el_gordo   0x7fffffff /* $2^{31}-1$, the largest value that \MP\ likes */
2462
2463
2464 @ One of \MP's most common operations is the calculation of
2465 $\lfloor{a+b\over2}\rfloor$,
2466 the midpoint of two given integers |a| and~|b|. The most decent way to do
2467 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2468 to calculate `|(a+b)>>1|'.
2469
2470 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2471 in this program. If \MP\ is being implemented with languages that permit
2472 binary shifting, the |half| macro should be changed to make this operation
2473 as efficient as possible.  Since some systems have shift operators that can
2474 only be trusted to work on positive numbers, there is also a macro |halfp|
2475 that is used only when the quantity being halved is known to be positive
2476 or zero.
2477
2478 @d half(A) ((A) / 2)
2479 @d halfp(A) (integer)((unsigned)(A) >> 1)
2480
2481 @ A single computation might use several subroutine calls, and it is
2482 desirable to avoid producing multiple error messages in case of arithmetic
2483 overflow. So the routines below set the global variable |arith_error| to |true|
2484 instead of reporting errors directly to the user.
2485 @^overflow in arithmetic@>
2486
2487 @<Glob...@>=
2488 boolean arith_error; /* has arithmetic overflow occurred recently? */
2489
2490 @ @<Allocate or ...@>=
2491 mp->arith_error=false;
2492
2493 @ At crucial points the program will say |check_arith|, to test if
2494 an arithmetic error has been detected.
2495
2496 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2497
2498 @c 
2499 static void mp_clear_arith (MP mp) { 
2500   print_err("Arithmetic overflow");
2501 @.Arithmetic overflow@>
2502   help4("Uh, oh. A little while ago one of the quantities that I was",
2503        "computing got too large, so I'm afraid your answers will be",
2504        "somewhat askew. You'll probably have to adopt different",
2505        "tactics next time. But I shall try to carry on anyway.");
2506   mp_error(mp); 
2507   mp->arith_error=false;
2508 }
2509
2510 @ Addition is not always checked to make sure that it doesn't overflow,
2511 but in places where overflow isn't too unlikely the |slow_add| routine
2512 is used.
2513
2514 @c static integer mp_slow_add (MP mp,integer x, integer y) { 
2515   if ( x>=0 )  {
2516     if ( y<=el_gordo-x ) { 
2517       return x+y;
2518     } else  { 
2519       mp->arith_error=true; 
2520           return el_gordo;
2521     }
2522   } else  if ( -y<=el_gordo+x ) {
2523     return x+y;
2524   } else { 
2525     mp->arith_error=true; 
2526         return -el_gordo;
2527   }
2528 }
2529
2530 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2531 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2532 positions from the right end of a binary computer word.
2533
2534 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2535 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2536 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2537 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2538 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2539 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2540
2541 @<Types...@>=
2542 typedef integer scaled; /* this type is used for scaled integers */
2543
2544 @ The following function is used to create a scaled integer from a given decimal
2545 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2546 given in |dig[i]|, and the calculation produces a correctly rounded result.
2547
2548 @c 
2549 static scaled mp_round_decimals (MP mp,quarterword k) {
2550   /* converts a decimal fraction */
2551  unsigned a = 0; /* the accumulator */
2552  while ( k-->0 ) { 
2553     a=(a+mp->dig[k]*two) / 10;
2554   }
2555   return (scaled)halfp(a+1);
2556 }
2557
2558 @ Conversely, here is a procedure analogous to |print_int|. If the output
2559 of this procedure is subsequently read by \MP\ and converted by the
2560 |round_decimals| routine above, it turns out that the original value will
2561 be reproduced exactly. A decimal point is printed only if the value is
2562 not an integer. If there is more than one way to print the result with
2563 the optimum number of digits following the decimal point, the closest
2564 possible value is given.
2565
2566 The invariant relation in the \&{repeat} loop is that a sequence of
2567 decimal digits yet to be printed will yield the original number if and only if
2568 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2569 We can stop if and only if $f=0$ satisfies this condition; the loop will
2570 terminate before $s$ can possibly become zero.
2571
2572 @<Basic printing...@>=
2573 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2574   scaled delta; /* amount of allowable inaccuracy */
2575   if ( s<0 ) { 
2576         mp_print_char(mp, xord('-')); 
2577     negate(s); /* print the sign, if negative */
2578   }
2579   mp_print_int(mp, s / unity); /* print the integer part */
2580   s=10*(s % unity)+5;
2581   if ( s!=5 ) { 
2582     delta=10; 
2583     mp_print_char(mp, xord('.'));
2584     do {  
2585       if ( delta>unity )
2586         s=s+0100000-(delta / 2); /* round the final digit */
2587       mp_print_char(mp, xord('0'+(s / unity))); 
2588       s=10*(s % unity); 
2589       delta=delta*10;
2590     } while (s>delta);
2591   }
2592 }
2593
2594 @ We often want to print two scaled quantities in parentheses,
2595 separated by a comma.
2596
2597 @<Basic printing...@>=
2598 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2599   mp_print_char(mp, xord('(')); 
2600   mp_print_scaled(mp, x); 
2601   mp_print_char(mp, xord(',')); 
2602   mp_print_scaled(mp, y);
2603   mp_print_char(mp, xord(')'));
2604 }
2605
2606 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2607 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2608 arithmetic with 28~significant bits of precision. A |fraction| denotes
2609 a scaled integer whose binary point is assumed to be 28 bit positions
2610 from the right.
2611
2612 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2613 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2614 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2615 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2616 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2617
2618 @<Types...@>=
2619 typedef integer fraction; /* this type is used for scaled fractions */
2620
2621 @ In fact, the two sorts of scaling discussed above aren't quite
2622 sufficient; \MP\ has yet another, used internally to keep track of angles
2623 in units of $2^{-20}$ degrees.
2624
2625 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2626 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2627 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2628 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2629
2630 @<Types...@>=
2631 typedef integer angle; /* this type is used for scaled angles */
2632
2633 @ The |make_fraction| routine produces the |fraction| equivalent of
2634 |p/q|, given integers |p| and~|q|; it computes the integer
2635 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2636 positive. If |p| and |q| are both of the same scaled type |t|,
2637 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2638 and it's also possible to use the subroutine ``backwards,'' using
2639 the relation |make_fraction(t,fraction)=t| between scaled types.
2640
2641 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2642 sets |arith_error:=true|. Most of \MP's internal computations have
2643 been designed to avoid this sort of error.
2644
2645 If this subroutine were programmed in assembly language on a typical
2646 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2647 double-precision product can often be input to a fixed-point division
2648 instruction. But when we are restricted to int-eger arithmetic it
2649 is necessary either to resort to multiple-precision maneuvering
2650 or to use a simple but slow iteration. The multiple-precision technique
2651 would be about three times faster than the code adopted here, but it
2652 would be comparatively long and tricky, involving about sixteen
2653 additional multiplications and divisions.
2654
2655 This operation is part of \MP's ``inner loop''; indeed, it will
2656 consume nearly 10\pct! of the running time (exclusive of input and output)
2657 if the code below is left unchanged. A machine-dependent recoding
2658 will therefore make \MP\ run faster. The present implementation
2659 is highly portable, but slow; it avoids multiplication and division
2660 except in the initial stage. System wizards should be careful to
2661 replace it with a routine that is guaranteed to produce identical
2662 results in all cases.
2663 @^system dependencies@>
2664
2665 As noted below, a few more routines should also be replaced by machine-dependent
2666 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2667 such changes aren't advisable; simplicity and robustness are
2668 preferable to trickery, unless the cost is too high.
2669 @^inner loop@>
2670
2671 @<Internal library declarations@>=
2672 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2673
2674 @ @<Declarations@>=
2675 static fraction mp_make_fraction (MP mp,integer p, integer q);
2676
2677 @ If FIXPT is not defined, we need these preprocessor values
2678
2679 @d TWEXP31  2147483648.0
2680 @d TWEXP28  268435456.0
2681 @d TWEXP16 65536.0
2682 @d TWEXP_16 (1.0/65536.0)
2683 @d TWEXP_28 (1.0/268435456.0)
2684
2685
2686 @c 
2687 fraction mp_make_fraction (MP mp,integer p, integer q) {
2688   fraction i;
2689   if ( q==0 ) mp_confusion(mp, "/");
2690 @:this can't happen /}{\quad \./@>
2691 #ifdef FIXPT
2692 {
2693   integer f; /* the fraction bits, with a leading 1 bit */
2694   integer n; /* the integer part of $\vert p/q\vert$ */
2695   boolean negative = false; /* should the result be negated? */
2696   if ( p<0 ) {
2697     negate(p); negative=true;
2698   }
2699   if ( q<0 ) { 
2700     negate(q); negative = ! negative;
2701   }
2702   n=p / q; p=p % q;
2703   if ( n>=8 ){ 
2704     mp->arith_error=true;
2705     i= ( negative ? -el_gordo : el_gordo);
2706   } else { 
2707     n=(n-1)*fraction_one;
2708     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2709     i = (negative ? (-(f+n)) : (f+n));
2710   }
2711 }
2712 #else /* FIXPT */
2713   {
2714     register double d;
2715         d = TWEXP28 * (double)p /(double)q;
2716         if ((p^q) >= 0) {
2717                 d += 0.5;
2718                 if (d>=TWEXP31) {mp->arith_error=true; return el_gordo;}
2719                 i = (integer) d;
2720                 if (d==(double)i && ( ((q>0 ? -q : q)&077777)
2721                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2722         } else {
2723                 d -= 0.5;
2724                 if (d<= -TWEXP31) {mp->arith_error=true; return -el_gordo;}
2725                 i = (integer) d;
2726                 if (d==(double)i && ( ((q>0 ? q : -q)&077777)
2727                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2728         }
2729   }
2730 #endif /* FIXPT */
2731   return i;
2732 }
2733
2734 @ The |repeat| loop here preserves the following invariant relations
2735 between |f|, |p|, and~|q|:
2736 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2737 $p_0$ is the original value of~$p$.
2738
2739 Notice that the computation specifies
2740 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2741 Let us hope that optimizing compilers do not miss this point; a
2742 special variable |be_careful| is used to emphasize the necessary
2743 order of computation. Optimizing compilers should keep |be_careful|
2744 in a register, not store it in memory.
2745 @^inner loop@>
2746
2747 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2748 {
2749   integer be_careful; /* disables certain compiler optimizations */
2750   f=1;
2751   do {  
2752     be_careful=p-q; p=be_careful+p;
2753     if ( p>=0 ) { 
2754       f=f+f+1;
2755     } else  { 
2756       f+=f; p=p+q;
2757     }
2758   } while (f<fraction_one);
2759   be_careful=p-q;
2760   if ( be_careful+p>=0 ) incr(f);
2761 }
2762
2763 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2764 given integer~|q| by a fraction~|f|. When the operands are positive, it
2765 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2766 of |q| and~|f|.
2767
2768 This routine is even more ``inner loopy'' than |make_fraction|;
2769 the present implementation consumes almost 20\pct! of \MP's computation
2770 time during typical jobs, so a machine-language substitute is advisable.
2771 @^inner loop@> @^system dependencies@>
2772
2773 @<Internal library declarations@>=
2774 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2775
2776 @ @c 
2777 #ifdef FIXPT
2778 integer mp_take_fraction (MP mp,integer q, fraction f) {
2779   integer p; /* the fraction so far */
2780   boolean negative; /* should the result be negated? */
2781   integer n; /* additional multiple of $q$ */
2782   integer be_careful; /* disables certain compiler optimizations */
2783   @<Reduce to the case that |f>=0| and |q>=0|@>;
2784   if ( f<fraction_one ) { 
2785     n=0;
2786   } else { 
2787     n=f / fraction_one; f=f % fraction_one;
2788     if ( q<=el_gordo / n ) { 
2789       n=n*q ; 
2790     } else { 
2791       mp->arith_error=true; n=el_gordo;
2792     }
2793   }
2794   f=f+fraction_one;
2795   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2796   be_careful=n-el_gordo;
2797   if ( be_careful+p>0 ){ 
2798     mp->arith_error=true; n=el_gordo-p;
2799   }
2800   if ( negative ) 
2801         return (-(n+p));
2802   else 
2803     return (n+p);
2804 #else /* FIXPT */
2805 integer mp_take_fraction (MP mp,integer p, fraction q) {
2806     register double d;
2807         register integer i;
2808         d = (double)p * (double)q * TWEXP_28;
2809         if ((p^q) >= 0) {
2810                 d += 0.5;
2811                 if (d>=TWEXP31) {
2812                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2813                                 mp->arith_error = true;
2814                         return el_gordo;
2815                 }
2816                 i = (integer) d;
2817                 if (d==(double)i && (((p&077777)*(q&077777))&040000)!=0) --i;
2818         } else {
2819                 d -= 0.5;
2820                 if (d<= -TWEXP31) {
2821                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2822                                 mp->arith_error = true;
2823                         return -el_gordo;
2824                 }
2825                 i = (integer) d;
2826                 if (d==(double)i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2827         }
2828         return i;
2829 #endif /* FIXPT */
2830 }
2831
2832 @ @<Reduce to the case that |f>=0| and |q>=0|@>=
2833 if ( f>=0 ) {
2834   negative=false;
2835 } else { 
2836   negate( f); negative=true;
2837 }
2838 if ( q<0 ) { 
2839   negate(q); negative=! negative;
2840 }
2841
2842 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2843 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2844 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2845 @^inner loop@>
2846
2847 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2848 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2849 if ( q<fraction_four ) {
2850   do {  
2851     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2852     f=halfp(f);
2853   } while (f!=1);
2854 } else  {
2855   do {  
2856     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2857     f=halfp(f);
2858   } while (f!=1);
2859 }
2860
2861
2862 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2863 analogous to |take_fraction| but with a different scaling.
2864 Given positive operands, |take_scaled|
2865 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2866
2867 Once again it is a good idea to use a machine-language replacement if
2868 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2869 when the Computer Modern fonts are being generated.
2870 @^inner loop@>
2871
2872 @c 
2873 #ifdef FIXPT
2874 integer mp_take_scaled (MP mp,integer q, scaled f) {
2875   integer p; /* the fraction so far */
2876   boolean negative; /* should the result be negated? */
2877   integer n; /* additional multiple of $q$ */
2878   integer be_careful; /* disables certain compiler optimizations */
2879   @<Reduce to the case that |f>=0| and |q>=0|@>;
2880   if ( f<unity ) { 
2881     n=0;
2882   } else  { 
2883     n=f / unity; f=f % unity;
2884     if ( q<=el_gordo / n ) {
2885       n=n*q;
2886     } else  { 
2887       mp->arith_error=true; n=el_gordo;
2888     }
2889   }
2890   f=f+unity;
2891   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2892   be_careful=n-el_gordo;
2893   if ( be_careful+p>0 ) { 
2894     mp->arith_error=true; n=el_gordo-p;
2895   }
2896   return ( negative ?(-(n+p)) :(n+p));
2897 #else /* FIXPT */
2898 integer mp_take_scaled (MP mp,integer p, scaled q) {
2899     register double d;
2900         register integer i;
2901         d = (double)p * (double)q * TWEXP_16;
2902         if ((p^q) >= 0) {
2903                 d += 0.5;
2904                 if (d>=TWEXP31) {
2905                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2906                                 mp->arith_error = true;
2907                         return el_gordo;
2908                 }
2909                 i = (integer) d;
2910                 if (d==(double)i && (((p&077777)*(q&077777))&040000)!=0) --i;
2911         } else {
2912                 d -= 0.5;
2913                 if (d<= -TWEXP31) {
2914                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2915                                 mp->arith_error = true;
2916                         return -el_gordo;
2917                 }
2918                 i = (integer) d;
2919                 if (d==(double)i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2920         }
2921         return i;
2922 #endif /* FIXPT */
2923 }
2924
2925 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2926 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2927 @^inner loop@>
2928 if ( q<fraction_four ) {
2929   do {  
2930     p = (odd(f) ? halfp(p+q) : halfp(p));
2931     f=halfp(f);
2932   } while (f!=1);
2933 } else {
2934   do {  
2935     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2936     f=halfp(f);
2937   } while (f!=1);
2938 }
2939
2940 @ For completeness, there's also |make_scaled|, which computes a
2941 quotient as a |scaled| number instead of as a |fraction|.
2942 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2943 operands are positive. \ (This procedure is not used especially often,
2944 so it is not part of \MP's inner loop.)
2945
2946 @<Internal library ...@>=
2947 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2948
2949 @ @c 
2950 scaled mp_make_scaled (MP mp,integer p, integer q) {
2951   register integer i;
2952   if ( q==0 ) mp_confusion(mp, "/");
2953 @:this can't happen /}{\quad \./@>
2954   {
2955 #ifdef FIXPT 
2956     integer f; /* the fraction bits, with a leading 1 bit */
2957     integer n; /* the integer part of $\vert p/q\vert$ */
2958     boolean negative; /* should the result be negated? */
2959     integer be_careful; /* disables certain compiler optimizations */
2960     if ( p>=0 ) negative=false;
2961     else  { negate(p); negative=true; };
2962     if ( q<0 ) { 
2963       negate(q); negative=! negative;
2964     }
2965     n=p / q; p=p % q;
2966     if ( n>=0100000 ) { 
2967       mp->arith_error=true;
2968       return (negative ? (-el_gordo) : el_gordo);
2969     } else  { 
2970       n=(n-1)*unity;
2971       @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2972       i = (negative ? (-(f+n)) :(f+n));
2973     }
2974 #else /* FIXPT */
2975     register double d;
2976         d = TWEXP16 * (double)p /(double)q;
2977         if ((p^q) >= 0) {
2978                 d += 0.5;
2979                 if (d>=TWEXP31) {mp->arith_error=true; return el_gordo;}
2980                 i = (integer) d;
2981                 if (d==(double)i && ( ((q>0 ? -q : q)&077777)
2982                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2983         } else {
2984                 d -= 0.5;
2985                 if (d<= -TWEXP31) {mp->arith_error=true; return -el_gordo;}
2986                 i = (integer) d;
2987                 if (d==(double)i && ( ((q>0 ? q : -q)&077777)
2988                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2989         }
2990 #endif /* FIXPT */
2991   }
2992   return i;
2993 }
2994
2995 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
2996 f=1;
2997 do {  
2998   be_careful=p-q; p=be_careful+p;
2999   if ( p>=0 ) f=f+f+1;
3000   else  { f+=f; p=p+q; };
3001 } while (f<unity);
3002 be_careful=p-q;
3003 if ( be_careful+p>=0 ) incr(f)
3004
3005 @ Here is a typical example of how the routines above can be used.
3006 It computes the function
3007 $${1\over3\tau}f(\theta,\phi)=
3008 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3009  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3010 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3011 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3012 fudge factor for placing the first control point of a curve that starts
3013 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3014 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3015
3016 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3017 (It's a sum of eight terms whose absolute values can be bounded using
3018 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3019 is positive; and since the tension $\tau$ is constrained to be at least
3020 $3\over4$, the numerator is less than $16\over3$. The denominator is
3021 nonnegative and at most~6.  Hence the fixed-point calculations below
3022 are guaranteed to stay within the bounds of a 32-bit computer word.
3023
3024 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3025 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3026 $\sin\phi$, and $\cos\phi$, respectively.
3027
3028 @c 
3029 static fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3030                       fraction cf, scaled t) {
3031   integer acc,num,denom; /* registers for intermediate calculations */
3032   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3033   acc=mp_take_fraction(mp, acc,ct-cf);
3034   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3035                    /* $2^{28}\sqrt2\approx379625062.497$ */
3036   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3037                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3038                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3039   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3040   /* |make_scaled(fraction,scaled)=fraction| */
3041   if ( num / 4>=denom ) 
3042     return fraction_four;
3043   else 
3044     return mp_make_fraction(mp, num, denom);
3045 }
3046
3047 @ The following somewhat different subroutine tests rigorously if $ab$ is
3048 greater than, equal to, or less than~$cd$,
3049 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3050 The result is $+1$, 0, or~$-1$ in the three respective cases.
3051
3052 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3053
3054 @c 
3055 static integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3056   integer q,r; /* temporary registers */
3057   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3058   while (1) { 
3059     q = a / d; r = c / b;
3060     if ( q!=r )
3061       return ( q>r ? 1 : -1);
3062     q = a % d; r = c % b;
3063     if ( r==0 )
3064       return (q ? 1 : 0);
3065     if ( q==0 ) return -1;
3066     a=b; b=q; c=d; d=r;
3067   } /* now |a>d>0| and |c>b>0| */
3068 }
3069
3070 @ @<Reduce to the case that |a...@>=
3071 if ( a<0 ) { negate(a); negate(b);  };
3072 if ( c<0 ) { negate(c); negate(d);  };
3073 if ( d<=0 ) { 
3074   if ( b>=0 ) {
3075     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3076     else return 1;
3077   }
3078   if ( d==0 )
3079     return ( a==0 ? 0 : -1);
3080   q=a; a=c; c=q; q=-b; b=-d; d=q;
3081 } else if ( b<=0 ) { 
3082   if ( b<0 ) if ( a>0 ) return -1;
3083   return (c==0 ? 0 : -1);
3084 }
3085
3086 @ We conclude this set of elementary routines with some simple rounding
3087 and truncation operations.
3088
3089 @<Internal library declarations@>=
3090 #define mp_floor_scaled(M,i) ((i)&(-65536))
3091 #define mp_round_unscaled(M,i) (((i/32768)+1)/2)
3092 #define mp_round_fraction(M,i) (((i/2048)+1)/2)
3093
3094
3095 @* \[8] Algebraic and transcendental functions.
3096 \MP\ computes all of the necessary special functions from scratch, without
3097 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3098
3099 @ To get the square root of a |scaled| number |x|, we want to calculate
3100 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3101 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3102 determines $s$ by an iterative method that maintains the invariant
3103 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3104 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3105 might, however, be zero at the start of the first iteration.
3106
3107 @<Declarations@>=
3108 static scaled mp_square_rt (MP mp,scaled x) ;
3109
3110 @ @c 
3111 scaled mp_square_rt (MP mp,scaled x) {
3112   quarterword k; /* iteration control counter */
3113   integer y; /* register for intermediate calculations */
3114   unsigned q; /* register for intermediate calculations */
3115   if ( x<=0 ) { 
3116     @<Handle square root of zero or negative argument@>;
3117   } else { 
3118     k=23; q=2;
3119     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3120       decr(k); x=x+x+x+x;
3121     }
3122     if ( x<fraction_four ) y=0;
3123     else  { x=x-fraction_four; y=1; };
3124     do {  
3125       @<Decrease |k| by 1, maintaining the invariant
3126       relations between |x|, |y|, and~|q|@>;
3127     } while (k!=0);
3128     return (scaled)(halfp(q));
3129   }
3130 }
3131
3132 @ @<Handle square root of zero...@>=
3133
3134   if ( x<0 ) { 
3135     print_err("Square root of ");
3136 @.Square root...replaced by 0@>
3137     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3138     help2("Since I don't take square roots of negative numbers,",
3139           "I'm zeroing this one. Proceed, with fingers crossed.");
3140     mp_error(mp);
3141   };
3142   return 0;
3143 }
3144
3145 @ @<Decrease |k| by 1, maintaining...@>=
3146 x+=x; y+=y;
3147 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3148   x=x-fraction_four; y++;
3149 };
3150 x+=x; y=y+y-q; q+=q;
3151 if ( x>=fraction_four ) { x=x-fraction_four; y++; };
3152 if ( y>(int)q ){ y=y-q; q=q+2; }
3153 else if ( y<=0 )  { q=q-2; y=y+q;  };
3154 decr(k)
3155
3156 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3157 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3158 @^Moler, Cleve Barry@>
3159 @^Morrison, Donald Ross@>
3160 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3161 in such a way that their Pythagorean sum remains invariant, while the
3162 smaller argument decreases.
3163
3164 @<Internal library ...@>=
3165 integer mp_pyth_add (MP mp,integer a, integer b);
3166
3167
3168 @ @c 
3169 integer mp_pyth_add (MP mp,integer a, integer b) {
3170   fraction r; /* register used to transform |a| and |b| */
3171   boolean big; /* is the result dangerously near $2^{31}$? */
3172   a=abs(a); b=abs(b);
3173   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3174   if ( b>0 ) {
3175     if ( a<fraction_two ) {
3176       big=false;
3177     } else { 
3178       a=a / 4; b=b / 4; big=true;
3179     }; /* we reduced the precision to avoid arithmetic overflow */
3180     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3181     if ( big ) {
3182       if ( a<fraction_two ) {
3183         a=a+a+a+a;
3184       } else  { 
3185         mp->arith_error=true; a=el_gordo;
3186       };
3187     }
3188   }
3189   return a;
3190 }
3191
3192 @ The key idea here is to reflect the vector $(a,b)$ about the
3193 line through $(a,b/2)$.
3194
3195 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3196 while (1) {  
3197   r=mp_make_fraction(mp, b,a);
3198   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3199   if ( r==0 ) break;
3200   r=mp_make_fraction(mp, r,fraction_four+r);
3201   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3202 }
3203
3204
3205 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3206 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3207
3208 @c 
3209 static integer mp_pyth_sub (MP mp,integer a, integer b) {
3210   fraction r; /* register used to transform |a| and |b| */
3211   boolean big; /* is the input dangerously near $2^{31}$? */
3212   a=abs(a); b=abs(b);
3213   if ( a<=b ) {
3214     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3215   } else { 
3216     if ( a<fraction_four ) {
3217       big=false;
3218     } else  { 
3219       a=(integer)halfp(a); b=(integer)halfp(b); big=true;
3220     }
3221     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3222     if ( big ) double(a);
3223   }
3224   return a;
3225 }
3226
3227 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3228 while (1) { 
3229   r=mp_make_fraction(mp, b,a);
3230   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3231   if ( r==0 ) break;
3232   r=mp_make_fraction(mp, r,fraction_four-r);
3233   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3234 }
3235
3236 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3237
3238   if ( a<b ){ 
3239     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3240     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3241     mp_print(mp, " has been replaced by 0");
3242 @.Pythagorean...@>
3243     help2("Since I don't take square roots of negative numbers,",
3244           "I'm zeroing this one. Proceed, with fingers crossed.");
3245     mp_error(mp);
3246   }
3247   a=0;
3248 }
3249
3250 @ The subroutines for logarithm and exponential involve two tables.
3251 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3252 a bit more calculation, which the author claims to have done correctly:
3253 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3254 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3255 nearest integer.
3256
3257 @d two_to_the(A) (1<<(unsigned)(A))
3258
3259 @<Declarations@>=
3260 static const integer spec_log[29] = { 0, /* special logarithms */
3261 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3262 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3263 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3264
3265 @ @<Local variables for initialization@>=
3266 integer k; /* all-purpose loop index */
3267
3268
3269 @ Here is the routine that calculates $2^8$ times the natural logarithm
3270 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3271 when |x| is a given positive integer.
3272
3273 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3274 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3275 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3276 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3277 during the calculation, and sixteen auxiliary bits to extend |y| are
3278 kept in~|z| during the initial argument reduction. (We add
3279 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3280 not become negative; also, the actual amount subtracted from~|y| is~96,
3281 not~100, because we want to add~4 for rounding before the final division by~8.)
3282
3283 @c 
3284 static scaled mp_m_log (MP mp,scaled x) {
3285   integer y,z; /* auxiliary registers */
3286   integer k; /* iteration counter */
3287   if ( x<=0 ) {
3288      @<Handle non-positive logarithm@>;
3289   } else  { 
3290     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3291     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3292     while ( x<fraction_four ) {
3293        double(x); y-=93032639; z-=48782;
3294     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3295     y=y+(z / unity); k=2;
3296     while ( x>fraction_four+4 ) {
3297       @<Increase |k| until |x| can be multiplied by a
3298         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3299     }
3300     return (y / 8);
3301   }
3302 }
3303
3304 @ @<Increase |k| until |x| can...@>=
3305
3306   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3307   while ( x<fraction_four+z ) { z=halfp(z+1); k++; };
3308   y+=spec_log[k]; x-=z;
3309 }
3310
3311 @ @<Handle non-positive logarithm@>=
3312
3313   print_err("Logarithm of ");
3314 @.Logarithm...replaced by 0@>
3315   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3316   help2("Since I don't take logs of non-positive numbers,",
3317         "I'm zeroing this one. Proceed, with fingers crossed.");
3318   mp_error(mp); 
3319   return 0;
3320 }
3321
3322 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3323 when |x| is |scaled|. The result is an integer approximation to
3324 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3325
3326 @c 
3327 static scaled mp_m_exp (MP mp,scaled x) {
3328   quarterword k; /* loop control index */
3329   integer y,z; /* auxiliary registers */
3330   if ( x>174436200 ) {
3331     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3332     mp->arith_error=true; 
3333     return el_gordo;
3334   } else if ( x<-197694359 ) {
3335         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3336     return 0;
3337   } else { 
3338     if ( x<=0 ) { 
3339        z=-8*x; y=04000000; /* $y=2^{20}$ */
3340     } else { 
3341       if ( x<=127919879 ) { 
3342         z=1023359037-8*x;
3343         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3344       } else {
3345        z=8*(174436200-x); /* |z| is always nonnegative */
3346       }
3347       y=el_gordo;
3348     };
3349     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3350     if ( x<=127919879 ) 
3351        return ((y+8) / 16);
3352      else 
3353        return y;
3354   }
3355 }
3356
3357 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3358 to multiplying |y| by $1-2^{-k}$.
3359
3360 A subtle point (which had to be checked) was that if $x=127919879$, the
3361 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3362 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3363 and by~16 when |k=27|.
3364
3365 @<Multiply |y| by...@>=
3366 k=1;
3367 while ( z>0 ) { 
3368   while ( z>=spec_log[k] ) { 
3369     z-=spec_log[k];
3370     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3371   }
3372   k++;
3373 }
3374
3375 @ The trigonometric subroutines use an auxiliary table such that
3376 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3377 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3378
3379 @<Declarations@>=
3380 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3381 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3382 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3383
3384 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3385 returns the |angle| whose tangent points in the direction $(x,y)$.
3386 This subroutine first determines the correct octant, then solves the
3387 problem for |0<=y<=x|, then converts the result appropriately to
3388 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3389 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3390 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3391
3392 The octants are represented in a ``Gray code,'' since that turns out
3393 to be computationally simplest.
3394
3395 @d negate_x 1
3396 @d negate_y 2
3397 @d switch_x_and_y 4
3398 @d first_octant 1
3399 @d second_octant (first_octant+switch_x_and_y)
3400 @d third_octant (first_octant+switch_x_and_y+negate_x)
3401 @d fourth_octant (first_octant+negate_x)
3402 @d fifth_octant (first_octant+negate_x+negate_y)
3403 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3404 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3405 @d eighth_octant (first_octant+negate_y)
3406
3407 @c 
3408 static angle mp_n_arg (MP mp,integer x, integer y) {
3409   angle z; /* auxiliary register */
3410   integer t; /* temporary storage */
3411   quarterword k; /* loop counter */
3412   int octant; /* octant code */
3413   if ( x>=0 ) {
3414     octant=first_octant;
3415   } else { 
3416     negate(x); octant=first_octant+negate_x;
3417   }
3418   if ( y<0 ) { 
3419     negate(y); octant=octant+negate_y;
3420   }
3421   if ( x<y ) { 
3422     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3423   }
3424   if ( x==0 ) { 
3425     @<Handle undefined arg@>; 
3426   } else { 
3427     @<Set variable |z| to the arg of $(x,y)$@>;
3428     @<Return an appropriate answer based on |z| and |octant|@>;
3429   }
3430 }
3431
3432 @ @<Handle undefined arg@>=
3433
3434   print_err("angle(0,0) is taken as zero");
3435 @.angle(0,0)...zero@>
3436   help2("The `angle' between two identical points is undefined.",
3437         "I'm zeroing this one. Proceed, with fingers crossed.");
3438   mp_error(mp); 
3439   return 0;
3440 }
3441
3442 @ @<Return an appropriate answer...@>=
3443 switch (octant) {
3444 case first_octant: return z;
3445 case second_octant: return (ninety_deg-z);
3446 case third_octant: return (ninety_deg+z);
3447 case fourth_octant: return (one_eighty_deg-z);
3448 case fifth_octant: return (z-one_eighty_deg);
3449 case sixth_octant: return (-z-ninety_deg);
3450 case seventh_octant: return (z-ninety_deg);
3451 case eighth_octant: return (-z);
3452 }; /* there are no other cases */
3453 return 0
3454
3455 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3456 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3457 will be made.
3458
3459 @<Set variable |z| to the arg...@>=
3460 while ( x>=fraction_two ) { 
3461   x=halfp(x); y=halfp(y);
3462 }
3463 z=0;
3464 if ( y>0 ) { 
3465  while ( x<fraction_one ) { 
3466     x+=x; y+=y; 
3467  };
3468  @<Increase |z| to the arg of $(x,y)$@>;
3469 }
3470
3471 @ During the calculations of this section, variables |x| and~|y|
3472 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3473 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3474 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3475 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3476 coordinates whose angle has decreased by~$\phi$; in the special case
3477 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3478 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3479 @^Meggitt, John E.@>
3480 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3481
3482 The initial value of |x| will be multiplied by at most
3483 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3484 there is no chance of integer overflow.
3485
3486 @<Increase |z|...@>=
3487 k=0;
3488 do {  
3489   y+=y; k++;
3490   if ( y>x ){ 
3491     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3492   };
3493 } while (k!=15);
3494 do {  
3495   y+=y; k++;
3496   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3497 } while (k!=26)
3498
3499 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3500 and cosine of that angle. The results of this routine are
3501 stored in global integer variables |n_sin| and |n_cos|.
3502
3503 @<Glob...@>=
3504 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3505
3506 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3507 the purpose of |n_sin_cos(z)| is to set
3508 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3509 for some rather large number~|r|. The maximum of |x| and |y|
3510 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3511 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3512
3513 @c 
3514 static void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3515                                        and cosine */ 
3516   quarterword k; /* loop control variable */
3517   int q; /* specifies the quadrant */
3518   fraction r; /* magnitude of |(x,y)| */
3519   integer x,y,t; /* temporary registers */
3520   while ( z<0 ) z=z+three_sixty_deg;
3521   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3522   q=z / forty_five_deg; z=z % forty_five_deg;
3523   x=fraction_one; y=x;
3524   if ( ! odd(q) ) z=forty_five_deg-z;
3525   @<Subtract angle |z| from |(x,y)|@>;
3526   @<Convert |(x,y)| to the octant determined by~|q|@>;
3527   r=mp_pyth_add(mp, x,y); 
3528   mp->n_cos=mp_make_fraction(mp, x,r); 
3529   mp->n_sin=mp_make_fraction(mp, y,r);
3530 }
3531
3532 @ In this case the octants are numbered sequentially.
3533
3534 @<Convert |(x,...@>=
3535 switch (q) {
3536 case 0: break;
3537 case 1: t=x; x=y; y=t; break;
3538 case 2: t=x; x=-y; y=t; break;
3539 case 3: negate(x); break;
3540 case 4: negate(x); negate(y); break;
3541 case 5: t=x; x=-y; y=-t; break;
3542 case 6: t=x; x=y; y=-t; break;
3543 case 7: negate(y); break;
3544 } /* there are no other cases */
3545
3546 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3547 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3548 that this loop is guaranteed to terminate before the (nonexistent) value
3549 |spec_atan[27]| would be required.
3550
3551 @<Subtract angle |z|...@>=
3552 k=1;
3553 while ( z>0 ){ 
3554   if ( z>=spec_atan[k] ) { 
3555     z=z-spec_atan[k]; t=x;
3556     x=t+y / two_to_the(k);
3557     y=y-t / two_to_the(k);
3558   }
3559   k++;
3560 }
3561 if ( y<0 ) y=0 /* this precaution may never be needed */
3562
3563 @ And now let's complete our collection of numeric utility routines
3564 by considering random number generation.
3565 \MP\ generates pseudo-random numbers with the additive scheme recommended
3566 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3567 results are random fractions between 0 and |fraction_one-1|, inclusive.
3568
3569 There's an auxiliary array |randoms| that contains 55 pseudo-random
3570 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3571 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3572 The global variable |j_random| tells which element has most recently
3573 been consumed.
3574 The global variable |random_seed| was introduced in version 0.9,
3575 for the sole reason of stressing the fact that the initial value of the
3576 random seed is system-dependant. The initialization code below will initialize
3577 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3578 is not good enough on modern fast machines that are capable of running
3579 multiple MetaPost processes within the same second.
3580 @^system dependencies@>
3581
3582 @<Glob...@>=
3583 fraction randoms[55]; /* the last 55 random values generated */
3584 int j_random; /* the number of unused |randoms| */
3585
3586 @ @<Option variables@>=
3587 int random_seed; /* the default random seed */
3588
3589 @ @<Allocate or initialize ...@>=
3590 mp->random_seed = (scaled)opt->random_seed;
3591
3592 @ To consume a random fraction, the program below will say `|next_random|'
3593 and then it will fetch |randoms[j_random]|.
3594
3595 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3596   else decr(mp->j_random); }
3597
3598 @c 
3599 static void mp_new_randoms (MP mp) {
3600   int k; /* index into |randoms| */
3601   fraction x; /* accumulator */
3602   for (k=0;k<=23;k++) { 
3603    x=mp->randoms[k]-mp->randoms[k+31];
3604     if ( x<0 ) x=x+fraction_one;
3605     mp->randoms[k]=x;
3606   }
3607   for (k=24;k<= 54;k++){ 
3608     x=mp->randoms[k]-mp->randoms[k-24];
3609     if ( x<0 ) x=x+fraction_one;
3610     mp->randoms[k]=x;
3611   }
3612   mp->j_random=54;
3613 }
3614
3615 @ @<Declarations@>=
3616 static void mp_init_randoms (MP mp,scaled seed);
3617
3618 @ To initialize the |randoms| table, we call the following routine.
3619
3620 @c 
3621 void mp_init_randoms (MP mp,scaled seed) {
3622   fraction j,jj,k; /* more or less random integers */
3623   int i; /* index into |randoms| */
3624   j=abs(seed);
3625   while ( j>=fraction_one ) j=halfp(j);
3626   k=1;
3627   for (i=0;i<=54;i++ ){ 
3628     jj=k; k=j-k; j=jj;
3629     if ( k<0 ) k=k+fraction_one;
3630     mp->randoms[(i*21)% 55]=j;
3631   }
3632   mp_new_randoms(mp); 
3633   mp_new_randoms(mp); 
3634   mp_new_randoms(mp); /* ``warm up'' the array */
3635 }
3636
3637 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3638 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3639
3640 Note that the call of |take_fraction| will produce the values 0 and~|x|
3641 with about half the probability that it will produce any other particular
3642 values between 0 and~|x|, because it rounds its answers.
3643
3644 @c 
3645 static scaled mp_unif_rand (MP mp,scaled x) {
3646   scaled y; /* trial value */
3647   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3648   if ( y==abs(x) ) return 0;
3649   else if ( x>0 ) return y;
3650   else return (-y);
3651 }
3652
3653 @ Finally, a normal deviate with mean zero and unit standard deviation
3654 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3655 {\sl The Art of Computer Programming\/}).
3656
3657 @c 
3658 static scaled mp_norm_rand (MP mp) {
3659   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3660   do { 
3661     do {  
3662       next_random;
3663       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3664       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3665       next_random; u=mp->randoms[mp->j_random];
3666     } while (abs(x)>=u);
3667     x=mp_make_fraction(mp, x,u);
3668     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3669   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3670   return x;
3671 }
3672
3673 @* \[9] Packed data.
3674 In order to make efficient use of storage space, \MP\ bases its major data
3675 structures on a |memory_word|, which contains either a (signed) integer,
3676 possibly scaled, or a small number of fields that are one half or one
3677 quarter of the size used for storing integers.
3678
3679 If |x| is a variable of type |memory_word|, it contains up to four
3680 fields that can be referred to as follows:
3681 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3682 |x|&.|int|&(an |integer|)\cr
3683 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3684 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3685 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3686   field)\cr
3687 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3688   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3689 This is somewhat cumbersome to write, and not very readable either, but
3690 macros will be used to make the notation shorter and more transparent.
3691 The code below gives a formal definition of |memory_word| and
3692 its subsidiary types, using packed variant records. \MP\ makes no
3693 assumptions about the relative positions of the fields within a word.
3694
3695 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3696 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3697
3698 @ Here are the inequalities that the quarterword and halfword values
3699 must satisfy (or rather, the inequalities that they mustn't satisfy):
3700
3701 @<Check the ``constant''...@>=
3702 if (mp->ini_version) {
3703   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3704 } else {
3705   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3706 }
3707 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3708 if ( mp->max_strings>max_halfword ) mp->bad=13;
3709
3710 @ The macros |qi| and |qo| are used for input to and output 
3711 from quarterwords. These are legacy macros.
3712 @^system dependencies@>
3713
3714 @d qo(A) (A) /* to read eight bits from a quarterword */
3715 @d qi(A) (quarterword)(A) /* to store eight bits in a quarterword */
3716
3717 @ The reader should study the following definitions closely:
3718 @^system dependencies@>
3719
3720 @d sc cint /* |scaled| data is equivalent to |integer| */
3721
3722 @<Types...@>=
3723 typedef short quarterword; /* 1/4 of a word */
3724 typedef int halfword; /* 1/2 of a word */
3725 typedef union {
3726   struct {
3727     halfword RH, LH;
3728   } v;
3729   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3730     halfword junk;
3731     quarterword B0, B1;
3732   } u;
3733 } two_halves;
3734 typedef struct {
3735   struct {
3736     quarterword B2, B3, B0, B1;
3737   } u;
3738 } four_quarters;
3739 typedef union {
3740   two_halves hh;
3741   integer cint;
3742   four_quarters qqqq;
3743 } memory_word;
3744 #define b0 u.B0
3745 #define b1 u.B1
3746 #define b2 u.B2
3747 #define b3 u.B3
3748 #define rh v.RH
3749 #define lh v.LH
3750
3751 @ When debugging, we may want to print a |memory_word| without knowing
3752 what type it is; so we print it in all modes.
3753 @^debugging@>
3754
3755 @c 
3756 void mp_print_word (MP mp,memory_word w) {
3757   /* prints |w| in all ways */
3758   mp_print_int(mp, w.cint); mp_print_char(mp, xord(' '));
3759   mp_print_scaled(mp, w.sc); mp_print_char(mp, xord(' ')); 
3760   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3761   mp_print_int(mp, w.hh.lh); mp_print_char(mp, xord('=')); 
3762   mp_print_int(mp, w.hh.b0); mp_print_char(mp, xord(':'));
3763   mp_print_int(mp, w.hh.b1); mp_print_char(mp, xord(';')); 
3764   mp_print_int(mp, w.hh.rh); mp_print_char(mp, xord(' '));
3765   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, xord(':')); 
3766   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, xord(':'));
3767   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, xord(':')); 
3768   mp_print_int(mp, w.qqqq.b3);
3769 }
3770
3771
3772 @* \[10] Dynamic memory allocation.
3773
3774 The \MP\ system does nearly all of its own memory allocation, so that it
3775 can readily be transported into environments that do not have automatic
3776 facilities for strings, garbage collection, etc., and so that it can be in
3777 control of what error messages the user receives. The dynamic storage
3778 requirements of \MP\ are handled by providing a large array |mem| in
3779 which consecutive blocks of words are used as nodes by the \MP\ routines.
3780
3781 Pointer variables are indices into this array, or into another array
3782 called |eqtb| that will be explained later. A pointer variable might
3783 also be a special flag that lies outside the bounds of |mem|, so we
3784 allow pointers to assume any |halfword| value. The minimum memory
3785 index represents a null pointer.
3786
3787 @d null 0 /* the null pointer */
3788 @d mp_void (null+1) /* a null pointer different from |null| */
3789
3790
3791 @<Types...@>=
3792 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3793
3794 @ The |mem| array is divided into two regions that are allocated separately,
3795 but the dividing line between these two regions is not fixed; they grow
3796 together until finding their ``natural'' size in a particular job.
3797 Locations less than or equal to |lo_mem_max| are used for storing
3798 variable-length records consisting of two or more words each. This region
3799 is maintained using an algorithm similar to the one described in exercise
3800 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3801 appears in the allocated nodes; the program is responsible for knowing the
3802 relevant size when a node is freed. Locations greater than or equal to
3803 |hi_mem_min| are used for storing one-word records; a conventional
3804 \.{AVAIL} stack is used for allocation in this region.
3805
3806 Locations of |mem| between |0| and |mem_top| may be dumped as part
3807 of preloaded mem files, by the \.{INIMP} preprocessor.
3808 @.INIMP@>
3809 Production versions of \MP\ may extend the memory at the top end in order to
3810 provide more space; these locations, between |mem_top| and |mem_max|,
3811 are always used for single-word nodes.
3812
3813 The key pointers that govern |mem| allocation have a prescribed order:
3814 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3815
3816 @<Glob...@>=
3817 memory_word *mem; /* the big dynamic storage area */
3818 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3819 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3820
3821
3822
3823 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3824 @d xrealloc(P,A,B) mp_xrealloc(mp,P,(size_t)A,B)
3825 @d xmalloc(A,B)  mp_xmalloc(mp,(size_t)A,B)
3826 @d xstrdup(A)  mp_xstrdup(mp,A)
3827 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3828
3829 @<Declare helpers@>=
3830 extern char *mp_strdup(const char *p) ;
3831 extern void mp_xfree ( @= /*@@only@@*/ /*@@out@@*/ /*@@null@@*/ @> void *x);
3832 extern @= /*@@only@@*/ @> void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3833 extern @= /*@@only@@*/ @> void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3834 extern @= /*@@only@@*/ @> char *mp_xstrdup(MP mp, const char *s);
3835 extern void mp_do_snprintf(char *str, int size, const char *fmt, ...);
3836
3837 @ The |max_size_test| guards against overflow, on the assumption that
3838 |size_t| is at least 31bits wide.
3839
3840 @d max_size_test 0x7FFFFFFF
3841
3842 @c
3843 char *mp_strdup(const char *p) {
3844   char *r;
3845   size_t l;
3846   if (p==NULL) return NULL;
3847   l = strlen(p);
3848   r = malloc (l*sizeof(char)+1);
3849   if (r==NULL)
3850     return NULL;
3851   return memcpy (r,p,(l+1));
3852 }
3853 void mp_xfree (void *x) {
3854   if (x!=NULL) free(x);
3855 }
3856 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3857   void *w ; 
3858   if ((max_size_test/size)<nmem) {
3859     do_fprintf(mp->err_out,"Memory size overflow!\n");
3860     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3861   }
3862   w = realloc (p,(nmem*size));
3863   if (w==NULL) {
3864     do_fprintf(mp->err_out,"Out of memory!\n");
3865     mp->history =mp_system_error_stop;    mp_jump_out(mp);
3866   }
3867   return w;
3868 }
3869 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3870   void *w;
3871   if ((max_size_test/size)<nmem) {
3872     do_fprintf(mp->err_out,"Memory size overflow!\n");
3873     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3874   }
3875   w = malloc (nmem*size);
3876   if (w==NULL) {
3877     do_fprintf(mp->err_out,"Out of memory!\n");
3878     mp->history =mp_system_error_stop;    mp_jump_out(mp);
3879   }
3880   return w;
3881 }
3882 char *mp_xstrdup(MP mp, const char *s) {
3883   char *w; 
3884   if (s==NULL)
3885     return NULL;
3886   w = mp_strdup(s);
3887   if (w==NULL) {
3888     do_fprintf(mp->err_out,"Out of memory!\n");
3889     mp->history =mp_system_error_stop;    mp_jump_out(mp);
3890   }
3891   return w;
3892 }
3893
3894 @ @<Internal library declarations@>=
3895 #ifdef HAVE_SNPRINTF
3896 #define mp_snprintf (void)snprintf
3897 #else
3898 #define mp_snprintf mp_do_snprintf
3899 #endif
3900
3901 @ This internal version is rather stupid, but good enough for its purpose.
3902
3903 @c
3904 static char *mp_itoa (int i) {
3905   char res[32] ;
3906   unsigned idx = 30;
3907   unsigned v = (unsigned)abs(i);
3908   memset(res,0,32*sizeof(char));
3909   while (v>=10) {
3910     char d = (char)(v % 10);
3911     v = v / 10;
3912     res[idx--] = d;
3913   }
3914   res[idx--] = (char)v;
3915   if (i<0) {
3916       res[idx--] = '-';
3917   }
3918   return mp_strdup(res+idx);
3919 }
3920 static char *mp_utoa (unsigned v) {
3921   char res[32] ;
3922   unsigned idx = 30;
3923   memset(res,0,32*sizeof(char));
3924   while (v>=10) {
3925     char d = (char)(v % 10);
3926     v = v / 10;
3927     res[idx--] = d;
3928   }
3929   res[idx--] = (char)v;
3930   return mp_strdup(res+idx);
3931 }
3932 void mp_do_snprintf (char *str, int size, const char *format, ...) {
3933   const char *fmt;
3934   char *res;
3935   va_list ap;
3936   va_start(ap, format);
3937   res = str;
3938   for (fmt=format;*fmt!='\0';fmt++) {
3939      if (*fmt=='%') {
3940        fmt++;
3941        switch(*fmt) {
3942        case 's':
3943          {
3944            char *s = va_arg(ap, char *);
3945            while (*s) {
3946              *res = *s++;
3947              if (size-->0) res++;
3948            }
3949          }
3950          break;
3951        case 'i':
3952        case 'd':
3953          {
3954            char *s = mp_itoa(va_arg(ap, int));
3955            if (s != NULL) {
3956              while (*s) {
3957                *res = *s++;
3958                if (size-->0) res++;
3959              }
3960            }
3961          }
3962          break;
3963        case 'u':
3964          {
3965            char *s = mp_utoa(va_arg(ap, unsigned));
3966            if (s != NULL) {
3967              while (*s) {
3968                *res = *s++;
3969                if (size-->0) res++;
3970              }
3971            }
3972          }
3973          break;
3974        case '%':
3975          *res = '%';
3976          if (size-->0) res++;
3977          break;
3978        default:
3979          *res = '%';
3980          if (size-->0) res++;
3981          *res = *fmt;
3982          if (size-->0) res++;
3983          break;
3984        }
3985      } else {
3986        *res = *fmt;
3987        if (size-->0) res++;
3988      }
3989   }
3990   *res = '\0';
3991   va_end(ap);
3992 }
3993
3994
3995 @<Allocate or initialize ...@>=
3996 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
3997 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
3998
3999 @ @<Dealloc variables@>=
4000 xfree(mp->mem);
4001
4002 @ Users who wish to study the memory requirements of particular applications can
4003 can use optional special features that keep track of current and
4004 maximum memory usage. When code between the delimiters |stat| $\ldots$
4005 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
4006 report these statistics when |mp_tracing_stats| is positive.
4007
4008 @<Glob...@>=
4009 integer var_used; integer dyn_used; /* how much memory is in use */
4010
4011 @ Let's consider the one-word memory region first, since it's the
4012 simplest. The pointer variable |mem_end| holds the highest-numbered location
4013 of |mem| that has ever been used. The free locations of |mem| that
4014 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
4015 |two_halves|, and we write |info(p)| and |mp_link(p)| for the |lh|
4016 and |rh| fields of |mem[p]| when it is of this type. The single-word
4017 free locations form a linked list
4018 $$|avail|,\;\hbox{|mp_link(avail)|},\;\hbox{|mp_link(mp_link(avail))|},\;\ldots$$
4019 terminated by |null|.
4020
4021 @d mp_link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
4022 @d info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
4023
4024 @<Glob...@>=
4025 pointer avail; /* head of the list of available one-word nodes */
4026 pointer mem_end; /* the last one-word node used in |mem| */
4027
4028 @ If one-word memory is exhausted, it might mean that the user has forgotten
4029 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
4030 later that try to help pinpoint the trouble.
4031
4032 @ The function |get_avail| returns a pointer to a new one-word node whose
4033 |link| field is null. However, \MP\ will halt if there is no more room left.
4034 @^inner loop@>
4035
4036 @c 
4037 static pointer mp_get_avail (MP mp) { /* single-word node allocation */
4038   pointer p; /* the new node being got */
4039   p=mp->avail; /* get top location in the |avail| stack */
4040   if ( p!=null ) {
4041     mp->avail=mp_link(mp->avail); /* and pop it off */
4042   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
4043     incr(mp->mem_end); p=mp->mem_end;
4044   } else { 
4045     decr(mp->hi_mem_min); p=mp->hi_mem_min;
4046     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
4047       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
4048       mp_overflow(mp, "main memory size",mp->mem_max);
4049       /* quit; all one-word nodes are busy */
4050 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4051     }
4052   }
4053   mp_link(p)=null; /* provide an oft-desired initialization of the new node */
4054   incr(mp->dyn_used);/* maintain statistics */
4055   return p;
4056 }
4057
4058 @ Conversely, a one-word node is recycled by calling |free_avail|.
4059
4060 @d free_avail(A)  /* single-word node liberation */
4061   { mp_link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
4062
4063 @ There's also a |fast_get_avail| routine, which saves the procedure-call
4064 overhead at the expense of extra programming. This macro is used in
4065 the places that would otherwise account for the most calls of |get_avail|.
4066 @^inner loop@>
4067
4068 @d fast_get_avail(A) { 
4069   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
4070   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
4071   else { mp->avail=mp_link((A)); mp_link((A))=null;  incr(mp->dyn_used); }
4072   }
4073
4074 @ The available-space list that keeps track of the variable-size portion
4075 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4076 pointed to by the roving pointer |rover|.
4077
4078 Each empty node has size 2 or more; the first word contains the special
4079 value |max_halfword| in its |link| field and the size in its |info| field;
4080 the second word contains the two pointers for double linking.
4081
4082 Each nonempty node also has size 2 or more. Its first word is of type
4083 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4084 Otherwise there is complete flexibility with respect to the contents
4085 of its other fields and its other words.
4086
4087 (We require |mem_max<max_halfword| because terrible things can happen
4088 when |max_halfword| appears in the |link| field of a nonempty node.)
4089
4090 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4091 @d is_empty(A)   (mp_link((A))==empty_flag) /* tests for empty node */
4092 @d node_size   info /* the size field in empty variable-size nodes */
4093 @d lmp_link(A)   info((A)+1) /* left link in doubly-linked list of empty nodes */
4094 @d rmp_link(A)   mp_link((A)+1) /* right link in doubly-linked list of empty nodes */
4095
4096 @<Glob...@>=
4097 pointer rover; /* points to some node in the list of empties */
4098
4099 @ A call to |get_node| with argument |s| returns a pointer to a new node
4100 of size~|s|, which must be 2~or more. The |link| field of the first word
4101 of this new node is set to null. An overflow stop occurs if no suitable
4102 space exists.
4103
4104 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4105 areas and returns the value |max_halfword|.
4106
4107 @<Internal library declarations@>=
4108 pointer mp_get_node (MP mp,integer s) ;
4109
4110 @ @c 
4111 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4112   pointer p; /* the node currently under inspection */
4113   pointer q;  /* the node physically after node |p| */
4114   integer r; /* the newly allocated node, or a candidate for this honor */
4115   integer t,tt; /* temporary registers */
4116 @^inner loop@>
4117  RESTART: 
4118   p=mp->rover; /* start at some free node in the ring */
4119   do {  
4120     @<Try to allocate within node |p| and its physical successors,
4121      and |goto found| if allocation was possible@>;
4122     if (rmp_link(p)==null || (rmp_link(p)==p && p!=mp->rover)) {
4123       print_err("Free list garbled");
4124       help3("I found an entry in the list of free nodes that links",
4125        "badly. I will try to ignore the broken link, but something",
4126        "is seriously amiss. It is wise to warn the maintainers.")
4127           mp_error(mp);
4128       rmp_link(p)=mp->rover;
4129     }
4130         p=rmp_link(p); /* move to the next node in the ring */
4131   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4132   if ( s==010000000000 ) { 
4133     return max_halfword;
4134   };
4135   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4136     if ( mp->lo_mem_max+2<=max_halfword ) {
4137       @<Grow more variable-size memory and |goto restart|@>;
4138     }
4139   }
4140   mp_overflow(mp, "main memory size",mp->mem_max);
4141   /* sorry, nothing satisfactory is left */
4142 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4143 FOUND: 
4144   mp_link(r)=null; /* this node is now nonempty */
4145   mp->var_used+=s; /* maintain usage statistics */
4146   return r;
4147 }
4148
4149 @ The lower part of |mem| grows by 1000 words at a time, unless
4150 we are very close to going under. When it grows, we simply link
4151 a new node into the available-space list. This method of controlled
4152 growth helps to keep the |mem| usage consecutive when \MP\ is
4153 implemented on ``virtual memory'' systems.
4154 @^virtual memory@>
4155
4156 @<Grow more variable-size memory and |goto restart|@>=
4157
4158   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4159     t=mp->lo_mem_max+1000;
4160   } else {
4161     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4162     /* |lo_mem_max+2<=t<hi_mem_min| */
4163   }
4164   if ( t>max_halfword ) t=max_halfword;
4165   p=lmp_link(mp->rover); q=mp->lo_mem_max; rmp_link(p)=q; lmp_link(mp->rover)=q;
4166   rmp_link(q)=mp->rover; lmp_link(q)=p; mp_link(q)=empty_flag; 
4167   node_size(q)=t-mp->lo_mem_max;
4168   mp->lo_mem_max=t; mp_link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4169   mp->rover=q; 
4170   goto RESTART;
4171 }
4172
4173 @ @<Try to allocate...@>=
4174 q=p+node_size(p); /* find the physical successor */
4175 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4176   t=rmp_link(q); tt=lmp_link(q);
4177 @^inner loop@>
4178   if ( q==mp->rover ) mp->rover=t;
4179   lmp_link(t)=tt; rmp_link(tt)=t;
4180   q=q+node_size(q);
4181 }
4182 r=q-s;
4183 if ( r>p+1 ) {
4184   @<Allocate from the top of node |p| and |goto found|@>;
4185 }
4186 if ( r==p ) { 
4187   if ( rmp_link(p)!=p ) {
4188     @<Allocate entire node |p| and |goto found|@>;
4189   }
4190 }
4191 node_size(p)=q-p /* reset the size in case it grew */
4192
4193 @ @<Allocate from the top...@>=
4194
4195   node_size(p)=r-p; /* store the remaining size */
4196   mp->rover=p; /* start searching here next time */
4197   goto FOUND;
4198 }
4199
4200 @ Here we delete node |p| from the ring, and let |rover| rove around.
4201
4202 @<Allocate entire...@>=
4203
4204   mp->rover=rmp_link(p); t=lmp_link(p);
4205   lmp_link(mp->rover)=t; rmp_link(t)=mp->rover;
4206   goto FOUND;
4207 }
4208
4209 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4210 the operation |free_node(p,s)| will make its words available, by inserting
4211 |p| as a new empty node just before where |rover| now points.
4212
4213 @<Internal library declarations@>=
4214 void mp_free_node (MP mp, pointer p, halfword s) ;
4215
4216 @ @c 
4217 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4218   liberation */
4219   pointer q; /* |lmp_link(rover)| */
4220   node_size(p)=s; mp_link(p)=empty_flag;
4221 @^inner loop@>
4222   q=lmp_link(mp->rover); lmp_link(p)=q; rmp_link(p)=mp->rover; /* set both links */
4223   lmp_link(mp->rover)=p; rmp_link(q)=p; /* insert |p| into the ring */
4224   mp->var_used-=s; /* maintain statistics */
4225 }
4226
4227 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4228 available space list. The list is probably very short at such times, so a
4229 simple insertion sort is used. The smallest available location will be
4230 pointed to by |rover|, the next-smallest by |rmp_link(rover)|, etc.
4231
4232 @c 
4233 static void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4234   by location */
4235   pointer p,q,r; /* indices into |mem| */
4236   pointer old_rover; /* initial |rover| setting */
4237   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4238   p=rmp_link(mp->rover); rmp_link(mp->rover)=max_halfword; old_rover=mp->rover;
4239   while ( p!=old_rover ) {
4240     @<Sort |p| into the list starting at |rover|
4241      and advance |p| to |rmp_link(p)|@>;
4242   }
4243   p=mp->rover;
4244   while ( rmp_link(p)!=max_halfword ) { 
4245     lmp_link(rmp_link(p))=p; p=rmp_link(p);
4246   };
4247   rmp_link(p)=mp->rover; lmp_link(mp->rover)=p;
4248 }
4249
4250 @ The following |while| loop is guaranteed to
4251 terminate, since the list that starts at
4252 |rover| ends with |max_halfword| during the sorting procedure.
4253
4254 @<Sort |p|...@>=
4255 if ( p<mp->rover ) { 
4256   q=p; p=rmp_link(q); rmp_link(q)=mp->rover; mp->rover=q;
4257 } else  { 
4258   q=mp->rover;
4259   while ( rmp_link(q)<p ) q=rmp_link(q);
4260   r=rmp_link(p); rmp_link(p)=rmp_link(q); rmp_link(q)=p; p=r;
4261 }
4262
4263 @* \[11] Memory layout.
4264 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4265 more efficient than dynamic allocation when we can get away with it. For
4266 example, locations |0| to |1| are always used to store a
4267 two-word dummy token whose second word is zero.
4268 The following macro definitions accomplish the static allocation by giving
4269 symbolic names to the fixed positions. Static variable-size nodes appear
4270 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4271 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4272
4273 @d null_dash (2) /* the first two words are reserved for a null value */
4274 @d dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4275 @d zero_val (dep_head+2) /* two words for a permanently zero value */
4276 @d temp_val (zero_val+2) /* two words for a temporary value node */
4277 @d end_attr temp_val /* we use |end_attr+2| only */
4278 @d inf_val (end_attr+2) /* and |inf_val+1| only */
4279 @d test_pen (inf_val+2)
4280   /* nine words for a pen used when testing the turning number */
4281 @d bad_vardef (test_pen+9) /* two words for \&{vardef} error recovery */
4282 @d lo_mem_stat_max (bad_vardef+1)  /* largest statically
4283   allocated word in the variable-size |mem| */
4284 @#
4285 @d sentinel mp->mem_top /* end of sorted lists */
4286 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4287 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4288 @d spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4289 @d hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4290   the one-word |mem| */
4291
4292 @ The following code gets the dynamic part of |mem| off to a good start,
4293 when \MP\ is initializing itself the slow way.
4294
4295 @<Initialize table entries (done by \.{INIMP} only)@>=
4296 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4297 mp_link(mp->rover)=empty_flag;
4298 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4299 lmp_link(mp->rover)=mp->rover; rmp_link(mp->rover)=mp->rover;
4300 mp->lo_mem_max=mp->rover+1000; 
4301 mp_link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null;
4302 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4303   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4304 }
4305 mp->avail=null; mp->mem_end=mp->mem_top;
4306 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4307 mp->var_used=lo_mem_stat_max+1; 
4308 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4309 @<Initialize a pen at |test_pen| so that it fits in nine words@>;
4310
4311 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4312 nodes that starts at a given position, until coming to |sentinel| or a
4313 pointer that is not in the one-word region. Another procedure,
4314 |flush_node_list|, frees an entire linked list of one-word and two-word
4315 nodes, until coming to a |null| pointer.
4316 @^inner loop@>
4317
4318 @c 
4319 static void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4320   pointer q,r; /* list traversers */
4321   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4322     r=p;
4323     do {  
4324       q=r; r=mp_link(r); 
4325       decr(mp->dyn_used);
4326       if ( r<mp->hi_mem_min ) break;
4327     } while (r!=sentinel);
4328   /* now |q| is the last node on the list */
4329     mp_link(q)=mp->avail; mp->avail=p;
4330   }
4331 }
4332 @#
4333 static void mp_flush_node_list (MP mp,pointer p) {
4334   pointer q; /* the node being recycled */
4335   while ( p!=null ){ 
4336     q=p; p=mp_link(p);
4337     if ( q<mp->hi_mem_min ) 
4338       mp_free_node(mp, q,2);
4339     else 
4340       free_avail(q);
4341   }
4342 }
4343
4344 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4345 For example, some pointers might be wrong, or some ``dead'' nodes might not
4346 have been freed when the last reference to them disappeared. Procedures
4347 |check_mem| and |search_mem| are available to help diagnose such
4348 problems. These procedures make use of two arrays called |free| and
4349 |was_free| that are present only if \MP's debugging routines have
4350 been included. (You may want to decrease the size of |mem| while you
4351 @^debugging@>
4352 are debugging.)
4353
4354 Because |boolean|s are typedef-d as ints, it is better to use
4355 unsigned chars here.
4356
4357 @<Glob...@>=
4358 unsigned char *free; /* free cells */
4359 unsigned char *was_free; /* previously free cells */
4360 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4361   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4362 boolean panicking; /* do we want to check memory constantly? */
4363
4364 @ @<Allocate or initialize ...@>=
4365 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4366 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4367
4368 @ @<Dealloc variables@>=
4369 xfree(mp->free);
4370 xfree(mp->was_free);
4371
4372 @ @<Allocate or ...@>=
4373 mp->was_hi_min=mp->mem_max;
4374 mp->panicking=false;
4375
4376 @ @<Declarations@>=
4377 static void mp_reallocate_memory(MP mp, int l) ;
4378
4379 @ @c
4380 static void mp_reallocate_memory(MP mp, int l) {
4381    XREALLOC(mp->free,     l, unsigned char);
4382    XREALLOC(mp->was_free, l, unsigned char);
4383    if (mp->mem) {
4384          int newarea = l-mp->mem_max;
4385      XREALLOC(mp->mem,      l, memory_word);
4386      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4387    } else {
4388      XREALLOC(mp->mem,      l, memory_word);
4389      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4390    }
4391    mp->mem_max = l;
4392    if (mp->ini_version) 
4393      mp->mem_top = l;
4394 }
4395
4396
4397
4398 @ Procedure |check_mem| makes sure that the available space lists of
4399 |mem| are well formed, and it optionally prints out all locations
4400 that are reserved now but were free the last time this procedure was called.
4401
4402 @c 
4403 void mp_check_mem (MP mp,boolean print_locs ) {
4404   pointer p,q,r; /* current locations of interest in |mem| */
4405   boolean clobbered; /* is something amiss? */
4406   for (p=0;p<=mp->lo_mem_max;p++) {
4407     mp->free[p]=false; /* you can probably do this faster */
4408   }
4409   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4410     mp->free[p]=false; /* ditto */
4411   }
4412   @<Check single-word |avail| list@>;
4413   @<Check variable-size |avail| list@>;
4414   @<Check flags of unavailable nodes@>;
4415   @<Check the list of linear dependencies@>;
4416   if ( print_locs ) {
4417     @<Print newly busy locations@>;
4418   }
4419   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4420   mp->was_mem_end=mp->mem_end; 
4421   mp->was_lo_max=mp->lo_mem_max; 
4422   mp->was_hi_min=mp->hi_mem_min;
4423 }
4424
4425 @ @<Check single-word...@>=
4426 p=mp->avail; q=null; clobbered=false;
4427 while ( p!=null ) { 
4428   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4429   else if ( mp->free[p] ) clobbered=true;
4430   if ( clobbered ) { 
4431     mp_print_nl(mp, "AVAIL list clobbered at ");
4432 @.AVAIL list clobbered...@>
4433     mp_print_int(mp, q); break;
4434   }
4435   mp->free[p]=true; q=p; p=mp_link(q);
4436 }
4437
4438 @ @<Check variable-size...@>=
4439 p=mp->rover; q=null; clobbered=false;
4440 do {  
4441   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4442   else if ( (rmp_link(p)>=mp->lo_mem_max)||(rmp_link(p)<0) ) clobbered=true;
4443   else if (  !(is_empty(p))||(node_size(p)<2)||
4444    (p+node_size(p)>mp->lo_mem_max)|| (lmp_link(rmp_link(p))!=p) ) clobbered=true;
4445   if ( clobbered ) { 
4446     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4447 @.Double-AVAIL list clobbered...@>
4448     mp_print_int(mp, q); break;
4449   }
4450   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4451     if ( mp->free[q] ) { 
4452       mp_print_nl(mp, "Doubly free location at ");
4453 @.Doubly free location...@>
4454       mp_print_int(mp, q); break;
4455     }
4456     mp->free[q]=true;
4457   }
4458   q=p; p=rmp_link(p);
4459 } while (p!=mp->rover)
4460
4461
4462 @ @<Check flags...@>=
4463 p=0;
4464 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4465   if ( is_empty(p) ) {
4466     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4467 @.Bad flag...@>
4468   }
4469   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) p++;
4470   while ( (p<=mp->lo_mem_max) && mp->free[p] ) p++;
4471 }
4472
4473 @ @<Print newly busy...@>=
4474
4475   @<Do intialization required before printing new busy locations@>;
4476   mp_print_nl(mp, "New busy locs:");
4477 @.New busy locs@>
4478   for (p=0;p<= mp->lo_mem_max;p++ ) {
4479     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4480       @<Indicate that |p| is a new busy location@>;
4481     }
4482   }
4483   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4484     if ( ! mp->free[p] &&
4485         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4486       @<Indicate that |p| is a new busy location@>;
4487     }
4488   }
4489   @<Finish printing new busy locations@>;
4490 }
4491
4492 @ There might be many new busy locations so we are careful to print contiguous
4493 blocks compactly.  During this operation |q| is the last new busy location and
4494 |r| is the start of the block containing |q|.
4495
4496 @<Indicate that |p| is a new busy location@>=
4497
4498   if ( p>q+1 ) { 
4499     if ( q>r ) { 
4500       mp_print(mp, ".."); mp_print_int(mp, q);
4501     }
4502     mp_print_char(mp, xord(' ')); mp_print_int(mp, p);
4503     r=p;
4504   }
4505   q=p;
4506 }
4507
4508 @ @<Do intialization required before printing new busy locations@>=
4509 q=mp->mem_max; r=mp->mem_max
4510
4511 @ @<Finish printing new busy locations@>=
4512 if ( q>r ) { 
4513   mp_print(mp, ".."); mp_print_int(mp, q);
4514 }
4515
4516 @ The |search_mem| procedure attempts to answer the question ``Who points
4517 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4518 that might not be of type |two_halves|. Strictly speaking, this is
4519 undefined, and it can lead to ``false drops'' (words that seem to
4520 point to |p| purely by coincidence). But for debugging purposes, we want
4521 to rule out the places that do {\sl not\/} point to |p|, so a few false
4522 drops are tolerable.
4523
4524 @c
4525 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4526   integer q; /* current position being searched */
4527   for (q=0;q<=mp->lo_mem_max;q++) { 
4528     if ( mp_link(q)==p ){ 
4529       mp_print_nl(mp, "MP_LINK("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4530     }
4531     if ( info(q)==p ) { 
4532       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4533     }
4534   }
4535   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4536     if ( mp_link(q)==p ) {
4537       mp_print_nl(mp, "MP_LINK("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4538     }
4539     if ( info(q)==p ) {
4540       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4541     }
4542   }
4543   @<Search |eqtb| for equivalents equal to |p|@>;
4544 }
4545
4546 @* \[12] The command codes.
4547 Before we can go much further, we need to define symbolic names for the internal
4548 code numbers that represent the various commands obeyed by \MP. These codes
4549 are somewhat arbitrary, but not completely so. For example,
4550 some codes have been made adjacent so that |case| statements in the
4551 program need not consider cases that are widely spaced, or so that |case|
4552 statements can be replaced by |if| statements. A command can begin an
4553 expression if and only if its code lies between |min_primary_command| and
4554 |max_primary_command|, inclusive. The first token of a statement that doesn't
4555 begin with an expression has a command code between |min_command| and
4556 |max_statement_command|, inclusive. Anything less than |min_command| is
4557 eliminated during macro expansions, and anything no more than |max_pre_command|
4558 is eliminated when expanding \TeX\ material.  Ranges such as
4559 |min_secondary_command..max_secondary_command| are used when parsing
4560 expressions, but the relative ordering within such a range is generally not
4561 critical.
4562
4563 The ordering of the highest-numbered commands
4564 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4565 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4566 for the smallest two commands.  The ordering is also important in the ranges
4567 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4568
4569 At any rate, here is the list, for future reference.
4570
4571 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4572 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4573 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4574 @d max_pre_command mpx_break
4575 @d if_test 4 /* conditional text (\&{if}) */
4576 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi}) */
4577 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4578 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4579 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4580 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4581 @d relax 10 /* do nothing (\.{\char`\\}) */
4582 @d scan_tokens 11 /* put a string into the input buffer */
4583 @d expand_after 12 /* look ahead one token */
4584 @d defined_macro 13 /* a macro defined by the user */
4585 @d min_command (defined_macro+1)
4586 @d save_command 14 /* save a list of tokens (\&{save}) */
4587 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4588 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4589 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4590 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4591 @d ship_out_command 19 /* output a character (\&{shipout}) */
4592 @d add_to_command 20 /* add to edges (\&{addto}) */
4593 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4594 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4595 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4596 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4597 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4598 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4599 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4600 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4601 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4602 @d special_command 30 /* output special info (\&{special})
4603                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4604 @d write_command 31 /* write text to a file (\&{write}) */
4605 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc.) */
4606 @d max_statement_command type_name
4607 @d min_primary_command type_name
4608 @d left_delimiter 33 /* the left delimiter of a matching pair */
4609 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4610 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4611 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4612 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4613 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4614 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4615 @d capsule_token 40 /* a value that has been put into a token list */
4616 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4617 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4618 @d min_suffix_token internal_quantity
4619 @d tag_token 43 /* a symbolic token without a primitive meaning */
4620 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4621 @d max_suffix_token numeric_token
4622 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4623 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4624 @d min_tertiary_command plus_or_minus
4625 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4626 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4627 @d max_tertiary_command tertiary_binary
4628 @d left_brace 48 /* the operator `\.{\char`\{}' */
4629 @d min_expression_command left_brace
4630 @d path_join 49 /* the operator `\.{..}' */
4631 @d ampersand 50 /* the operator `\.\&' */
4632 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4633 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4634 @d equals 53 /* the operator `\.=' */
4635 @d max_expression_command equals
4636 @d and_command 54 /* the operator `\&{and}' */
4637 @d min_secondary_command and_command
4638 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4639 @d slash 56 /* the operator `\./' */
4640 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4641 @d max_secondary_command secondary_binary
4642 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4643 @d controls 59 /* specify control points explicitly (\&{controls}) */
4644 @d tension 60 /* specify tension between knots (\&{tension}) */
4645 @d at_least 61 /* bounded tension value (\&{atleast}) */
4646 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4647 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4648 @d right_delimiter 64 /* the right delimiter of a matching pair */
4649 @d left_bracket 65 /* the operator `\.[' */
4650 @d right_bracket 66 /* the operator `\.]' */
4651 @d right_brace 67 /* the operator `\.{\char`\}}' */
4652 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4653 @d thing_to_add 69
4654   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4655 @d of_token 70 /* the operator `\&{of}' */
4656 @d to_token 71 /* the operator `\&{to}' */
4657 @d step_token 72 /* the operator `\&{step}' */
4658 @d until_token 73 /* the operator `\&{until}' */
4659 @d within_token 74 /* the operator `\&{within}' */
4660 @d lig_kern_token 75
4661   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}', etc. */
4662 @d assignment 76 /* the operator `\.{:=}' */
4663 @d skip_to 77 /* the operation `\&{skipto}' */
4664 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4665 @d double_colon 79 /* the operator `\.{::}' */
4666 @d colon 80 /* the operator `\.:' */
4667 @#
4668 @d comma 81 /* the operator `\.,', must be |colon+1| */
4669 @d end_of_statement (mp->cur_cmd>comma)
4670 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4671 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4672 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4673 @d max_command_code stop
4674 @d outer_tag (max_command_code+1) /* protection code added to command code */
4675
4676 @<Types...@>=
4677 typedef int command_code;
4678
4679 @ Variables and capsules in \MP\ have a variety of ``types,''
4680 distinguished by the code numbers defined here. These numbers are also
4681 not completely arbitrary.  Things that get expanded must have types
4682 |>mp_independent|; a type remaining after expansion is numeric if and only if
4683 its code number is at least |numeric_type|; objects containing numeric
4684 parts must have types between |transform_type| and |pair_type|;
4685 all other types must be smaller than |transform_type|; and among the types
4686 that are not unknown or vacuous, the smallest two must be |boolean_type|
4687 and |string_type| in that order.
4688  
4689 @d undefined 0 /* no type has been declared */
4690 @d unknown_tag 1 /* this constant is added to certain type codes below */
4691 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4692   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4693
4694 @<Types...@>=
4695 enum mp_variable_type {
4696 mp_vacuous=1, /* no expression was present */
4697 mp_boolean_type, /* \&{boolean} with a known value */
4698 mp_unknown_boolean,
4699 mp_string_type, /* \&{string} with a known value */
4700 mp_unknown_string,
4701 mp_pen_type, /* \&{pen} with a known value */
4702 mp_unknown_pen,
4703 mp_path_type, /* \&{path} with a known value */
4704 mp_unknown_path,
4705 mp_picture_type, /* \&{picture} with a known value */
4706 mp_unknown_picture,
4707 mp_transform_type, /* \&{transform} variable or capsule */
4708 mp_color_type, /* \&{color} variable or capsule */
4709 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4710 mp_pair_type, /* \&{pair} variable or capsule */
4711 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4712 mp_known, /* \&{numeric} with a known value */
4713 mp_dependent, /* a linear combination with |fraction| coefficients */
4714 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4715 mp_independent, /* \&{numeric} with unknown value */
4716 mp_token_list, /* variable name or suffix argument or text argument */
4717 mp_structured, /* variable with subscripts and attributes */
4718 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4719 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4720 } ;
4721
4722 @ @<Declarations@>=
4723 static void mp_print_type (MP mp,quarterword t) ;
4724
4725 @ @<Basic printing procedures@>=
4726 void mp_print_type (MP mp,quarterword t) { 
4727   switch (t) {
4728   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4729   case mp_boolean_type:mp_print(mp, "boolean"); break;
4730   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4731   case mp_string_type:mp_print(mp, "string"); break;
4732   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4733   case mp_pen_type:mp_print(mp, "pen"); break;
4734   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4735   case mp_path_type:mp_print(mp, "path"); break;
4736   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4737   case mp_picture_type:mp_print(mp, "picture"); break;
4738   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4739   case mp_transform_type:mp_print(mp, "transform"); break;
4740   case mp_color_type:mp_print(mp, "color"); break;
4741   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4742   case mp_pair_type:mp_print(mp, "pair"); break;
4743   case mp_known:mp_print(mp, "known numeric"); break;
4744   case mp_dependent:mp_print(mp, "dependent"); break;
4745   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4746   case mp_numeric_type:mp_print(mp, "numeric"); break;
4747   case mp_independent:mp_print(mp, "independent"); break;
4748   case mp_token_list:mp_print(mp, "token list"); break;
4749   case mp_structured:mp_print(mp, "mp_structured"); break;
4750   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4751   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4752   default: mp_print(mp, "undefined"); break;
4753   }
4754 }
4755
4756 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4757 as well as a |type|. The possibilities for |name_type| are defined
4758 here; they will be explained in more detail later.
4759
4760 @<Types...@>=
4761 enum mp_name_type {
4762  mp_root=0, /* |name_type| at the top level of a variable */
4763  mp_saved_root, /* same, when the variable has been saved */
4764  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4765  mp_subscr, /* |name_type| in a subscript node */
4766  mp_attr, /* |name_type| in an attribute node */
4767  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4768  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4769  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4770  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4771  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4772  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4773  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4774  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4775  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4776  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4777  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4778  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4779  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4780  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4781  mp_capsule, /* |name_type| in stashed-away subexpressions */
4782  mp_token  /* |name_type| in a numeric token or string token */
4783 };
4784
4785 @ Primitive operations that produce values have a secondary identification
4786 code in addition to their command code; it's something like genera and species.
4787 For example, `\.*' has the command code |primary_binary|, and its
4788 secondary identification is |times|. The secondary codes start at 30 so that
4789 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4790 are used as operators as well as type identifications.  The relative values
4791 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4792 and |filled_op..bounded_op|.  The restrictions are that
4793 |and_op-false_code=or_op-true_code|, that the ordering of
4794 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4795 and the ordering of |filled_op..bounded_op| must match that of the code
4796 values they test for.
4797
4798 @d true_code 30 /* operation code for \.{true} */
4799 @d false_code 31 /* operation code for \.{false} */
4800 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4801 @d null_pen_code 33 /* operation code for \.{nullpen} */
4802 @d job_name_op 34 /* operation code for \.{jobname} */
4803 @d read_string_op 35 /* operation code for \.{readstring} */
4804 @d pen_circle 36 /* operation code for \.{pencircle} */
4805 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4806 @d read_from_op 38 /* operation code for \.{readfrom} */
4807 @d close_from_op 39 /* operation code for \.{closefrom} */
4808 @d odd_op 40 /* operation code for \.{odd} */
4809 @d known_op 41 /* operation code for \.{known} */
4810 @d unknown_op 42 /* operation code for \.{unknown} */
4811 @d not_op 43 /* operation code for \.{not} */
4812 @d decimal 44 /* operation code for \.{decimal} */
4813 @d reverse 45 /* operation code for \.{reverse} */
4814 @d make_path_op 46 /* operation code for \.{makepath} */
4815 @d make_pen_op 47 /* operation code for \.{makepen} */
4816 @d oct_op 48 /* operation code for \.{oct} */
4817 @d hex_op 49 /* operation code for \.{hex} */
4818 @d ASCII_op 50 /* operation code for \.{ASCII} */
4819 @d char_op 51 /* operation code for \.{char} */
4820 @d length_op 52 /* operation code for \.{length} */
4821 @d turning_op 53 /* operation code for \.{turningnumber} */
4822 @d color_model_part 54 /* operation code for \.{colormodel} */
4823 @d x_part 55 /* operation code for \.{xpart} */
4824 @d y_part 56 /* operation code for \.{ypart} */
4825 @d xx_part 57 /* operation code for \.{xxpart} */
4826 @d xy_part 58 /* operation code for \.{xypart} */
4827 @d yx_part 59 /* operation code for \.{yxpart} */
4828 @d yy_part 60 /* operation code for \.{yypart} */
4829 @d red_part 61 /* operation code for \.{redpart} */
4830 @d green_part 62 /* operation code for \.{greenpart} */
4831 @d blue_part 63 /* operation code for \.{bluepart} */
4832 @d cyan_part 64 /* operation code for \.{cyanpart} */
4833 @d magenta_part 65 /* operation code for \.{magentapart} */
4834 @d yellow_part 66 /* operation code for \.{yellowpart} */
4835 @d black_part 67 /* operation code for \.{blackpart} */
4836 @d grey_part 68 /* operation code for \.{greypart} */
4837 @d font_part 69 /* operation code for \.{fontpart} */
4838 @d text_part 70 /* operation code for \.{textpart} */
4839 @d path_part 71 /* operation code for \.{pathpart} */
4840 @d pen_part 72 /* operation code for \.{penpart} */
4841 @d dash_part 73 /* operation code for \.{dashpart} */
4842 @d sqrt_op 74 /* operation code for \.{sqrt} */
4843 @d mp_m_exp_op 75 /* operation code for \.{mexp} */
4844 @d mp_m_log_op 76 /* operation code for \.{mlog} */
4845 @d sin_d_op 77 /* operation code for \.{sind} */
4846 @d cos_d_op 78 /* operation code for \.{cosd} */
4847 @d floor_op 79 /* operation code for \.{floor} */
4848 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4849 @d char_exists_op 81 /* operation code for \.{charexists} */
4850 @d font_size 82 /* operation code for \.{fontsize} */
4851 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4852 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4853 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4854 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4855 @d arc_length 87 /* operation code for \.{arclength} */
4856 @d angle_op 88 /* operation code for \.{angle} */
4857 @d cycle_op 89 /* operation code for \.{cycle} */
4858 @d filled_op 90 /* operation code for \.{filled} */
4859 @d stroked_op 91 /* operation code for \.{stroked} */
4860 @d textual_op 92 /* operation code for \.{textual} */
4861 @d clipped_op 93 /* operation code for \.{clipped} */
4862 @d bounded_op 94 /* operation code for \.{bounded} */
4863 @d plus 95 /* operation code for \.+ */
4864 @d minus 96 /* operation code for \.- */
4865 @d times 97 /* operation code for \.* */
4866 @d over 98 /* operation code for \./ */
4867 @d pythag_add 99 /* operation code for \.{++} */
4868 @d pythag_sub 100 /* operation code for \.{+-+} */
4869 @d or_op 101 /* operation code for \.{or} */
4870 @d and_op 102 /* operation code for \.{and} */
4871 @d less_than 103 /* operation code for \.< */
4872 @d less_or_equal 104 /* operation code for \.{<=} */
4873 @d greater_than 105 /* operation code for \.> */
4874 @d greater_or_equal 106 /* operation code for \.{>=} */
4875 @d equal_to 107 /* operation code for \.= */
4876 @d unequal_to 108 /* operation code for \.{<>} */
4877 @d concatenate 109 /* operation code for \.\& */
4878 @d rotated_by 110 /* operation code for \.{rotated} */
4879 @d slanted_by 111 /* operation code for \.{slanted} */
4880 @d scaled_by 112 /* operation code for \.{scaled} */
4881 @d shifted_by 113 /* operation code for \.{shifted} */
4882 @d transformed_by 114 /* operation code for \.{transformed} */
4883 @d x_scaled 115 /* operation code for \.{xscaled} */
4884 @d y_scaled 116 /* operation code for \.{yscaled} */
4885 @d z_scaled 117 /* operation code for \.{zscaled} */
4886 @d in_font 118 /* operation code for \.{infont} */
4887 @d intersect 119 /* operation code for \.{intersectiontimes} */
4888 @d double_dot 120 /* operation code for improper \.{..} */
4889 @d substring_of 121 /* operation code for \.{substring} */
4890 @d min_of substring_of
4891 @d subpath_of 122 /* operation code for \.{subpath} */
4892 @d direction_time_of 123 /* operation code for \.{directiontime} */
4893 @d point_of 124 /* operation code for \.{point} */
4894 @d precontrol_of 125 /* operation code for \.{precontrol} */
4895 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4896 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4897 @d arc_time_of 128 /* operation code for \.{arctime} */
4898 @d mp_version 129 /* operation code for \.{mpversion} */
4899 @d envelope_of 130 /* operation code for \.{envelope} */
4900
4901 @c static void mp_print_op (MP mp,quarterword c) { 
4902   if (c<=mp_numeric_type ) {
4903     mp_print_type(mp, c);
4904   } else {
4905     switch (c) {
4906     case true_code:mp_print(mp, "true"); break;
4907     case false_code:mp_print(mp, "false"); break;
4908     case null_picture_code:mp_print(mp, "nullpicture"); break;
4909     case null_pen_code:mp_print(mp, "nullpen"); break;
4910     case job_name_op:mp_print(mp, "jobname"); break;
4911     case read_string_op:mp_print(mp, "readstring"); break;
4912     case pen_circle:mp_print(mp, "pencircle"); break;
4913     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4914     case read_from_op:mp_print(mp, "readfrom"); break;
4915     case close_from_op:mp_print(mp, "closefrom"); break;
4916     case odd_op:mp_print(mp, "odd"); break;
4917     case known_op:mp_print(mp, "known"); break;
4918     case unknown_op:mp_print(mp, "unknown"); break;
4919     case not_op:mp_print(mp, "not"); break;
4920     case decimal:mp_print(mp, "decimal"); break;
4921     case reverse:mp_print(mp, "reverse"); break;
4922     case make_path_op:mp_print(mp, "makepath"); break;
4923     case make_pen_op:mp_print(mp, "makepen"); break;
4924     case oct_op:mp_print(mp, "oct"); break;
4925     case hex_op:mp_print(mp, "hex"); break;
4926     case ASCII_op:mp_print(mp, "ASCII"); break;
4927     case char_op:mp_print(mp, "char"); break;
4928     case length_op:mp_print(mp, "length"); break;
4929     case turning_op:mp_print(mp, "turningnumber"); break;
4930     case x_part:mp_print(mp, "xpart"); break;
4931     case y_part:mp_print(mp, "ypart"); break;
4932     case xx_part:mp_print(mp, "xxpart"); break;
4933     case xy_part:mp_print(mp, "xypart"); break;
4934     case yx_part:mp_print(mp, "yxpart"); break;
4935     case yy_part:mp_print(mp, "yypart"); break;
4936     case red_part:mp_print(mp, "redpart"); break;
4937     case green_part:mp_print(mp, "greenpart"); break;
4938     case blue_part:mp_print(mp, "bluepart"); break;
4939     case cyan_part:mp_print(mp, "cyanpart"); break;
4940     case magenta_part:mp_print(mp, "magentapart"); break;
4941     case yellow_part:mp_print(mp, "yellowpart"); break;
4942     case black_part:mp_print(mp, "blackpart"); break;
4943     case grey_part:mp_print(mp, "greypart"); break;
4944     case color_model_part:mp_print(mp, "colormodel"); break;
4945     case font_part:mp_print(mp, "fontpart"); break;
4946     case text_part:mp_print(mp, "textpart"); break;
4947     case path_part:mp_print(mp, "pathpart"); break;
4948     case pen_part:mp_print(mp, "penpart"); break;
4949     case dash_part:mp_print(mp, "dashpart"); break;
4950     case sqrt_op:mp_print(mp, "sqrt"); break;
4951     case mp_m_exp_op:mp_print(mp, "mexp"); break;
4952     case mp_m_log_op:mp_print(mp, "mlog"); break;
4953     case sin_d_op:mp_print(mp, "sind"); break;
4954     case cos_d_op:mp_print(mp, "cosd"); break;
4955     case floor_op:mp_print(mp, "floor"); break;
4956     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4957     case char_exists_op:mp_print(mp, "charexists"); break;
4958     case font_size:mp_print(mp, "fontsize"); break;
4959     case ll_corner_op:mp_print(mp, "llcorner"); break;
4960     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4961     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4962     case ur_corner_op:mp_print(mp, "urcorner"); break;
4963     case arc_length:mp_print(mp, "arclength"); break;
4964     case angle_op:mp_print(mp, "angle"); break;
4965     case cycle_op:mp_print(mp, "cycle"); break;
4966     case filled_op:mp_print(mp, "filled"); break;
4967     case stroked_op:mp_print(mp, "stroked"); break;
4968     case textual_op:mp_print(mp, "textual"); break;
4969     case clipped_op:mp_print(mp, "clipped"); break;
4970     case bounded_op:mp_print(mp, "bounded"); break;
4971     case plus:mp_print_char(mp, xord('+')); break;
4972     case minus:mp_print_char(mp, xord('-')); break;
4973     case times:mp_print_char(mp, xord('*')); break;
4974     case over:mp_print_char(mp, xord('/')); break;
4975     case pythag_add:mp_print(mp, "++"); break;
4976     case pythag_sub:mp_print(mp, "+-+"); break;
4977     case or_op:mp_print(mp, "or"); break;
4978     case and_op:mp_print(mp, "and"); break;
4979     case less_than:mp_print_char(mp, xord('<')); break;
4980     case less_or_equal:mp_print(mp, "<="); break;
4981     case greater_than:mp_print_char(mp, xord('>')); break;
4982     case greater_or_equal:mp_print(mp, ">="); break;
4983     case equal_to:mp_print_char(mp, xord('=')); break;
4984     case unequal_to:mp_print(mp, "<>"); break;
4985     case concatenate:mp_print(mp, "&"); break;
4986     case rotated_by:mp_print(mp, "rotated"); break;
4987     case slanted_by:mp_print(mp, "slanted"); break;
4988     case scaled_by:mp_print(mp, "scaled"); break;
4989     case shifted_by:mp_print(mp, "shifted"); break;
4990     case transformed_by:mp_print(mp, "transformed"); break;
4991     case x_scaled:mp_print(mp, "xscaled"); break;
4992     case y_scaled:mp_print(mp, "yscaled"); break;
4993     case z_scaled:mp_print(mp, "zscaled"); break;
4994     case in_font:mp_print(mp, "infont"); break;
4995     case intersect:mp_print(mp, "intersectiontimes"); break;
4996     case substring_of:mp_print(mp, "substring"); break;
4997     case subpath_of:mp_print(mp, "subpath"); break;
4998     case direction_time_of:mp_print(mp, "directiontime"); break;
4999     case point_of:mp_print(mp, "point"); break;
5000     case precontrol_of:mp_print(mp, "precontrol"); break;
5001     case postcontrol_of:mp_print(mp, "postcontrol"); break;
5002     case pen_offset_of:mp_print(mp, "penoffset"); break;
5003     case arc_time_of:mp_print(mp, "arctime"); break;
5004     case mp_version:mp_print(mp, "mpversion"); break;
5005     case envelope_of:mp_print(mp, "envelope"); break;
5006     default: mp_print(mp, ".."); break;
5007     }
5008   }
5009 }
5010
5011 @ \MP\ also has a bunch of internal parameters that a user might want to
5012 fuss with. Every such parameter has an identifying code number, defined here.
5013
5014 @<Types...@>=
5015 enum mp_given_internal {
5016   mp_tracing_titles=1, /* show titles online when they appear */
5017   mp_tracing_equations, /* show each variable when it becomes known */
5018   mp_tracing_capsules, /* show capsules too */
5019   mp_tracing_choices, /* show the control points chosen for paths */
5020   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
5021   mp_tracing_commands, /* show commands and operations before they are performed */
5022   mp_tracing_restores, /* show when a variable or internal is restored */
5023   mp_tracing_macros, /* show macros before they are expanded */
5024   mp_tracing_output, /* show digitized edges as they are output */
5025   mp_tracing_stats, /* show memory usage at end of job */
5026   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
5027   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
5028   mp_year, /* the current year (e.g., 1984) */
5029   mp_month, /* the current month (e.g., 3 $\equiv$ March) */
5030   mp_day, /* the current day of the month */
5031   mp_time, /* the number of minutes past midnight when this job started */
5032   mp_char_code, /* the number of the next character to be output */
5033   mp_char_ext, /* the extension code of the next character to be output */
5034   mp_char_wd, /* the width of the next character to be output */
5035   mp_char_ht, /* the height of the next character to be output */
5036   mp_char_dp, /* the depth of the next character to be output */
5037   mp_char_ic, /* the italic correction of the next character to be output */
5038   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
5039   mp_pausing, /* positive to display lines on the terminal before they are read */
5040   mp_showstopping, /* positive to stop after each \&{show} command */
5041   mp_fontmaking, /* positive if font metric output is to be produced */
5042   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
5043   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
5044   mp_miterlimit, /* controls miter length as in \ps */
5045   mp_warning_check, /* controls error message when variable value is large */
5046   mp_boundary_char, /* the right boundary character for ligatures */
5047   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
5048   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
5049   mp_default_color_model, /* the default color model for unspecified items */
5050   mp_restore_clip_color,
5051   mp_procset, /* wether or not create PostScript command shortcuts */
5052   mp_gtroffmode  /* whether the user specified |-troff| on the command line */
5053 };
5054
5055 @
5056
5057 @d max_given_internal mp_gtroffmode
5058
5059 @<Glob...@>=
5060 scaled *internal;  /* the values of internal quantities */
5061 char **int_name;  /* their names */
5062 int int_ptr;  /* the maximum internal quantity defined so far */
5063 int max_internal; /* current maximum number of internal quantities */
5064
5065 @ @<Option variables@>=
5066 int troff_mode; 
5067
5068 @ @<Allocate or initialize ...@>=
5069 mp->max_internal=2*max_given_internal;
5070 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5071 memset(mp->internal,0,(mp->max_internal+1)* sizeof(scaled));
5072 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5073 memset(mp->int_name,0,(mp->max_internal+1) * sizeof(char *));
5074 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5075
5076 @ @<Exported function ...@>=
5077 int mp_troff_mode(MP mp);
5078
5079 @ @c
5080 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5081
5082 @ @<Set initial ...@>=
5083 mp->int_ptr=max_given_internal;
5084
5085 @ The symbolic names for internal quantities are put into \MP's hash table
5086 by using a routine called |primitive|, which will be defined later. Let us
5087 enter them now, so that we don't have to list all those names again
5088 anywhere else.
5089
5090 @<Put each of \MP's primitives into the hash table@>=
5091 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5092 @:tracingtitles_}{\&{tracingtitles} primitive@>
5093 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5094 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5095 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5096 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5097 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5098 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5099 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5100 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5101 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5102 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5103 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5104 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5105 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5106 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5107 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5108 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5109 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5110 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5111 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5112 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5113 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5114 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5115 mp_primitive(mp, "year",internal_quantity,mp_year);
5116 @:mp_year_}{\&{year} primitive@>
5117 mp_primitive(mp, "month",internal_quantity,mp_month);
5118 @:mp_month_}{\&{month} primitive@>
5119 mp_primitive(mp, "day",internal_quantity,mp_day);
5120 @:mp_day_}{\&{day} primitive@>
5121 mp_primitive(mp, "time",internal_quantity,mp_time);
5122 @:time_}{\&{time} primitive@>
5123 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5124 @:mp_char_code_}{\&{charcode} primitive@>
5125 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5126 @:mp_char_ext_}{\&{charext} primitive@>
5127 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5128 @:mp_char_wd_}{\&{charwd} primitive@>
5129 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5130 @:mp_char_ht_}{\&{charht} primitive@>
5131 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5132 @:mp_char_dp_}{\&{chardp} primitive@>
5133 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5134 @:mp_char_ic_}{\&{charic} primitive@>
5135 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5136 @:mp_design_size_}{\&{designsize} primitive@>
5137 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5138 @:mp_pausing_}{\&{pausing} primitive@>
5139 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5140 @:mp_showstopping_}{\&{showstopping} primitive@>
5141 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5142 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5143 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5144 @:mp_linejoin_}{\&{linejoin} primitive@>
5145 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5146 @:mp_linecap_}{\&{linecap} primitive@>
5147 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5148 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5149 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5150 @:mp_warning_check_}{\&{warningcheck} primitive@>
5151 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5152 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5153 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5154 @:mp_prologues_}{\&{prologues} primitive@>
5155 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5156 @:mp_true_corners_}{\&{truecorners} primitive@>
5157 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5158 @:mp_procset_}{\&{mpprocset} primitive@>
5159 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5160 @:troffmode_}{\&{troffmode} primitive@>
5161 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5162 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5163 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5164 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5165
5166 @ Colors can be specified in four color models. In the special
5167 case of |no_model|, MetaPost does not output any color operator to
5168 the postscript output.
5169
5170 Note: these values are passed directly on to |with_option|. This only
5171 works because the other possible values passed to |with_option| are
5172 8 and 10 respectively (from |with_pen| and |with_picture|).
5173
5174 There is a first state, that is only used for |gs_colormodel|. It flags
5175 the fact that there has not been any kind of color specification by
5176 the user so far in the game.
5177
5178 @(mplib.h@>=
5179 enum mp_color_model {
5180   mp_no_model=1,
5181   mp_grey_model=3,
5182   mp_rgb_model=5,
5183   mp_cmyk_model=7,
5184   mp_uninitialized_model=9
5185 };
5186
5187
5188 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5189 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5190 mp->internal[mp_restore_clip_color]=unity;
5191
5192 @ Well, we do have to list the names one more time, for use in symbolic
5193 printouts.
5194
5195 @<Initialize table...@>=
5196 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5197 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5198 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5199 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5200 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5201 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5202 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5203 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5204 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5205 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5206 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5207 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5208 mp->int_name[mp_year]=xstrdup("year");
5209 mp->int_name[mp_month]=xstrdup("month");
5210 mp->int_name[mp_day]=xstrdup("day");
5211 mp->int_name[mp_time]=xstrdup("time");
5212 mp->int_name[mp_char_code]=xstrdup("charcode");
5213 mp->int_name[mp_char_ext]=xstrdup("charext");
5214 mp->int_name[mp_char_wd]=xstrdup("charwd");
5215 mp->int_name[mp_char_ht]=xstrdup("charht");
5216 mp->int_name[mp_char_dp]=xstrdup("chardp");
5217 mp->int_name[mp_char_ic]=xstrdup("charic");
5218 mp->int_name[mp_design_size]=xstrdup("designsize");
5219 mp->int_name[mp_pausing]=xstrdup("pausing");
5220 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5221 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5222 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5223 mp->int_name[mp_linecap]=xstrdup("linecap");
5224 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5225 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5226 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5227 mp->int_name[mp_prologues]=xstrdup("prologues");
5228 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5229 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5230 mp->int_name[mp_procset]=xstrdup("mpprocset");
5231 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5232 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5233
5234 @ The following procedure, which is called just before \MP\ initializes its
5235 input and output, establishes the initial values of the date and time.
5236 @^system dependencies@>
5237
5238 Note that the values are |scaled| integers. Hence \MP\ can no longer
5239 be used after the year 32767.
5240
5241 @c 
5242 static void mp_fix_date_and_time (MP mp) { 
5243   time_t aclock = time ((time_t *) 0);
5244   struct tm *tmptr = localtime (&aclock);
5245   mp->internal[mp_time]=
5246       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5247   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5248   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5249   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5250 }
5251
5252 @ @<Declarations@>=
5253 static void mp_fix_date_and_time (MP mp) ;
5254
5255 @ \MP\ is occasionally supposed to print diagnostic information that
5256 goes only into the transcript file, unless |mp_tracing_online| is positive.
5257 Now that we have defined |mp_tracing_online| we can define
5258 two routines that adjust the destination of print commands:
5259
5260 @<Declarations@>=
5261 static void mp_begin_diagnostic (MP mp) ;
5262 static void mp_end_diagnostic (MP mp,boolean blank_line);
5263 static void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) ;
5264
5265 @ @<Basic printing...@>=
5266 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5267   mp->old_setting=mp->selector;
5268   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5269     decr(mp->selector);
5270     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5271   }
5272 }
5273 @#
5274 void mp_end_diagnostic (MP mp,boolean blank_line) {
5275   /* restore proper conditions after tracing */
5276   mp_print_nl(mp, "");
5277   if ( blank_line ) mp_print_ln(mp);
5278   mp->selector=mp->old_setting;
5279 }
5280
5281
5282
5283 @<Glob...@>=
5284 unsigned int old_setting;
5285
5286 @ We will occasionally use |begin_diagnostic| in connection with line-number
5287 printing, as follows. (The parameter |s| is typically |"Path"| or
5288 |"Cycle spec"|, etc.)
5289
5290 @<Basic printing...@>=
5291 void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) { 
5292   mp_begin_diagnostic(mp);
5293   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5294   mp_print(mp, " at line "); 
5295   mp_print_int(mp, mp_true_line(mp));
5296   mp_print(mp, t); mp_print_char(mp, xord(':'));
5297 }
5298
5299 @ The 256 |ASCII_code| characters are grouped into classes by means of
5300 the |char_class| table. Individual class numbers have no semantic
5301 or syntactic significance, except in a few instances defined here.
5302 There's also |max_class|, which can be used as a basis for additional
5303 class numbers in nonstandard extensions of \MP.
5304
5305 @d digit_class 0 /* the class number of \.{0123456789} */
5306 @d period_class 1 /* the class number of `\..' */
5307 @d space_class 2 /* the class number of spaces and nonstandard characters */
5308 @d percent_class 3 /* the class number of `\.\%' */
5309 @d string_class 4 /* the class number of `\."' */
5310 @d right_paren_class 8 /* the class number of `\.)' */
5311 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5312 @d letter_class 9 /* letters and the underline character */
5313 @d left_bracket_class 17 /* `\.[' */
5314 @d right_bracket_class 18 /* `\.]' */
5315 @d invalid_class 20 /* bad character in the input */
5316 @d max_class 20 /* the largest class number */
5317
5318 @<Glob...@>=
5319 int char_class[256]; /* the class numbers */
5320
5321 @ If changes are made to accommodate non-ASCII character sets, they should
5322 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5323 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5324 @^system dependencies@>
5325
5326 @<Set initial ...@>=
5327 for (k='0';k<='9';k++) 
5328   mp->char_class[k]=digit_class;
5329 mp->char_class['.']=period_class;
5330 mp->char_class[' ']=space_class;
5331 mp->char_class['%']=percent_class;
5332 mp->char_class['"']=string_class;
5333 mp->char_class[',']=5;
5334 mp->char_class[';']=6;
5335 mp->char_class['(']=7;
5336 mp->char_class[')']=right_paren_class;
5337 for (k='A';k<= 'Z';k++ )
5338   mp->char_class[k]=letter_class;
5339 for (k='a';k<='z';k++) 
5340   mp->char_class[k]=letter_class;
5341 mp->char_class['_']=letter_class;
5342 mp->char_class['<']=10;
5343 mp->char_class['=']=10;
5344 mp->char_class['>']=10;
5345 mp->char_class[':']=10;
5346 mp->char_class['|']=10;
5347 mp->char_class['`']=11;
5348 mp->char_class['\'']=11;
5349 mp->char_class['+']=12;
5350 mp->char_class['-']=12;
5351 mp->char_class['/']=13;
5352 mp->char_class['*']=13;
5353 mp->char_class['\\']=13;
5354 mp->char_class['!']=14;
5355 mp->char_class['?']=14;
5356 mp->char_class['#']=15;
5357 mp->char_class['&']=15;
5358 mp->char_class['@@']=15;
5359 mp->char_class['$']=15;
5360 mp->char_class['^']=16;
5361 mp->char_class['~']=16;
5362 mp->char_class['[']=left_bracket_class;
5363 mp->char_class[']']=right_bracket_class;
5364 mp->char_class['{']=19;
5365 mp->char_class['}']=19;
5366 for (k=0;k<' ';k++)
5367   mp->char_class[k]=invalid_class;
5368 mp->char_class['\t']=space_class;
5369 mp->char_class['\f']=space_class;
5370 for (k=127;k<=255;k++)
5371   mp->char_class[k]=invalid_class;
5372
5373 @* \[13] The hash table.
5374 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5375 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5376 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5377 table, it is never removed.
5378
5379 The actual sequence of characters forming a symbolic token is
5380 stored in the |str_pool| array together with all the other strings. An
5381 auxiliary array |hash| consists of items with two halfword fields per
5382 word. The first of these, called |mp_next(p)|, points to the next identifier
5383 belonging to the same coalesced list as the identifier corresponding to~|p|;
5384 and the other, called |text(p)|, points to the |str_start| entry for
5385 |p|'s identifier. If position~|p| of the hash table is empty, we have
5386 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5387 hash list, we have |mp_next(p)=0|.
5388
5389 An auxiliary pointer variable called |hash_used| is maintained in such a
5390 way that all locations |p>=hash_used| are nonempty. The global variable
5391 |st_count| tells how many symbolic tokens have been defined, if statistics
5392 are being kept.
5393
5394 The first 256 locations of |hash| are reserved for symbols of length one.
5395
5396 There's a parallel array called |eqtb| that contains the current equivalent
5397 values of each symbolic token. The entries of this array consist of
5398 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5399 piece of information that qualifies the |eq_type|).
5400
5401 @d mp_next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5402 @d text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5403 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5404 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5405 @d hash_base 257 /* hashing actually starts here */
5406 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5407
5408 @<Glob...@>=
5409 pointer hash_used; /* allocation pointer for |hash| */
5410 integer st_count; /* total number of known identifiers */
5411
5412 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5413 since they are used in error recovery.
5414
5415 @d hash_top (integer)(hash_base+mp->hash_size) /* the first location of the frozen area */
5416 @d frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5417 @d frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5418 @d frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5419 @d frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5420 @d frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5421 @d frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5422 @d frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5423 @d frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5424 @d frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5425 @d frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5426 @d frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5427 @d frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5428 @d frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5429 @d frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5430 @d frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5431 @d hash_end (integer)(hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5432
5433 @<Glob...@>=
5434 two_halves *hash; /* the hash table */
5435 two_halves *eqtb; /* the equivalents */
5436
5437 @ @<Allocate or initialize ...@>=
5438 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5439 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5440
5441 @ @<Dealloc variables@>=
5442 xfree(mp->hash);
5443 xfree(mp->eqtb);
5444
5445 @ @<Set init...@>=
5446 mp_next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5447 for (k=2;k<=hash_end;k++)  { 
5448   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5449 }
5450
5451 @ @<Initialize table entries...@>=
5452 mp->hash_used=frozen_inaccessible; /* nothing is used */
5453 mp->st_count=0;
5454 text(frozen_bad_vardef)=intern("a bad variable");
5455 text(frozen_etex)=intern("etex");
5456 text(frozen_mpx_break)=intern("mpxbreak");
5457 text(frozen_fi)=intern("fi");
5458 text(frozen_end_group)=intern("endgroup");
5459 text(frozen_end_def)=intern("enddef");
5460 text(frozen_end_for)=intern("endfor");
5461 text(frozen_semicolon)=intern(";");
5462 text(frozen_colon)=intern(":");
5463 text(frozen_slash)=intern("/");
5464 text(frozen_left_bracket)=intern("[");
5465 text(frozen_right_delimiter)=intern(")");
5466 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5467 eq_type(frozen_right_delimiter)=right_delimiter;
5468
5469 @ @<Check the ``constant'' values...@>=
5470 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5471
5472 @ Here is the subroutine that searches the hash table for an identifier
5473 that matches a given string of length~|l| appearing in |buffer[j..
5474 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5475 will always be found, and the corresponding hash table address
5476 will be returned.
5477
5478 @c 
5479 static pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5480   integer h; /* hash code */
5481   pointer p; /* index in |hash| array */
5482   pointer k; /* index in |buffer| array */
5483   if (l==1) {
5484     @<Treat special case of length 1 and |break|@>;
5485   }
5486   @<Compute the hash code |h|@>;
5487   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5488   while (true)  { 
5489         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5490       break;
5491     if ( mp_next(p)==0 ) {
5492       @<Insert a new symbolic token after |p|, then
5493         make |p| point to it and |break|@>;
5494     }
5495     p=mp_next(p);
5496   }
5497   return p;
5498 }
5499
5500 @ @<Treat special case of length 1...@>=
5501  p=mp->buffer[j]+1; text(p)=p-1; return p;
5502
5503
5504 @ @<Insert a new symbolic...@>=
5505 {
5506 if ( text(p)>0 ) { 
5507   do {  
5508     if ( hash_is_full )
5509       mp_overflow(mp, "hash size",(integer)mp->hash_size);
5510 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5511     decr(mp->hash_used);
5512   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5513   mp_next(p)=mp->hash_used; 
5514   p=mp->hash_used;
5515 }
5516 str_room(l);
5517 for (k=j;k<=j+l-1;k++) {
5518   append_char(mp->buffer[k]);
5519 }
5520 text(p)=mp_make_string(mp); 
5521 mp->str_ref[text(p)]=max_str_ref;
5522 incr(mp->st_count);
5523 break;
5524 }
5525
5526
5527 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5528 should be a prime number.  The theory of hashing tells us to expect fewer
5529 than two table probes, on the average, when the search is successful.
5530 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5531 @^Vitter, Jeffrey Scott@>
5532
5533 @<Compute the hash code |h|@>=
5534 h=mp->buffer[j];
5535 for (k=j+1;k<=j+l-1;k++){ 
5536   h=h+h+mp->buffer[k];
5537   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5538 }
5539
5540 @ @<Search |eqtb| for equivalents equal to |p|@>=
5541 for (q=1;q<=hash_end;q++) { 
5542   if ( equiv(q)==p ) { 
5543     mp_print_nl(mp, "EQUIV("); 
5544     mp_print_int(mp, q); 
5545     mp_print_char(mp, xord(')'));
5546   }
5547 }
5548
5549 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5550 table, together with their command code (which will be the |eq_type|)
5551 and an operand (which will be the |equiv|). The |primitive| procedure
5552 does this, in a way that no \MP\ user can. The global value |cur_sym|
5553 contains the new |eqtb| pointer after |primitive| has acted.
5554
5555 @c 
5556 static void mp_primitive (MP mp, const char *ss, halfword c, halfword o) {
5557   pool_pointer k; /* index into |str_pool| */
5558   quarterword j; /* index into |buffer| */
5559   quarterword l; /* length of the string */
5560   str_number s;
5561   s = intern(ss);
5562   k=mp->str_start[s]; l=str_stop(s)-k;
5563   /* we will move |s| into the (empty) |buffer| */
5564   for (j=0;j<=l-1;j++) {
5565     mp->buffer[j]=mp->str_pool[k+j];
5566   }
5567   mp->cur_sym=mp_id_lookup(mp, 0,l);
5568   if ( s>=256 ) { /* we don't want to have the string twice */
5569     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5570   };
5571   eq_type(mp->cur_sym)=c; 
5572   equiv(mp->cur_sym)=o;
5573 }
5574
5575
5576 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5577 by their |eq_type| alone. These primitives are loaded into the hash table
5578 as follows:
5579
5580 @<Put each of \MP's primitives into the hash table@>=
5581 mp_primitive(mp, "..",path_join,0);
5582 @:.._}{\.{..} primitive@>
5583 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5584 @:[ }{\.{[} primitive@>
5585 mp_primitive(mp, "]",right_bracket,0);
5586 @:] }{\.{]} primitive@>
5587 mp_primitive(mp, "}",right_brace,0);
5588 @:]]}{\.{\char`\}} primitive@>
5589 mp_primitive(mp, "{",left_brace,0);
5590 @:][}{\.{\char`\{} primitive@>
5591 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5592 @:: }{\.{:} primitive@>
5593 mp_primitive(mp, "::",double_colon,0);
5594 @::: }{\.{::} primitive@>
5595 mp_primitive(mp, "||:",bchar_label,0);
5596 @:::: }{\.{\char'174\char'174:} primitive@>
5597 mp_primitive(mp, ":=",assignment,0);
5598 @::=_}{\.{:=} primitive@>
5599 mp_primitive(mp, ",",comma,0);
5600 @:, }{\., primitive@>
5601 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5602 @:; }{\.; primitive@>
5603 mp_primitive(mp, "\\",relax,0);
5604 @:]]\\}{\.{\char`\\} primitive@>
5605 @#
5606 mp_primitive(mp, "addto",add_to_command,0);
5607 @:add_to_}{\&{addto} primitive@>
5608 mp_primitive(mp, "atleast",at_least,0);
5609 @:at_least_}{\&{atleast} primitive@>
5610 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5611 @:begin_group_}{\&{begingroup} primitive@>
5612 mp_primitive(mp, "controls",controls,0);
5613 @:controls_}{\&{controls} primitive@>
5614 mp_primitive(mp, "curl",curl_command,0);
5615 @:curl_}{\&{curl} primitive@>
5616 mp_primitive(mp, "delimiters",delimiters,0);
5617 @:delimiters_}{\&{delimiters} primitive@>
5618 mp_primitive(mp, "endgroup",end_group,0);
5619  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5620 @:endgroup_}{\&{endgroup} primitive@>
5621 mp_primitive(mp, "everyjob",every_job_command,0);
5622 @:every_job_}{\&{everyjob} primitive@>
5623 mp_primitive(mp, "exitif",exit_test,0);
5624 @:exit_if_}{\&{exitif} primitive@>
5625 mp_primitive(mp, "expandafter",expand_after,0);
5626 @:expand_after_}{\&{expandafter} primitive@>
5627 mp_primitive(mp, "interim",interim_command,0);
5628 @:interim_}{\&{interim} primitive@>
5629 mp_primitive(mp, "let",let_command,0);
5630 @:let_}{\&{let} primitive@>
5631 mp_primitive(mp, "newinternal",new_internal,0);
5632 @:new_internal_}{\&{newinternal} primitive@>
5633 mp_primitive(mp, "of",of_token,0);
5634 @:of_}{\&{of} primitive@>
5635 mp_primitive(mp, "randomseed",mp_random_seed,0);
5636 @:mp_random_seed_}{\&{randomseed} primitive@>
5637 mp_primitive(mp, "save",save_command,0);
5638 @:save_}{\&{save} primitive@>
5639 mp_primitive(mp, "scantokens",scan_tokens,0);
5640 @:scan_tokens_}{\&{scantokens} primitive@>
5641 mp_primitive(mp, "shipout",ship_out_command,0);
5642 @:ship_out_}{\&{shipout} primitive@>
5643 mp_primitive(mp, "skipto",skip_to,0);
5644 @:skip_to_}{\&{skipto} primitive@>
5645 mp_primitive(mp, "special",special_command,0);
5646 @:special}{\&{special} primitive@>
5647 mp_primitive(mp, "fontmapfile",special_command,1);
5648 @:fontmapfile}{\&{fontmapfile} primitive@>
5649 mp_primitive(mp, "fontmapline",special_command,2);
5650 @:fontmapline}{\&{fontmapline} primitive@>
5651 mp_primitive(mp, "step",step_token,0);
5652 @:step_}{\&{step} primitive@>
5653 mp_primitive(mp, "str",str_op,0);
5654 @:str_}{\&{str} primitive@>
5655 mp_primitive(mp, "tension",tension,0);
5656 @:tension_}{\&{tension} primitive@>
5657 mp_primitive(mp, "to",to_token,0);
5658 @:to_}{\&{to} primitive@>
5659 mp_primitive(mp, "until",until_token,0);
5660 @:until_}{\&{until} primitive@>
5661 mp_primitive(mp, "within",within_token,0);
5662 @:within_}{\&{within} primitive@>
5663 mp_primitive(mp, "write",write_command,0);
5664 @:write_}{\&{write} primitive@>
5665
5666 @ Each primitive has a corresponding inverse, so that it is possible to
5667 display the cryptic numeric contents of |eqtb| in symbolic form.
5668 Every call of |primitive| in this program is therefore accompanied by some
5669 straightforward code that forms part of the |print_cmd_mod| routine
5670 explained below.
5671
5672 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5673 case add_to_command:mp_print(mp, "addto"); break;
5674 case assignment:mp_print(mp, ":="); break;
5675 case at_least:mp_print(mp, "atleast"); break;
5676 case bchar_label:mp_print(mp, "||:"); break;
5677 case begin_group:mp_print(mp, "begingroup"); break;
5678 case colon:mp_print(mp, ":"); break;
5679 case comma:mp_print(mp, ","); break;
5680 case controls:mp_print(mp, "controls"); break;
5681 case curl_command:mp_print(mp, "curl"); break;
5682 case delimiters:mp_print(mp, "delimiters"); break;
5683 case double_colon:mp_print(mp, "::"); break;
5684 case end_group:mp_print(mp, "endgroup"); break;
5685 case every_job_command:mp_print(mp, "everyjob"); break;
5686 case exit_test:mp_print(mp, "exitif"); break;
5687 case expand_after:mp_print(mp, "expandafter"); break;
5688 case interim_command:mp_print(mp, "interim"); break;
5689 case left_brace:mp_print(mp, "{"); break;
5690 case left_bracket:mp_print(mp, "["); break;
5691 case let_command:mp_print(mp, "let"); break;
5692 case new_internal:mp_print(mp, "newinternal"); break;
5693 case of_token:mp_print(mp, "of"); break;
5694 case path_join:mp_print(mp, ".."); break;
5695 case mp_random_seed:mp_print(mp, "randomseed"); break;
5696 case relax:mp_print_char(mp, xord('\\')); break;
5697 case right_brace:mp_print_char(mp, xord('}')); break;
5698 case right_bracket:mp_print_char(mp, xord(']')); break;
5699 case save_command:mp_print(mp, "save"); break;
5700 case scan_tokens:mp_print(mp, "scantokens"); break;
5701 case semicolon:mp_print_char(mp, xord(';')); break;
5702 case ship_out_command:mp_print(mp, "shipout"); break;
5703 case skip_to:mp_print(mp, "skipto"); break;
5704 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5705                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5706                  mp_print(mp, "special"); break;
5707 case step_token:mp_print(mp, "step"); break;
5708 case str_op:mp_print(mp, "str"); break;
5709 case tension:mp_print(mp, "tension"); break;
5710 case to_token:mp_print(mp, "to"); break;
5711 case until_token:mp_print(mp, "until"); break;
5712 case within_token:mp_print(mp, "within"); break;
5713 case write_command:mp_print(mp, "write"); break;
5714
5715 @ We will deal with the other primitives later, at some point in the program
5716 where their |eq_type| and |equiv| values are more meaningful.  For example,
5717 the primitives for macro definitions will be loaded when we consider the
5718 routines that define macros.
5719 It is easy to find where each particular
5720 primitive was treated by looking in the index at the end; for example, the
5721 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5722
5723 @* \[14] Token lists.
5724 A \MP\ token is either symbolic or numeric or a string, or it denotes
5725 a macro parameter or capsule; so there are five corresponding ways to encode it
5726 @^token@>
5727 internally: (1)~A symbolic token whose hash code is~|p|
5728 is represented by the number |p|, in the |info| field of a single-word
5729 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5730 represented in a two-word node of~|mem|; the |type| field is |known|,
5731 the |name_type| field is |token|, and the |value| field holds~|v|.
5732 The fact that this token appears in a two-word node rather than a
5733 one-word node is, of course, clear from the node address.
5734 (3)~A string token is also represented in a two-word node; the |type|
5735 field is |mp_string_type|, the |name_type| field is |token|, and the
5736 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5737 |name_type=capsule|, and their |type| and |value| fields represent
5738 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5739 are like symbolic tokens in that they appear in |info| fields of
5740 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5741 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5742 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5743 Actual values of these parameters are kept in a separate stack, as we will
5744 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5745 of course, chosen so that there will be no confusion between symbolic
5746 tokens and parameters of various types.
5747
5748 Note that
5749 the `\\{type}' field of a node has nothing to do with ``type'' in a
5750 printer's sense. It's curious that the same word is used in such different ways.
5751
5752 @d type(A)   mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5753 @d name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5754 @d token_node_size 2 /* the number of words in a large token node */
5755 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5756 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5757 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5758 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5759 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5760
5761 @<Check the ``constant''...@>=
5762 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5763
5764 @ We have set aside a two word node beginning at |null| so that we can have
5765 |value(null)=0|.  We will make use of this coincidence later.
5766
5767 @<Initialize table entries...@>=
5768 mp_link(null)=null; value(null)=0;
5769
5770 @ A numeric token is created by the following trivial routine.
5771
5772 @c 
5773 static pointer mp_new_num_tok (MP mp,scaled v) {
5774   pointer p; /* the new node */
5775   p=mp_get_node(mp, token_node_size); value(p)=v;
5776   type(p)=mp_known; name_type(p)=mp_token; 
5777   return p;
5778 }
5779
5780 @ A token list is a singly linked list of nodes in |mem|, where
5781 each node contains a token and a link.  Here's a subroutine that gets rid
5782 of a token list when it is no longer needed.
5783
5784 @c static void mp_flush_token_list (MP mp,pointer p) {
5785   pointer q; /* the node being recycled */
5786   while ( p!=null ) { 
5787     q=p; p=mp_link(p);
5788     if ( q>=mp->hi_mem_min ) {
5789      free_avail(q);
5790     } else { 
5791       switch (type(q)) {
5792       case mp_vacuous: case mp_boolean_type: case mp_known:
5793         break;
5794       case mp_string_type:
5795         delete_str_ref(value(q));
5796         break;
5797       case unknown_types: case mp_pen_type: case mp_path_type: 
5798       case mp_picture_type: case mp_pair_type: case mp_color_type:
5799       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5800       case mp_proto_dependent: case mp_independent:
5801         mp_recycle_value(mp,q);
5802         break;
5803       default: mp_confusion(mp, "token");
5804 @:this can't happen token}{\quad token@>
5805       }
5806       mp_free_node(mp, q,token_node_size);
5807     }
5808   }
5809 }
5810
5811 @ The procedure |show_token_list|, which prints a symbolic form of
5812 the token list that starts at a given node |p|, illustrates these
5813 conventions. The token list being displayed should not begin with a reference
5814 count. However, the procedure is intended to be fairly robust, so that if the
5815 memory links are awry or if |p| is not really a pointer to a token list,
5816 almost nothing catastrophic can happen.
5817
5818 An additional parameter |q| is also given; this parameter is either null
5819 or it points to a node in the token list where a certain magic computation
5820 takes place that will be explained later. (Basically, |q| is non-null when
5821 we are printing the two-line context information at the time of an error
5822 message; |q| marks the place corresponding to where the second line
5823 should begin.)
5824
5825 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5826 of printing exceeds a given limit~|l|; the length of printing upon entry is
5827 assumed to be a given amount called |null_tally|. (Note that
5828 |show_token_list| sometimes uses itself recursively to print
5829 variable names within a capsule.)
5830 @^recursion@>
5831
5832 Unusual entries are printed in the form of all-caps tokens
5833 preceded by a space, e.g., `\.{\char`\ BAD}'.
5834
5835 @<Declarations@>=
5836 static void mp_show_token_list (MP mp, integer p, integer q, integer l,
5837                          integer null_tally) ;
5838
5839 @ @c
5840 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5841                          integer null_tally) {
5842   quarterword class,c; /* the |char_class| of previous and new tokens */
5843   integer r,v; /* temporary registers */
5844   class=percent_class;
5845   mp->tally=null_tally;
5846   while ( (p!=null) && (mp->tally<l) ) { 
5847     if ( p==q ) 
5848       @<Do magic computation@>;
5849     @<Display token |p| and set |c| to its class;
5850       but |return| if there are problems@>;
5851     class=c; p=mp_link(p);
5852   }
5853   if ( p!=null ) 
5854      mp_print(mp, " ETC.");
5855 @.ETC@>
5856   return;
5857 }
5858
5859 @ @<Display token |p| and set |c| to its class...@>=
5860 c=letter_class; /* the default */
5861 if ( (p<0)||(p>mp->mem_end) ) { 
5862   mp_print(mp, " CLOBBERED"); return;
5863 @.CLOBBERED@>
5864 }
5865 if ( p<mp->hi_mem_min ) { 
5866   @<Display two-word token@>;
5867 } else { 
5868   r=info(p);
5869   if ( r>=expr_base ) {
5870      @<Display a parameter token@>;
5871   } else {
5872     if ( r<1 ) {
5873       if ( r==0 ) { 
5874         @<Display a collective subscript@>
5875       } else {
5876         mp_print(mp, " IMPOSSIBLE");
5877 @.IMPOSSIBLE@>
5878       }
5879     } else { 
5880       r=text(r);
5881       if ( (r<0)||(r>mp->max_str_ptr) ) {
5882         mp_print(mp, " NONEXISTENT");
5883 @.NONEXISTENT@>
5884       } else {
5885        @<Print string |r| as a symbolic token
5886         and set |c| to its class@>;
5887       }
5888     }
5889   }
5890 }
5891
5892 @ @<Display two-word token@>=
5893 if ( name_type(p)==mp_token ) {
5894   if ( type(p)==mp_known ) {
5895     @<Display a numeric token@>;
5896   } else if ( type(p)!=mp_string_type ) {
5897     mp_print(mp, " BAD");
5898 @.BAD@>
5899   } else { 
5900     mp_print_char(mp, xord('"')); mp_print_str(mp, value(p)); mp_print_char(mp, xord('"'));
5901     c=string_class;
5902   }
5903 } else if ((name_type(p)!=mp_capsule)||(type(p)<mp_vacuous)||(type(p)>mp_independent) ) {
5904   mp_print(mp, " BAD");
5905 } else { 
5906   mp_print_capsule(mp,p); c=right_paren_class;
5907 }
5908
5909 @ @<Display a numeric token@>=
5910 if ( class==digit_class ) 
5911   mp_print_char(mp, xord(' '));
5912 v=value(p);
5913 if ( v<0 ){ 
5914   if ( class==left_bracket_class ) 
5915     mp_print_char(mp, xord(' '));
5916   mp_print_char(mp, xord('[')); mp_print_scaled(mp, v); mp_print_char(mp, xord(']'));
5917   c=right_bracket_class;
5918 } else { 
5919   mp_print_scaled(mp, v); c=digit_class;
5920 }
5921
5922
5923 @ Strictly speaking, a genuine token will never have |info(p)=0|.
5924 But we will see later (in the |print_variable_name| routine) that
5925 it is convenient to let |info(p)=0| stand for `\.{[]}'.
5926
5927 @<Display a collective subscript@>=
5928 {
5929 if ( class==left_bracket_class ) 
5930   mp_print_char(mp, xord(' '));
5931 mp_print(mp, "[]"); c=right_bracket_class;
5932 }
5933
5934 @ @<Display a parameter token@>=
5935 {
5936 if ( r<suffix_base ) { 
5937   mp_print(mp, "(EXPR"); r=r-(expr_base);
5938 @.EXPR@>
5939 } else if ( r<text_base ) { 
5940   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5941 @.SUFFIX@>
5942 } else { 
5943   mp_print(mp, "(TEXT"); r=r-(text_base);
5944 @.TEXT@>
5945 }
5946 mp_print_int(mp, r); mp_print_char(mp, xord(')')); c=right_paren_class;
5947 }
5948
5949
5950 @ @<Print string |r| as a symbolic token...@>=
5951
5952 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5953 if ( c==class ) {
5954   switch (c) {
5955   case letter_class:mp_print_char(mp, xord('.')); break;
5956   case isolated_classes: break;
5957   default: mp_print_char(mp, xord(' ')); break;
5958   }
5959 }
5960 mp_print_str(mp, r);
5961 }
5962
5963 @ @<Declarations@>=
5964 static void mp_print_capsule (MP mp, pointer p);
5965
5966 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5967 void mp_print_capsule (MP mp, pointer p) { 
5968   mp_print_char(mp, xord('(')); mp_print_exp(mp,p,0); mp_print_char(mp, xord(')'));
5969 }
5970
5971 @ Macro definitions are kept in \MP's memory in the form of token lists
5972 that have a few extra one-word nodes at the beginning.
5973
5974 The first node contains a reference count that is used to tell when the
5975 list is no longer needed. To emphasize the fact that a reference count is
5976 present, we shall refer to the |info| field of this special node as the
5977 |ref_count| field.
5978 @^reference counts@>
5979
5980 The next node or nodes after the reference count serve to describe the
5981 formal parameters. They consist of zero or more parameter tokens followed
5982 by a code for the type of macro.
5983
5984 @d ref_count info
5985   /* reference count preceding a macro definition or picture header */
5986 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
5987 @d general_macro 0 /* preface to a macro defined with a parameter list */
5988 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
5989 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
5990 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
5991 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
5992 @d of_macro 5 /* preface to a macro with
5993   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
5994 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
5995 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
5996
5997 @c 
5998 static void mp_delete_mac_ref (MP mp,pointer p) {
5999   /* |p| points to the reference count of a macro list that is
6000     losing one reference */
6001   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
6002   else decr(ref_count(p));
6003 }
6004
6005 @ The following subroutine displays a macro, given a pointer to its
6006 reference count.
6007
6008 @c 
6009 static void mp_show_macro (MP mp, pointer p, integer q, integer l) {
6010   pointer r; /* temporary storage */
6011   p=mp_link(p); /* bypass the reference count */
6012   while ( info(p)>text_macro ){ 
6013     r=mp_link(p); mp_link(p)=null;
6014     mp_show_token_list(mp, p,null,l,0); mp_link(p)=r; p=r;
6015     if ( l>0 ) l=l-mp->tally; else return;
6016   } /* control printing of `\.{ETC.}' */
6017 @.ETC@>
6018   mp->tally=0;
6019   switch(info(p)) {
6020   case general_macro:mp_print(mp, "->"); break;
6021 @.->@>
6022   case primary_macro: case secondary_macro: case tertiary_macro:
6023     mp_print_char(mp, xord('<'));
6024     mp_print_cmd_mod(mp, param_type,info(p)); 
6025     mp_print(mp, ">->");
6026     break;
6027   case expr_macro:mp_print(mp, "<expr>->"); break;
6028   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
6029   case suffix_macro:mp_print(mp, "<suffix>->"); break;
6030   case text_macro:mp_print(mp, "<text>->"); break;
6031   } /* there are no other cases */
6032   mp_show_token_list(mp, mp_link(p),q,l-mp->tally,0);
6033 }
6034
6035 @* \[15] Data structures for variables.
6036 The variables of \MP\ programs can be simple, like `\.x', or they can
6037 combine the structural properties of arrays and records, like `\.{x20a.b}'.
6038 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
6039 example, `\.{boolean} \.{x[]a.b}'. It's time for us to study how such
6040 things are represented inside of the computer.
6041
6042 Each variable value occupies two consecutive words, either in a two-word
6043 node called a value node, or as a two-word subfield of a larger node.  One
6044 of those two words is called the |value| field; it is an integer,
6045 containing either a |scaled| numeric value or the representation of some
6046 other type of quantity. (It might also be subdivided into halfwords, in
6047 which case it is referred to by other names instead of |value|.) The other
6048 word is broken into subfields called |type|, |name_type|, and |link|.  The
6049 |type| field is a quarterword that specifies the variable's type, and
6050 |name_type| is a quarterword from which \MP\ can reconstruct the
6051 variable's name (sometimes by using the |link| field as well).  Thus, only
6052 1.25 words are actually devoted to the value itself; the other
6053 three-quarters of a word are overhead, but they aren't wasted because they
6054 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6055
6056 In this section we shall be concerned only with the structural aspects of
6057 variables, not their values. Later parts of the program will change the
6058 |type| and |value| fields, but we shall treat those fields as black boxes
6059 whose contents should not be touched.
6060
6061 However, if the |type| field is |mp_structured|, there is no |value| field,
6062 and the second word is broken into two pointer fields called |attr_head|
6063 and |subscr_head|. Those fields point to additional nodes that
6064 contain structural information, as we shall see.
6065
6066 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6067 @d attr_head(A)   info(subscr_head_loc((A))) /* pointer to attribute info */
6068 @d subscr_head(A)   mp_link(subscr_head_loc((A))) /* pointer to subscript info */
6069 @d value_node_size 2 /* the number of words in a value node */
6070
6071 @ An attribute node is three words long. Two of these words contain |type|
6072 and |value| fields as described above, and the third word contains
6073 additional information:  There is an |attr_loc| field, which contains the
6074 hash address of the token that names this attribute; and there's also a
6075 |parent| field, which points to the value node of |mp_structured| type at the
6076 next higher level (i.e., at the level to which this attribute is
6077 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6078 |link| field points to the next attribute with the same parent; these are
6079 arranged in increasing order, so that |attr_loc(mp_link(p))>attr_loc(p)|. The
6080 final attribute node links to the constant |end_attr|, whose |attr_loc|
6081 field is greater than any legal hash address. The |attr_head| in the
6082 parent points to a node whose |name_type| is |mp_structured_root|; this
6083 node represents the null attribute, i.e., the variable that is relevant
6084 when no attributes are attached to the parent. The |attr_head| node
6085 has the fields of either
6086 a value node, a subscript node, or an attribute node, depending on what
6087 the parent would be if it were not structured; but the subscript and
6088 attribute fields are ignored, so it effectively contains only the data of
6089 a value node. The |link| field in this special node points to an attribute
6090 node whose |attr_loc| field is zero; the latter node represents a collective
6091 subscript `\.{[]}' attached to the parent, and its |link| field points to
6092 the first non-special attribute node (or to |end_attr| if there are none).
6093
6094 A subscript node likewise occupies three words, with |type| and |value| fields
6095 plus extra information; its |name_type| is |subscr|. In this case the
6096 third word is called the |subscript| field, which is a |scaled| integer.
6097 The |link| field points to the subscript node with the next larger
6098 subscript, if any; otherwise the |link| points to the attribute node
6099 for collective subscripts at this level. We have seen that the latter node
6100 contains an upward pointer, so that the parent can be deduced.
6101
6102 The |name_type| in a parent-less value node is |root|, and the |link|
6103 is the hash address of the token that names this value.
6104
6105 In other words, variables have a hierarchical structure that includes
6106 enough threads running around so that the program is able to move easily
6107 between siblings, parents, and children. An example should be helpful:
6108 (The reader is advised to draw a picture while reading the following
6109 description, since that will help to firm up the ideas.)
6110 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6111 and `\.{x20b}' have been mentioned in a user's program, where
6112 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6113 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6114 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6115 node with |name_type(p)=root| and |mp_link(p)=h(x)|. We have |type(p)=mp_structured|,
6116 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6117 node and |r| to a subscript node. (Are you still following this? Use
6118 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6119 |type(q)| and |value(q)|; furthermore
6120 |name_type(q)=mp_structured_root| and |mp_link(q)=q1|, where |q1| points
6121 to an attribute node representing `\.{x[]}'. Thus |name_type(q1)=attr|,
6122 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6123 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6124 |qq| is a  three-word ``attribute-as-value'' node with |type(qq)=numeric_type|
6125 (assuming that \.{x5} is numeric, because |qq| represents `\.{x[]}' 
6126 with no further attributes), |name_type(qq)=structured_root|, 
6127 |attr_loc(qq)=0|, |parent(qq)=p|, and
6128 |mp_link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6129 an attribute node representing `\.{x[][]}', which has never yet
6130 occurred; its |type| field is |undefined|, and its |value| field is
6131 undefined. We have |name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6132 |parent(qq1)=q1|, and |mp_link(qq1)=qq2|. Since |qq2| represents
6133 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6134 |parent(qq2)=q1|, |name_type(qq2)=attr|, |mp_link(qq2)=end_attr|.
6135 (Maybe colored lines will help untangle your picture.)
6136  Node |r| is a subscript node with |type| and |value|
6137 representing `\.{x5}'; |name_type(r)=subscr|, |subscript(r)=5.0|,
6138 and |mp_link(r)=r1| is another subscript node. To complete the picture,
6139 see if you can guess what |mp_link(r1)| is; give up? It's~|q1|.
6140 Furthermore |subscript(r1)=20.0|, |name_type(r1)=subscr|,
6141 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6142 and we finish things off with three more nodes
6143 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6144 with a larger sheet of paper.) The value of variable \.{x20b}
6145 appears in node~|qqq2|, as you can well imagine.
6146
6147 If the example in the previous paragraph doesn't make things crystal
6148 clear, a glance at some of the simpler subroutines below will reveal how
6149 things work out in practice.
6150
6151 The only really unusual thing about these conventions is the use of
6152 collective subscript attributes. The idea is to avoid repeating a lot of
6153 type information when many elements of an array are identical macros
6154 (for which distinct values need not be stored) or when they don't have
6155 all of the possible attributes. Branches of the structure below collective
6156 subscript attributes do not carry actual values except for macro identifiers;
6157 branches of the structure below subscript nodes do not carry significant
6158 information in their collective subscript attributes.
6159
6160 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6161 @d attr_loc(A) info(attr_loc_loc((A))) /* hash address of this attribute */
6162 @d parent(A) mp_link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6163 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6164 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6165 @d attr_node_size 3 /* the number of words in an attribute node */
6166 @d subscr_node_size 3 /* the number of words in a subscript node */
6167 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6168
6169 @<Initialize table...@>=
6170 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6171
6172 @ Variables of type \&{pair} will have values that point to four-word
6173 nodes containing two numeric values. The first of these values has
6174 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6175 the |link| in the first points back to the node whose |value| points
6176 to this four-word node.
6177
6178 Variables of type \&{transform} are similar, but in this case their
6179 |value| points to a 12-word node containing six values, identified by
6180 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6181 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6182 Finally, variables of type \&{color} have 3~values in 6~words
6183 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6184
6185 When an entire structured variable is saved, the |root| indication
6186 is temporarily replaced by |saved_root|.
6187
6188 Some variables have no name; they just are used for temporary storage
6189 while expressions are being evaluated. We call them {\sl capsules}.
6190
6191 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6192 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6193 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6194 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6195 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6196 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6197 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6198 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6199 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6200 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6201 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6202 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6203 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6204 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6205 @#
6206 @d pair_node_size 4 /* the number of words in a pair node */
6207 @d transform_node_size 12 /* the number of words in a transform node */
6208 @d color_node_size 6 /* the number of words in a color node */
6209 @d cmykcolor_node_size 8 /* the number of words in a color node */
6210
6211 @<Glob...@>=
6212 quarterword big_node_size[mp_pair_type+1];
6213 quarterword sector0[mp_pair_type+1];
6214 quarterword sector_offset[mp_black_part_sector+1];
6215
6216 @ The |sector0| array gives for each big node type, |name_type| values
6217 for its first subfield; the |sector_offset| array gives for each
6218 |name_type| value, the offset from the first subfield in words;
6219 and the |big_node_size| array gives the size in words for each type of
6220 big node.
6221
6222 @<Set init...@>=
6223 mp->big_node_size[mp_transform_type]=transform_node_size;
6224 mp->big_node_size[mp_pair_type]=pair_node_size;
6225 mp->big_node_size[mp_color_type]=color_node_size;
6226 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6227 mp->sector0[mp_transform_type]=mp_x_part_sector;
6228 mp->sector0[mp_pair_type]=mp_x_part_sector;
6229 mp->sector0[mp_color_type]=mp_red_part_sector;
6230 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6231 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6232   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6233 }
6234 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6235   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6236 }
6237 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6238   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6239 }
6240
6241 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6242 procedure call |init_big_node(p)| will allocate a pair or transform node
6243 for~|p|.  The individual parts of such nodes are initially of type
6244 |mp_independent|.
6245
6246 @c 
6247 static void mp_init_big_node (MP mp,pointer p) {
6248   pointer q; /* the new node */
6249   quarterword s; /* its size */
6250   s=mp->big_node_size[type(p)]; q=mp_get_node(mp, s);
6251   do {  
6252     s=s-2; 
6253     @<Make variable |q+s| newly independent@>;
6254     name_type(q+s)=halfp(s)+mp->sector0[type(p)]; 
6255     mp_link(q+s)=null;
6256   } while (s!=0);
6257   mp_link(q)=p; value(p)=q;
6258 }
6259
6260 @ The |id_transform| function creates a capsule for the
6261 identity transformation.
6262
6263 @c 
6264 static pointer mp_id_transform (MP mp) {
6265   pointer p,q,r; /* list manipulation registers */
6266   p=mp_get_node(mp, value_node_size); type(p)=mp_transform_type;
6267   name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6268   r=q+transform_node_size;
6269   do {  
6270     r=r-2;
6271     type(r)=mp_known; value(r)=0;
6272   } while (r!=q);
6273   value(xx_part_loc(q))=unity; 
6274   value(yy_part_loc(q))=unity;
6275   return p;
6276 }
6277
6278 @ Tokens are of type |tag_token| when they first appear, but they point
6279 to |null| until they are first used as the root of a variable.
6280 The following subroutine establishes the root node on such grand occasions.
6281
6282 @c 
6283 static void mp_new_root (MP mp,pointer x) {
6284   pointer p; /* the new node */
6285   p=mp_get_node(mp, value_node_size); type(p)=undefined; name_type(p)=mp_root;
6286   mp_link(p)=x; equiv(x)=p;
6287 }
6288
6289 @ These conventions for variable representation are illustrated by the
6290 |print_variable_name| routine, which displays the full name of a
6291 variable given only a pointer to its two-word value packet.
6292
6293 @<Declarations@>=
6294 static void mp_print_variable_name (MP mp, pointer p);
6295
6296 @ @c 
6297 void mp_print_variable_name (MP mp, pointer p) {
6298   pointer q; /* a token list that will name the variable's suffix */
6299   pointer r; /* temporary for token list creation */
6300   while ( name_type(p)>=mp_x_part_sector ) {
6301     @<Preface the output with a part specifier; |return| in the
6302       case of a capsule@>;
6303   }
6304   q=null;
6305   while ( name_type(p)>mp_saved_root ) {
6306     @<Ascend one level, pushing a token onto list |q|
6307      and replacing |p| by its parent@>;
6308   }
6309   r=mp_get_avail(mp); info(r)=mp_link(p); mp_link(r)=q;
6310   if ( name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6311 @.SAVED@>
6312   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6313   mp_flush_token_list(mp, r);
6314 }
6315
6316 @ @<Ascend one level, pushing a token onto list |q|...@>=
6317
6318   if ( name_type(p)==mp_subscr ) { 
6319     r=mp_new_num_tok(mp, subscript(p));
6320     do {  
6321       p=mp_link(p);
6322     } while (name_type(p)!=mp_attr);
6323   } else if ( name_type(p)==mp_structured_root ) {
6324     p=mp_link(p); goto FOUND;
6325   } else { 
6326     if ( name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6327 @:this can't happen var}{\quad var@>
6328     r=mp_get_avail(mp); info(r)=attr_loc(p);
6329   }
6330   mp_link(r)=q; q=r;
6331 FOUND:  
6332   p=parent(p);
6333 }
6334
6335 @ @<Preface the output with a part specifier...@>=
6336 { switch (name_type(p)) {
6337   case mp_x_part_sector: mp_print_char(mp, xord('x')); break;
6338   case mp_y_part_sector: mp_print_char(mp, xord('y')); break;
6339   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6340   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6341   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6342   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6343   case mp_red_part_sector: mp_print(mp, "red"); break;
6344   case mp_green_part_sector: mp_print(mp, "green"); break;
6345   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6346   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6347   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6348   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6349   case mp_black_part_sector: mp_print(mp, "black"); break;
6350   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6351   case mp_capsule: 
6352     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6353     break;
6354 @.CAPSULE@>
6355   } /* there are no other cases */
6356   mp_print(mp, "part "); 
6357   p=mp_link(p-mp->sector_offset[name_type(p)]);
6358 }
6359
6360 @ The |interesting| function returns |true| if a given variable is not
6361 in a capsule, or if the user wants to trace capsules.
6362
6363 @c 
6364 static boolean mp_interesting (MP mp,pointer p) {
6365   quarterword t; /* a |name_type| */
6366   if ( mp->internal[mp_tracing_capsules]>0 ) {
6367     return true;
6368   } else { 
6369     t=name_type(p);
6370     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6371       t=name_type(mp_link(p-mp->sector_offset[t]));
6372     return (t!=mp_capsule);
6373   }
6374 }
6375
6376 @ Now here is a subroutine that converts an unstructured type into an
6377 equivalent structured type, by inserting a |mp_structured| node that is
6378 capable of growing. This operation is done only when |name_type(p)=root|,
6379 |subscr|, or |attr|.
6380
6381 The procedure returns a pointer to the new node that has taken node~|p|'s
6382 place in the structure. Node~|p| itself does not move, nor are its
6383 |value| or |type| fields changed in any way.
6384
6385 @c 
6386 static pointer mp_new_structure (MP mp,pointer p) {
6387   pointer q,r=0; /* list manipulation registers */
6388   switch (name_type(p)) {
6389   case mp_root: 
6390     q=mp_link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6391     break;
6392   case mp_subscr: 
6393     @<Link a new subscript node |r| in place of node |p|@>;
6394     break;
6395   case mp_attr: 
6396     @<Link a new attribute node |r| in place of node |p|@>;
6397     break;
6398   default: 
6399     mp_confusion(mp, "struct");
6400 @:this can't happen struct}{\quad struct@>
6401     break;
6402   }
6403   mp_link(r)=mp_link(p); type(r)=mp_structured; name_type(r)=name_type(p);
6404   attr_head(r)=p; name_type(p)=mp_structured_root;
6405   q=mp_get_node(mp, attr_node_size); mp_link(p)=q; subscr_head(r)=q;
6406   parent(q)=r; type(q)=undefined; name_type(q)=mp_attr; mp_link(q)=end_attr;
6407   attr_loc(q)=collective_subscript; 
6408   return r;
6409 }
6410
6411 @ @<Link a new subscript node |r| in place of node |p|@>=
6412
6413   q=p;
6414   do {  
6415     q=mp_link(q);
6416   } while (name_type(q)!=mp_attr);
6417   q=parent(q); r=subscr_head_loc(q); /* |mp_link(r)=subscr_head(q)| */
6418   do {  
6419     q=r; r=mp_link(r);
6420   } while (r!=p);
6421   r=mp_get_node(mp, subscr_node_size);
6422   mp_link(q)=r; subscript(r)=subscript(p);
6423 }
6424
6425 @ If the attribute is |collective_subscript|, there are two pointers to
6426 node~|p|, so we must change both of them.
6427
6428 @<Link a new attribute node |r| in place of node |p|@>=
6429
6430   q=parent(p); r=attr_head(q);
6431   do {  
6432     q=r; r=mp_link(r);
6433   } while (r!=p);
6434   r=mp_get_node(mp, attr_node_size); mp_link(q)=r;
6435   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6436   if ( attr_loc(p)==collective_subscript ) { 
6437     q=subscr_head_loc(parent(p));
6438     while ( mp_link(q)!=p ) q=mp_link(q);
6439     mp_link(q)=r;
6440   }
6441 }
6442
6443 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6444 list of suffixes; it returns a pointer to the corresponding two-word
6445 value. For example, if |t| points to token \.x followed by a numeric
6446 token containing the value~7, |find_variable| finds where the value of
6447 \.{x7} is stored in memory. This may seem a simple task, and it
6448 usually is, except when \.{x7} has never been referenced before.
6449 Indeed, \.x may never have even been subscripted before; complexities
6450 arise with respect to updating the collective subscript information.
6451
6452 If a macro type is detected anywhere along path~|t|, or if the first
6453 item on |t| isn't a |tag_token|, the value |null| is returned.
6454 Otherwise |p| will be a non-null pointer to a node such that
6455 |undefined<type(p)<mp_structured|.
6456
6457 @d abort_find { return null; }
6458
6459 @c 
6460 static pointer mp_find_variable (MP mp,pointer t) {
6461   pointer p,q,r,s; /* nodes in the ``value'' line */
6462   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6463   integer n; /* subscript or attribute */
6464   memory_word save_word; /* temporary storage for a word of |mem| */
6465 @^inner loop@>
6466   p=info(t); t=mp_link(t);
6467   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6468   if ( equiv(p)==null ) mp_new_root(mp, p);
6469   p=equiv(p); pp=p;
6470   while ( t!=null ) { 
6471     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6472     if ( t<mp->hi_mem_min ) {
6473       @<Descend one level for the subscript |value(t)|@>
6474     } else {
6475       @<Descend one level for the attribute |info(t)|@>;
6476     }
6477     t=mp_link(t);
6478   }
6479   if ( type(pp)>=mp_structured ) {
6480     if ( type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6481   }
6482   if ( type(p)==mp_structured ) p=attr_head(p);
6483   if ( type(p)==undefined ) { 
6484     if ( type(pp)==undefined ) { type(pp)=mp_numeric_type; value(pp)=null; };
6485     type(p)=type(pp); value(p)=null;
6486   };
6487   return p;
6488 }
6489
6490 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6491 |pp|~stays in the collective line while |p|~goes through actual subscript
6492 values.
6493
6494 @<Make sure that both nodes |p| and |pp|...@>=
6495 if ( type(pp)!=mp_structured ) { 
6496   if ( type(pp)>mp_structured ) abort_find;
6497   ss=mp_new_structure(mp, pp);
6498   if ( p==pp ) p=ss;
6499   pp=ss;
6500 }; /* now |type(pp)=mp_structured| */
6501 if ( type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6502   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6503
6504 @ We want this part of the program to be reasonably fast, in case there are
6505 @^inner loop@>
6506 lots of subscripts at the same level of the data structure. Therefore
6507 we store an ``infinite'' value in the word that appears at the end of the
6508 subscript list, even though that word isn't part of a subscript node.
6509
6510 @<Descend one level for the subscript |value(t)|@>=
6511
6512   n=value(t);
6513   pp=mp_link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6514   q=mp_link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6515   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |mp_link(s)=subscr_head(p)| */
6516   do {  
6517     r=s; s=mp_link(s);
6518   } while (n>subscript(s));
6519   if ( n==subscript(s) ) {
6520     p=s;
6521   } else { 
6522     p=mp_get_node(mp, subscr_node_size); mp_link(r)=p; mp_link(p)=s;
6523     subscript(p)=n; name_type(p)=mp_subscr; type(p)=undefined;
6524   }
6525   mp->mem[subscript_loc(q)]=save_word;
6526 }
6527
6528 @ @<Descend one level for the attribute |info(t)|@>=
6529
6530   n=info(t);
6531   ss=attr_head(pp);
6532   do {  
6533     rr=ss; ss=mp_link(ss);
6534   } while (n>attr_loc(ss));
6535   if ( n<attr_loc(ss) ) { 
6536     qq=mp_get_node(mp, attr_node_size); mp_link(rr)=qq; mp_link(qq)=ss;
6537     attr_loc(qq)=n; name_type(qq)=mp_attr; type(qq)=undefined;
6538     parent(qq)=pp; ss=qq;
6539   }
6540   if ( p==pp ) { 
6541     p=ss; pp=ss;
6542   } else { 
6543     pp=ss; s=attr_head(p);
6544     do {  
6545       r=s; s=mp_link(s);
6546     } while (n>attr_loc(s));
6547     if ( n==attr_loc(s) ) {
6548       p=s;
6549     } else { 
6550       q=mp_get_node(mp, attr_node_size); mp_link(r)=q; mp_link(q)=s;
6551       attr_loc(q)=n; name_type(q)=mp_attr; type(q)=undefined;
6552       parent(q)=p; p=q;
6553     }
6554   }
6555 }
6556
6557 @ Variables lose their former values when they appear in a type declaration,
6558 or when they are defined to be macros or \&{let} equal to something else.
6559 A subroutine will be defined later that recycles the storage associated
6560 with any particular |type| or |value|; our goal now is to study a higher
6561 level process called |flush_variable|, which selectively frees parts of a
6562 variable structure.
6563
6564 This routine has some complexity because of examples such as
6565 `\hbox{\tt numeric x[]a[]b}'
6566 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6567 `\hbox{\tt vardef x[]a[]=...}'
6568 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6569 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6570 to handle such examples is to use recursion; so that's what we~do.
6571 @^recursion@>
6572
6573 Parameter |p| points to the root information of the variable;
6574 parameter |t| points to a list of one-word nodes that represent
6575 suffixes, with |info=collective_subscript| for subscripts.
6576
6577 @<Declarations@>=
6578 static void mp_flush_cur_exp (MP mp,scaled v) ;
6579
6580 @ @c 
6581 static void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6582   pointer q,r; /* list manipulation */
6583   halfword n; /* attribute to match */
6584   while ( t!=null ) { 
6585     if ( type(p)!=mp_structured ) return;
6586     n=info(t); t=mp_link(t);
6587     if ( n==collective_subscript ) { 
6588       r=subscr_head_loc(p); q=mp_link(r); /* |q=subscr_head(p)| */
6589       while ( name_type(q)==mp_subscr ){ 
6590         mp_flush_variable(mp, q,t,discard_suffixes);
6591         if ( t==null ) {
6592           if ( type(q)==mp_structured ) r=q;
6593           else  { mp_link(r)=mp_link(q); mp_free_node(mp, q,subscr_node_size);   }
6594         } else {
6595           r=q;
6596         }
6597         q=mp_link(r);
6598       }
6599     }
6600     p=attr_head(p);
6601     do {  
6602       r=p; p=mp_link(p);
6603     } while (attr_loc(p)<n);
6604     if ( attr_loc(p)!=n ) return;
6605   }
6606   if ( discard_suffixes ) {
6607     mp_flush_below_variable(mp, p);
6608   } else { 
6609     if ( type(p)==mp_structured ) p=attr_head(p);
6610     mp_recycle_value(mp, p);
6611   }
6612 }
6613
6614 @ The next procedure is simpler; it wipes out everything but |p| itself,
6615 which becomes undefined.
6616
6617 @<Declarations@>=
6618 static void mp_flush_below_variable (MP mp, pointer p);
6619
6620 @ @c
6621 void mp_flush_below_variable (MP mp,pointer p) {
6622    pointer q,r; /* list manipulation registers */
6623   if ( type(p)!=mp_structured ) {
6624     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6625   } else { 
6626     q=subscr_head(p);
6627     while ( name_type(q)==mp_subscr ) { 
6628       mp_flush_below_variable(mp, q); r=q; q=mp_link(q);
6629       mp_free_node(mp, r,subscr_node_size);
6630     }
6631     r=attr_head(p); q=mp_link(r); mp_recycle_value(mp, r);
6632     if ( name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6633     else mp_free_node(mp, r,subscr_node_size);
6634     /* we assume that |subscr_node_size=attr_node_size| */
6635     do {  
6636       mp_flush_below_variable(mp, q); r=q; q=mp_link(q); mp_free_node(mp, r,attr_node_size);
6637     } while (q!=end_attr);
6638     type(p)=undefined;
6639   }
6640 }
6641
6642 @ Just before assigning a new value to a variable, we will recycle the
6643 old value and make the old value undefined. The |und_type| routine
6644 determines what type of undefined value should be given, based on
6645 the current type before recycling.
6646
6647 @c 
6648 static quarterword mp_und_type (MP mp,pointer p) { 
6649   switch (type(p)) {
6650   case undefined: case mp_vacuous:
6651     return undefined;
6652   case mp_boolean_type: case mp_unknown_boolean:
6653     return mp_unknown_boolean;
6654   case mp_string_type: case mp_unknown_string:
6655     return mp_unknown_string;
6656   case mp_pen_type: case mp_unknown_pen:
6657     return mp_unknown_pen;
6658   case mp_path_type: case mp_unknown_path:
6659     return mp_unknown_path;
6660   case mp_picture_type: case mp_unknown_picture:
6661     return mp_unknown_picture;
6662   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6663   case mp_pair_type: case mp_numeric_type: 
6664     return type(p);
6665   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6666     return mp_numeric_type;
6667   } /* there are no other cases */
6668   return 0;
6669 }
6670
6671 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6672 of a symbolic token. It must remove any variable structure or macro
6673 definition that is currently attached to that symbol. If the |saving|
6674 parameter is true, a subsidiary structure is saved instead of destroyed.
6675
6676 @c 
6677 static void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6678   pointer q; /* |equiv(p)| */
6679   q=equiv(p);
6680   switch (eq_type(p) % outer_tag)  {
6681   case defined_macro:
6682   case secondary_primary_macro:
6683   case tertiary_secondary_macro:
6684   case expression_tertiary_macro: 
6685     if ( ! saving ) mp_delete_mac_ref(mp, q);
6686     break;
6687   case tag_token:
6688     if ( q!=null ) {
6689       if ( saving ) {
6690         name_type(q)=mp_saved_root;
6691       } else { 
6692         mp_flush_below_variable(mp, q); 
6693             mp_free_node(mp,q,value_node_size); 
6694       }
6695     }
6696     break;
6697   default:
6698     break;
6699   }
6700   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6701 }
6702
6703 @* \[16] Saving and restoring equivalents.
6704 The nested structure given by \&{begingroup} and \&{endgroup}
6705 allows |eqtb| entries to be saved and restored, so that temporary changes
6706 can be made without difficulty.  When the user requests a current value to
6707 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6708 \&{endgroup} ultimately causes the old values to be removed from the save
6709 stack and put back in their former places.
6710
6711 The save stack is a linked list containing three kinds of entries,
6712 distinguished by their |info| fields. If |p| points to a saved item,
6713 then
6714
6715 \smallskip\hang
6716 |info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6717 such an item to the save stack and each \&{endgroup} cuts back the stack
6718 until the most recent such entry has been removed.
6719
6720 \smallskip\hang
6721 |info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6722 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6723 commands.
6724
6725 \smallskip\hang
6726 |info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6727 integer to be restored to internal parameter number~|q|. Such entries
6728 are generated by \&{interim} commands.
6729
6730 \smallskip\noindent
6731 The global variable |save_ptr| points to the top item on the save stack.
6732
6733 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6734 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6735 @d save_boundary_item(A) { (A)=mp_get_avail(mp); info((A))=0;
6736   mp_link((A))=mp->save_ptr; mp->save_ptr=(A);
6737   }
6738
6739 @<Glob...@>=
6740 pointer save_ptr; /* the most recently saved item */
6741
6742 @ @<Set init...@>=mp->save_ptr=null;
6743
6744 @ The |save_variable| routine is given a hash address |q|; it salts this
6745 address in the save stack, together with its current equivalent,
6746 then makes token~|q| behave as though it were brand new.
6747
6748 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6749 things from the stack when the program is not inside a group, so there's
6750 no point in wasting the space.
6751
6752 @c 
6753 static void mp_save_variable (MP mp,pointer q) {
6754   pointer p; /* temporary register */
6755   if ( mp->save_ptr!=null ){ 
6756     p=mp_get_node(mp, save_node_size); info(p)=q; mp_link(p)=mp->save_ptr;
6757     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6758   }
6759   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6760 }
6761
6762 @ Similarly, |save_internal| is given the location |q| of an internal
6763 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6764 third kind.
6765
6766 @c 
6767 static void mp_save_internal (MP mp,halfword q) {
6768   pointer p; /* new item for the save stack */
6769   if ( mp->save_ptr!=null ){ 
6770      p=mp_get_node(mp, save_node_size); info(p)=hash_end+q;
6771     mp_link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6772   }
6773 }
6774
6775 @ At the end of a group, the |unsave| routine restores all of the saved
6776 equivalents in reverse order. This routine will be called only when there
6777 is at least one boundary item on the save stack.
6778
6779 @c 
6780 static void mp_unsave (MP mp) {
6781   pointer q; /* index to saved item */
6782   pointer p; /* temporary register */
6783   while ( info(mp->save_ptr)!=0 ) {
6784     q=info(mp->save_ptr);
6785     if ( q>hash_end ) {
6786       if ( mp->internal[mp_tracing_restores]>0 ) {
6787         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6788         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, xord('='));
6789         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, xord('}'));
6790         mp_end_diagnostic(mp, false);
6791       }
6792       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6793     } else { 
6794       if ( mp->internal[mp_tracing_restores]>0 ) {
6795         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6796         mp_print_text(q); mp_print_char(mp, xord('}'));
6797         mp_end_diagnostic(mp, false);
6798       }
6799       mp_clear_symbol(mp, q,false);
6800       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6801       if ( eq_type(q) % outer_tag==tag_token ) {
6802         p=equiv(q);
6803         if ( p!=null ) name_type(p)=mp_root;
6804       }
6805     }
6806     p=mp_link(mp->save_ptr); 
6807     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6808   }
6809   p=mp_link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6810 }
6811
6812 @* \[17] Data structures for paths.
6813 When a \MP\ user specifies a path, \MP\ will create a list of knots
6814 and control points for the associated cubic spline curves. If the
6815 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6816 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6817 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6818 @:Bezier}{B\'ezier, Pierre Etienne@>
6819 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6820 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6821 for |0<=t<=1|.
6822
6823 There is a 8-word node for each knot $z_k$, containing one word of
6824 control information and six words for the |x| and |y| coordinates of
6825 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6826 |mp_left_type| and |mp_right_type| fields, which each occupy a quarter of
6827 the first word in the node; they specify properties of the curve as it
6828 enters and leaves the knot. There's also a halfword |link| field,
6829 which points to the following knot, and a final supplementary word (of
6830 which only a quarter is used).
6831
6832 If the path is a closed contour, knots 0 and |n| are identical;
6833 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6834 is not closed, the |mp_left_type| of knot~0 and the |mp_right_type| of knot~|n|
6835 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6836 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6837
6838 @d mp_left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6839 @d mp_right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6840 @d mp_x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */ 
6841 @d mp_y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6842 @d mp_left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6843 @d mp_left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6844 @d mp_right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6845 @d mp_right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6846 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6847 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6848 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6849 @d left_coord(A)   mp->mem[(A)+2].sc
6850   /* coordinate of previous control point given |x_loc| or |y_loc| */
6851 @d right_coord(A)   mp->mem[(A)+4].sc
6852   /* coordinate of next control point given |x_loc| or |y_loc| */
6853 @d knot_node_size 8 /* number of words in a knot node */
6854
6855 @(mplib.h@>=
6856 enum mp_knot_type {
6857  mp_endpoint=0, /* |mp_left_type| at path beginning and |mp_right_type| at path end */
6858  mp_explicit, /* |mp_left_type| or |mp_right_type| when control points are known */
6859  mp_given, /* |mp_left_type| or |mp_right_type| when a direction is given */
6860  mp_curl, /* |mp_left_type| or |mp_right_type| when a curl is desired */
6861  mp_open, /* |mp_left_type| or |mp_right_type| when \MP\ should choose the direction */
6862  mp_end_cycle
6863 };
6864
6865 @ Before the B\'ezier control points have been calculated, the memory
6866 space they will ultimately occupy is taken up by information that can be
6867 used to compute them. There are four cases:
6868
6869 \yskip
6870 \textindent{$\bullet$} If |mp_right_type=mp_open|, the curve should leave
6871 the knot in the same direction it entered; \MP\ will figure out a
6872 suitable direction.
6873
6874 \yskip
6875 \textindent{$\bullet$} If |mp_right_type=mp_curl|, the curve should leave the
6876 knot in a direction depending on the angle at which it enters the next
6877 knot and on the curl parameter stored in |right_curl|.
6878
6879 \yskip
6880 \textindent{$\bullet$} If |mp_right_type=mp_given|, the curve should leave the
6881 knot in a nonzero direction stored as an |angle| in |right_given|.
6882
6883 \yskip
6884 \textindent{$\bullet$} If |mp_right_type=mp_explicit|, the B\'ezier control
6885 point for leaving this knot has already been computed; it is in the
6886 |mp_right_x| and |mp_right_y| fields.
6887
6888 \yskip\noindent
6889 The rules for |mp_left_type| are similar, but they refer to the curve entering
6890 the knot, and to \\{left} fields instead of \\{right} fields.
6891
6892 Non-|explicit| control points will be chosen based on ``tension'' parameters
6893 in the |left_tension| and |right_tension| fields. The
6894 `\&{atleast}' option is represented by negative tension values.
6895 @:at_least_}{\&{atleast} primitive@>
6896
6897 For example, the \MP\ path specification
6898 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6899   3 and 4..p},$$
6900 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6901 by the six knots
6902 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6903 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6904 |mp_left_type|&\\{left} info&|mp_x_coord,mp_y_coord|&|mp_right_type|&\\{right} info\cr
6905 \noalign{\yskip}
6906 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6907 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6908 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6909 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6910 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6911 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6912 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6913 Of course, this example is more complicated than anything a normal user
6914 would ever write.
6915
6916 These types must satisfy certain restrictions because of the form of \MP's
6917 path syntax:
6918 (i)~|open| type never appears in the same node together with |endpoint|,
6919 |given|, or |curl|.
6920 (ii)~The |mp_right_type| of a node is |explicit| if and only if the
6921 |mp_left_type| of the following node is |explicit|.
6922 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6923
6924 @d left_curl mp_left_x /* curl information when entering this knot */
6925 @d left_given mp_left_x /* given direction when entering this knot */
6926 @d left_tension mp_left_y /* tension information when entering this knot */
6927 @d right_curl mp_right_x /* curl information when leaving this knot */
6928 @d right_given mp_right_x /* given direction when leaving this knot */
6929 @d right_tension mp_right_y /* tension information when leaving this knot */
6930
6931 @ Knots can be user-supplied, or they can be created by program code,
6932 like the |split_cubic| function, or |copy_path|. The distinction is
6933 needed for the cleanup routine that runs after |split_cubic|, because
6934 it should only delete knots it has previously inserted, and never
6935 anything that was user-supplied. In order to be able to differentiate
6936 one knot from another, we will set |originator(p):=mp_metapost_user| when
6937 it appeared in the actual metapost program, and
6938 |originator(p):=mp_program_code| in all other cases.
6939
6940 @d mp_originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6941
6942 @<Exported types@>=
6943 enum mp_knot_originator {
6944   mp_program_code=0, /* not created by a user */
6945   mp_metapost_user /* created by a user */
6946 };
6947
6948 @ Here is a routine that prints a given knot list
6949 in symbolic form. It illustrates the conventions discussed above,
6950 and checks for anomalies that might arise while \MP\ is being debugged.
6951
6952 @<Declarations@>=
6953 static void mp_pr_path (MP mp,pointer h);
6954
6955 @ @c
6956 void mp_pr_path (MP mp,pointer h) {
6957   pointer p,q; /* for list traversal */
6958   p=h;
6959   do {  
6960     q=mp_link(p);
6961     if ( (p==null)||(q==null) ) { 
6962       mp_print_nl(mp, "???"); return; /* this won't happen */
6963 @.???@>
6964     }
6965     @<Print information for adjacent knots |p| and |q|@>;
6966   DONE1:
6967     p=q;
6968     if ( (p!=h)||(mp_left_type(h)!=mp_endpoint) ) {
6969       @<Print two dots, followed by |given| or |curl| if present@>;
6970     }
6971   } while (p!=h);
6972   if ( mp_left_type(h)!=mp_endpoint ) 
6973     mp_print(mp, "cycle");
6974 }
6975
6976 @ @<Print information for adjacent knots...@>=
6977 mp_print_two(mp, mp_x_coord(p),mp_y_coord(p));
6978 switch (mp_right_type(p)) {
6979 case mp_endpoint: 
6980   if ( mp_left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6981 @.open?@>
6982   if ( (mp_left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6983   goto DONE1;
6984   break;
6985 case mp_explicit: 
6986   @<Print control points between |p| and |q|, then |goto done1|@>;
6987   break;
6988 case mp_open: 
6989   @<Print information for a curve that begins |open|@>;
6990   break;
6991 case mp_curl:
6992 case mp_given: 
6993   @<Print information for a curve that begins |curl| or |given|@>;
6994   break;
6995 default:
6996   mp_print(mp, "???"); /* can't happen */
6997 @.???@>
6998   break;
6999 }
7000 if ( mp_left_type(q)<=mp_explicit ) {
7001   mp_print(mp, "..control?"); /* can't happen */
7002 @.control?@>
7003 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
7004   @<Print tension between |p| and |q|@>;
7005 }
7006
7007 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
7008 were |scaled|, the magnitude of a |given| direction vector will be~4096.
7009
7010 @<Print two dots...@>=
7011
7012   mp_print_nl(mp, " ..");
7013   if ( mp_left_type(p)==mp_given ) { 
7014     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, xord('{'));
7015     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, xord(','));
7016     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, xord('}'));
7017   } else if ( mp_left_type(p)==mp_curl ){ 
7018     mp_print(mp, "{curl "); 
7019     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, xord('}'));
7020   }
7021 }
7022
7023 @ @<Print tension between |p| and |q|@>=
7024
7025   mp_print(mp, "..tension ");
7026   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
7027   mp_print_scaled(mp, abs(right_tension(p)));
7028   if ( right_tension(p)!=left_tension(q) ){ 
7029     mp_print(mp, " and ");
7030     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
7031     mp_print_scaled(mp, abs(left_tension(q)));
7032   }
7033 }
7034
7035 @ @<Print control points between |p| and |q|, then |goto done1|@>=
7036
7037   mp_print(mp, "..controls "); 
7038   mp_print_two(mp, mp_right_x(p),mp_right_y(p)); 
7039   mp_print(mp, " and ");
7040   if ( mp_left_type(q)!=mp_explicit ) { 
7041     mp_print(mp, "??"); /* can't happen */
7042 @.??@>
7043   } else {
7044     mp_print_two(mp, mp_left_x(q),mp_left_y(q));
7045   }
7046   goto DONE1;
7047 }
7048
7049 @ @<Print information for a curve that begins |open|@>=
7050 if ( (mp_left_type(p)!=mp_explicit)&&(mp_left_type(p)!=mp_open) ) {
7051   mp_print(mp, "{open?}"); /* can't happen */
7052 @.open?@>
7053 }
7054
7055 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7056 \MP's default curl is present.
7057
7058 @<Print information for a curve that begins |curl|...@>=
7059
7060   if ( mp_left_type(p)==mp_open )  
7061     mp_print(mp, "??"); /* can't happen */
7062 @.??@>
7063   if ( mp_right_type(p)==mp_curl ) { 
7064     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7065   } else { 
7066     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, xord('{'));
7067     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, xord(',')); 
7068     mp_print_scaled(mp, mp->n_sin);
7069   }
7070   mp_print_char(mp, xord('}'));
7071 }
7072
7073 @ It is convenient to have another version of |pr_path| that prints the path
7074 as a diagnostic message.
7075
7076 @<Declarations@>=
7077 static void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) ;
7078
7079 @ @c
7080 void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) { 
7081   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7082 @.Path at line...@>
7083   mp_pr_path(mp, h);
7084   mp_end_diagnostic(mp, true);
7085 }
7086
7087 @ If we want to duplicate a knot node, we can say |copy_knot|:
7088
7089 @c 
7090 static pointer mp_copy_knot (MP mp,pointer p) {
7091   pointer q; /* the copy */
7092   int k; /* runs through the words of a knot node */
7093   q=mp_get_node(mp, knot_node_size);
7094   for (k=0;k<knot_node_size;k++) {
7095     mp->mem[q+k]=mp->mem[p+k];
7096   }
7097   mp_originator(q)=mp_originator(p);
7098   return q;
7099 }
7100
7101 @ The |copy_path| routine makes a clone of a given path.
7102
7103 @c 
7104 static pointer mp_copy_path (MP mp, pointer p) {
7105   pointer q,pp,qq; /* for list manipulation */
7106   q=mp_copy_knot(mp, p);
7107   qq=q; pp=mp_link(p);
7108   while ( pp!=p ) { 
7109     mp_link(qq)=mp_copy_knot(mp, pp);
7110     qq=mp_link(qq);
7111     pp=mp_link(pp);
7112   }
7113   mp_link(qq)=q;
7114   return q;
7115 }
7116
7117
7118 @ Just before |ship_out|, knot lists are exported for printing.
7119
7120 The |gr_XXXX| macros are defined in |mppsout.h|.
7121
7122 @c 
7123 static mp_knot *mp_export_knot (MP mp,pointer p) {
7124   mp_knot *q; /* the copy */
7125   if (p==null)
7126      return NULL;
7127   q = xmalloc(1, sizeof (mp_knot));
7128   memset(q,0,sizeof (mp_knot));
7129   gr_left_type(q)  = (unsigned short)mp_left_type(p);
7130   gr_right_type(q) = (unsigned short)mp_right_type(p);
7131   gr_x_coord(q)    = mp_x_coord(p);
7132   gr_y_coord(q)    = mp_y_coord(p);
7133   gr_left_x(q)     = mp_left_x(p);
7134   gr_left_y(q)     = mp_left_y(p);
7135   gr_right_x(q)    = mp_right_x(p);
7136   gr_right_y(q)    = mp_right_y(p);
7137   gr_originator(q) = (unsigned char)mp_originator(p);
7138   return q;
7139 }
7140
7141 @ The |export_knot_list| routine therefore also makes a clone 
7142 of a given path.
7143
7144 @c 
7145 static mp_knot *mp_export_knot_list (MP mp, pointer p) {
7146   mp_knot *q, *qq; /* for list manipulation */
7147   pointer pp; /* for list manipulation */
7148   if (p==null)
7149      return NULL;
7150   q=mp_export_knot(mp, p);
7151   qq=q; pp=mp_link(p);
7152   while ( pp!=p ) { 
7153     gr_next_knot(qq)=mp_export_knot(mp, pp);
7154     qq=gr_next_knot(qq);
7155     pp=mp_link(pp);
7156   }
7157   gr_next_knot(qq)=q;
7158   return q;
7159 }
7160
7161
7162 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7163 returns a pointer to the first node of the copy, if the path is a cycle,
7164 but to the final node of a non-cyclic copy. The global
7165 variable |path_tail| will point to the final node of the original path;
7166 this trick makes it easier to implement `\&{doublepath}'.
7167
7168 All node types are assumed to be |endpoint| or |explicit| only.
7169
7170 @c 
7171 static pointer mp_htap_ypoc (MP mp,pointer p) {
7172   pointer q,pp,qq,rr; /* for list manipulation */
7173   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7174   qq=q; pp=p;
7175   while (1) { 
7176     mp_right_type(qq)=mp_left_type(pp); mp_left_type(qq)=mp_right_type(pp);
7177     mp_x_coord(qq)=mp_x_coord(pp); mp_y_coord(qq)=mp_y_coord(pp);
7178     mp_right_x(qq)=mp_left_x(pp); mp_right_y(qq)=mp_left_y(pp);
7179     mp_left_x(qq)=mp_right_x(pp); mp_left_y(qq)=mp_right_y(pp);
7180     mp_originator(qq)=mp_originator(pp);
7181     if ( mp_link(pp)==p ) { 
7182       mp_link(q)=qq; mp->path_tail=pp; return q;
7183     }
7184     rr=mp_get_node(mp, knot_node_size); mp_link(rr)=qq; qq=rr; pp=mp_link(pp);
7185   }
7186 }
7187
7188 @ @<Glob...@>=
7189 pointer path_tail; /* the node that links to the beginning of a path */
7190
7191 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7192 calling the following subroutine.
7193
7194 @<Declarations@>=
7195 static void mp_toss_knot_list (MP mp,pointer p) ;
7196
7197 @ @c
7198 void mp_toss_knot_list (MP mp,pointer p) {
7199   pointer q; /* the node being freed */
7200   pointer r; /* the next node */
7201   q=p;
7202   do {  
7203     r=mp_link(q); 
7204     mp_free_node(mp, q,knot_node_size); q=r;
7205   } while (q!=p);
7206 }
7207
7208 @* \[18] Choosing control points.
7209 Now we must actually delve into one of \MP's more difficult routines,
7210 the |make_choices| procedure that chooses angles and control points for
7211 the splines of a curve when the user has not specified them explicitly.
7212 The parameter to |make_choices| points to a list of knots and
7213 path information, as described above.
7214
7215 A path decomposes into independent segments at ``breakpoint'' knots,
7216 which are knots whose left and right angles are both prespecified in
7217 some way (i.e., their |mp_left_type| and |mp_right_type| aren't both open).
7218
7219 @c 
7220 static void mp_make_choices (MP mp,pointer knots) {
7221   pointer h; /* the first breakpoint */
7222   pointer p,q; /* consecutive breakpoints being processed */
7223   @<Other local variables for |make_choices|@>;
7224   check_arith; /* make sure that |arith_error=false| */
7225   if ( mp->internal[mp_tracing_choices]>0 )
7226     mp_print_path(mp, knots,", before choices",true);
7227   @<If consecutive knots are equal, join them explicitly@>;
7228   @<Find the first breakpoint, |h|, on the path;
7229     insert an artificial breakpoint if the path is an unbroken cycle@>;
7230   p=h;
7231   do {  
7232     @<Fill in the control points between |p| and the next breakpoint,
7233       then advance |p| to that breakpoint@>;
7234   } while (p!=h);
7235   if ( mp->internal[mp_tracing_choices]>0 )
7236     mp_print_path(mp, knots,", after choices",true);
7237   if ( mp->arith_error ) {
7238     @<Report an unexpected problem during the choice-making@>;
7239   }
7240 }
7241
7242 @ @<Report an unexpected problem during the choice...@>=
7243
7244   print_err("Some number got too big");
7245 @.Some number got too big@>
7246   help2("The path that I just computed is out of range.",
7247         "So it will probably look funny. Proceed, for a laugh.");
7248   mp_put_get_error(mp); mp->arith_error=false;
7249 }
7250
7251 @ Two knots in a row with the same coordinates will always be joined
7252 by an explicit ``curve'' whose control points are identical with the
7253 knots.
7254
7255 @<If consecutive knots are equal, join them explicitly@>=
7256 p=knots;
7257 do {  
7258   q=mp_link(p);
7259   if ( mp_x_coord(p)==mp_x_coord(q) && 
7260        mp_y_coord(p)==mp_y_coord(q) && mp_right_type(p)>mp_explicit ) { 
7261     mp_right_type(p)=mp_explicit;
7262     if ( mp_left_type(p)==mp_open ) { 
7263       mp_left_type(p)=mp_curl; left_curl(p)=unity;
7264     }
7265     mp_left_type(q)=mp_explicit;
7266     if ( mp_right_type(q)==mp_open ) { 
7267       mp_right_type(q)=mp_curl; right_curl(q)=unity;
7268     }
7269     mp_right_x(p)=mp_x_coord(p); mp_left_x(q)=mp_x_coord(p);
7270     mp_right_y(p)=mp_y_coord(p); mp_left_y(q)=mp_y_coord(p);
7271   }
7272   p=q;
7273 } while (p!=knots)
7274
7275 @ If there are no breakpoints, it is necessary to compute the direction
7276 angles around an entire cycle. In this case the |mp_left_type| of the first
7277 node is temporarily changed to |end_cycle|.
7278
7279 @<Find the first breakpoint, |h|, on the path...@>=
7280 h=knots;
7281 while (1) { 
7282   if ( mp_left_type(h)!=mp_open ) break;
7283   if ( mp_right_type(h)!=mp_open ) break;
7284   h=mp_link(h);
7285   if ( h==knots ) { 
7286     mp_left_type(h)=mp_end_cycle; break;
7287   }
7288 }
7289
7290 @ If |mp_right_type(p)<given| and |q=mp_link(p)|, we must have
7291 |mp_right_type(p)=mp_left_type(q)=mp_explicit| or |endpoint|.
7292
7293 @<Fill in the control points between |p| and the next breakpoint...@>=
7294 q=mp_link(p);
7295 if ( mp_right_type(p)>=mp_given ) { 
7296   while ( (mp_left_type(q)==mp_open)&&(mp_right_type(q)==mp_open) ) q=mp_link(q);
7297   @<Fill in the control information between
7298     consecutive breakpoints |p| and |q|@>;
7299 } else if ( mp_right_type(p)==mp_endpoint ) {
7300   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7301 }
7302 p=q
7303
7304 @ This step makes it possible to transform an explicitly computed path without
7305 checking the |mp_left_type| and |mp_right_type| fields.
7306
7307 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7308
7309   mp_right_x(p)=mp_x_coord(p); mp_right_y(p)=mp_y_coord(p);
7310   mp_left_x(q)=mp_x_coord(q); mp_left_y(q)=mp_y_coord(q);
7311 }
7312
7313 @ Before we can go further into the way choices are made, we need to
7314 consider the underlying theory. The basic ideas implemented in |make_choices|
7315 are due to John Hobby, who introduced the notion of ``mock curvature''
7316 @^Hobby, John Douglas@>
7317 at a knot. Angles are chosen so that they preserve mock curvature when
7318 a knot is passed, and this has been found to produce excellent results.
7319
7320 It is convenient to introduce some notations that simplify the necessary
7321 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7322 between knots |k| and |k+1|; and let
7323 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7324 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7325 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7326 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7327 $$\eqalign{z_k^+&=z_k+
7328   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7329  z\k^-&=z\k-
7330   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7331 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7332 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7333 corresponding ``offset angles.'' These angles satisfy the condition
7334 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7335 whenever the curve leaves an intermediate knot~|k| in the direction that
7336 it enters.
7337
7338 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7339 the curve at its beginning and ending points. This means that
7340 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7341 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7342 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7343 z\k^-,z\k^{\phantom+};t)$
7344 has curvature
7345 @^curvature@>
7346 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7347 \qquad{\rm and}\qquad
7348 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7349 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7350 @^mock curvature@>
7351 approximation to this true curvature that arises in the limit for
7352 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7353 The standard velocity function satisfies
7354 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7355 hence the mock curvatures are respectively
7356 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7357 \qquad{\rm and}\qquad
7358 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7359
7360 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7361 determines $\phi_k$ when $\theta_k$ is known, so the task of
7362 angle selection is essentially to choose appropriate values for each
7363 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7364 from $(**)$, we obtain a system of linear equations of the form
7365 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7366 where
7367 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7368 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7369 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7370 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7371 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7372 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7373 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7374 hence they have a unique solution. Moreover, in most cases the tensions
7375 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7376 solution numerically stable, and there is an exponential damping
7377 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7378 a factor of~$O(2^{-j})$.
7379
7380 @ However, we still must consider the angles at the starting and ending
7381 knots of a non-cyclic path. These angles might be given explicitly, or
7382 they might be specified implicitly in terms of an amount of ``curl.''
7383
7384 Let's assume that angles need to be determined for a non-cyclic path
7385 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7386 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7387 have been given for $0<k<n$, and it will be convenient to introduce
7388 equations of the same form for $k=0$ and $k=n$, where
7389 $$A_0=B_0=C_n=D_n=0.$$
7390 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7391 define $C_0=1$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7392 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7393 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7394 mock curvature at $z_1$; i.e.,
7395 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7396 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7397 This equation simplifies to
7398 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7399  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7400  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7401 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7402 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7403 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7404 hence the linear equations remain nonsingular.
7405
7406 Similar considerations apply at the right end, when the final angle $\phi_n$
7407 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7408 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7409 or we have
7410 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7411 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7412   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7413
7414 When |make_choices| chooses angles, it must compute the coefficients of
7415 these linear equations, then solve the equations. To compute the coefficients,
7416 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7417 When the equations are solved, the chosen directions $\theta_k$ are put
7418 back into the form of control points by essentially computing sines and
7419 cosines.
7420
7421 @ OK, we are ready to make the hard choices of |make_choices|.
7422 Most of the work is relegated to an auxiliary procedure
7423 called |solve_choices|, which has been introduced to keep
7424 |make_choices| from being extremely long.
7425
7426 @<Fill in the control information between...@>=
7427 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7428   set $n$ to the length of the path@>;
7429 @<Remove |open| types at the breakpoints@>;
7430 mp_solve_choices(mp, p,q,n)
7431
7432 @ It's convenient to precompute quantities that will be needed several
7433 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7434 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7435 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7436 and $z\k-z_k$ will be stored in |psi[k]|.
7437
7438 @<Glob...@>=
7439 int path_size; /* maximum number of knots between breakpoints of a path */
7440 scaled *delta_x;
7441 scaled *delta_y;
7442 scaled *delta; /* knot differences */
7443 angle  *psi; /* turning angles */
7444
7445 @ @<Dealloc variables@>=
7446 xfree(mp->delta_x);
7447 xfree(mp->delta_y);
7448 xfree(mp->delta);
7449 xfree(mp->psi);
7450
7451 @ @<Other local variables for |make_choices|@>=
7452   int k,n; /* current and final knot numbers */
7453   pointer s,t; /* registers for list traversal */
7454   scaled delx,dely; /* directions where |open| meets |explicit| */
7455   fraction sine,cosine; /* trig functions of various angles */
7456
7457 @ @<Calculate the turning angles...@>=
7458 {
7459 RESTART:
7460   k=0; s=p; n=mp->path_size;
7461   do {  
7462     t=mp_link(s);
7463     mp->delta_x[k]=mp_x_coord(t)-mp_x_coord(s);
7464     mp->delta_y[k]=mp_y_coord(t)-mp_y_coord(s);
7465     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7466     if ( k>0 ) { 
7467       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7468       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7469       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7470         mp_take_fraction(mp, mp->delta_y[k],sine),
7471         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7472           mp_take_fraction(mp, mp->delta_x[k],sine));
7473     }
7474     incr(k); s=t;
7475     if ( k==mp->path_size ) {
7476       mp_reallocate_paths(mp, mp->path_size+(mp->path_size/4));
7477       goto RESTART; /* retry, loop size has changed */
7478     }
7479     if ( s==q ) n=k;
7480   } while (!((k>=n)&&(mp_left_type(s)!=mp_end_cycle)));
7481   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7482 }
7483
7484 @ When we get to this point of the code, |mp_right_type(p)| is either
7485 |given| or |curl| or |open|. If it is |open|, we must have
7486 |mp_left_type(p)=mp_end_cycle| or |mp_left_type(p)=mp_explicit|. In the latter
7487 case, the |open| type is converted to |given|; however, if the
7488 velocity coming into this knot is zero, the |open| type is
7489 converted to a |curl|, since we don't know the incoming direction.
7490
7491 Similarly, |mp_left_type(q)| is either |given| or |curl| or |open| or
7492 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7493
7494 @<Remove |open| types at the breakpoints@>=
7495 if ( mp_left_type(q)==mp_open ) { 
7496   delx=mp_right_x(q)-mp_x_coord(q); dely=mp_right_y(q)-mp_y_coord(q);
7497   if ( (delx==0)&&(dely==0) ) { 
7498     mp_left_type(q)=mp_curl; left_curl(q)=unity;
7499   } else { 
7500     mp_left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7501   }
7502 }
7503 if ( (mp_right_type(p)==mp_open)&&(mp_left_type(p)==mp_explicit) ) { 
7504   delx=mp_x_coord(p)-mp_left_x(p); dely=mp_y_coord(p)-mp_left_y(p);
7505   if ( (delx==0)&&(dely==0) ) { 
7506     mp_right_type(p)=mp_curl; right_curl(p)=unity;
7507   } else { 
7508     mp_right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7509   }
7510 }
7511
7512 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7513 and exactly one of the breakpoints involves a curl. The simplest case occurs
7514 when |n=1| and there is a curl at both breakpoints; then we simply draw
7515 a straight line.
7516
7517 But before coding up the simple cases, we might as well face the general case,
7518 since we must deal with it sooner or later, and since the general case
7519 is likely to give some insight into the way simple cases can be handled best.
7520
7521 When there is no cycle, the linear equations to be solved form a tridiagonal
7522 system, and we can apply the standard technique of Gaussian elimination
7523 to convert that system to a sequence of equations of the form
7524 $$\theta_0+u_0\theta_1=v_0,\quad
7525 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7526 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7527 \theta_n=v_n.$$
7528 It is possible to do this diagonalization while generating the equations.
7529 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7530 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7531
7532 The procedure is slightly more complex when there is a cycle, but the
7533 basic idea will be nearly the same. In the cyclic case the right-hand
7534 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7535 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7536 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7537 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7538 eliminate the $w$'s from the system, after which the solution can be
7539 obtained as before.
7540
7541 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7542 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7543 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7544 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7545
7546 @<Glob...@>=
7547 angle *theta; /* values of $\theta_k$ */
7548 fraction *uu; /* values of $u_k$ */
7549 angle *vv; /* values of $v_k$ */
7550 fraction *ww; /* values of $w_k$ */
7551
7552 @ @<Dealloc variables@>=
7553 xfree(mp->theta);
7554 xfree(mp->uu);
7555 xfree(mp->vv);
7556 xfree(mp->ww);
7557
7558 @ @<Declarations@>=
7559 static void mp_reallocate_paths (MP mp, int l);
7560
7561 @ @c
7562 void mp_reallocate_paths (MP mp, int l) {
7563   XREALLOC (mp->delta_x, l, scaled);
7564   XREALLOC (mp->delta_y, l, scaled);
7565   XREALLOC (mp->delta,   l, scaled);
7566   XREALLOC (mp->psi,     l, angle);
7567   XREALLOC (mp->theta,   l, angle);
7568   XREALLOC (mp->uu,      l, fraction);
7569   XREALLOC (mp->vv,      l, angle);
7570   XREALLOC (mp->ww,      l, fraction);
7571   mp->path_size = l;
7572 }
7573
7574 @ Our immediate problem is to get the ball rolling by setting up the
7575 first equation or by realizing that no equations are needed, and to fit
7576 this initialization into a framework suitable for the overall computation.
7577
7578 @<Declarations@>=
7579 static void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) ;
7580
7581 @ @c
7582 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7583   int k; /* current knot number */
7584   pointer r,s,t; /* registers for list traversal */
7585   @<Other local variables for |solve_choices|@>;
7586   k=0; s=p; r=0;
7587   while (1) { 
7588     t=mp_link(s);
7589     if ( k==0 ) {
7590       @<Get the linear equations started; or |return|
7591         with the control points in place, if linear equations
7592         needn't be solved@>
7593     } else  { 
7594       switch (mp_left_type(s)) {
7595       case mp_end_cycle: case mp_open:
7596         @<Set up equation to match mock curvatures
7597           at $z_k$; then |goto found| with $\theta_n$
7598           adjusted to equal $\theta_0$, if a cycle has ended@>;
7599         break;
7600       case mp_curl:
7601         @<Set up equation for a curl at $\theta_n$
7602           and |goto found|@>;
7603         break;
7604       case mp_given:
7605         @<Calculate the given value of $\theta_n$
7606           and |goto found|@>;
7607         break;
7608       } /* there are no other cases */
7609     }
7610     r=s; s=t; incr(k);
7611   }
7612 FOUND:
7613   @<Finish choosing angles and assigning control points@>;
7614 }
7615
7616 @ On the first time through the loop, we have |k=0| and |r| is not yet
7617 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7618
7619 @<Get the linear equations started...@>=
7620 switch (mp_right_type(s)) {
7621 case mp_given: 
7622   if ( mp_left_type(t)==mp_given ) {
7623     @<Reduce to simple case of two givens  and |return|@>
7624   } else {
7625     @<Set up the equation for a given value of $\theta_0$@>;
7626   }
7627   break;
7628 case mp_curl: 
7629   if ( mp_left_type(t)==mp_curl ) {
7630     @<Reduce to simple case of straight line and |return|@>
7631   } else {
7632     @<Set up the equation for a curl at $\theta_0$@>;
7633   }
7634   break;
7635 case mp_open: 
7636   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7637   /* this begins a cycle */
7638   break;
7639 } /* there are no other cases */
7640
7641 @ The general equation that specifies equality of mock curvature at $z_k$ is
7642 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7643 as derived above. We want to combine this with the already-derived equation
7644 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7645 a new equation
7646 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7647 equation
7648 $$(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}
7649     -A_kw_{k-1}\theta_0$$
7650 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7651 fixed-point arithmetic, avoiding the chance of overflow while retaining
7652 suitable precision.
7653
7654 The calculations will be performed in several registers that
7655 provide temporary storage for intermediate quantities.
7656
7657 @<Other local variables for |solve_choices|@>=
7658 fraction aa,bb,cc,ff,acc; /* temporary registers */
7659 scaled dd,ee; /* likewise, but |scaled| */
7660 scaled lt,rt; /* tension values */
7661
7662 @ @<Set up equation to match mock curvatures...@>=
7663 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7664     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7665     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7666   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7667   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7668   @<Calculate the values of $v_k$ and $w_k$@>;
7669   if ( mp_left_type(s)==mp_end_cycle ) {
7670     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7671   }
7672 }
7673
7674 @ Since tension values are never less than 3/4, the values |aa| and
7675 |bb| computed here are never more than 4/5.
7676
7677 @<Calculate the values $\\{aa}=...@>=
7678 if ( abs(right_tension(r))==unity) { 
7679   aa=fraction_half; dd=2*mp->delta[k];
7680 } else { 
7681   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7682   dd=mp_take_fraction(mp, mp->delta[k],
7683     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7684 }
7685 if ( abs(left_tension(t))==unity ){ 
7686   bb=fraction_half; ee=2*mp->delta[k-1];
7687 } else { 
7688   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7689   ee=mp_take_fraction(mp, mp->delta[k-1],
7690     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7691 }
7692 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7693
7694 @ The ratio to be calculated in this step can be written in the form
7695 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7696   \\{cc}\cdot\\{dd},$$
7697 because of the quantities just calculated. The values of |dd| and |ee|
7698 will not be needed after this step has been performed.
7699
7700 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7701 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7702 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7703   if ( lt<rt ) { 
7704     ff=mp_make_fraction(mp, lt,rt);
7705     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7706     dd=mp_take_fraction(mp, dd,ff);
7707   } else { 
7708     ff=mp_make_fraction(mp, rt,lt);
7709     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7710     ee=mp_take_fraction(mp, ee,ff);
7711   }
7712 }
7713 ff=mp_make_fraction(mp, ee,ee+dd)
7714
7715 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7716 equation was specified by a curl. In that case we must use a special
7717 method of computation to prevent overflow.
7718
7719 Fortunately, the calculations turn out to be even simpler in this ``hard''
7720 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7721 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7722
7723 @<Calculate the values of $v_k$ and $w_k$@>=
7724 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7725 if ( mp_right_type(r)==mp_curl ) { 
7726   mp->ww[k]=0;
7727   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7728 } else { 
7729   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7730     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7731   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7732   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7733   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7734   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7735   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7736 }
7737
7738 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7739 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7740 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7741 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7742 were no cycle.
7743
7744 The idea in the following code is to observe that
7745 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7746 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7747   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7748 so we can solve for $\theta_n=\theta_0$.
7749
7750 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7751
7752 aa=0; bb=fraction_one; /* we have |k=n| */
7753 do {  decr(k);
7754 if ( k==0 ) k=n;
7755   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7756   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7757 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7758 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7759 mp->theta[n]=aa; mp->vv[0]=aa;
7760 for (k=1;k<=n-1;k++) {
7761   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7762 }
7763 goto FOUND;
7764 }
7765
7766 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7767   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7768
7769 @<Calculate the given value of $\theta_n$...@>=
7770
7771   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7772   reduce_angle(mp->theta[n]);
7773   goto FOUND;
7774 }
7775
7776 @ @<Set up the equation for a given value of $\theta_0$@>=
7777
7778   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7779   reduce_angle(mp->vv[0]);
7780   mp->uu[0]=0; mp->ww[0]=0;
7781 }
7782
7783 @ @<Set up the equation for a curl at $\theta_0$@>=
7784 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7785   if ( (rt==unity)&&(lt==unity) )
7786     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7787   else 
7788     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7789   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7790 }
7791
7792 @ @<Set up equation for a curl at $\theta_n$...@>=
7793 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7794   if ( (rt==unity)&&(lt==unity) )
7795     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7796   else 
7797     ff=mp_curl_ratio(mp, cc,lt,rt);
7798   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7799     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7800   goto FOUND;
7801 }
7802
7803 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7804 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7805 a somewhat tedious program to calculate
7806 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7807   \alpha^3\gamma+(3-\beta)\beta^2},$$
7808 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7809 is necessary only if the curl and tension are both large.)
7810 The values of $\alpha$ and $\beta$ will be at most~4/3.
7811
7812 @<Declarations@>=
7813 static fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7814                         scaled b_tension) ;
7815
7816 @ @c
7817 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7818                         scaled b_tension) {
7819   fraction alpha,beta,num,denom,ff; /* registers */
7820   alpha=mp_make_fraction(mp, unity,a_tension);
7821   beta=mp_make_fraction(mp, unity,b_tension);
7822   if ( alpha<=beta ) {
7823     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7824     gamma=mp_take_fraction(mp, gamma,ff);
7825     beta=beta / 010000; /* convert |fraction| to |scaled| */
7826     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7827     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7828   } else { 
7829     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7830     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7831     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7832       /* $1365\approx 2^{12}/3$ */
7833     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7834   }
7835   if ( num>=denom+denom+denom+denom ) return fraction_four;
7836   else return mp_make_fraction(mp, num,denom);
7837 }
7838
7839 @ We're in the home stretch now.
7840
7841 @<Finish choosing angles and assigning control points@>=
7842 for (k=n-1;k>=0;k--) {
7843   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7844 }
7845 s=p; k=0;
7846 do {  
7847   t=mp_link(s);
7848   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7849   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7850   mp_set_controls(mp, s,t,k);
7851   incr(k); s=t;
7852 } while (k!=n)
7853
7854 @ The |set_controls| routine actually puts the control points into
7855 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7856 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7857 $\cos\phi$ needed in this calculation.
7858
7859 @<Glob...@>=
7860 fraction st;
7861 fraction ct;
7862 fraction sf;
7863 fraction cf; /* sines and cosines */
7864
7865 @ @<Declarations@>=
7866 static void mp_set_controls (MP mp,pointer p, pointer q, integer k);
7867
7868 @ @c
7869 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7870   fraction rr,ss; /* velocities, divided by thrice the tension */
7871   scaled lt,rt; /* tensions */
7872   fraction sine; /* $\sin(\theta+\phi)$ */
7873   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7874   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7875   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7876   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7877     @<Decrease the velocities,
7878       if necessary, to stay inside the bounding triangle@>;
7879   }
7880   mp_right_x(p)=mp_x_coord(p)+mp_take_fraction(mp, 
7881                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7882                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7883   mp_right_y(p)=mp_y_coord(p)+mp_take_fraction(mp, 
7884                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7885                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7886   mp_left_x(q)=mp_x_coord(q)-mp_take_fraction(mp, 
7887                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7888                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7889   mp_left_y(q)=mp_y_coord(q)-mp_take_fraction(mp, 
7890                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7891                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7892   mp_right_type(p)=mp_explicit; mp_left_type(q)=mp_explicit;
7893 }
7894
7895 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7896 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7897 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7898 there is no ``bounding triangle.''
7899
7900 @<Decrease the velocities, if necessary...@>=
7901 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7902   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7903                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7904   if ( sine>0 ) {
7905     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7906     if ( right_tension(p)<0 )
7907      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7908       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7909     if ( left_tension(q)<0 )
7910      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7911       ss=mp_make_fraction(mp, abs(mp->st),sine);
7912   }
7913 }
7914
7915 @ Only the simple cases remain to be handled.
7916
7917 @<Reduce to simple case of two givens and |return|@>=
7918
7919   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7920   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7921   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7922   mp_set_controls(mp, p,q,0); return;
7923 }
7924
7925 @ @<Reduce to simple case of straight line and |return|@>=
7926
7927   mp_right_type(p)=mp_explicit; mp_left_type(q)=mp_explicit;
7928   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7929   if ( rt==unity ) {
7930     if ( mp->delta_x[0]>=0 ) mp_right_x(p)=mp_x_coord(p)+((mp->delta_x[0]+1) / 3);
7931     else mp_right_x(p)=mp_x_coord(p)+((mp->delta_x[0]-1) / 3);
7932     if ( mp->delta_y[0]>=0 ) mp_right_y(p)=mp_y_coord(p)+((mp->delta_y[0]+1) / 3);
7933     else mp_right_y(p)=mp_y_coord(p)+((mp->delta_y[0]-1) / 3);
7934   } else { 
7935     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7936     mp_right_x(p)=mp_x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7937     mp_right_y(p)=mp_y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7938   }
7939   if ( lt==unity ) {
7940     if ( mp->delta_x[0]>=0 ) mp_left_x(q)=mp_x_coord(q)-((mp->delta_x[0]+1) / 3);
7941     else mp_left_x(q)=mp_x_coord(q)-((mp->delta_x[0]-1) / 3);
7942     if ( mp->delta_y[0]>=0 ) mp_left_y(q)=mp_y_coord(q)-((mp->delta_y[0]+1) / 3);
7943     else mp_left_y(q)=mp_y_coord(q)-((mp->delta_y[0]-1) / 3);
7944   } else  { 
7945     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7946     mp_left_x(q)=mp_x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7947     mp_left_y(q)=mp_y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7948   }
7949   return;
7950 }
7951
7952 @* \[19] Measuring paths.
7953 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7954 allow the user to measure the bounding box of anything that can go into a
7955 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7956 by just finding the bounding box of the knots and the control points. We
7957 need a more accurate version of the bounding box, but we can still use the
7958 easy estimate to save time by focusing on the interesting parts of the path.
7959
7960 @ Computing an accurate bounding box involves a theme that will come up again
7961 and again. Given a Bernshte{\u\i}n polynomial
7962 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7963 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7964 we can conveniently bisect its range as follows:
7965
7966 \smallskip
7967 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7968
7969 \smallskip
7970 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7971 |0<=k<n-j|, for |0<=j<n|.
7972
7973 \smallskip\noindent
7974 Then
7975 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7976  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7977 This formula gives us the coefficients of polynomials to use over the ranges
7978 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7979
7980 @ Now here's a subroutine that's handy for all sorts of path computations:
7981 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7982 returns the unique |fraction| value |t| between 0 and~1 at which
7983 $B(a,b,c;t)$ changes from positive to negative, or returns
7984 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7985 is already negative at |t=0|), |crossing_point| returns the value zero.
7986
7987 @d no_crossing {  return (fraction_one+1); }
7988 @d one_crossing { return fraction_one; }
7989 @d zero_crossing { return 0; }
7990 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
7991
7992 @c static fraction mp_do_crossing_point (integer a, integer b, integer c) {
7993   integer d; /* recursive counter */
7994   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
7995   if ( a<0 ) zero_crossing;
7996   if ( c>=0 ) { 
7997     if ( b>=0 ) {
7998       if ( c>0 ) { no_crossing; }
7999       else if ( (a==0)&&(b==0) ) { no_crossing;} 
8000       else { one_crossing; } 
8001     }
8002     if ( a==0 ) zero_crossing;
8003   } else if ( a==0 ) {
8004     if ( b<=0 ) zero_crossing;
8005   }
8006   @<Use bisection to find the crossing point, if one exists@>;
8007 }
8008
8009 @ The general bisection method is quite simple when $n=2$, hence
8010 |crossing_point| does not take much time. At each stage in the
8011 recursion we have a subinterval defined by |l| and~|j| such that
8012 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
8013 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
8014
8015 It is convenient for purposes of calculation to combine the values
8016 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
8017 of bisection then corresponds simply to doubling $d$ and possibly
8018 adding~1. Furthermore it proves to be convenient to modify
8019 our previous conventions for bisection slightly, maintaining the
8020 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
8021 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
8022 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
8023
8024 The following code maintains the invariant relations
8025 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
8026 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
8027 it has been constructed in such a way that no arithmetic overflow
8028 will occur if the inputs satisfy
8029 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
8030
8031 @<Use bisection to find the crossing point...@>=
8032 d=1; x0=a; x1=a-b; x2=b-c;
8033 do {  
8034   x=half(x1+x2);
8035   if ( x1-x0>x0 ) { 
8036     x2=x; x0+=x0; d+=d;  
8037   } else { 
8038     xx=x1+x-x0;
8039     if ( xx>x0 ) { 
8040       x2=x; x0+=x0; d+=d;
8041     }  else { 
8042       x0=x0-xx;
8043       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
8044       x1=x; d=d+d+1;
8045     }
8046   }
8047 } while (d<fraction_one);
8048 return (d-fraction_one)
8049
8050 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
8051 a cubic corresponding to the |fraction| value~|t|.
8052
8053 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
8054 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
8055
8056 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8057
8058 @c static scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8059   scaled x1,x2,x3; /* intermediate values */
8060   x1=t_of_the_way(knot_coord(p),right_coord(p));
8061   x2=t_of_the_way(right_coord(p),left_coord(q));
8062   x3=t_of_the_way(left_coord(q),knot_coord(q));
8063   x1=t_of_the_way(x1,x2);
8064   x2=t_of_the_way(x2,x3);
8065   return t_of_the_way(x1,x2);
8066 }
8067
8068 @ The actual bounding box information is stored in global variables.
8069 Since it is convenient to address the $x$ and $y$ information
8070 separately, we define arrays indexed by |x_code..y_code| and use
8071 macros to give them more convenient names.
8072
8073 @<Types...@>=
8074 enum mp_bb_code  {
8075   mp_x_code=0, /* index for |minx| and |maxx| */
8076   mp_y_code /* index for |miny| and |maxy| */
8077 } ;
8078
8079
8080 @d minx mp->bbmin[mp_x_code]
8081 @d maxx mp->bbmax[mp_x_code]
8082 @d miny mp->bbmin[mp_y_code]
8083 @d maxy mp->bbmax[mp_y_code]
8084
8085 @<Glob...@>=
8086 scaled bbmin[mp_y_code+1];
8087 scaled bbmax[mp_y_code+1]; 
8088 /* the result of procedures that compute bounding box information */
8089
8090 @ Now we're ready for the key part of the bounding box computation.
8091 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8092 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8093     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8094 $$
8095 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8096 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8097 The |c| parameter is |x_code| or |y_code|.
8098
8099 @c static void mp_bound_cubic (MP mp,pointer p, pointer q, quarterword c) {
8100   boolean wavy; /* whether we need to look for extremes */
8101   scaled del1,del2,del3,del,dmax; /* proportional to the control
8102      points of a quadratic derived from a cubic */
8103   fraction t,tt; /* where a quadratic crosses zero */
8104   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8105   x=knot_coord(q);
8106   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8107   @<Check the control points against the bounding box and set |wavy:=true|
8108     if any of them lie outside@>;
8109   if ( wavy ) {
8110     del1=right_coord(p)-knot_coord(p);
8111     del2=left_coord(q)-right_coord(p);
8112     del3=knot_coord(q)-left_coord(q);
8113     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8114       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8115     if ( del<0 ) {
8116       negate(del1); negate(del2); negate(del3);
8117     };
8118     t=mp_crossing_point(mp, del1,del2,del3);
8119     if ( t<fraction_one ) {
8120       @<Test the extremes of the cubic against the bounding box@>;
8121     }
8122   }
8123 }
8124
8125 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8126 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8127 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8128
8129 @ @<Check the control points against the bounding box and set...@>=
8130 wavy=true;
8131 if ( mp->bbmin[c]<=right_coord(p) )
8132   if ( right_coord(p)<=mp->bbmax[c] )
8133     if ( mp->bbmin[c]<=left_coord(q) )
8134       if ( left_coord(q)<=mp->bbmax[c] )
8135         wavy=false
8136
8137 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8138 section. We just set |del=0| in that case.
8139
8140 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8141 if ( del1!=0 ) del=del1;
8142 else if ( del2!=0 ) del=del2;
8143 else del=del3;
8144 if ( del!=0 ) {
8145   dmax=abs(del1);
8146   if ( abs(del2)>dmax ) dmax=abs(del2);
8147   if ( abs(del3)>dmax ) dmax=abs(del3);
8148   while ( dmax<fraction_half ) {
8149     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8150   }
8151 }
8152
8153 @ Since |crossing_point| has tried to choose |t| so that
8154 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8155 slope, the value of |del2| computed below should not be positive.
8156 But rounding error could make it slightly positive in which case we
8157 must cut it to zero to avoid confusion.
8158
8159 @<Test the extremes of the cubic against the bounding box@>=
8160
8161   x=mp_eval_cubic(mp, p,q,t);
8162   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8163   del2=t_of_the_way(del2,del3);
8164     /* now |0,del2,del3| represent the derivative on the remaining interval */
8165   if ( del2>0 ) del2=0;
8166   tt=mp_crossing_point(mp, 0,-del2,-del3);
8167   if ( tt<fraction_one ) {
8168     @<Test the second extreme against the bounding box@>;
8169   }
8170 }
8171
8172 @ @<Test the second extreme against the bounding box@>=
8173 {
8174    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8175   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8176 }
8177
8178 @ Finding the bounding box of a path is basically a matter of applying
8179 |bound_cubic| twice for each pair of adjacent knots.
8180
8181 @c static void mp_path_bbox (MP mp,pointer h) {
8182   pointer p,q; /* a pair of adjacent knots */
8183    minx=mp_x_coord(h); miny=mp_y_coord(h);
8184   maxx=minx; maxy=miny;
8185   p=h;
8186   do {  
8187     if ( mp_right_type(p)==mp_endpoint ) return;
8188     q=mp_link(p);
8189     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8190     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8191     p=q;
8192   } while (p!=h);
8193 }
8194
8195 @ Another important way to measure a path is to find its arc length.  This
8196 is best done by using the general bisection algorithm to subdivide the path
8197 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8198 by simple means.
8199
8200 Since the arc length is the integral with respect to time of the magnitude of
8201 the velocity, it is natural to use Simpson's rule for the approximation.
8202 @^Simpson's rule@>
8203 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8204 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8205 for the arc length of a path of length~1.  For a cubic spline
8206 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8207 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8208 approximation is
8209 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8210 where
8211 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8212 is the result of the bisection algorithm.
8213
8214 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8215 This could be done via the theoretical error bound for Simpson's rule,
8216 @^Simpson's rule@>
8217 but this is impractical because it requires an estimate of the fourth
8218 derivative of the quantity being integrated.  It is much easier to just perform
8219 a bisection step and see how much the arc length estimate changes.  Since the
8220 error for Simpson's rule is proportional to the fourth power of the sample
8221 spacing, the remaining error is typically about $1\over16$ of the amount of
8222 the change.  We say ``typically'' because the error has a pseudo-random behavior
8223 that could cause the two estimates to agree when each contain large errors.
8224
8225 To protect against disasters such as undetected cusps, the bisection process
8226 should always continue until all the $dz_i$ vectors belong to a single
8227 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8228 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8229 If such a spline happens to produce an erroneous arc length estimate that
8230 is little changed by bisection, the amount of the error is likely to be fairly
8231 small.  We will try to arrange things so that freak accidents of this type do
8232 not destroy the inverse relationship between the \&{arclength} and
8233 \&{arctime} operations.
8234 @:arclength_}{\&{arclength} primitive@>
8235 @:arctime_}{\&{arctime} primitive@>
8236
8237 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8238 @^recursion@>
8239 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8240 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8241 returns the time when the arc length reaches |a_goal| if there is such a time.
8242 Thus the return value is either an arc length less than |a_goal| or, if the
8243 arc length would be at least |a_goal|, it returns a time value decreased by
8244 |two|.  This allows the caller to use the sign of the result to distinguish
8245 between arc lengths and time values.  On certain types of overflow, it is
8246 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8247 Otherwise, the result is always less than |a_goal|.
8248
8249 Rather than halving the control point coordinates on each recursive call to
8250 |arc_test|, it is better to keep them proportional to velocity on the original
8251 curve and halve the results instead.  This means that recursive calls can
8252 potentially use larger error tolerances in their arc length estimates.  How
8253 much larger depends on to what extent the errors behave as though they are
8254 independent of each other.  To save computing time, we use optimistic assumptions
8255 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8256 call.
8257
8258 In addition to the tolerance parameter, |arc_test| should also have parameters
8259 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8260 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8261 and they are needed in different instances of |arc_test|.
8262
8263 @c 
8264 static scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8265                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8266                     scaled v2, scaled a_goal, scaled tol) {
8267   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8268   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8269   scaled v002, v022;
8270     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8271   scaled arc; /* best arc length estimate before recursion */
8272   @<Other local variables in |arc_test|@>;
8273   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8274     |dx2|, |dy2|@>;
8275   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8276     set |arc_test| and |return|@>;
8277   @<Test if the control points are confined to one quadrant or rotating them
8278     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8279   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8280     if ( arc < a_goal ) {
8281       return arc;
8282     } else {
8283        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8284          that time minus |two|@>;
8285     }
8286   } else {
8287     @<Use one or two recursive calls to compute the |arc_test| function@>;
8288   }
8289 }
8290
8291 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8292 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8293 |make_fraction| in this inner loop.
8294 @^inner loop@>
8295
8296 @<Use one or two recursive calls to compute the |arc_test| function@>=
8297
8298   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8299     large as possible@>;
8300   tol = tol + halfp(tol);
8301   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8302                   halfp(v02), a_new, tol);
8303   if ( a<0 )  {
8304      return (-halfp(two-a));
8305   } else { 
8306     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8307     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8308                     halfp(v02), v022, v2, a_new, tol);
8309     if ( b<0 )  
8310       return (-halfp(-b) - half_unit);
8311     else  
8312       return (a + half(b-a));
8313   }
8314 }
8315
8316 @ @<Other local variables in |arc_test|@>=
8317 scaled a,b; /* results of recursive calls */
8318 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8319
8320 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8321 a_aux = el_gordo - a_goal;
8322 if ( a_goal > a_aux ) {
8323   a_aux = a_goal - a_aux;
8324   a_new = el_gordo;
8325 } else { 
8326   a_new = a_goal + a_goal;
8327   a_aux = 0;
8328 }
8329
8330 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8331 to force the additions and subtractions to be done in an order that avoids
8332 overflow.
8333
8334 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8335 if ( a > a_aux ) {
8336   a_aux = a_aux - a;
8337   a_new = a_new + a_aux;
8338 }
8339
8340 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8341 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8342 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8343 this bound.  Note that recursive calls will maintain this invariant.
8344
8345 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8346 dx01 = half(dx0 + dx1);
8347 dx12 = half(dx1 + dx2);
8348 dx02 = half(dx01 + dx12);
8349 dy01 = half(dy0 + dy1);
8350 dy12 = half(dy1 + dy2);
8351 dy02 = half(dy01 + dy12)
8352
8353 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8354 |a_goal=el_gordo| is guaranteed to yield the arc length.
8355
8356 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8357 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8358 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8359 tmp = halfp(v02+2);
8360 arc1 = v002 + half(halfp(v0+tmp) - v002);
8361 arc = v022 + half(halfp(v2+tmp) - v022);
8362 if ( (arc < el_gordo-arc1) )  {
8363   arc = arc+arc1;
8364 } else { 
8365   mp->arith_error = true;
8366   if ( a_goal==el_gordo )  return (el_gordo);
8367   else return (-two);
8368 }
8369
8370 @ @<Other local variables in |arc_test|@>=
8371 scaled tmp, tmp2; /* all purpose temporary registers */
8372 scaled arc1; /* arc length estimate for the first half */
8373
8374 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8375 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8376          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8377 if ( simple )
8378   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8379            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8380 if ( ! simple ) {
8381   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8382            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8383   if ( simple ) 
8384     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8385              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8386 }
8387
8388 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8389 @^Simpson's rule@>
8390 it is appropriate to use the same approximation to decide when the integral
8391 reaches the intermediate value |a_goal|.  At this point
8392 $$\eqalign{
8393     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8394     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8395     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8396     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8397     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8398 }
8399 $$
8400 and
8401 $$ {\vb\dot B(t)\vb\over 3} \approx
8402   \cases{B\left(\hbox{|v0|},
8403       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8404       {1\over 2}\hbox{|v02|}; 2t \right)&
8405     if $t\le{1\over 2}$\cr
8406   B\left({1\over 2}\hbox{|v02|},
8407       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8408       \hbox{|v2|}; 2t-1 \right)&
8409     if $t\ge{1\over 2}$.\cr}
8410  \eqno (*)
8411 $$
8412 We can integrate $\vb\dot B(t)\vb$ by using
8413 $$\int 3B(a,b,c;\tau)\,dt =
8414   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8415 $$
8416
8417 This construction allows us to find the time when the arc length reaches
8418 |a_goal| by solving a cubic equation of the form
8419 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8420 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8421 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8422 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8423 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8424 $\tau$ given $a$, $b$, $c$, and $x$.
8425
8426 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8427
8428   tmp = (v02 + 2) / 4;
8429   if ( a_goal<=arc1 ) {
8430     tmp2 = halfp(v0);
8431     return 
8432       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8433   } else { 
8434     tmp2 = halfp(v2);
8435     return ((half_unit - two) +
8436       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8437   }
8438 }
8439
8440 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8441 $$ B(0, a, a+b, a+b+c; t) = x. $$
8442 This routine is based on |crossing_point| but is simplified by the
8443 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8444 If rounding error causes this condition to be violated slightly, we just ignore
8445 it and proceed with binary search.  This finds a time when the function value
8446 reaches |x| and the slope is positive.
8447
8448 @<Declarations@>=
8449 static scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) ;
8450
8451 @ @c
8452 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8453   scaled ab, bc, ac; /* bisection results */
8454   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8455   integer xx; /* temporary for updating |x| */
8456   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8457 @:this can't happen rising?}{\quad rising?@>
8458   if ( x<=0 ) {
8459         return 0;
8460   } else if ( x >= a+b+c ) {
8461     return unity;
8462   } else { 
8463     t = 1;
8464     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8465       |el_gordo div 3|@>;
8466     do {  
8467       t+=t;
8468       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8469       xx = x - a - ab - ac;
8470       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8471       else { x = x + xx;  a=ac; b=bc; t = t+1; };
8472     } while (t < unity);
8473     return (t - unity);
8474   }
8475 }
8476
8477 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8478 ab = half(a+b);
8479 bc = half(b+c);
8480 ac = half(ab+bc)
8481
8482 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8483
8484 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8485 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8486   a = halfp(a);
8487   b = half(b);
8488   c = halfp(c);
8489   x = halfp(x);
8490 }
8491
8492 @ It is convenient to have a simpler interface to |arc_test| that requires no
8493 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8494 length less than |fraction_four|.
8495
8496 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8497
8498 @c static scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8499                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8500   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8501   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8502   v0 = mp_pyth_add(mp, dx0,dy0);
8503   v1 = mp_pyth_add(mp, dx1,dy1);
8504   v2 = mp_pyth_add(mp, dx2,dy2);
8505   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8506     mp->arith_error = true;
8507     if ( a_goal==el_gordo )  return el_gordo;
8508     else return (-two);
8509   } else { 
8510     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8511     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8512                                  v0, v02, v2, a_goal, arc_tol));
8513   }
8514 }
8515
8516 @ Now it is easy to find the arc length of an entire path.
8517
8518 @c static scaled mp_get_arc_length (MP mp,pointer h) {
8519   pointer p,q; /* for traversing the path */
8520   scaled a,a_tot; /* current and total arc lengths */
8521   a_tot = 0;
8522   p = h;
8523   while ( mp_right_type(p)!=mp_endpoint ){ 
8524     q = mp_link(p);
8525     a = mp_do_arc_test(mp, mp_right_x(p)-mp_x_coord(p), mp_right_y(p)-mp_y_coord(p),
8526       mp_left_x(q)-mp_right_x(p), mp_left_y(q)-mp_right_y(p),
8527       mp_x_coord(q)-mp_left_x(q), mp_y_coord(q)-mp_left_y(q), el_gordo);
8528     a_tot = mp_slow_add(mp, a, a_tot);
8529     if ( q==h ) break;  else p=q;
8530   }
8531   check_arith;
8532   return a_tot;
8533 }
8534
8535 @ The inverse operation of finding the time on a path~|h| when the arc length
8536 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8537 is required to handle very large times or negative times on cyclic paths.  For
8538 non-cyclic paths, |arc0| values that are negative or too large cause
8539 |get_arc_time| to return 0 or the length of path~|h|.
8540
8541 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8542 time value greater than the length of the path.  Since it could be much greater,
8543 we must be prepared to compute the arc length of path~|h| and divide this into
8544 |arc0| to find how many multiples of the length of path~|h| to add.
8545
8546 @c static scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8547   pointer p,q; /* for traversing the path */
8548   scaled t_tot; /* accumulator for the result */
8549   scaled t; /* the result of |do_arc_test| */
8550   scaled arc; /* portion of |arc0| not used up so far */
8551   integer n; /* number of extra times to go around the cycle */
8552   if ( arc0<0 ) {
8553     @<Deal with a negative |arc0| value and |return|@>;
8554   }
8555   if ( arc0==el_gordo ) decr(arc0);
8556   t_tot = 0;
8557   arc = arc0;
8558   p = h;
8559   while ( (mp_right_type(p)!=mp_endpoint) && (arc>0) ) {
8560     q = mp_link(p);
8561     t = mp_do_arc_test(mp, mp_right_x(p)-mp_x_coord(p), mp_right_y(p)-mp_y_coord(p),
8562       mp_left_x(q)-mp_right_x(p), mp_left_y(q)-mp_right_y(p),
8563       mp_x_coord(q)-mp_left_x(q), mp_y_coord(q)-mp_left_y(q), arc);
8564     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8565     if ( q==h ) {
8566       @<Update |t_tot| and |arc| to avoid going around the cyclic
8567         path too many times but set |arith_error:=true| and |goto done| on
8568         overflow@>;
8569     }
8570     p = q;
8571   }
8572   check_arith;
8573   return t_tot;
8574 }
8575
8576 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8577 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8578 else { t_tot = t_tot + unity;  arc = arc - t;  }
8579
8580 @ @<Deal with a negative |arc0| value and |return|@>=
8581
8582   if ( mp_left_type(h)==mp_endpoint ) {
8583     t_tot=0;
8584   } else { 
8585     p = mp_htap_ypoc(mp, h);
8586     t_tot = -mp_get_arc_time(mp, p, -arc0);
8587     mp_toss_knot_list(mp, p);
8588   }
8589   check_arith;
8590   return t_tot;
8591 }
8592
8593 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8594 if ( arc>0 ) { 
8595   n = arc / (arc0 - arc);
8596   arc = arc - n*(arc0 - arc);
8597   if ( t_tot > (el_gordo / (n+1)) ) { 
8598         return el_gordo;
8599   }
8600   t_tot = (n + 1)*t_tot;
8601 }
8602
8603 @* \[20] Data structures for pens.
8604 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8605 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8606 @:stroke}{\&{stroke} command@>
8607 converted into an area fill as described in the next part of this program.
8608 The mathematics behind this process is based on simple aspects of the theory
8609 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8610 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8611 Foundations of Computer Science {\bf 24} (1983), 100--111].
8612
8613 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8614 @:makepen_}{\&{makepen} primitive@>
8615 This path representation is almost sufficient for our purposes except that
8616 a pen path should always be a convex polygon with the vertices in
8617 counter-clockwise order.
8618 Since we will need to scan pen polygons both forward and backward, a pen
8619 should be represented as a doubly linked ring of knot nodes.  There is
8620 room for the extra back pointer because we do not need the
8621 |mp_left_type| or |mp_right_type| fields.  In fact, we don't need the |mp_left_x|,
8622 |mp_left_y|, |mp_right_x|, or |mp_right_y| fields either but we leave these alone
8623 so that certain procedures can operate on both pens and paths.  In particular,
8624 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8625
8626 @d knil info
8627   /* this replaces the |mp_left_type| and |mp_right_type| fields in a pen knot */
8628
8629 @ The |make_pen| procedure turns a path into a pen by initializing
8630 the |knil| pointers and making sure the knots form a convex polygon.
8631 Thus each cubic in the given path becomes a straight line and the control
8632 points are ignored.  If the path is not cyclic, the ends are connected by a
8633 straight line.
8634
8635 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8636
8637 @c 
8638 static pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8639   pointer p,q; /* two consecutive knots */
8640   q=h;
8641   do {  
8642     p=q; q=mp_link(q);
8643     knil(q)=p;
8644   } while (q!=h);
8645   if ( need_hull ){ 
8646     h=mp_convex_hull(mp, h);
8647     @<Make sure |h| isn't confused with an elliptical pen@>;
8648   }
8649   return h;
8650 }
8651
8652 @ The only information required about an elliptical pen is the overall
8653 transformation that has been applied to the original \&{pencircle}.
8654 @:pencircle_}{\&{pencircle} primitive@>
8655 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8656 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8657 knot node and transformed as if it were a path.
8658
8659 @d pen_is_elliptical(A) ((A)==mp_link((A)))
8660
8661 @c 
8662 static pointer mp_get_pen_circle (MP mp,scaled diam) {
8663   pointer h; /* the knot node to return */
8664   h=mp_get_node(mp, knot_node_size);
8665   mp_link(h)=h; knil(h)=h;
8666   mp_originator(h)=mp_program_code;
8667   mp_x_coord(h)=0; mp_y_coord(h)=0;
8668   mp_left_x(h)=diam; mp_left_y(h)=0;
8669   mp_right_x(h)=0; mp_right_y(h)=diam;
8670   return h;
8671 }
8672
8673 @ If the polygon being returned by |make_pen| has only one vertex, it will
8674 be interpreted as an elliptical pen.  This is no problem since a degenerate
8675 polygon can equally well be thought of as a degenerate ellipse.  We need only
8676 initialize the |mp_left_x|, |mp_left_y|, |mp_right_x|, and |mp_right_y| fields.
8677
8678 @<Make sure |h| isn't confused with an elliptical pen@>=
8679 if ( pen_is_elliptical( h) ){ 
8680   mp_left_x(h)=mp_x_coord(h); mp_left_y(h)=mp_y_coord(h);
8681   mp_right_x(h)=mp_x_coord(h); mp_right_y(h)=mp_y_coord(h);
8682 }
8683
8684 @ We have to cheat a little here but most operations on pens only use
8685 the first three words in each knot node.
8686 @^data structure assumptions@>
8687
8688 @<Initialize a pen at |test_pen| so that it fits in nine words@>=
8689 mp_x_coord(test_pen)=-half_unit;
8690 mp_y_coord(test_pen)=0;
8691 mp_x_coord(test_pen+3)=half_unit;
8692 mp_y_coord(test_pen+3)=0;
8693 mp_x_coord(test_pen+6)=0;
8694 mp_y_coord(test_pen+6)=unity;
8695 mp_link(test_pen)=test_pen+3;
8696 mp_link(test_pen+3)=test_pen+6;
8697 mp_link(test_pen+6)=test_pen;
8698 knil(test_pen)=test_pen+6;
8699 knil(test_pen+3)=test_pen;
8700 knil(test_pen+6)=test_pen+3
8701
8702 @ Printing a polygonal pen is very much like printing a path
8703
8704 @<Declarations@>=
8705 static void mp_pr_pen (MP mp,pointer h) ;
8706
8707 @ @c
8708 void mp_pr_pen (MP mp,pointer h) {
8709   pointer p,q; /* for list traversal */
8710   if ( pen_is_elliptical(h) ) {
8711     @<Print the elliptical pen |h|@>;
8712   } else { 
8713     p=h;
8714     do {  
8715       mp_print_two(mp, mp_x_coord(p),mp_y_coord(p));
8716       mp_print_nl(mp, " .. ");
8717       @<Advance |p| making sure the links are OK and |return| if there is
8718         a problem@>;
8719      } while (p!=h);
8720      mp_print(mp, "cycle");
8721   }
8722 }
8723
8724 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8725 q=mp_link(p);
8726 if ( (q==null) || (knil(q)!=p) ) { 
8727   mp_print_nl(mp, "???"); return; /* this won't happen */
8728 @.???@>
8729 }
8730 p=q
8731
8732 @ @<Print the elliptical pen |h|@>=
8733
8734 mp_print(mp, "pencircle transformed (");
8735 mp_print_scaled(mp, mp_x_coord(h));
8736 mp_print_char(mp, xord(','));
8737 mp_print_scaled(mp, mp_y_coord(h));
8738 mp_print_char(mp, xord(','));
8739 mp_print_scaled(mp, mp_left_x(h)-mp_x_coord(h));
8740 mp_print_char(mp, xord(','));
8741 mp_print_scaled(mp, mp_right_x(h)-mp_x_coord(h));
8742 mp_print_char(mp, xord(','));
8743 mp_print_scaled(mp, mp_left_y(h)-mp_y_coord(h));
8744 mp_print_char(mp, xord(','));
8745 mp_print_scaled(mp, mp_right_y(h)-mp_y_coord(h));
8746 mp_print_char(mp, xord(')'));
8747 }
8748
8749 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8750 message.
8751
8752 @<Declarations@>=
8753 static void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) ;
8754
8755 @ @c
8756 void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) { 
8757   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8758 @.Pen at line...@>
8759   mp_pr_pen(mp, h);
8760   mp_end_diagnostic(mp, true);
8761 }
8762
8763 @ Making a polygonal pen into a path involves restoring the |mp_left_type| and
8764 |mp_right_type| fields and setting the control points so as to make a polygonal
8765 path.
8766
8767 @c 
8768 static void mp_make_path (MP mp,pointer h) {
8769   pointer p; /* for traversing the knot list */
8770   quarterword k; /* a loop counter */
8771   @<Other local variables in |make_path|@>;
8772   if ( pen_is_elliptical(h) ) {
8773     @<Make the elliptical pen |h| into a path@>;
8774   } else { 
8775     p=h;
8776     do {  
8777       mp_left_type(p)=mp_explicit;
8778       mp_right_type(p)=mp_explicit;
8779       @<copy the coordinates of knot |p| into its control points@>;
8780        p=mp_link(p);
8781     } while (p!=h);
8782   }
8783 }
8784
8785 @ @<copy the coordinates of knot |p| into its control points@>=
8786 mp_left_x(p)=mp_x_coord(p);
8787 mp_left_y(p)=mp_y_coord(p);
8788 mp_right_x(p)=mp_x_coord(p);
8789 mp_right_y(p)=mp_y_coord(p)
8790
8791 @ We need an eight knot path to get a good approximation to an ellipse.
8792
8793 @<Make the elliptical pen |h| into a path@>=
8794
8795   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8796   p=h;
8797   for (k=0;k<=7;k++ ) { 
8798     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8799       transforming it appropriately@>;
8800     if ( k==7 ) mp_link(p)=h;  else mp_link(p)=mp_get_node(mp, knot_node_size);
8801     p=mp_link(p);
8802   }
8803 }
8804
8805 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8806 center_x=mp_x_coord(h);
8807 center_y=mp_y_coord(h);
8808 width_x=mp_left_x(h)-center_x;
8809 width_y=mp_left_y(h)-center_y;
8810 height_x=mp_right_x(h)-center_x;
8811 height_y=mp_right_y(h)-center_y
8812
8813 @ @<Other local variables in |make_path|@>=
8814 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8815 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8816 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8817 scaled dx,dy; /* the vector from knot |p| to its right control point */
8818 integer kk;
8819   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8820
8821 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8822 find the point $k/8$ of the way around the circle and the direction vector
8823 to use there.
8824
8825 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8826 kk=(k+6)% 8;
8827 mp_x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8828            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8829 mp_y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8830            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8831 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8832    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8833 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8834    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8835 mp_right_x(p)=mp_x_coord(p)+dx;
8836 mp_right_y(p)=mp_y_coord(p)+dy;
8837 mp_left_x(p)=mp_x_coord(p)-dx;
8838 mp_left_y(p)=mp_y_coord(p)-dy;
8839 mp_left_type(p)=mp_explicit;
8840 mp_right_type(p)=mp_explicit;
8841 mp_originator(p)=mp_program_code
8842
8843 @ @<Glob...@>=
8844 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8845 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8846
8847 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8848 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8849 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8850 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8851   \approx 0.132608244919772.
8852 $$
8853
8854 @<Set init...@>=
8855 mp->half_cos[0]=fraction_half;
8856 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8857 mp->half_cos[2]=0;
8858 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8859 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8860 mp->d_cos[2]=0;
8861 for (k=3;k<= 4;k++ ) { 
8862   mp->half_cos[k]=-mp->half_cos[4-k];
8863   mp->d_cos[k]=-mp->d_cos[4-k];
8864 }
8865 for (k=5;k<= 7;k++ ) { 
8866   mp->half_cos[k]=mp->half_cos[8-k];
8867   mp->d_cos[k]=mp->d_cos[8-k];
8868 }
8869
8870 @ The |convex_hull| function forces a pen polygon to be convex when it is
8871 returned by |make_pen| and after any subsequent transformation where rounding
8872 error might allow the convexity to be lost.
8873 The convex hull algorithm used here is described by F.~P. Preparata and
8874 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8875
8876 @<Declarations@>=
8877 static pointer mp_convex_hull (MP mp,pointer h);
8878
8879 @ @c
8880 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8881   pointer l,r; /* the leftmost and rightmost knots */
8882   pointer p,q; /* knots being scanned */
8883   pointer s; /* the starting point for an upcoming scan */
8884   scaled dx,dy; /* a temporary pointer */
8885   if ( pen_is_elliptical(h) ) {
8886      return h;
8887   } else { 
8888     @<Set |l| to the leftmost knot in polygon~|h|@>;
8889     @<Set |r| to the rightmost knot in polygon~|h|@>;
8890     if ( l!=r ) { 
8891       s=mp_link(r);
8892       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8893         move them past~|r|@>;
8894       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8895         move them past~|l|@>;
8896       @<Sort the path from |l| to |r| by increasing $x$@>;
8897       @<Sort the path from |r| to |l| by decreasing $x$@>;
8898     }
8899     if ( l!=mp_link(l) ) {
8900       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8901     }
8902     return l;
8903   }
8904 }
8905
8906 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8907
8908 @<Set |l| to the leftmost knot in polygon~|h|@>=
8909 l=h;
8910 p=mp_link(h);
8911 while ( p!=h ) { 
8912   if ( mp_x_coord(p)<=mp_x_coord(l) )
8913     if ( (mp_x_coord(p)<mp_x_coord(l)) || (mp_y_coord(p)<mp_y_coord(l)) )
8914       l=p;
8915   p=mp_link(p);
8916 }
8917
8918 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8919 r=h;
8920 p=mp_link(h);
8921 while ( p!=h ) { 
8922   if ( mp_x_coord(p)>=mp_x_coord(r) )
8923     if ( (mp_x_coord(p)>mp_x_coord(r)) || (mp_y_coord(p)>mp_y_coord(r)) )
8924       r=p;
8925   p=mp_link(p);
8926 }
8927
8928 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8929 dx=mp_x_coord(r)-mp_x_coord(l);
8930 dy=mp_y_coord(r)-mp_y_coord(l);
8931 p=mp_link(l);
8932 while ( p!=r ) { 
8933   q=mp_link(p);
8934   if ( mp_ab_vs_cd(mp, dx,mp_y_coord(p)-mp_y_coord(l),dy,mp_x_coord(p)-mp_x_coord(l))>0 )
8935     mp_move_knot(mp, p, r);
8936   p=q;
8937 }
8938
8939 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8940 it after |q|.
8941
8942 @ @<Declarations@>=
8943 static void mp_move_knot (MP mp,pointer p, pointer q) ;
8944
8945 @ @c
8946 void mp_move_knot (MP mp,pointer p, pointer q) { 
8947   mp_link(knil(p))=mp_link(p);
8948   knil(mp_link(p))=knil(p);
8949   knil(p)=q;
8950   mp_link(p)=mp_link(q);
8951   mp_link(q)=p;
8952   knil(mp_link(p))=p;
8953 }
8954
8955 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8956 p=s;
8957 while ( p!=l ) { 
8958   q=mp_link(p);
8959   if ( mp_ab_vs_cd(mp, dx,mp_y_coord(p)-mp_y_coord(l),dy,mp_x_coord(p)-mp_x_coord(l))<0 )
8960     mp_move_knot(mp, p,l);
8961   p=q;
8962 }
8963
8964 @ The list is likely to be in order already so we just do linear insertions.
8965 Secondary comparisons on $y$ ensure that the sort is consistent with the
8966 choice of |l| and |r|.
8967
8968 @<Sort the path from |l| to |r| by increasing $x$@>=
8969 p=mp_link(l);
8970 while ( p!=r ) { 
8971   q=knil(p);
8972   while ( mp_x_coord(q)>mp_x_coord(p) ) q=knil(q);
8973   while ( mp_x_coord(q)==mp_x_coord(p) ) {
8974     if ( mp_y_coord(q)>mp_y_coord(p) ) q=knil(q); else break;
8975   }
8976   if ( q==knil(p) ) p=mp_link(p);
8977   else { p=mp_link(p); mp_move_knot(mp, knil(p),q); };
8978 }
8979
8980 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8981 p=mp_link(r);
8982 while ( p!=l ){ 
8983   q=knil(p);
8984   while ( mp_x_coord(q)<mp_x_coord(p) ) q=knil(q);
8985   while ( mp_x_coord(q)==mp_x_coord(p) ) {
8986     if ( mp_y_coord(q)<mp_y_coord(p) ) q=knil(q); else break;
8987   }
8988   if ( q==knil(p) ) p=mp_link(p);
8989   else { p=mp_link(p); mp_move_knot(mp, knil(p),q); };
8990 }
8991
8992 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8993 at knot |q|.  There usually will be a left turn so we streamline the case
8994 where the |then| clause is not executed.
8995
8996 @<Do a Gramm scan and remove vertices where there...@>=
8997
8998 p=l; q=mp_link(l);
8999 while (1) { 
9000   dx=mp_x_coord(q)-mp_x_coord(p);
9001   dy=mp_y_coord(q)-mp_y_coord(p);
9002   p=q; q=mp_link(q);
9003   if ( p==l ) break;
9004   if ( p!=r )
9005     if ( mp_ab_vs_cd(mp, dx,mp_y_coord(q)-mp_y_coord(p),dy,mp_x_coord(q)-mp_x_coord(p))<=0 ) {
9006       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
9007     }
9008   }
9009 }
9010
9011 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
9012
9013 s=knil(p);
9014 mp_free_node(mp, p,knot_node_size);
9015 mp_link(s)=q; knil(q)=s;
9016 if ( s==l ) p=s;
9017 else { p=knil(s); q=s; };
9018 }
9019
9020 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
9021 offset associated with the given direction |(x,y)|.  If two different offsets
9022 apply, it chooses one of them.
9023
9024 @c 
9025 static void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
9026   pointer p,q; /* consecutive knots */
9027   scaled wx,wy,hx,hy;
9028   /* the transformation matrix for an elliptical pen */
9029   fraction xx,yy; /* untransformed offset for an elliptical pen */
9030   fraction d; /* a temporary register */
9031   if ( pen_is_elliptical(h) ) {
9032     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
9033   } else { 
9034     q=h;
9035     do {  
9036       p=q; q=mp_link(q);
9037     } while (!(mp_ab_vs_cd(mp, mp_x_coord(q)-mp_x_coord(p),y, mp_y_coord(q)-mp_y_coord(p),x)>=0));
9038     do {  
9039       p=q; q=mp_link(q);
9040     } while (!(mp_ab_vs_cd(mp, mp_x_coord(q)-mp_x_coord(p),y, mp_y_coord(q)-mp_y_coord(p),x)<=0));
9041     mp->cur_x=mp_x_coord(p);
9042     mp->cur_y=mp_y_coord(p);
9043   }
9044 }
9045
9046 @ @<Glob...@>=
9047 scaled cur_x;
9048 scaled cur_y; /* all-purpose return value registers */
9049
9050 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
9051 if ( (x==0) && (y==0) ) {
9052   mp->cur_x=mp_x_coord(h); mp->cur_y=mp_y_coord(h);  
9053 } else { 
9054   @<Find the non-constant part of the transformation for |h|@>;
9055   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
9056     x+=x; y+=y;  
9057   };
9058   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
9059     untransformed version of |(x,y)|@>;
9060   mp->cur_x=mp_x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
9061   mp->cur_y=mp_y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
9062 }
9063
9064 @ @<Find the non-constant part of the transformation for |h|@>=
9065 wx=mp_left_x(h)-mp_x_coord(h);
9066 wy=mp_left_y(h)-mp_y_coord(h);
9067 hx=mp_right_x(h)-mp_x_coord(h);
9068 hy=mp_right_y(h)-mp_y_coord(h)
9069
9070 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9071 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9072 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9073 d=mp_pyth_add(mp, xx,yy);
9074 if ( d>0 ) { 
9075   xx=half(mp_make_fraction(mp, xx,d));
9076   yy=half(mp_make_fraction(mp, yy,d));
9077 }
9078
9079 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9080 But we can handle that case by just calling |find_offset| twice.  The answer
9081 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9082
9083 @c 
9084 static void mp_pen_bbox (MP mp,pointer h) {
9085   pointer p; /* for scanning the knot list */
9086   if ( pen_is_elliptical(h) ) {
9087     @<Find the bounding box of an elliptical pen@>;
9088   } else { 
9089     minx=mp_x_coord(h); maxx=minx;
9090     miny=mp_y_coord(h); maxy=miny;
9091     p=mp_link(h);
9092     while ( p!=h ) {
9093       if ( mp_x_coord(p)<minx ) minx=mp_x_coord(p);
9094       if ( mp_y_coord(p)<miny ) miny=mp_y_coord(p);
9095       if ( mp_x_coord(p)>maxx ) maxx=mp_x_coord(p);
9096       if ( mp_y_coord(p)>maxy ) maxy=mp_y_coord(p);
9097       p=mp_link(p);
9098     }
9099   }
9100 }
9101
9102 @ @<Find the bounding box of an elliptical pen@>=
9103
9104 mp_find_offset(mp, 0,fraction_one,h);
9105 maxx=mp->cur_x;
9106 minx=2*mp_x_coord(h)-mp->cur_x;
9107 mp_find_offset(mp, -fraction_one,0,h);
9108 maxy=mp->cur_y;
9109 miny=2*mp_y_coord(h)-mp->cur_y;
9110 }
9111
9112 @* \[21] Edge structures.
9113 Now we come to \MP's internal scheme for representing pictures.
9114 The representation is very different from \MF's edge structures
9115 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9116 images.  However, the basic idea is somewhat similar in that shapes
9117 are represented via their boundaries.
9118
9119 The main purpose of edge structures is to keep track of graphical objects
9120 until it is time to translate them into \ps.  Since \MP\ does not need to
9121 know anything about an edge structure other than how to translate it into
9122 \ps\ and how to find its bounding box, edge structures can be just linked
9123 lists of graphical objects.  \MP\ has no easy way to determine whether
9124 two such objects overlap, but it suffices to draw the first one first and
9125 let the second one overwrite it if necessary.
9126
9127 @(mplib.h@>=
9128 enum mp_graphical_object_code {
9129   @<Graphical object codes@>
9130   mp_final_graphic
9131 };
9132
9133 @ Let's consider the types of graphical objects one at a time.
9134 First of all, a filled contour is represented by a eight-word node.  The first
9135 word contains |type| and |link| fields, and the next six words contain a
9136 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9137 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9138 give the relevant information.
9139
9140 @d path_p(A) mp_link((A)+1)
9141   /* a pointer to the path that needs filling */
9142 @d pen_p(A) info((A)+1)
9143   /* a pointer to the pen to fill or stroke with */
9144 @d color_model(A) type((A)+2) /*  the color model  */
9145 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9146 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9147 @d obj_grey_loc obj_red_loc  /* the location for the color */
9148 @d red_val(A) mp->mem[(A)+3].sc
9149   /* the red component of the color in the range $0\ldots1$ */
9150 @d cyan_val red_val
9151 @d grey_val red_val
9152 @d green_val(A) mp->mem[(A)+4].sc
9153   /* the green component of the color in the range $0\ldots1$ */
9154 @d magenta_val green_val
9155 @d blue_val(A) mp->mem[(A)+5].sc
9156   /* the blue component of the color in the range $0\ldots1$ */
9157 @d yellow_val blue_val
9158 @d black_val(A) mp->mem[(A)+6].sc
9159   /* the blue component of the color in the range $0\ldots1$ */
9160 @d ljoin_val(A) name_type((A))  /* the value of \&{linejoin} */
9161 @:mp_linejoin_}{\&{linejoin} primitive@>
9162 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9163 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9164 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9165   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9166 @d pre_script(A) mp->mem[(A)+8].hh.lh
9167 @d post_script(A) mp->mem[(A)+8].hh.rh
9168 @d fill_node_size 9
9169
9170 @ @<Graphical object codes@>=
9171 mp_fill_code=1,
9172
9173 @ @c 
9174 static pointer mp_new_fill_node (MP mp,pointer p) {
9175   /* make a fill node for cyclic path |p| and color black */
9176   pointer t; /* the new node */
9177   t=mp_get_node(mp, fill_node_size);
9178   type(t)=mp_fill_code;
9179   path_p(t)=p;
9180   pen_p(t)=null; /* |null| means don't use a pen */
9181   red_val(t)=0;
9182   green_val(t)=0;
9183   blue_val(t)=0;
9184   black_val(t)=0;
9185   color_model(t)=mp_uninitialized_model;
9186   pre_script(t)=null;
9187   post_script(t)=null;
9188   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9189   return t;
9190 }
9191
9192 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9193 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9194 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9195 else ljoin_val(t)=0;
9196 if ( mp->internal[mp_miterlimit]<unity )
9197   miterlim_val(t)=unity;
9198 else
9199   miterlim_val(t)=mp->internal[mp_miterlimit]
9200
9201 @ A stroked path is represented by an eight-word node that is like a filled
9202 contour node except that it contains the current \&{linecap} value, a scale
9203 factor for the dash pattern, and a pointer that is non-null if the stroke
9204 is to be dashed.  The purpose of the scale factor is to allow a picture to
9205 be transformed without touching the picture that |dash_p| points to.
9206
9207 @d dash_p(A) mp_link((A)+9)
9208   /* a pointer to the edge structure that gives the dash pattern */
9209 @d lcap_val(A) type((A)+9)
9210   /* the value of \&{linecap} */
9211 @:mp_linecap_}{\&{linecap} primitive@>
9212 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9213 @d stroked_node_size 11
9214
9215 @ @<Graphical object codes@>=
9216 mp_stroked_code=2,
9217
9218 @ @c 
9219 static pointer mp_new_stroked_node (MP mp,pointer p) {
9220   /* make a stroked node for path |p| with |pen_p(p)| temporarily |null| */
9221   pointer t; /* the new node */
9222   t=mp_get_node(mp, stroked_node_size);
9223   type(t)=mp_stroked_code;
9224   path_p(t)=p; pen_p(t)=null;
9225   dash_p(t)=null;
9226   dash_scale(t)=unity;
9227   red_val(t)=0;
9228   green_val(t)=0;
9229   blue_val(t)=0;
9230   black_val(t)=0;
9231   color_model(t)=mp_uninitialized_model;
9232   pre_script(t)=null;
9233   post_script(t)=null;
9234   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9235   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9236   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9237   else lcap_val(t)=0;
9238   return t;
9239 }
9240
9241 @ When a dashed line is computed in a transformed coordinate system, the dash
9242 lengths get scaled like the pen shape and we need to compensate for this.  Since
9243 there is no unique scale factor for an arbitrary transformation, we use the
9244 the square root of the determinant.  The properties of the determinant make it
9245 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9246 except for the initialization of the scale factor |s|.  The factor of 64 is
9247 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9248 to counteract the effect of |take_fraction|.
9249
9250 @ @c
9251 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9252   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9253   unsigned s; /* amount by which the result of |square_rt| needs to be scaled */
9254   @<Initialize |maxabs|@>;
9255   s=64;
9256   while ( (maxabs<fraction_one) && (s>1) ){ 
9257     a+=a; b+=b; c+=c; d+=d;
9258     maxabs+=maxabs; s=(unsigned)(halfp(s));
9259   }
9260   return (scaled)(s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c))));
9261 }
9262 @#
9263 static scaled mp_get_pen_scale (MP mp,pointer p) { 
9264   return mp_sqrt_det(mp, 
9265     mp_left_x(p)-mp_x_coord(p), mp_right_x(p)-mp_x_coord(p),
9266     mp_left_y(p)-mp_y_coord(p), mp_right_y(p)-mp_y_coord(p));
9267 }
9268
9269 @ @<Declarations@>=
9270 static scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9271
9272
9273 @ @<Initialize |maxabs|@>=
9274 maxabs=abs(a);
9275 if ( abs(b)>maxabs ) maxabs=abs(b);
9276 if ( abs(c)>maxabs ) maxabs=abs(c);
9277 if ( abs(d)>maxabs ) maxabs=abs(d)
9278
9279 @ When a picture contains text, this is represented by a fourteen-word node
9280 where the color information and |type| and |link| fields are augmented by
9281 additional fields that describe the text and  how it is transformed.
9282 The |path_p| and |pen_p| pointers are replaced by a number that identifies
9283 the font and a string number that gives the text to be displayed.
9284 The |width|, |height|, and |depth| fields
9285 give the dimensions of the text at its design size, and the remaining six
9286 words give a transformation to be applied to the text.  The |new_text_node|
9287 function initializes everything to default values so that the text comes out
9288 black with its reference point at the origin.
9289
9290 @d text_p(A) mp_link((A)+1)  /* a string pointer for the text to display */
9291 @d font_n(A) info((A)+1)  /* the font number */
9292 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9293 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9294 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9295 @d text_tx_loc(A) ((A)+11)
9296   /* the first of six locations for transformation parameters */
9297 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9298 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9299 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9300 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9301 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9302 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9303 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9304     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9305 @d text_node_size 17
9306
9307 @ @<Graphical object codes@>=
9308 mp_text_code=3,
9309
9310 @ @c
9311 static pointer mp_new_text_node (MP mp,char *f,str_number s) {
9312   /* make a text node for font |f| and text string |s| */
9313   pointer t; /* the new node */
9314   t=mp_get_node(mp, text_node_size);
9315   type(t)=mp_text_code;
9316   text_p(t)=s;
9317   font_n(t)=(halfword)mp_find_font(mp, f); /* this identifies the font */
9318   red_val(t)=0;
9319   green_val(t)=0;
9320   blue_val(t)=0;
9321   black_val(t)=0;
9322   color_model(t)=mp_uninitialized_model;
9323   pre_script(t)=null;
9324   post_script(t)=null;
9325   tx_val(t)=0; ty_val(t)=0;
9326   txx_val(t)=unity; txy_val(t)=0;
9327   tyx_val(t)=0; tyy_val(t)=unity;
9328   mp_set_text_box(mp, t); /* this finds the bounding box */
9329   return t;
9330 }
9331
9332 @ The last two types of graphical objects that can occur in an edge structure
9333 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9334 @:set_bounds_}{\&{setbounds} primitive@>
9335 to implement because we must keep track of exactly what is being clipped or
9336 bounded when pictures get merged together.  For this reason, each clipping or
9337 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9338 two-word node whose |path_p| gives the relevant path, then there is the list
9339 of objects to clip or bound followed by a two-word node whose second word is
9340 unused.
9341
9342 Using at least two words for each graphical object node allows them all to be
9343 allocated and deallocated similarly with a global array |gr_object_size| to
9344 give the size in words for each object type.
9345
9346 @d start_clip_size 2
9347 @d start_bounds_size 2
9348 @d stop_clip_size 2 /* the second word is not used here */
9349 @d stop_bounds_size 2 /* the second word is not used here */
9350 @#
9351 @d stop_type(A) ((A)+2)
9352   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9353 @d has_color(A) (type((A))<mp_start_clip_code)
9354   /* does a graphical object have color fields? */
9355 @d has_pen(A) (type((A))<mp_text_code)
9356   /* does a graphical object have a |pen_p| field? */
9357 @d is_start_or_stop(A) (type((A))>=mp_start_clip_code)
9358 @d is_stop(A) (type((A))>=mp_stop_clip_code)
9359
9360 @ @<Graphical object codes@>=
9361 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9362 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9363 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9364 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9365
9366 @ @c 
9367 static pointer mp_new_bounds_node (MP mp,pointer p, quarterword  c) {
9368   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9369   pointer t; /* the new node */
9370   t=mp_get_node(mp, mp->gr_object_size[c]);
9371   type(t)=c;
9372   path_p(t)=p;
9373   return t;
9374 }
9375
9376 @ We need an array to keep track of the sizes of graphical objects.
9377
9378 @<Glob...@>=
9379 quarterword gr_object_size[mp_stop_bounds_code+1];
9380
9381 @ @<Set init...@>=
9382 mp->gr_object_size[mp_fill_code]=fill_node_size;
9383 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9384 mp->gr_object_size[mp_text_code]=text_node_size;
9385 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9386 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9387 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9388 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9389
9390 @ All the essential information in an edge structure is encoded as a linked list
9391 of graphical objects as we have just seen, but it is helpful to add some
9392 redundant information.  A single edge structure might be used as a dash pattern
9393 many times, and it would be nice to avoid scanning the same structure
9394 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9395 has a header that gives a list of dashes in a sorted order designed for rapid
9396 translation into \ps.
9397
9398 Each dash is represented by a three-word node containing the initial and final
9399 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9400 the dash node with the next higher $x$-coordinates and the final link points
9401 to a special location called |null_dash|.  (There should be no overlap between
9402 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9403 the period of repetition, this needs to be stored in the edge header along
9404 with a pointer to the list of dash nodes.
9405
9406 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9407 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9408 @d dash_node_size 3
9409 @d dash_list mp_link
9410   /* in an edge header this points to the first dash node */
9411 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9412
9413 @ It is also convenient for an edge header to contain the bounding
9414 box information needed by the \&{llcorner} and \&{urcorner} operators
9415 so that this does not have to be recomputed unnecessarily.  This is done by
9416 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9417 how far the bounding box computation has gotten.  Thus if the user asks for
9418 the bounding box and then adds some more text to the picture before asking
9419 for more bounding box information, the second computation need only look at
9420 the additional text.
9421
9422 When the bounding box has not been computed, the |bblast| pointer points
9423 to a dummy link at the head of the graphical object list while the |minx_val|
9424 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9425 fields contain |-el_gordo|.
9426
9427 Since the bounding box of pictures containing objects of type
9428 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9429 @:mp_true_corners_}{\&{truecorners} primitive@>
9430 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9431 field is needed to keep track of this.
9432
9433 @d minx_val(A) mp->mem[(A)+2].sc
9434 @d miny_val(A) mp->mem[(A)+3].sc
9435 @d maxx_val(A) mp->mem[(A)+4].sc
9436 @d maxy_val(A) mp->mem[(A)+5].sc
9437 @d bblast(A) mp_link((A)+6)  /* last item considered in bounding box computation */
9438 @d bbtype(A) info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9439 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9440 @d no_bounds 0
9441   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9442 @d bounds_set 1
9443   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9444 @d bounds_unset 2
9445   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9446
9447 @c 
9448 static void mp_init_bbox (MP mp,pointer h) {
9449   /* Initialize the bounding box information in edge structure |h| */
9450   bblast(h)=dummy_loc(h);
9451   bbtype(h)=no_bounds;
9452   minx_val(h)=el_gordo;
9453   miny_val(h)=el_gordo;
9454   maxx_val(h)=-el_gordo;
9455   maxy_val(h)=-el_gordo;
9456 }
9457
9458 @ The only other entries in an edge header are a reference count in the first
9459 word and a pointer to the tail of the object list in the last word.
9460
9461 @d obj_tail(A) info((A)+7)  /* points to the last entry in the object list */
9462 @d edge_header_size 8
9463
9464 @c 
9465 static void mp_init_edges (MP mp,pointer h) {
9466   /* initialize an edge header to null values */
9467   dash_list(h)=null_dash;
9468   obj_tail(h)=dummy_loc(h);
9469   mp_link(dummy_loc(h))=null;
9470   ref_count(h)=null;
9471   mp_init_bbox(mp, h);
9472 }
9473
9474 @ Here is how edge structures are deleted.  The process can be recursive because
9475 of the need to dereference edge structures that are used as dash patterns.
9476 @^recursion@>
9477
9478 @d add_edge_ref(A) incr(ref_count(A))
9479 @d delete_edge_ref(A) { 
9480    if ( ref_count((A))==null ) 
9481      mp_toss_edges(mp, A);
9482    else 
9483      decr(ref_count(A)); 
9484    }
9485
9486 @<Declarations@>=
9487 static void mp_flush_dash_list (MP mp,pointer h);
9488 static pointer mp_toss_gr_object (MP mp,pointer p) ;
9489 static void mp_toss_edges (MP mp,pointer h) ;
9490
9491 @ @c void mp_toss_edges (MP mp,pointer h) {
9492   pointer p,q;  /* pointers that scan the list being recycled */
9493   pointer r; /* an edge structure that object |p| refers to */
9494   mp_flush_dash_list(mp, h);
9495   q=mp_link(dummy_loc(h));
9496   while ( (q!=null) ) { 
9497     p=q; q=mp_link(q);
9498     r=mp_toss_gr_object(mp, p);
9499     if ( r!=null ) delete_edge_ref(r);
9500   }
9501   mp_free_node(mp, h,edge_header_size);
9502 }
9503 void mp_flush_dash_list (MP mp,pointer h) {
9504   pointer p,q;  /* pointers that scan the list being recycled */
9505   q=dash_list(h);
9506   while ( q!=null_dash ) { 
9507     p=q; q=mp_link(q);
9508     mp_free_node(mp, p,dash_node_size);
9509   }
9510   dash_list(h)=null_dash;
9511 }
9512 pointer mp_toss_gr_object (MP mp,pointer p) {
9513   /* returns an edge structure that needs to be dereferenced */
9514   pointer e; /* the edge structure to return */
9515   e=null;
9516   @<Prepare to recycle graphical object |p|@>;
9517   mp_free_node(mp, p,mp->gr_object_size[type(p)]);
9518   return e;
9519 }
9520
9521 @ @<Prepare to recycle graphical object |p|@>=
9522 switch (type(p)) {
9523 case mp_fill_code: 
9524   mp_toss_knot_list(mp, path_p(p));
9525   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9526   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9527   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9528   break;
9529 case mp_stroked_code: 
9530   mp_toss_knot_list(mp, path_p(p));
9531   if ( pen_p(p)!=null ) mp_toss_knot_list(mp, pen_p(p));
9532   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9533   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9534   e=dash_p(p);
9535   break;
9536 case mp_text_code: 
9537   delete_str_ref(text_p(p));
9538   if ( pre_script(p)!=null ) delete_str_ref(pre_script(p));
9539   if ( post_script(p)!=null ) delete_str_ref(post_script(p));
9540   break;
9541 case mp_start_clip_code:
9542 case mp_start_bounds_code: 
9543   mp_toss_knot_list(mp, path_p(p));
9544   break;
9545 case mp_stop_clip_code:
9546 case mp_stop_bounds_code: 
9547   break;
9548 } /* there are no other cases */
9549
9550 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9551 to be done before making a significant change to an edge structure.  Much of
9552 the work is done in a separate routine |copy_objects| that copies a list of
9553 graphical objects into a new edge header.
9554
9555 @c
9556 static pointer mp_private_edges (MP mp,pointer h) {
9557   /* make a private copy of the edge structure headed by |h| */
9558   pointer hh;  /* the edge header for the new copy */
9559   pointer p,pp;  /* pointers for copying the dash list */
9560   if ( ref_count(h)==null ) {
9561     return h;
9562   } else { 
9563     decr(ref_count(h));
9564     hh=mp_copy_objects(mp, mp_link(dummy_loc(h)),null);
9565     @<Copy the dash list from |h| to |hh|@>;
9566     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9567       point into the new object list@>;
9568     return hh;
9569   }
9570 }
9571
9572 @ Here we use the fact that |dash_list(hh)=mp_link(hh)|.
9573 @^data structure assumptions@>
9574
9575 @<Copy the dash list from |h| to |hh|@>=
9576 pp=hh; p=dash_list(h);
9577 while ( (p!=null_dash) ) { 
9578   mp_link(pp)=mp_get_node(mp, dash_node_size);
9579   pp=mp_link(pp);
9580   start_x(pp)=start_x(p);
9581   stop_x(pp)=stop_x(p);
9582   p=mp_link(p);
9583 }
9584 mp_link(pp)=null_dash;
9585 dash_y(hh)=dash_y(h)
9586
9587
9588 @ |h| is an edge structure
9589
9590 @c
9591 static mp_dash_object *mp_export_dashes (MP mp, pointer q, scaled *w) {
9592   mp_dash_object *d;
9593   pointer p, h;
9594   scaled scf; /* scale factor */
9595   int *dashes = NULL;
9596   int num_dashes = 1;
9597   h = dash_p(q);
9598   if (h==null ||  dash_list(h)==null_dash) 
9599         return NULL;
9600   p = dash_list(h);
9601   scf=mp_get_pen_scale(mp, pen_p(q));
9602   if (scf==0) {
9603     if (*w==0) scf = dash_scale(q); else return NULL;
9604   } else {
9605     scf=mp_make_scaled(mp, *w,scf);
9606     scf=mp_take_scaled(mp, scf,dash_scale(q));
9607   }
9608   *w = scf;
9609   d = xmalloc(1,sizeof(mp_dash_object));
9610   start_x(null_dash)=start_x(p)+dash_y(h);
9611   while (p != null_dash) { 
9612         dashes = xrealloc(dashes, (num_dashes+2), sizeof(scaled));
9613         dashes[(num_dashes-1)] = 
9614       mp_take_scaled(mp,(stop_x(p)-start_x(p)),scf);
9615         dashes[(num_dashes)]   = 
9616       mp_take_scaled(mp,(start_x(mp_link(p))-stop_x(p)),scf);
9617         dashes[(num_dashes+1)] = -1; /* terminus */
9618         num_dashes+=2;
9619     p=mp_link(p);
9620   }
9621   d->array_field  = dashes;
9622   d->offset_field = 
9623     mp_take_scaled(mp,mp_dash_offset(mp, h),scf);
9624   return d;
9625 }
9626
9627
9628
9629 @ @<Copy the bounding box information from |h| to |hh|...@>=
9630 minx_val(hh)=minx_val(h);
9631 miny_val(hh)=miny_val(h);
9632 maxx_val(hh)=maxx_val(h);
9633 maxy_val(hh)=maxy_val(h);
9634 bbtype(hh)=bbtype(h);
9635 p=dummy_loc(h); pp=dummy_loc(hh);
9636 while ((p!=bblast(h)) ) { 
9637   if ( p==null ) mp_confusion(mp, "bblast");
9638 @:this can't happen bblast}{\quad bblast@>
9639   p=mp_link(p); pp=mp_link(pp);
9640 }
9641 bblast(hh)=pp
9642
9643 @ Here is the promised routine for copying graphical objects into a new edge
9644 structure.  It starts copying at object~|p| and stops just before object~|q|.
9645 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9646 structure requires further initialization by |init_bbox|.
9647
9648 @<Declarations@>=
9649 static pointer mp_copy_objects (MP mp, pointer p, pointer q);
9650
9651 @ @c
9652 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9653   pointer hh;  /* the new edge header */
9654   pointer pp;  /* the last newly copied object */
9655   quarterword k;  /* temporary register */
9656   hh=mp_get_node(mp, edge_header_size);
9657   dash_list(hh)=null_dash;
9658   ref_count(hh)=null;
9659   pp=dummy_loc(hh);
9660   while ( (p!=q) ) {
9661     @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9662   }
9663   obj_tail(hh)=pp;
9664   mp_link(pp)=null;
9665   return hh;
9666 }
9667
9668 @ @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9669 { k=mp->gr_object_size[type(p)];
9670   mp_link(pp)=mp_get_node(mp, k);
9671   pp=mp_link(pp);
9672   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9673   @<Fix anything in graphical object |pp| that should differ from the
9674     corresponding field in |p|@>;
9675   p=mp_link(p);
9676 }
9677
9678 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9679 switch (type(p)) {
9680 case mp_start_clip_code:
9681 case mp_start_bounds_code: 
9682   path_p(pp)=mp_copy_path(mp, path_p(p));
9683   break;
9684 case mp_fill_code: 
9685   path_p(pp)=mp_copy_path(mp, path_p(p));
9686   if ( pre_script(p)!=null )  add_str_ref(pre_script(p));
9687   if ( post_script(p)!=null ) add_str_ref(post_script(p));
9688   if ( pen_p(p)!=null ) pen_p(pp)=copy_pen(pen_p(p));
9689   break;
9690 case mp_stroked_code: 
9691   if ( pre_script(p)!=null )  add_str_ref(pre_script(p));
9692   if ( post_script(p)!=null ) add_str_ref(post_script(p));
9693   path_p(pp)=mp_copy_path(mp, path_p(p));
9694   pen_p(pp)=copy_pen(pen_p(p));
9695   if ( dash_p(p)!=null ) add_edge_ref(dash_p(pp));
9696   break;
9697 case mp_text_code: 
9698   if ( pre_script(p)!=null )  add_str_ref(pre_script(p));
9699   if ( post_script(p)!=null ) add_str_ref(post_script(p));
9700   add_str_ref(text_p(pp));
9701   break;
9702 case mp_stop_clip_code:
9703 case mp_stop_bounds_code: 
9704   break;
9705 }  /* there are no other cases */
9706
9707 @ Here is one way to find an acceptable value for the second argument to
9708 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9709 skips past one picture component, where a ``picture component'' is a single
9710 graphical object, or a start bounds or start clip object and everything up
9711 through the matching stop bounds or stop clip object.  The macro version avoids
9712 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9713 unless |p| points to a stop bounds or stop clip node, in which case it executes
9714 |e| instead.
9715
9716 @d skip_component(A)
9717     if ( ! is_start_or_stop((A)) ) (A)=mp_link((A));
9718     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9719     else 
9720
9721 @c 
9722 static pointer mp_skip_1component (MP mp,pointer p) {
9723   integer lev; /* current nesting level */
9724   lev=0;
9725   do {  
9726    if ( is_start_or_stop(p) ) {
9727      if ( is_stop(p) ) decr(lev);  else incr(lev);
9728    }
9729    p=mp_link(p);
9730   } while (lev!=0);
9731   return p;
9732 }
9733
9734 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9735
9736 @<Declarations@>=
9737 static void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) ;
9738
9739 @ @c
9740 void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) {
9741   pointer p;  /* a graphical object to be printed */
9742   pointer hh,pp;  /* temporary pointers */
9743   scaled scf;  /* a scale factor for the dash pattern */
9744   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9745   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9746   p=dummy_loc(h);
9747   while ( mp_link(p)!=null ) { 
9748     p=mp_link(p);
9749     mp_print_ln(mp);
9750     switch (type(p)) {
9751       @<Cases for printing graphical object node |p|@>;
9752     default: 
9753           mp_print(mp, "[unknown object type!]");
9754           break;
9755     }
9756   }
9757   mp_print_nl(mp, "End edges");
9758   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9759 @.End edges?@>
9760   mp_end_diagnostic(mp, true);
9761 }
9762
9763 @ @<Cases for printing graphical object node |p|@>=
9764 case mp_fill_code: 
9765   mp_print(mp, "Filled contour ");
9766   mp_print_obj_color(mp, p);
9767   mp_print_char(mp, xord(':')); mp_print_ln(mp);
9768   mp_pr_path(mp, path_p(p)); mp_print_ln(mp);
9769   if ( (pen_p(p)!=null) ) {
9770     @<Print join type for graphical object |p|@>;
9771     mp_print(mp, " with pen"); mp_print_ln(mp);
9772     mp_pr_pen(mp, pen_p(p));
9773   }
9774   break;
9775
9776 @ @<Print join type for graphical object |p|@>=
9777 switch (ljoin_val(p)) {
9778 case 0:
9779   mp_print(mp, "mitered joins limited ");
9780   mp_print_scaled(mp, miterlim_val(p));
9781   break;
9782 case 1:
9783   mp_print(mp, "round joins");
9784   break;
9785 case 2:
9786   mp_print(mp, "beveled joins");
9787   break;
9788 default: 
9789   mp_print(mp, "?? joins");
9790 @.??@>
9791   break;
9792 }
9793
9794 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9795
9796 @<Print join and cap types for stroked node |p|@>=
9797 switch (lcap_val(p)) {
9798 case 0:mp_print(mp, "butt"); break;
9799 case 1:mp_print(mp, "round"); break;
9800 case 2:mp_print(mp, "square"); break;
9801 default: mp_print(mp, "??"); break;
9802 @.??@>
9803 }
9804 mp_print(mp, " ends, ");
9805 @<Print join type for graphical object |p|@>
9806
9807 @ Here is a routine that prints the color of a graphical object if it isn't
9808 black (the default color).
9809
9810 @<Declarations@>=
9811 static void mp_print_obj_color (MP mp,pointer p) ;
9812
9813 @ @c
9814 void mp_print_obj_color (MP mp,pointer p) { 
9815   if ( color_model(p)==mp_grey_model ) {
9816     if ( grey_val(p)>0 ) { 
9817       mp_print(mp, "greyed ");
9818       mp_print_compact_node(mp, obj_grey_loc(p),1);
9819     };
9820   } else if ( color_model(p)==mp_cmyk_model ) {
9821     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9822          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9823       mp_print(mp, "processcolored ");
9824       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9825     };
9826   } else if ( color_model(p)==mp_rgb_model ) {
9827     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9828       mp_print(mp, "colored "); 
9829       mp_print_compact_node(mp, obj_red_loc(p),3);
9830     };
9831   }
9832 }
9833
9834 @ We also need a procedure for printing consecutive scaled values as if they
9835 were a known big node.
9836
9837 @<Declarations@>=
9838 static void mp_print_compact_node (MP mp,pointer p, quarterword k) ;
9839
9840 @ @c
9841 void mp_print_compact_node (MP mp,pointer p, quarterword k) {
9842   pointer q;  /* last location to print */
9843   q=p+k-1;
9844   mp_print_char(mp, xord('('));
9845   while ( p<=q ){ 
9846     mp_print_scaled(mp, mp->mem[p].sc);
9847     if ( p<q ) mp_print_char(mp, xord(','));
9848     incr(p);
9849   }
9850   mp_print_char(mp, xord(')'));
9851 }
9852
9853 @ @<Cases for printing graphical object node |p|@>=
9854 case mp_stroked_code: 
9855   mp_print(mp, "Filled pen stroke ");
9856   mp_print_obj_color(mp, p);
9857   mp_print_char(mp, xord(':')); mp_print_ln(mp);
9858   mp_pr_path(mp, path_p(p));
9859   if ( dash_p(p)!=null ) { 
9860     mp_print_nl(mp, "dashed (");
9861     @<Finish printing the dash pattern that |p| refers to@>;
9862   }
9863   mp_print_ln(mp);
9864   @<Print join and cap types for stroked node |p|@>;
9865   mp_print(mp, " with pen"); mp_print_ln(mp);
9866   if ( pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9867 @.???@>
9868   else mp_pr_pen(mp, pen_p(p));
9869   break;
9870
9871 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9872 when it is not known to define a suitable dash pattern.  This is disallowed
9873 here because the |dash_p| field should never point to such an edge header.
9874 Note that memory is allocated for |start_x(null_dash)| and we are free to
9875 give it any convenient value.
9876
9877 @<Finish printing the dash pattern that |p| refers to@>=
9878 ok_to_dash=pen_is_elliptical(pen_p(p));
9879 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9880 hh=dash_p(p);
9881 pp=dash_list(hh);
9882 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9883   mp_print(mp, " ??");
9884 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9885   while ( pp!=null_dash ) { 
9886     mp_print(mp, "on ");
9887     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9888     mp_print(mp, " off ");
9889     mp_print_scaled(mp, mp_take_scaled(mp, start_x(mp_link(pp))-stop_x(pp),scf));
9890     pp = mp_link(pp);
9891     if ( pp!=null_dash ) mp_print_char(mp, xord(' '));
9892   }
9893   mp_print(mp, ") shifted ");
9894   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9895   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9896 }
9897
9898 @ @<Declarations@>=
9899 static scaled mp_dash_offset (MP mp,pointer h) ;
9900
9901 @ @c
9902 scaled mp_dash_offset (MP mp,pointer h) {
9903   scaled x;  /* the answer */
9904   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9905 @:this can't happen dash0}{\quad dash0@>
9906   if ( dash_y(h)==0 ) {
9907     x=0; 
9908   } else { 
9909     x=-(start_x(dash_list(h)) % dash_y(h));
9910     if ( x<0 ) x=x+dash_y(h);
9911   }
9912   return x;
9913 }
9914
9915 @ @<Cases for printing graphical object node |p|@>=
9916 case mp_text_code: 
9917   mp_print_char(mp, xord('"')); mp_print_str(mp,text_p(p));
9918   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[font_n(p)]);
9919   mp_print_char(mp, xord('"')); mp_print_ln(mp);
9920   mp_print_obj_color(mp, p);
9921   mp_print(mp, "transformed ");
9922   mp_print_compact_node(mp, text_tx_loc(p),6);
9923   break;
9924
9925 @ @<Cases for printing graphical object node |p|@>=
9926 case mp_start_clip_code: 
9927   mp_print(mp, "clipping path:");
9928   mp_print_ln(mp);
9929   mp_pr_path(mp, path_p(p));
9930   break;
9931 case mp_stop_clip_code: 
9932   mp_print(mp, "stop clipping");
9933   break;
9934
9935 @ @<Cases for printing graphical object node |p|@>=
9936 case mp_start_bounds_code: 
9937   mp_print(mp, "setbounds path:");
9938   mp_print_ln(mp);
9939   mp_pr_path(mp, path_p(p));
9940   break;
9941 case mp_stop_bounds_code: 
9942   mp_print(mp, "end of setbounds");
9943   break;
9944
9945 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9946 subroutine that scans an edge structure and tries to interpret it as a dash
9947 pattern.  This can only be done when there are no filled regions or clipping
9948 paths and all the pen strokes have the same color.  The first step is to let
9949 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9950 project all the pen stroke paths onto the line $y=y_0$ and require that there
9951 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9952 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9953 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9954
9955 @c 
9956 static pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9957   pointer p;  /* this scans the stroked nodes in the object list */
9958   pointer p0;  /* if not |null| this points to the first stroked node */
9959   pointer pp,qq,rr;  /* pointers into |path_p(p)| */
9960   pointer d,dd;  /* pointers used to create the dash list */
9961   scaled y0;
9962   @<Other local variables in |make_dashes|@>;
9963   y0=0;  /* the initial $y$ coordinate */
9964   if ( dash_list(h)!=null_dash ) 
9965         return h;
9966   p0=null;
9967   p=mp_link(dummy_loc(h));
9968   while ( p!=null ) { 
9969     if ( type(p)!=mp_stroked_code ) {
9970       @<Compain that the edge structure contains a node of the wrong type
9971         and |goto not_found|@>;
9972     }
9973     pp=path_p(p);
9974     if ( p0==null ){ p0=p; y0=mp_y_coord(pp);  };
9975     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9976       or |goto not_found| if there is an error@>;
9977     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9978     p=mp_link(p);
9979   }
9980   if ( dash_list(h)==null_dash ) 
9981     goto NOT_FOUND; /* No error message */
9982   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9983   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9984   return h;
9985 NOT_FOUND: 
9986   @<Flush the dash list, recycle |h| and return |null|@>;
9987 }
9988
9989 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9990
9991 print_err("Picture is too complicated to use as a dash pattern");
9992 help3("When you say `dashed p', picture p should not contain any",
9993   "text, filled regions, or clipping paths.  This time it did",
9994   "so I'll just make it a solid line instead.");
9995 mp_put_get_error(mp);
9996 goto NOT_FOUND;
9997 }
9998
9999 @ A similar error occurs when monotonicity fails.
10000
10001 @<Declarations@>=
10002 static void mp_x_retrace_error (MP mp) ;
10003
10004 @ @c
10005 void mp_x_retrace_error (MP mp) { 
10006 print_err("Picture is too complicated to use as a dash pattern");
10007 help3("When you say `dashed p', every path in p should be monotone",
10008   "in x and there must be no overlapping.  This failed",
10009   "so I'll just make it a solid line instead.");
10010 mp_put_get_error(mp);
10011 }
10012
10013 @ We stash |p| in |info(d)| if |dash_p(p)<>0| so that subsequent processing can
10014 handle the case where the pen stroke |p| is itself dashed.
10015
10016 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
10017 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
10018   an error@>;
10019 rr=pp;
10020 if ( mp_link(pp)!=pp ) {
10021   do {  
10022     qq=rr; rr=mp_link(rr);
10023     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
10024       if there is a problem@>;
10025   } while (mp_right_type(rr)!=mp_endpoint);
10026 }
10027 d=mp_get_node(mp, dash_node_size);
10028 if ( dash_p(p)==0 ) info(d)=0;  else info(d)=p;
10029 if ( mp_x_coord(pp)<mp_x_coord(rr) ) { 
10030   start_x(d)=mp_x_coord(pp);
10031   stop_x(d)=mp_x_coord(rr);
10032 } else { 
10033   start_x(d)=mp_x_coord(rr);
10034   stop_x(d)=mp_x_coord(pp);
10035 }
10036
10037 @ We also need to check for the case where the segment from |qq| to |rr| is
10038 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
10039
10040 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
10041 x0=mp_x_coord(qq);
10042 x1=mp_right_x(qq);
10043 x2=mp_left_x(rr);
10044 x3=mp_x_coord(rr);
10045 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
10046   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
10047     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
10048       mp_x_retrace_error(mp); goto NOT_FOUND;
10049     }
10050   }
10051 }
10052 if ( (mp_x_coord(pp)>x0) || (x0>x3) ) {
10053   if ( (mp_x_coord(pp)<x0) || (x0<x3) ) {
10054     mp_x_retrace_error(mp); goto NOT_FOUND;
10055   }
10056 }
10057
10058 @ @<Other local variables in |make_dashes|@>=
10059   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
10060
10061 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
10062 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
10063   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
10064   print_err("Picture is too complicated to use as a dash pattern");
10065   help3("When you say `dashed p', everything in picture p should",
10066     "be the same color.  I can\'t handle your color changes",
10067     "so I'll just make it a solid line instead.");
10068   mp_put_get_error(mp);
10069   goto NOT_FOUND;
10070 }
10071
10072 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
10073 start_x(null_dash)=stop_x(d);
10074 dd=h; /* this makes |mp_link(dd)=dash_list(h)| */
10075 while ( start_x(mp_link(dd))<stop_x(d) )
10076   dd=mp_link(dd);
10077 if ( dd!=h ) {
10078   if ( (stop_x(dd)>start_x(d)) )
10079     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
10080 }
10081 mp_link(d)=mp_link(dd);
10082 mp_link(dd)=d
10083
10084 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
10085 d=dash_list(h);
10086 while ( (mp_link(d)!=null_dash) )
10087   d=mp_link(d);
10088 dd=dash_list(h);
10089 dash_y(h)=stop_x(d)-start_x(dd);
10090 if ( abs(y0)>dash_y(h) ) {
10091   dash_y(h)=abs(y0);
10092 } else if ( d!=dd ) { 
10093   dash_list(h)=mp_link(dd);
10094   stop_x(d)=stop_x(dd)+dash_y(h);
10095   mp_free_node(mp, dd,dash_node_size);
10096 }
10097
10098 @ We get here when the argument is a null picture or when there is an error.
10099 Recovering from an error involves making |dash_list(h)| empty to indicate
10100 that |h| is not known to be a valid dash pattern.  We also dereference |h|
10101 since it is not being used for the return value.
10102
10103 @<Flush the dash list, recycle |h| and return |null|@>=
10104 mp_flush_dash_list(mp, h);
10105 delete_edge_ref(h);
10106 return null
10107
10108 @ Having carefully saved the dashed stroked nodes in the
10109 corresponding dash nodes, we must be prepared to break up these dashes into
10110 smaller dashes.
10111
10112 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10113 d=h;  /* now |mp_link(d)=dash_list(h)| */
10114 while ( mp_link(d)!=null_dash ) {
10115   ds=info(mp_link(d));
10116   if ( ds==null ) { 
10117     d=mp_link(d);
10118   } else {
10119     hh=dash_p(ds);
10120     hsf=dash_scale(ds);
10121     if ( (hh==null) ) mp_confusion(mp, "dash1");
10122 @:this can't happen dash0}{\quad dash1@>
10123     if ( dash_y(hh)==0 ) {
10124       d=mp_link(d);
10125     } else { 
10126       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10127 @:this can't happen dash0}{\quad dash1@>
10128       @<Replace |mp_link(d)| by a dashed version as determined by edge header
10129           |hh| and scale factor |ds|@>;
10130     }
10131   }
10132 }
10133
10134 @ @<Other local variables in |make_dashes|@>=
10135 pointer dln;  /* |mp_link(d)| */
10136 pointer hh;  /* an edge header that tells how to break up |dln| */
10137 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10138 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10139 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10140
10141 @ @<Replace |mp_link(d)| by a dashed version as determined by edge header...@>=
10142 dln=mp_link(d);
10143 dd=dash_list(hh);
10144 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10145         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10146 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10147                    +mp_take_scaled(mp, hsf,dash_y(hh));
10148 stop_x(null_dash)=start_x(null_dash);
10149 @<Advance |dd| until finding the first dash that overlaps |dln| when
10150   offset by |xoff|@>;
10151 while ( start_x(dln)<=stop_x(dln) ) {
10152   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10153   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10154     of |dd|@>;
10155   dd=mp_link(dd);
10156   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10157 }
10158 mp_link(d)=mp_link(dln);
10159 mp_free_node(mp, dln,dash_node_size)
10160
10161 @ The name of this module is a bit of a lie because we just find the
10162 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10163 overlap possible.  It could be that the unoffset version of dash |dln| falls
10164 in the gap between |dd| and its predecessor.
10165
10166 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10167 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10168   dd=mp_link(dd);
10169 }
10170
10171 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10172 if ( dd==null_dash ) { 
10173   dd=dash_list(hh);
10174   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10175 }
10176
10177 @ At this point we already know that
10178 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10179
10180 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10181 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10182   mp_link(d)=mp_get_node(mp, dash_node_size);
10183   d=mp_link(d);
10184   mp_link(d)=dln;
10185   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10186     start_x(d)=start_x(dln);
10187   else 
10188     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10189   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10190     stop_x(d)=stop_x(dln);
10191   else 
10192     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10193 }
10194
10195 @ The next major task is to update the bounding box information in an edge
10196 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10197 header's bounding box to accommodate the box computed by |path_bbox| or
10198 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10199 |maxy|.)
10200
10201 @c static void mp_adjust_bbox (MP mp,pointer h) { 
10202   if ( minx<minx_val(h) ) minx_val(h)=minx;
10203   if ( miny<miny_val(h) ) miny_val(h)=miny;
10204   if ( maxx>maxx_val(h) ) maxx_val(h)=maxx;
10205   if ( maxy>maxy_val(h) ) maxy_val(h)=maxy;
10206 }
10207
10208 @ Here is a special routine for updating the bounding box information in
10209 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10210 that is to be stroked with the pen~|pp|.
10211
10212 @c static void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10213   pointer q;  /* a knot node adjacent to knot |p| */
10214   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10215   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10216   scaled z;  /* a coordinate being tested against the bounding box */
10217   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10218   integer i; /* a loop counter */
10219   if ( mp_right_type(p)!=mp_endpoint ) { 
10220     q=mp_link(p);
10221     while (1) { 
10222       @<Make |(dx,dy)| the final direction for the path segment from
10223         |q| to~|p|; set~|d|@>;
10224       d=mp_pyth_add(mp, dx,dy);
10225       if ( d>0 ) { 
10226          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10227          for (i=1;i<= 2;i++) { 
10228            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10229              update the bounding box to accommodate it@>;
10230            dx=-dx; dy=-dy; 
10231         }
10232       }
10233       if ( mp_right_type(p)==mp_endpoint ) {
10234          return;
10235       } else {
10236         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10237       } 
10238     }
10239   }
10240 }
10241
10242 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10243 if ( q==mp_link(p) ) { 
10244   dx=mp_x_coord(p)-mp_right_x(p);
10245   dy=mp_y_coord(p)-mp_right_y(p);
10246   if ( (dx==0)&&(dy==0) ) {
10247     dx=mp_x_coord(p)-mp_left_x(q);
10248     dy=mp_y_coord(p)-mp_left_y(q);
10249   }
10250 } else { 
10251   dx=mp_x_coord(p)-mp_left_x(p);
10252   dy=mp_y_coord(p)-mp_left_y(p);
10253   if ( (dx==0)&&(dy==0) ) {
10254     dx=mp_x_coord(p)-mp_right_x(q);
10255     dy=mp_y_coord(p)-mp_right_y(q);
10256   }
10257 }
10258 dx=mp_x_coord(p)-mp_x_coord(q);
10259 dy=mp_y_coord(p)-mp_y_coord(q)
10260
10261 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10262 dx=mp_make_fraction(mp, dx,d);
10263 dy=mp_make_fraction(mp, dy,d);
10264 mp_find_offset(mp, -dy,dx,pp);
10265 xx=mp->cur_x; yy=mp->cur_y
10266
10267 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10268 mp_find_offset(mp, dx,dy,pp);
10269 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10270 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10271   mp_confusion(mp, "box_ends");
10272 @:this can't happen box ends}{\quad\\{box\_ends}@>
10273 z=mp_x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10274 if ( z<minx_val(h) ) minx_val(h)=z;
10275 if ( z>maxx_val(h) ) maxx_val(h)=z;
10276 z=mp_y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10277 if ( z<miny_val(h) ) miny_val(h)=z;
10278 if ( z>maxy_val(h) ) maxy_val(h)=z
10279
10280 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10281 do {  
10282   q=p;
10283   p=mp_link(p);
10284 } while (mp_right_type(p)!=mp_endpoint)
10285
10286 @ The major difficulty in finding the bounding box of an edge structure is the
10287 effect of clipping paths.  We treat them conservatively by only clipping to the
10288 clipping path's bounding box, but this still
10289 requires recursive calls to |set_bbox| in order to find the bounding box of
10290 @^recursion@>
10291 the objects to be clipped.  Such calls are distinguished by the fact that the
10292 boolean parameter |top_level| is false.
10293
10294 @c 
10295 void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10296   pointer p;  /* a graphical object being considered */
10297   scaled sminx,sminy,smaxx,smaxy;
10298   /* for saving the bounding box during recursive calls */
10299   scaled x0,x1,y0,y1;  /* temporary registers */
10300   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10301   @<Wipe out any existing bounding box information if |bbtype(h)| is
10302   incompatible with |internal[mp_true_corners]|@>;
10303   while ( mp_link(bblast(h))!=null ) { 
10304     p=mp_link(bblast(h));
10305     bblast(h)=p;
10306     switch (type(p)) {
10307     case mp_stop_clip_code: 
10308       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10309 @:this can't happen bbox}{\quad bbox@>
10310       break;
10311     @<Other cases for updating the bounding box based on the type of object |p|@>;
10312     } /* all cases are enumerated above */
10313   }
10314   if ( ! top_level ) mp_confusion(mp, "bbox");
10315 }
10316
10317 @ @<Declarations@>=
10318 static void mp_set_bbox (MP mp,pointer h, boolean top_level);
10319
10320 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10321 switch (bbtype(h)) {
10322 case no_bounds: 
10323   break;
10324 case bounds_set: 
10325   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10326   break;
10327 case bounds_unset: 
10328   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10329   break;
10330 } /* there are no other cases */
10331
10332 @ @<Other cases for updating the bounding box...@>=
10333 case mp_fill_code: 
10334   mp_path_bbox(mp, path_p(p));
10335   if ( pen_p(p)!=null ) { 
10336     x0=minx; y0=miny;
10337     x1=maxx; y1=maxy;
10338     mp_pen_bbox(mp, pen_p(p));
10339     minx=minx+x0;
10340     miny=miny+y0;
10341     maxx=maxx+x1;
10342     maxy=maxy+y1;
10343   }
10344   mp_adjust_bbox(mp, h);
10345   break;
10346
10347 @ @<Other cases for updating the bounding box...@>=
10348 case mp_start_bounds_code: 
10349   if ( mp->internal[mp_true_corners]>0 ) {
10350     bbtype(h)=bounds_unset;
10351   } else { 
10352     bbtype(h)=bounds_set;
10353     mp_path_bbox(mp, path_p(p));
10354     mp_adjust_bbox(mp, h);
10355     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10356       |bblast(h)|@>;
10357   }
10358   break;
10359 case mp_stop_bounds_code: 
10360   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10361 @:this can't happen bbox2}{\quad bbox2@>
10362   break;
10363
10364 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10365 lev=1;
10366 while ( lev!=0 ) { 
10367   if ( mp_link(p)==null ) mp_confusion(mp, "bbox2");
10368 @:this can't happen bbox2}{\quad bbox2@>
10369   p=mp_link(p);
10370   if ( type(p)==mp_start_bounds_code ) incr(lev);
10371   else if ( type(p)==mp_stop_bounds_code ) decr(lev);
10372 }
10373 bblast(h)=p
10374
10375 @ It saves a lot of grief here to be slightly conservative and not account for
10376 omitted parts of dashed lines.  We also don't worry about the material omitted
10377 when using butt end caps.  The basic computation is for round end caps and
10378 |box_ends| augments it for square end caps.
10379
10380 @<Other cases for updating the bounding box...@>=
10381 case mp_stroked_code: 
10382   mp_path_bbox(mp, path_p(p));
10383   x0=minx; y0=miny;
10384   x1=maxx; y1=maxy;
10385   mp_pen_bbox(mp, pen_p(p));
10386   minx=minx+x0;
10387   miny=miny+y0;
10388   maxx=maxx+x1;
10389   maxy=maxy+y1;
10390   mp_adjust_bbox(mp, h);
10391   if ( (mp_left_type(path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10392     mp_box_ends(mp, path_p(p), pen_p(p), h);
10393   break;
10394
10395 @ The height width and depth information stored in a text node determines a
10396 rectangle that needs to be transformed according to the transformation
10397 parameters stored in the text node.
10398
10399 @<Other cases for updating the bounding box...@>=
10400 case mp_text_code: 
10401   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10402   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10403   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10404   minx=tx_val(p);
10405   maxx=minx;
10406   if ( y0<y1 ) { minx=minx+y0; maxx=maxx+y1;  }
10407   else         { minx=minx+y1; maxx=maxx+y0;  }
10408   if ( x1<0 ) minx=minx+x1;  else maxx=maxx+x1;
10409   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10410   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10411   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10412   miny=ty_val(p);
10413   maxy=miny;
10414   if ( y0<y1 ) { miny=miny+y0; maxy=maxy+y1;  }
10415   else         { miny=miny+y1; maxy=maxy+y0;  }
10416   if ( x1<0 ) miny=miny+x1;  else maxy=maxy+x1;
10417   mp_adjust_bbox(mp, h);
10418   break;
10419
10420 @ This case involves a recursive call that advances |bblast(h)| to the node of
10421 type |mp_stop_clip_code| that matches |p|.
10422
10423 @<Other cases for updating the bounding box...@>=
10424 case mp_start_clip_code: 
10425   mp_path_bbox(mp, path_p(p));
10426   x0=minx; y0=miny;
10427   x1=maxx; y1=maxy;
10428   sminx=minx_val(h); sminy=miny_val(h);
10429   smaxx=maxx_val(h); smaxy=maxy_val(h);
10430   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10431     starting at |mp_link(p)|@>;
10432   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10433     |y0|, |y1|@>;
10434   minx=sminx; miny=sminy;
10435   maxx=smaxx; maxy=smaxy;
10436   mp_adjust_bbox(mp, h);
10437   break;
10438
10439 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10440 minx_val(h)=el_gordo;
10441 miny_val(h)=el_gordo;
10442 maxx_val(h)=-el_gordo;
10443 maxy_val(h)=-el_gordo;
10444 mp_set_bbox(mp, h,false)
10445
10446 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10447 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10448 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10449 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10450 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10451
10452 @* \[22] Finding an envelope.
10453 When \MP\ has a path and a polygonal pen, it needs to express the desired
10454 shape in terms of things \ps\ can understand.  The present task is to compute
10455 a new path that describes the region to be filled.  It is convenient to
10456 define this as a two step process where the first step is determining what
10457 offset to use for each segment of the path.
10458
10459 @ Given a pointer |c| to a cyclic path,
10460 and a pointer~|h| to the first knot of a pen polygon,
10461 the |offset_prep| routine changes the path into cubics that are
10462 associated with particular pen offsets. Thus if the cubic between |p|
10463 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10464 has offset |l| then |info(q)=zero_off+l-k|. (The constant |zero_off| is added
10465 to because |l-k| could be negative.)
10466
10467 After overwriting the type information with offset differences, we no longer
10468 have a true path so we refer to the knot list returned by |offset_prep| as an
10469 ``envelope spec.''
10470 @^envelope spec@>
10471 Since an envelope spec only determines relative changes in pen offsets,
10472 |offset_prep| sets a global variable |spec_offset| to the relative change from
10473 |h| to the first offset.
10474
10475 @d zero_off 16384 /* added to offset changes to make them positive */
10476
10477 @<Glob...@>=
10478 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10479
10480 @ @c
10481 static pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10482   halfword n; /* the number of vertices in the pen polygon */
10483   pointer c0,p,q,q0,r,w, ww; /* for list manipulation */
10484   integer k_needed; /* amount to be added to |info(p)| when it is computed */
10485   pointer w0; /* a pointer to pen offset to use just before |p| */
10486   scaled dxin,dyin; /* the direction into knot |p| */
10487   integer turn_amt; /* change in pen offsets for the current cubic */
10488   @<Other local variables for |offset_prep|@>;
10489   dx0=0; dy0=0;
10490   @<Initialize the pen size~|n|@>;
10491   @<Initialize the incoming direction and pen offset at |c|@>;
10492   p=c; c0=c; k_needed=0;
10493   do {  
10494     q=mp_link(p);
10495     @<Split the cubic between |p| and |q|, if necessary, into cubics
10496       associated with single offsets, after which |q| should
10497       point to the end of the final such cubic@>;
10498   NOT_FOUND:
10499     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10500       might have been introduced by the splitting process@>;
10501   } while (q!=c);
10502   @<Fix the offset change in |info(c)| and set |c| to the return value of
10503     |offset_prep|@>;
10504   return c;
10505 }
10506
10507 @ We shall want to keep track of where certain knots on the cyclic path
10508 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10509 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10510 |offset_prep| updates the following pointers
10511
10512 @<Glob...@>=
10513 pointer spec_p1;
10514 pointer spec_p2; /* pointers to distinguished knots */
10515
10516 @ @<Set init...@>=
10517 mp->spec_p1=null; mp->spec_p2=null;
10518
10519 @ @<Initialize the pen size~|n|@>=
10520 n=0; p=h;
10521 do {  
10522   incr(n);
10523   p=mp_link(p);
10524 } while (p!=h)
10525
10526 @ Since the true incoming direction isn't known yet, we just pick a direction
10527 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10528 later.
10529
10530 @<Initialize the incoming direction and pen offset at |c|@>=
10531 dxin=mp_x_coord(mp_link(h))-mp_x_coord(knil(h));
10532 dyin=mp_y_coord(mp_link(h))-mp_y_coord(knil(h));
10533 if ( (dxin==0)&&(dyin==0) ) {
10534   dxin=mp_y_coord(knil(h))-mp_y_coord(h);
10535   dyin=mp_x_coord(h)-mp_x_coord(knil(h));
10536 }
10537 w0=h
10538
10539 @ We must be careful not to remove the only cubic in a cycle.
10540
10541 But we must also be careful for another reason. If the user-supplied
10542 path starts with a set of degenerate cubics, the target node |q| can
10543 be collapsed to the initial node |p| which might be the same as the
10544 initial node |c| of the curve. This would cause the |offset_prep| routine
10545 to bail out too early, causing distress later on. (See for example
10546 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10547 on Sarovar.)
10548
10549 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10550 q0=q;
10551 do { 
10552   r=mp_link(p);
10553   if ( mp_x_coord(p)==mp_right_x(p) && mp_y_coord(p)==mp_right_y(p) &&
10554        mp_x_coord(p)==mp_left_x(r)  && mp_y_coord(p)==mp_left_y(r) &&
10555        mp_x_coord(p)==mp_x_coord(r) && mp_y_coord(p)==mp_y_coord(r) &&
10556        r!=p ) {
10557       @<Remove the cubic following |p| and update the data structures
10558         to merge |r| into |p|@>;
10559   }
10560   p=r;
10561 } while (p!=q);
10562 /* Check if we removed too much */
10563 if ((q!=q0)&&(q!=c||c==c0))
10564   q = mp_link(q)
10565
10566 @ @<Remove the cubic following |p| and update the data structures...@>=
10567 { k_needed=info(p)-zero_off;
10568   if ( r==q ) { 
10569     q=p;
10570   } else { 
10571     info(p)=k_needed+info(r);
10572     k_needed=0;
10573   };
10574   if ( r==c ) { info(p)=info(c); c=p; };
10575   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10576   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10577   r=p; mp_remove_cubic(mp, p);
10578 }
10579
10580 @ Not setting the |info| field of the newly created knot allows the splitting
10581 routine to work for paths.
10582
10583 @<Declarations@>=
10584 static void mp_split_cubic (MP mp,pointer p, fraction t) ;
10585
10586 @ @c
10587 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10588   scaled v; /* an intermediate value */
10589   pointer q,r; /* for list manipulation */
10590   q=mp_link(p); r=mp_get_node(mp, knot_node_size); mp_link(p)=r; mp_link(r)=q;
10591   mp_originator(r)=mp_program_code;
10592   mp_left_type(r)=mp_explicit; mp_right_type(r)=mp_explicit;
10593   v=t_of_the_way(mp_right_x(p),mp_left_x(q));
10594   mp_right_x(p)=t_of_the_way(mp_x_coord(p),mp_right_x(p));
10595   mp_left_x(q)=t_of_the_way(mp_left_x(q),mp_x_coord(q));
10596   mp_left_x(r)=t_of_the_way(mp_right_x(p),v);
10597   mp_right_x(r)=t_of_the_way(v,mp_left_x(q));
10598   mp_x_coord(r)=t_of_the_way(mp_left_x(r),mp_right_x(r));
10599   v=t_of_the_way(mp_right_y(p),mp_left_y(q));
10600   mp_right_y(p)=t_of_the_way(mp_y_coord(p),mp_right_y(p));
10601   mp_left_y(q)=t_of_the_way(mp_left_y(q),mp_y_coord(q));
10602   mp_left_y(r)=t_of_the_way(mp_right_y(p),v);
10603   mp_right_y(r)=t_of_the_way(v,mp_left_y(q));
10604   mp_y_coord(r)=t_of_the_way(mp_left_y(r),mp_right_y(r));
10605 }
10606
10607 @ This does not set |info(p)| or |mp_right_type(p)|.
10608
10609 @<Declarations@>=
10610 static void mp_remove_cubic (MP mp,pointer p) ; 
10611
10612 @ @c
10613 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10614   pointer q; /* the node that disappears */
10615   q=mp_link(p); mp_link(p)=mp_link(q);
10616   mp_right_x(p)=mp_right_x(q); mp_right_y(p)=mp_right_y(q);
10617   mp_free_node(mp, q,knot_node_size);
10618 }
10619
10620 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10621 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10622 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10623 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10624 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10625 When listed by increasing $k$, these directions occur in counter-clockwise
10626 order so that $d_k\preceq d\k$ for all~$k$.
10627 The goal of |offset_prep| is to find an offset index~|k| to associate with
10628 each cubic, such that the direction $d(t)$ of the cubic satisfies
10629 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10630 We may have to split a cubic into many pieces before each
10631 piece corresponds to a unique offset.
10632
10633 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10634 info(p)=zero_off+k_needed;
10635 k_needed=0;
10636 @<Prepare for derivative computations;
10637   |goto not_found| if the current cubic is dead@>;
10638 @<Find the initial direction |(dx,dy)|@>;
10639 @<Update |info(p)| and find the offset $w_k$ such that
10640   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10641   the direction change at |p|@>;
10642 @<Find the final direction |(dxin,dyin)|@>;
10643 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10644 @<Complete the offset splitting process@>;
10645 w0=mp_pen_walk(mp, w0,turn_amt)
10646
10647 @ @<Declarations@>=
10648 static pointer mp_pen_walk (MP mp,pointer w, integer k) ;
10649
10650 @ @c
10651 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10652   /* walk |k| steps around a pen from |w| */
10653   while ( k>0 ) { w=mp_link(w); decr(k);  };
10654   while ( k<0 ) { w=knil(w); incr(k);  };
10655   return w;
10656 }
10657
10658 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10659 calculated from the quadratic polynomials
10660 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10661 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10662 Since we may be calculating directions from several cubics
10663 split from the current one, it is desirable to do these calculations
10664 without losing too much precision. ``Scaled up'' values of the
10665 derivatives, which will be less tainted by accumulated errors than
10666 derivatives found from the cubics themselves, are maintained in
10667 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10668 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10669 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)$.
10670
10671 @<Other local variables for |offset_prep|@>=
10672 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10673 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10674 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10675 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10676 integer max_coef; /* used while scaling */
10677 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10678 fraction t; /* where the derivative passes through zero */
10679 fraction s; /* a temporary value */
10680
10681 @ @<Prepare for derivative computations...@>=
10682 x0=mp_right_x(p)-mp_x_coord(p);
10683 x2=mp_x_coord(q)-mp_left_x(q);
10684 x1=mp_left_x(q)-mp_right_x(p);
10685 y0=mp_right_y(p)-mp_y_coord(p); y2=mp_y_coord(q)-mp_left_y(q);
10686 y1=mp_left_y(q)-mp_right_y(p);
10687 max_coef=abs(x0);
10688 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10689 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10690 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10691 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10692 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10693 if ( max_coef==0 ) goto NOT_FOUND;
10694 while ( max_coef<fraction_half ) {
10695   double(max_coef);
10696   double(x0); double(x1); double(x2);
10697   double(y0); double(y1); double(y2);
10698 }
10699
10700 @ Let us first solve a special case of the problem: Suppose we
10701 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10702 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10703 $d(0)\succ d_{k-1}$.
10704 Then, in a sense, we're halfway done, since one of the two relations
10705 in $(*)$ is satisfied, and the other couldn't be satisfied for
10706 any other value of~|k|.
10707
10708 Actually, the conditions can be relaxed somewhat since a relation such as
10709 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10710 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10711 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10712 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10713 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10714 counterclockwise direction.
10715
10716 The |fin_offset_prep| subroutine solves the stated subproblem.
10717 It has a parameter called |rise| that is |1| in
10718 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10719 the derivative of the cubic following |p|.
10720 The |w| parameter should point to offset~$w_k$ and |info(p)| should already
10721 be set properly.  The |turn_amt| parameter gives the absolute value of the
10722 overall net change in pen offsets.
10723
10724 @<Declarations@>=
10725 static void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10726   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10727   integer rise, integer turn_amt) ;
10728
10729 @ @c
10730 void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10731   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10732   integer rise, integer turn_amt)  {
10733   pointer ww; /* for list manipulation */
10734   scaled du,dv; /* for slope calculation */
10735   integer t0,t1,t2; /* test coefficients */
10736   fraction t; /* place where the derivative passes a critical slope */
10737   fraction s; /* slope or reciprocal slope */
10738   integer v; /* intermediate value for updating |x0..y2| */
10739   pointer q; /* original |mp_link(p)| */
10740   q=mp_link(p);
10741   while (1)  { 
10742     if ( rise>0 ) ww=mp_link(w); /* a pointer to $w\k$ */
10743     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10744     @<Compute test coefficients |(t0,t1,t2)|
10745       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10746     t=mp_crossing_point(mp, t0,t1,t2);
10747     if ( t>=fraction_one ) {
10748       if ( turn_amt>0 ) t=fraction_one;  else return;
10749     }
10750     @<Split the cubic at $t$,
10751       and split off another cubic if the derivative crosses back@>;
10752     w=ww;
10753   }
10754 }
10755
10756 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10757 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10758 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10759 begins to fail.
10760
10761 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10762 du=mp_x_coord(ww)-mp_x_coord(w); dv=mp_y_coord(ww)-mp_y_coord(w);
10763 if ( abs(du)>=abs(dv) ) {
10764   s=mp_make_fraction(mp, dv,du);
10765   t0=mp_take_fraction(mp, x0,s)-y0;
10766   t1=mp_take_fraction(mp, x1,s)-y1;
10767   t2=mp_take_fraction(mp, x2,s)-y2;
10768   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10769 } else { 
10770   s=mp_make_fraction(mp, du,dv);
10771   t0=x0-mp_take_fraction(mp, y0,s);
10772   t1=x1-mp_take_fraction(mp, y1,s);
10773   t2=x2-mp_take_fraction(mp, y2,s);
10774   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10775 }
10776 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10777
10778 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10779 $(*)$, and it might cross again and return towards $s_{k-1}$ or $s_k$,
10780 respectively, yielding another solution of $(*)$.
10781
10782 @<Split the cubic at $t$, and split off another...@>=
10783
10784 mp_split_cubic(mp, p,t); p=mp_link(p); info(p)=zero_off+rise;
10785 decr(turn_amt);
10786 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10787 x0=t_of_the_way(v,x1);
10788 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10789 y0=t_of_the_way(v,y1);
10790 if ( turn_amt<0 ) {
10791   t1=t_of_the_way(t1,t2);
10792   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10793   t=mp_crossing_point(mp, 0,-t1,-t2);
10794   if ( t>fraction_one ) t=fraction_one;
10795   incr(turn_amt);
10796   if ( (t==fraction_one)&&(mp_link(p)!=q) ) {
10797     info(mp_link(p))=info(mp_link(p))-rise;
10798   } else { 
10799     mp_split_cubic(mp, p,t); info(mp_link(p))=zero_off-rise;
10800     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10801     x2=t_of_the_way(x1,v);
10802     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10803     y2=t_of_the_way(y1,v);
10804   }
10805 }
10806 }
10807
10808 @ Now we must consider the general problem of |offset_prep|, when
10809 nothing is known about a given cubic. We start by finding its
10810 direction in the vicinity of |t=0|.
10811
10812 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10813 has not yet introduced any more numerical errors.  Thus we can compute
10814 the true initial direction for the given cubic, even if it is almost
10815 degenerate.
10816
10817 @<Find the initial direction |(dx,dy)|@>=
10818 dx=x0; dy=y0;
10819 if ( dx==0 && dy==0 ) { 
10820   dx=x1; dy=y1;
10821   if ( dx==0 && dy==0 ) { 
10822     dx=x2; dy=y2;
10823   }
10824 }
10825 if ( p==c ) { dx0=dx; dy0=dy;  }
10826
10827 @ @<Find the final direction |(dxin,dyin)|@>=
10828 dxin=x2; dyin=y2;
10829 if ( dxin==0 && dyin==0 ) {
10830   dxin=x1; dyin=y1;
10831   if ( dxin==0 && dyin==0 ) {
10832     dxin=x0; dyin=y0;
10833   }
10834 }
10835
10836 @ The next step is to bracket the initial direction between consecutive
10837 edges of the pen polygon.  We must be careful to turn clockwise only if
10838 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10839 counter-clockwise in order to make \&{doublepath} envelopes come out
10840 @:double_path_}{\&{doublepath} primitive@>
10841 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10842
10843 @<Update |info(p)| and find the offset $w_k$ such that...@>=
10844 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10845 w=mp_pen_walk(mp, w0, turn_amt);
10846 w0=w;
10847 info(p)=info(p)+turn_amt
10848
10849 @ Decide how many pen offsets to go away from |w| in order to find the offset
10850 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10851 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10852 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10853
10854 If the pen polygon has only two edges, they could both be parallel
10855 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10856 such edge in order to avoid an infinite loop.
10857
10858 @<Declarations@>=
10859 static integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10860                          scaled dy, boolean  ccw);
10861
10862 @ @c
10863 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10864                          scaled dy, boolean  ccw) {
10865   pointer ww; /* a neighbor of knot~|w| */
10866   integer s; /* turn amount so far */
10867   integer t; /* |ab_vs_cd| result */
10868   s=0;
10869   if ( ccw ) { 
10870     ww=mp_link(w);
10871     do {  
10872       t=mp_ab_vs_cd(mp, dy,(mp_x_coord(ww)-mp_x_coord(w)),
10873                         dx,(mp_y_coord(ww)-mp_y_coord(w)));
10874       if ( t<0 ) break;
10875       incr(s);
10876       w=ww; ww=mp_link(ww);
10877     } while (t>0);
10878   } else { 
10879     ww=knil(w);
10880     while ( mp_ab_vs_cd(mp, dy,(mp_x_coord(w)-mp_x_coord(ww)),
10881                             dx,(mp_y_coord(w)-mp_y_coord(ww))) < 0) { 
10882       decr(s);
10883       w=ww; ww=knil(ww);
10884     }
10885   }
10886   return s;
10887 }
10888
10889 @ When we're all done, the final offset is |w0| and the final curve direction
10890 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10891 can correct |info(c)| which was erroneously based on an incoming offset
10892 of~|h|.
10893
10894 @d fix_by(A) info(c)=info(c)+(A)
10895
10896 @<Fix the offset change in |info(c)| and set |c| to the return value of...@>=
10897 mp->spec_offset=info(c)-zero_off;
10898 if ( mp_link(c)==c ) {
10899   info(c)=zero_off+n;
10900 } else { 
10901   fix_by(k_needed);
10902   while ( w0!=h ) { fix_by(1); w0=mp_link(w0);  };
10903   while ( info(c)<=zero_off-n ) fix_by(n);
10904   while ( info(c)>zero_off ) fix_by(-n);
10905   if ( (info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10906 }
10907
10908 @ Finally we want to reduce the general problem to situations that
10909 |fin_offset_prep| can handle. We split the cubic into at most three parts
10910 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10911
10912 @<Complete the offset splitting process@>=
10913 ww=knil(w);
10914 @<Compute test coeff...@>;
10915 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10916   |t:=fraction_one+1|@>;
10917 if ( t>fraction_one ) {
10918   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10919 } else {
10920   mp_split_cubic(mp, p,t); r=mp_link(p);
10921   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10922   x2a=t_of_the_way(x1a,x1);
10923   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10924   y2a=t_of_the_way(y1a,y1);
10925   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10926   info(r)=zero_off-1;
10927   if ( turn_amt>=0 ) {
10928     t1=t_of_the_way(t1,t2);
10929     if ( t1>0 ) t1=0;
10930     t=mp_crossing_point(mp, 0,-t1,-t2);
10931     if ( t>fraction_one ) t=fraction_one;
10932     @<Split off another rising cubic for |fin_offset_prep|@>;
10933     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10934   } else {
10935     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10936   }
10937 }
10938
10939 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10940 mp_split_cubic(mp, r,t); info(mp_link(r))=zero_off+1;
10941 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10942 x0a=t_of_the_way(x1,x1a);
10943 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10944 y0a=t_of_the_way(y1,y1a);
10945 mp_fin_offset_prep(mp, mp_link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10946 x2=x0a; y2=y0a
10947
10948 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10949 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10950 need to decide whether the directions are parallel or antiparallel.  We
10951 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10952 should be avoided when the value of |turn_amt| already determines the
10953 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10954 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10955 crossing and the first crossing cannot be antiparallel.
10956
10957 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10958 t=mp_crossing_point(mp, t0,t1,t2);
10959 if ( turn_amt>=0 ) {
10960   if ( t2<0 ) {
10961     t=fraction_one+1;
10962   } else { 
10963     u0=t_of_the_way(x0,x1);
10964     u1=t_of_the_way(x1,x2);
10965     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10966     v0=t_of_the_way(y0,y1);
10967     v1=t_of_the_way(y1,y2);
10968     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10969     if ( ss<0 ) t=fraction_one+1;
10970   }
10971 } else if ( t>fraction_one ) {
10972   t=fraction_one;
10973 }
10974
10975 @ @<Other local variables for |offset_prep|@>=
10976 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10977 integer ss = 0; /* the part of the dot product computed so far */
10978 int d_sign; /* sign of overall change in direction for this cubic */
10979
10980 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10981 problem to decide which way it loops around but that's OK as long we're
10982 consistent.  To make \&{doublepath} envelopes work properly, reversing
10983 the path should always change the sign of |turn_amt|.
10984
10985 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10986 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10987 if ( d_sign==0 ) {
10988   @<Check rotation direction based on node position@>
10989 }
10990 if ( d_sign==0 ) {
10991   if ( dx==0 ) {
10992     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10993   } else {
10994     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10995   }
10996 }
10997 @<Make |ss| negative if and only if the total change in direction is
10998   more than $180^\circ$@>;
10999 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
11000 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
11001
11002 @ We check rotation direction by looking at the vector connecting the current
11003 node with the next. If its angle with incoming and outgoing tangents has the
11004 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
11005 Otherwise we proceed to the cusp code.
11006
11007 @<Check rotation direction based on node position@>=
11008 u0=mp_x_coord(q)-mp_x_coord(p);
11009 u1=mp_y_coord(q)-mp_y_coord(p);
11010 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
11011   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
11012
11013 @ In order to be invariant under path reversal, the result of this computation
11014 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
11015 then swapped with |(x2,y2)|.  We make use of the identities
11016 |take_fraction(-a,-b)=take_fraction(a,b)| and
11017 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
11018
11019 @<Make |ss| negative if and only if the total change in direction is...@>=
11020 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
11021 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
11022 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
11023 if ( t0>0 ) {
11024   t=mp_crossing_point(mp, t0,t1,-t0);
11025   u0=t_of_the_way(x0,x1);
11026   u1=t_of_the_way(x1,x2);
11027   v0=t_of_the_way(y0,y1);
11028   v1=t_of_the_way(y1,y2);
11029 } else { 
11030   t=mp_crossing_point(mp, -t0,t1,t0);
11031   u0=t_of_the_way(x2,x1);
11032   u1=t_of_the_way(x1,x0);
11033   v0=t_of_the_way(y2,y1);
11034   v1=t_of_the_way(y1,y0);
11035 }
11036 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
11037    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
11038
11039 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
11040 that the |cur_pen| has not been walked around to the first offset.
11041
11042 @c 
11043 static void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, const char *s) {
11044   pointer p,q; /* list traversal */
11045   pointer w; /* the current pen offset */
11046   mp_print_diagnostic(mp, "Envelope spec",s,true);
11047   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
11048   mp_print_ln(mp);
11049   mp_print_two(mp, mp_x_coord(cur_spec),mp_y_coord(cur_spec));
11050   mp_print(mp, " % beginning with offset ");
11051   mp_print_two(mp, mp_x_coord(w),mp_y_coord(w));
11052   do { 
11053     while (1) {  
11054       q=mp_link(p);
11055       @<Print the cubic between |p| and |q|@>;
11056       p=q;
11057           if ((p==cur_spec) || (info(p)!=zero_off)) 
11058         break;
11059     }
11060     if ( info(p)!=zero_off ) {
11061       @<Update |w| as indicated by |info(p)| and print an explanation@>;
11062     }
11063   } while (p!=cur_spec);
11064   mp_print_nl(mp, " & cycle");
11065   mp_end_diagnostic(mp, true);
11066 }
11067
11068 @ @<Update |w| as indicated by |info(p)| and print an explanation@>=
11069
11070   w=mp_pen_walk(mp, w, (info(p)-zero_off));
11071   mp_print(mp, " % ");
11072   if ( info(p)>zero_off ) mp_print(mp, "counter");
11073   mp_print(mp, "clockwise to offset ");
11074   mp_print_two(mp, mp_x_coord(w),mp_y_coord(w));
11075 }
11076
11077 @ @<Print the cubic between |p| and |q|@>=
11078
11079   mp_print_nl(mp, "   ..controls ");
11080   mp_print_two(mp, mp_right_x(p),mp_right_y(p));
11081   mp_print(mp, " and ");
11082   mp_print_two(mp, mp_left_x(q),mp_left_y(q));
11083   mp_print_nl(mp, " ..");
11084   mp_print_two(mp, mp_x_coord(q),mp_y_coord(q));
11085 }
11086
11087 @ Once we have an envelope spec, the remaining task to construct the actual
11088 envelope by offsetting each cubic as determined by the |info| fields in
11089 the knots.  First we use |offset_prep| to convert the |c| into an envelope
11090 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
11091 the envelope.
11092
11093 The |ljoin| and |miterlim| parameters control the treatment of points where the
11094 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
11095 The endpoints are easily located because |c| is given in undoubled form
11096 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
11097 track of the endpoints and treat them like very sharp corners.
11098 Butt end caps are treated like beveled joins; round end caps are treated like
11099 round joins; and square end caps are achieved by setting |join_type:=3|.
11100
11101 None of these parameters apply to inside joins where the convolution tracing
11102 has retrograde lines.  In such cases we use a simple connect-the-endpoints
11103 approach that is achieved by setting |join_type:=2|.
11104
11105 @c
11106 static pointer mp_make_envelope (MP mp,pointer c, pointer h, quarterword ljoin,
11107   quarterword lcap, scaled miterlim) {
11108   pointer p,q,r,q0; /* for manipulating the path */
11109   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
11110   pointer w,w0; /* the pen knot for the current offset */
11111   scaled qx,qy; /* unshifted coordinates of |q| */
11112   halfword k,k0; /* controls pen edge insertion */
11113   @<Other local variables for |make_envelope|@>;
11114   dxin=0; dyin=0; dxout=0; dyout=0;
11115   mp->spec_p1=null; mp->spec_p2=null;
11116   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
11117   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
11118     the initial offset@>;
11119   w=h;
11120   p=c;
11121   do {  
11122     q=mp_link(p); q0=q;
11123     qx=mp_x_coord(q); qy=mp_y_coord(q);
11124     k=info(q);
11125     k0=k; w0=w;
11126     if ( k!=zero_off ) {
11127       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11128     }
11129     @<Add offset |w| to the cubic from |p| to |q|@>;
11130     while ( k!=zero_off ) { 
11131       @<Step |w| and move |k| one step closer to |zero_off|@>;
11132       if ( (join_type==1)||(k==zero_off) )
11133          q=mp_insert_knot(mp, q,qx+mp_x_coord(w),qy+mp_y_coord(w));
11134     };
11135     if ( q!=mp_link(p) ) {
11136       @<Set |p=mp_link(p)| and add knots between |p| and |q| as
11137         required by |join_type|@>;
11138     }
11139     p=q;
11140   } while (q0!=c);
11141   return c;
11142 }
11143
11144 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11145 c=mp_offset_prep(mp, c,h);
11146 if ( mp->internal[mp_tracing_specs]>0 ) 
11147   mp_print_spec(mp, c,h,"");
11148 h=mp_pen_walk(mp, h,mp->spec_offset)
11149
11150 @ Mitered and squared-off joins depend on path directions that are difficult to
11151 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11152 have degenerate cubics only if the entire cycle collapses to a single
11153 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11154 envelope degenerate as well.
11155
11156 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11157 if ( k<zero_off ) {
11158   join_type=2;
11159 } else {
11160   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11161   else if ( lcap==2 ) join_type=3;
11162   else join_type=2-lcap;
11163   if ( (join_type==0)||(join_type==3) ) {
11164     @<Set the incoming and outgoing directions at |q|; in case of
11165       degeneracy set |join_type:=2|@>;
11166     if ( join_type==0 ) {
11167       @<If |miterlim| is less than the secant of half the angle at |q|
11168         then set |join_type:=2|@>;
11169     }
11170   }
11171 }
11172
11173 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11174
11175   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11176       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11177   if ( tmp<unity )
11178     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11179 }
11180
11181 @ @<Other local variables for |make_envelope|@>=
11182 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11183 scaled tmp; /* a temporary value */
11184
11185 @ The coordinates of |p| have already been shifted unless |p| is the first
11186 knot in which case they get shifted at the very end.
11187
11188 @<Add offset |w| to the cubic from |p| to |q|@>=
11189 mp_right_x(p)=mp_right_x(p)+mp_x_coord(w);
11190 mp_right_y(p)=mp_right_y(p)+mp_y_coord(w);
11191 mp_left_x(q)=mp_left_x(q)+mp_x_coord(w);
11192 mp_left_y(q)=mp_left_y(q)+mp_y_coord(w);
11193 mp_x_coord(q)=mp_x_coord(q)+mp_x_coord(w);
11194 mp_y_coord(q)=mp_y_coord(q)+mp_y_coord(w);
11195 mp_left_type(q)=mp_explicit;
11196 mp_right_type(q)=mp_explicit
11197
11198 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11199 if ( k>zero_off ){ w=mp_link(w); decr(k);  }
11200 else { w=knil(w); incr(k);  }
11201
11202 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11203 the |mp_right_x| and |mp_right_y| fields of |r| are set from |q|.  This is done in
11204 case the cubic containing these control points is ``yet to be examined.''
11205
11206 @<Declarations@>=
11207 static pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y);
11208
11209 @ @c
11210 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11211   /* returns the inserted knot */
11212   pointer r; /* the new knot */
11213   r=mp_get_node(mp, knot_node_size);
11214   mp_link(r)=mp_link(q); mp_link(q)=r;
11215   mp_right_x(r)=mp_right_x(q);
11216   mp_right_y(r)=mp_right_y(q);
11217   mp_x_coord(r)=x;
11218   mp_y_coord(r)=y;
11219   mp_right_x(q)=mp_x_coord(q);
11220   mp_right_y(q)=mp_y_coord(q);
11221   mp_left_x(r)=mp_x_coord(r);
11222   mp_left_y(r)=mp_y_coord(r);
11223   mp_left_type(r)=mp_explicit;
11224   mp_right_type(r)=mp_explicit;
11225   mp_originator(r)=mp_program_code;
11226   return r;
11227 }
11228
11229 @ After setting |p:=mp_link(p)|, either |join_type=1| or |q=mp_link(p)|.
11230
11231 @<Set |p=mp_link(p)| and add knots between |p| and |q| as...@>=
11232
11233   p=mp_link(p);
11234   if ( (join_type==0)||(join_type==3) ) {
11235     if ( join_type==0 ) {
11236       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11237     } else {
11238       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11239         squared join@>;
11240     }
11241     if ( r!=null ) { 
11242       mp_right_x(r)=mp_x_coord(r);
11243       mp_right_y(r)=mp_y_coord(r);
11244     }
11245   }
11246 }
11247
11248 @ For very small angles, adding a knot is unnecessary and would cause numerical
11249 problems, so we just set |r:=null| in that case.
11250
11251 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11252
11253   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11254   if ( abs(det)<26844 ) { 
11255      r=null; /* sine $<10^{-4}$ */
11256   } else { 
11257     tmp=mp_take_fraction(mp, mp_x_coord(q)-mp_x_coord(p),dyout)-
11258         mp_take_fraction(mp, mp_y_coord(q)-mp_y_coord(p),dxout);
11259     tmp=mp_make_fraction(mp, tmp,det);
11260     r=mp_insert_knot(mp, p,mp_x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11261       mp_y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11262   }
11263 }
11264
11265 @ @<Other local variables for |make_envelope|@>=
11266 fraction det; /* a determinant used for mitered join calculations */
11267
11268 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11269
11270   ht_x=mp_y_coord(w)-mp_y_coord(w0);
11271   ht_y=mp_x_coord(w0)-mp_x_coord(w);
11272   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11273     ht_x+=ht_x; ht_y+=ht_y;
11274   }
11275   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11276     product with |(ht_x,ht_y)|@>;
11277   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11278                                   mp_take_fraction(mp, dyin,ht_y));
11279   r=mp_insert_knot(mp, p,mp_x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11280                          mp_y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11281   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11282                                   mp_take_fraction(mp, dyout,ht_y));
11283   r=mp_insert_knot(mp, r,mp_x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11284                          mp_y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11285 }
11286
11287 @ @<Other local variables for |make_envelope|@>=
11288 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11289 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11290 halfword kk; /* keeps track of the pen vertices being scanned */
11291 pointer ww; /* the pen vertex being tested */
11292
11293 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11294 from zero to |max_ht|.
11295
11296 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11297 max_ht=0;
11298 kk=zero_off;
11299 ww=w;
11300 while (1)  { 
11301   @<Step |ww| and move |kk| one step closer to |k0|@>;
11302   if ( kk==k0 ) break;
11303   tmp=mp_take_fraction(mp, (mp_x_coord(ww)-mp_x_coord(w0)),ht_x)+
11304       mp_take_fraction(mp, (mp_y_coord(ww)-mp_y_coord(w0)),ht_y);
11305   if ( tmp>max_ht ) max_ht=tmp;
11306 }
11307
11308
11309 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11310 if ( kk>k0 ) { ww=mp_link(ww); decr(kk);  }
11311 else { ww=knil(ww); incr(kk);  }
11312
11313 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11314 if ( mp_left_type(c)==mp_endpoint ) { 
11315   mp->spec_p1=mp_htap_ypoc(mp, c);
11316   mp->spec_p2=mp->path_tail;
11317   mp_originator(mp->spec_p1)=mp_program_code;
11318   mp_link(mp->spec_p2)=mp_link(mp->spec_p1);
11319   mp_link(mp->spec_p1)=c;
11320   mp_remove_cubic(mp, mp->spec_p1);
11321   c=mp->spec_p1;
11322   if ( c!=mp_link(c) ) {
11323     mp_originator(mp->spec_p2)=mp_program_code;
11324     mp_remove_cubic(mp, mp->spec_p2);
11325   } else {
11326     @<Make |c| look like a cycle of length one@>;
11327   }
11328 }
11329
11330 @ @<Make |c| look like a cycle of length one@>=
11331
11332   mp_left_type(c)=mp_explicit; mp_right_type(c)=mp_explicit;
11333   mp_left_x(c)=mp_x_coord(c); mp_left_y(c)=mp_y_coord(c);
11334   mp_right_x(c)=mp_x_coord(c); mp_right_y(c)=mp_y_coord(c);
11335 }
11336
11337 @ In degenerate situations we might have to look at the knot preceding~|q|.
11338 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11339
11340 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11341 dxin=mp_x_coord(q)-mp_left_x(q);
11342 dyin=mp_y_coord(q)-mp_left_y(q);
11343 if ( (dxin==0)&&(dyin==0) ) {
11344   dxin=mp_x_coord(q)-mp_right_x(p);
11345   dyin=mp_y_coord(q)-mp_right_y(p);
11346   if ( (dxin==0)&&(dyin==0) ) {
11347     dxin=mp_x_coord(q)-mp_x_coord(p);
11348     dyin=mp_y_coord(q)-mp_y_coord(p);
11349     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11350       dxin=dxin+mp_x_coord(w);
11351       dyin=dyin+mp_y_coord(w);
11352     }
11353   }
11354 }
11355 tmp=mp_pyth_add(mp, dxin,dyin);
11356 if ( tmp==0 ) {
11357   join_type=2;
11358 } else { 
11359   dxin=mp_make_fraction(mp, dxin,tmp);
11360   dyin=mp_make_fraction(mp, dyin,tmp);
11361   @<Set the outgoing direction at |q|@>;
11362 }
11363
11364 @ If |q=c| then the coordinates of |r| and the control points between |q|
11365 and~|r| have already been offset by |h|.
11366
11367 @<Set the outgoing direction at |q|@>=
11368 dxout=mp_right_x(q)-mp_x_coord(q);
11369 dyout=mp_right_y(q)-mp_y_coord(q);
11370 if ( (dxout==0)&&(dyout==0) ) {
11371   r=mp_link(q);
11372   dxout=mp_left_x(r)-mp_x_coord(q);
11373   dyout=mp_left_y(r)-mp_y_coord(q);
11374   if ( (dxout==0)&&(dyout==0) ) {
11375     dxout=mp_x_coord(r)-mp_x_coord(q);
11376     dyout=mp_y_coord(r)-mp_y_coord(q);
11377   }
11378 }
11379 if ( q==c ) {
11380   dxout=dxout-mp_x_coord(h);
11381   dyout=dyout-mp_y_coord(h);
11382 }
11383 tmp=mp_pyth_add(mp, dxout,dyout);
11384 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11385 @:this can't happen degerate spec}{\quad degenerate spec@>
11386 dxout=mp_make_fraction(mp, dxout,tmp);
11387 dyout=mp_make_fraction(mp, dyout,tmp)
11388
11389 @* \[23] Direction and intersection times.
11390 A path of length $n$ is defined parametrically by functions $x(t)$ and
11391 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11392 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11393 we shall consider operations that determine special times associated with
11394 given paths: the first time that a path travels in a given direction, and
11395 a pair of times at which two paths cross each other.
11396
11397 @ Let's start with the easier task. The function |find_direction_time| is
11398 given a direction |(x,y)| and a path starting at~|h|. If the path never
11399 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11400 it will be nonnegative.
11401
11402 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11403 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11404 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11405 assumed to match any given direction at time~|t|.
11406
11407 The routine solves this problem in nondegenerate cases by rotating the path
11408 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11409 to find when a given path first travels ``due east.''
11410
11411 @c 
11412 static scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11413   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11414   pointer p,q; /* for list traversal */
11415   scaled n; /* the direction time at knot |p| */
11416   scaled tt; /* the direction time within a cubic */
11417   @<Other local variables for |find_direction_time|@>;
11418   @<Normalize the given direction for better accuracy;
11419     but |return| with zero result if it's zero@>;
11420   n=0; p=h; phi=0;
11421   while (1) { 
11422     if ( mp_right_type(p)==mp_endpoint ) break;
11423     q=mp_link(p);
11424     @<Rotate the cubic between |p| and |q|; then
11425       |goto found| if the rotated cubic travels due east at some time |tt|;
11426       but |break| if an entire cyclic path has been traversed@>;
11427     p=q; n=n+unity;
11428   }
11429   return (-unity);
11430 FOUND: 
11431   return (n+tt);
11432 }
11433
11434 @ @<Normalize the given direction for better accuracy...@>=
11435 if ( abs(x)<abs(y) ) { 
11436   x=mp_make_fraction(mp, x,abs(y));
11437   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11438 } else if ( x==0 ) { 
11439   return 0;
11440 } else  { 
11441   y=mp_make_fraction(mp, y,abs(x));
11442   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11443 }
11444
11445 @ Since we're interested in the tangent directions, we work with the
11446 derivative $${1\over3}B'(x_0,x_1,x_2,x_3;t)=
11447 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11448 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11449 in order to achieve better accuracy.
11450
11451 The given path may turn abruptly at a knot, and it might pass the critical
11452 tangent direction at such a time. Therefore we remember the direction |phi|
11453 in which the previous rotated cubic was traveling. (The value of |phi| will be
11454 undefined on the first cubic, i.e., when |n=0|.)
11455
11456 @<Rotate the cubic between |p| and |q|; then...@>=
11457 tt=0;
11458 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11459   points of the rotated derivatives@>;
11460 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11461 if ( n>0 ) { 
11462   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11463   if ( p==h ) break;
11464   };
11465 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11466 @<Exit to |found| if the curve whose derivatives are specified by
11467   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11468
11469 @ @<Other local variables for |find_direction_time|@>=
11470 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11471 angle theta,phi; /* angles of exit and entry at a knot */
11472 fraction t; /* temp storage */
11473
11474 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11475 x1=mp_right_x(p)-mp_x_coord(p); x2=mp_left_x(q)-mp_right_x(p);
11476 x3=mp_x_coord(q)-mp_left_x(q);
11477 y1=mp_right_y(p)-mp_y_coord(p); y2=mp_left_y(q)-mp_right_y(p);
11478 y3=mp_y_coord(q)-mp_left_y(q);
11479 max=abs(x1);
11480 if ( abs(x2)>max ) max=abs(x2);
11481 if ( abs(x3)>max ) max=abs(x3);
11482 if ( abs(y1)>max ) max=abs(y1);
11483 if ( abs(y2)>max ) max=abs(y2);
11484 if ( abs(y3)>max ) max=abs(y3);
11485 if ( max==0 ) goto FOUND;
11486 while ( max<fraction_half ){ 
11487   max+=max; x1+=x1; x2+=x2; x3+=x3;
11488   y1+=y1; y2+=y2; y3+=y3;
11489 }
11490 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11491 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11492 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11493 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11494 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11495 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11496
11497 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11498 theta=mp_n_arg(mp, x1,y1);
11499 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11500 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11501
11502 @ In this step we want to use the |crossing_point| routine to find the
11503 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11504 Several complications arise: If the quadratic equation has a double root,
11505 the curve never crosses zero, and |crossing_point| will find nothing;
11506 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11507 equation has simple roots, or only one root, we may have to negate it
11508 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11509 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11510 identically zero.
11511
11512 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11513 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11514 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11515   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11516     either |goto found| or |goto done|@>;
11517 }
11518 if ( y1<=0 ) {
11519   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11520   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11521 }
11522 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11523   $B(x_1,x_2,x_3;t)\ge0$@>;
11524 DONE:
11525
11526 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11527 two roots, because we know that it isn't identically zero.
11528
11529 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11530 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11531 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11532 subject to rounding errors. Yet this code optimistically tries to
11533 do the right thing.
11534
11535 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11536
11537 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11538 t=mp_crossing_point(mp, y1,y2,y3);
11539 if ( t>fraction_one ) goto DONE;
11540 y2=t_of_the_way(y2,y3);
11541 x1=t_of_the_way(x1,x2);
11542 x2=t_of_the_way(x2,x3);
11543 x1=t_of_the_way(x1,x2);
11544 if ( x1>=0 ) we_found_it;
11545 if ( y2>0 ) y2=0;
11546 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11547 if ( t>fraction_one ) goto DONE;
11548 x1=t_of_the_way(x1,x2);
11549 x2=t_of_the_way(x2,x3);
11550 if ( t_of_the_way(x1,x2)>=0 ) { 
11551   t=t_of_the_way(tt,fraction_one); we_found_it;
11552 }
11553
11554 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11555     either |goto found| or |goto done|@>=
11556
11557   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11558     t=mp_make_fraction(mp, y1,y1-y2);
11559     x1=t_of_the_way(x1,x2);
11560     x2=t_of_the_way(x2,x3);
11561     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11562   } else if ( y3==0 ) {
11563     if ( y1==0 ) {
11564       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11565     } else if ( x3>=0 ) {
11566       tt=unity; goto FOUND;
11567     }
11568   }
11569   goto DONE;
11570 }
11571
11572 @ At this point we know that the derivative of |y(t)| is identically zero,
11573 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11574 traveling east.
11575
11576 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11577
11578   t=mp_crossing_point(mp, -x1,-x2,-x3);
11579   if ( t<=fraction_one ) we_found_it;
11580   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11581     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11582   }
11583 }
11584
11585 @ The intersection of two cubics can be found by an interesting variant
11586 of the general bisection scheme described in the introduction to
11587 |crossing_point|.\
11588 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)$,
11589 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11590 if an intersection exists. First we find the smallest rectangle that
11591 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11592 the smallest rectangle that encloses
11593 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11594 But if the rectangles do overlap, we bisect the intervals, getting
11595 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11596 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11597 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11598 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11599 levels of bisection we will have determined the intersection times $t_1$
11600 and~$t_2$ to $l$~bits of accuracy.
11601
11602 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11603 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11604 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11605 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11606 to determine when the enclosing rectangles overlap. Here's why:
11607 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11608 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11609 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11610 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11611 overlap if and only if $u\submin\L x\submax$ and
11612 $x\submin\L u\submax$. Letting
11613 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11614   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11615 we have $2^lu\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11616 reduces to
11617 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11618 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11619 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11620 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11621 because of the overlap condition; i.e., we know that $X\submin$,
11622 $X\submax$, and their relatives are bounded, hence $X\submax-
11623 U\submin$ and $X\submin-U\submax$ are bounded.
11624
11625 @ Incidentally, if the given cubics intersect more than once, the process
11626 just sketched will not necessarily find the lexicographically smallest pair
11627 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11628 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11629 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11630 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11631 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11632 Shuffled order agrees with lexicographic order if all pairs of solutions
11633 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11634 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11635 and the bisection algorithm would be substantially less efficient if it were
11636 constrained by lexicographic order.
11637
11638 For example, suppose that an overlap has been found for $l=3$ and
11639 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11640 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11641 Then there is probably an intersection in one of the subintervals
11642 $(.1011,.011x)$; but lexicographic order would require us to explore
11643 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11644 want to store all of the subdivision data for the second path, so the
11645 subdivisions would have to be regenerated many times. Such inefficiencies
11646 would be associated with every `1' in the binary representation of~$t_1$.
11647
11648 @ The subdivision process introduces rounding errors, hence we need to
11649 make a more liberal test for overlap. It is not hard to show that the
11650 computed values of $U_i$ differ from the truth by at most~$l$, on
11651 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11652 If $\beta$ is an upper bound on the absolute error in the computed
11653 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11654 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11655 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11656
11657 More accuracy is obtained if we try the algorithm first with |tol=0|;
11658 the more liberal tolerance is used only if an exact approach fails.
11659 It is convenient to do this double-take by letting `3' in the preceding
11660 paragraph be a parameter, which is first 0, then 3.
11661
11662 @<Glob...@>=
11663 unsigned int tol_step; /* either 0 or 3, usually */
11664
11665 @ We shall use an explicit stack to implement the recursive bisection
11666 method described above. The |bisect_stack| array will contain numerous 5-word
11667 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11668 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11669
11670 The following macros define the allocation of stack positions to
11671 the quantities needed for bisection-intersection.
11672
11673 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11674 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11675 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11676 @d stack_min(A) mp->bisect_stack[(A)+3]
11677   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11678 @d stack_max(A) mp->bisect_stack[(A)+4]
11679   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11680 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11681 @#
11682 @d u_packet(A) ((A)-5)
11683 @d v_packet(A) ((A)-10)
11684 @d x_packet(A) ((A)-15)
11685 @d y_packet(A) ((A)-20)
11686 @d l_packets (mp->bisect_ptr-int_packets)
11687 @d r_packets mp->bisect_ptr
11688 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11689 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11690 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11691 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11692 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11693 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11694 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11695 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11696 @#
11697 @d u1l stack_1(ul_packet) /* $U'_1$ */
11698 @d u2l stack_2(ul_packet) /* $U'_2$ */
11699 @d u3l stack_3(ul_packet) /* $U'_3$ */
11700 @d v1l stack_1(vl_packet) /* $V'_1$ */
11701 @d v2l stack_2(vl_packet) /* $V'_2$ */
11702 @d v3l stack_3(vl_packet) /* $V'_3$ */
11703 @d x1l stack_1(xl_packet) /* $X'_1$ */
11704 @d x2l stack_2(xl_packet) /* $X'_2$ */
11705 @d x3l stack_3(xl_packet) /* $X'_3$ */
11706 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11707 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11708 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11709 @d u1r stack_1(ur_packet) /* $U''_1$ */
11710 @d u2r stack_2(ur_packet) /* $U''_2$ */
11711 @d u3r stack_3(ur_packet) /* $U''_3$ */
11712 @d v1r stack_1(vr_packet) /* $V''_1$ */
11713 @d v2r stack_2(vr_packet) /* $V''_2$ */
11714 @d v3r stack_3(vr_packet) /* $V''_3$ */
11715 @d x1r stack_1(xr_packet) /* $X''_1$ */
11716 @d x2r stack_2(xr_packet) /* $X''_2$ */
11717 @d x3r stack_3(xr_packet) /* $X''_3$ */
11718 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11719 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11720 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11721 @#
11722 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11723 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11724 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11725 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11726 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11727 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11728
11729 @<Glob...@>=
11730 integer *bisect_stack;
11731 integer bisect_ptr;
11732
11733 @ @<Allocate or initialize ...@>=
11734 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11735
11736 @ @<Dealloc variables@>=
11737 xfree(mp->bisect_stack);
11738
11739 @ @<Check the ``constant''...@>=
11740 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11741
11742 @ Computation of the min and max is a tedious but fairly fast sequence of
11743 instructions; exactly four comparisons are made in each branch.
11744
11745 @d set_min_max(A) 
11746   if ( stack_1((A))<0 ) {
11747     if ( stack_3((A))>=0 ) {
11748       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11749       else stack_min((A))=stack_1((A));
11750       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11751       if ( stack_max((A))<0 ) stack_max((A))=0;
11752     } else { 
11753       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11754       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11755       stack_max((A))=stack_1((A))+stack_2((A));
11756       if ( stack_max((A))<0 ) stack_max((A))=0;
11757     }
11758   } else if ( stack_3((A))<=0 ) {
11759     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11760     else stack_max((A))=stack_1((A));
11761     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11762     if ( stack_min((A))>0 ) stack_min((A))=0;
11763   } else  { 
11764     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11765     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11766     stack_min((A))=stack_1((A))+stack_2((A));
11767     if ( stack_min((A))>0 ) stack_min((A))=0;
11768   }
11769
11770 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11771 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11772 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11773 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11774 plus the |scaled| values of $t_1$ and~$t_2$.
11775
11776 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11777 finds no intersection. The routine gives up and gives an approximate answer
11778 if it has backtracked
11779 more than 5000 times (otherwise there are cases where several minutes
11780 of fruitless computation would be possible).
11781
11782 @d max_patience 5000
11783
11784 @<Glob...@>=
11785 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11786 integer time_to_go; /* this many backtracks before giving up */
11787 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11788
11789 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11790 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,mp_link(p))|
11791 and |(pp,mp_link(pp))|, respectively.
11792
11793 @c 
11794 static void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11795   pointer q,qq; /* |mp_link(p)|, |mp_link(pp)| */
11796   mp->time_to_go=max_patience; mp->max_t=2;
11797   @<Initialize for intersections at level zero@>;
11798 CONTINUE:
11799   while (1) { 
11800     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11801     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11802     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11803     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11804     { 
11805       if ( mp->cur_t>=mp->max_t ){ 
11806         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11807            mp->cur_t=halfp(mp->cur_t+1); 
11808                mp->cur_tt=halfp(mp->cur_tt+1); 
11809            return;
11810         }
11811         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11812       }
11813       @<Subdivide for a new level of intersection@>;
11814       goto CONTINUE;
11815     }
11816     if ( mp->time_to_go>0 ) {
11817       decr(mp->time_to_go);
11818     } else { 
11819       while ( mp->appr_t<unity ) { 
11820         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11821       }
11822       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11823     }
11824     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11825   }
11826 }
11827
11828 @ The following variables are global, although they are used only by
11829 |cubic_intersection|, because it is necessary on some machines to
11830 split |cubic_intersection| up into two procedures.
11831
11832 @<Glob...@>=
11833 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11834 integer tol; /* bound on the uncertainty in the overlap test */
11835 integer uv;
11836 integer xy; /* pointers to the current packets of interest */
11837 integer three_l; /* |tol_step| times the bisection level */
11838 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11839
11840 @ We shall assume that the coordinates are sufficiently non-extreme that
11841 integer overflow will not occur.
11842 @^overflow in arithmetic@>
11843
11844 @<Initialize for intersections at level zero@>=
11845 q=mp_link(p); qq=mp_link(pp); mp->bisect_ptr=int_packets;
11846 u1r=mp_right_x(p)-mp_x_coord(p); u2r=mp_left_x(q)-mp_right_x(p);
11847 u3r=mp_x_coord(q)-mp_left_x(q); set_min_max(ur_packet);
11848 v1r=mp_right_y(p)-mp_y_coord(p); v2r=mp_left_y(q)-mp_right_y(p);
11849 v3r=mp_y_coord(q)-mp_left_y(q); set_min_max(vr_packet);
11850 x1r=mp_right_x(pp)-mp_x_coord(pp); x2r=mp_left_x(qq)-mp_right_x(pp);
11851 x3r=mp_x_coord(qq)-mp_left_x(qq); set_min_max(xr_packet);
11852 y1r=mp_right_y(pp)-mp_y_coord(pp); y2r=mp_left_y(qq)-mp_right_y(pp);
11853 y3r=mp_y_coord(qq)-mp_left_y(qq); set_min_max(yr_packet);
11854 mp->delx=mp_x_coord(p)-mp_x_coord(pp); mp->dely=mp_y_coord(p)-mp_y_coord(pp);
11855 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11856 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11857
11858 @ @<Subdivide for a new level of intersection@>=
11859 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11860 stack_uv=mp->uv; stack_xy=mp->xy;
11861 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11862 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11863 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11864 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11865 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11866 u3l=half(u2l+u2r); u1r=u3l;
11867 set_min_max(ul_packet); set_min_max(ur_packet);
11868 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11869 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11870 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11871 v3l=half(v2l+v2r); v1r=v3l;
11872 set_min_max(vl_packet); set_min_max(vr_packet);
11873 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11874 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11875 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11876 x3l=half(x2l+x2r); x1r=x3l;
11877 set_min_max(xl_packet); set_min_max(xr_packet);
11878 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11879 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11880 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11881 y3l=half(y2l+y2r); y1r=y3l;
11882 set_min_max(yl_packet); set_min_max(yr_packet);
11883 mp->uv=l_packets; mp->xy=l_packets;
11884 mp->delx+=mp->delx; mp->dely+=mp->dely;
11885 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11886 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11887
11888 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11889 NOT_FOUND: 
11890 if ( odd(mp->cur_tt) ) {
11891   if ( odd(mp->cur_t) ) {
11892      @<Descend to the previous level and |goto not_found|@>;
11893   } else { 
11894     incr(mp->cur_t);
11895     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11896       +stack_3(u_packet(mp->uv));
11897     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11898       +stack_3(v_packet(mp->uv));
11899     mp->uv=mp->uv+int_packets; /* switch from |l_packets| to |r_packets| */
11900     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11901          /* switch from |r_packets| to |l_packets| */
11902     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11903       +stack_3(x_packet(mp->xy));
11904     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11905       +stack_3(y_packet(mp->xy));
11906   }
11907 } else { 
11908   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11909   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11910     -stack_3(x_packet(mp->xy));
11911   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11912     -stack_3(y_packet(mp->xy));
11913   mp->xy=mp->xy+int_packets; /* switch from |l_packets| to |r_packets| */
11914 }
11915
11916 @ @<Descend to the previous level...@>=
11917
11918   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11919   if ( mp->cur_t==0 ) return;
11920   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11921   mp->three_l=mp->three_l-mp->tol_step;
11922   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11923   mp->uv=stack_uv; mp->xy=stack_xy;
11924   goto NOT_FOUND;
11925 }
11926
11927 @ The |path_intersection| procedure is much simpler.
11928 It invokes |cubic_intersection| in lexicographic order until finding a
11929 pair of cubics that intersect. The final intersection times are placed in
11930 |cur_t| and~|cur_tt|.
11931
11932 @c 
11933 static void mp_path_intersection (MP mp,pointer h, pointer hh) {
11934   pointer p,pp; /* link registers that traverse the given paths */
11935   integer n,nn; /* integer parts of intersection times, minus |unity| */
11936   @<Change one-point paths into dead cycles@>;
11937   mp->tol_step=0;
11938   do {  
11939     n=-unity; p=h;
11940     do {  
11941       if ( mp_right_type(p)!=mp_endpoint ) { 
11942         nn=-unity; pp=hh;
11943         do {  
11944           if ( mp_right_type(pp)!=mp_endpoint )  { 
11945             mp_cubic_intersection(mp, p,pp);
11946             if ( mp->cur_t>0 ) { 
11947               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11948               return;
11949             }
11950           }
11951           nn=nn+unity; pp=mp_link(pp);
11952         } while (pp!=hh);
11953       }
11954       n=n+unity; p=mp_link(p);
11955     } while (p!=h);
11956     mp->tol_step=mp->tol_step+3;
11957   } while (mp->tol_step<=3);
11958   mp->cur_t=-unity; mp->cur_tt=-unity;
11959 }
11960
11961 @ @<Change one-point paths...@>=
11962 if ( mp_right_type(h)==mp_endpoint ) {
11963   mp_right_x(h)=mp_x_coord(h); mp_left_x(h)=mp_x_coord(h);
11964   mp_right_y(h)=mp_y_coord(h); mp_left_y(h)=mp_y_coord(h); mp_right_type(h)=mp_explicit;
11965 }
11966 if ( mp_right_type(hh)==mp_endpoint ) {
11967   mp_right_x(hh)=mp_x_coord(hh); mp_left_x(hh)=mp_x_coord(hh);
11968   mp_right_y(hh)=mp_y_coord(hh); mp_left_y(hh)=mp_y_coord(hh); mp_right_type(hh)=mp_explicit;
11969 }
11970
11971 @* \[24] Dynamic linear equations.
11972 \MP\ users define variables implicitly by stating equations that should be
11973 satisfied; the computer is supposed to be smart enough to solve those equations.
11974 And indeed, the computer tries valiantly to do so, by distinguishing five
11975 different types of numeric values:
11976
11977 \smallskip\hang
11978 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11979 of the variable whose address is~|p|.
11980
11981 \smallskip\hang
11982 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11983 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11984 as a |scaled| number plus a sum of independent variables with |fraction|
11985 coefficients.
11986
11987 \smallskip\hang
11988 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11989 number'' reflecting the time this variable was first used in an equation;
11990 also |0<=m<64|, and each dependent variable
11991 that refers to this one is actually referring to the future value of
11992 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11993 scaling are sometimes needed to keep the coefficients in dependency lists
11994 from getting too large. The value of~|m| will always be even.)
11995
11996 \smallskip\hang
11997 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11998 equation before, but it has been explicitly declared to be numeric.
11999
12000 \smallskip\hang
12001 |type(p)=undefined| means that variable |p| hasn't appeared before.
12002
12003 \smallskip\noindent
12004 We have actually discussed these five types in the reverse order of their
12005 history during a computation: Once |known|, a variable never again
12006 becomes |dependent|; once |dependent|, it almost never again becomes
12007 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
12008 and once |mp_numeric_type|, it never again becomes |undefined| (except
12009 of course when the user specifically decides to scrap the old value
12010 and start again). A backward step may, however, take place: Sometimes
12011 a |dependent| variable becomes |mp_independent| again, when one of the
12012 independent variables it depends on is reverting to |undefined|.
12013
12014
12015 The next patch detects overflow of independent-variable serial
12016 numbers. Diagnosed and patched by Thorsten Dahlheimer.
12017
12018 @d s_scale 64 /* the serial numbers are multiplied by this factor */
12019 @d new_indep(A)  /* create a new independent variable */
12020   { if ( mp->serial_no>el_gordo-s_scale )
12021     mp_fatal_error(mp, "variable instance identifiers exhausted");
12022   type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
12023   value((A))=mp->serial_no;
12024   }
12025
12026 @<Glob...@>=
12027 integer serial_no; /* the most recent serial number, times |s_scale| */
12028
12029 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
12030
12031 @ But how are dependency lists represented? It's simple: The linear combination
12032 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
12033 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
12034 @t$\alpha_1$@>| (which is a |fraction|); |info(q)| points to the location
12035 of $\alpha_1$; and |mp_link(p)| points to the dependency list
12036 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
12037 then |value(q)=@t$\beta$@>| (which is |scaled|) and |info(q)=null|.
12038 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
12039 they appear in decreasing order of their |value| fields (i.e., of
12040 their serial numbers). \ (It is convenient to use decreasing order,
12041 since |value(null)=0|. If the independent variables were not sorted by
12042 serial number but by some other criterion, such as their location in |mem|,
12043 the equation-solving mechanism would be too system-dependent, because
12044 the ordering can affect the computed results.)
12045
12046 The |link| field in the node that contains the constant term $\beta$ is
12047 called the {\sl final link\/} of the dependency list. \MP\ maintains
12048 a doubly-linked master list of all dependency lists, in terms of a permanently
12049 allocated node
12050 in |mem| called |dep_head|. If there are no dependencies, we have
12051 |mp_link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
12052 otherwise |mp_link(dep_head)| points to the first dependent variable, say~|p|,
12053 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
12054 points to its dependency list. If the final link of that dependency list
12055 occurs in location~|q|, then |mp_link(q)| points to the next dependent
12056 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
12057
12058 @d dep_list(A) mp_link(value_loc((A)))
12059   /* half of the |value| field in a |dependent| variable */
12060 @d prev_dep(A) info(value_loc((A)))
12061   /* the other half; makes a doubly linked list */
12062 @d dep_node_size 2 /* the number of words per dependency node */
12063
12064 @<Initialize table entries...@>= mp->serial_no=0;
12065 mp_link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
12066 info(dep_head)=null; dep_list(dep_head)=null;
12067
12068 @ Actually the description above contains a little white lie. There's
12069 another kind of variable called |mp_proto_dependent|, which is
12070 just like a |dependent| one except that the $\alpha$ coefficients
12071 in its dependency list are |scaled| instead of being fractions.
12072 Proto-dependency lists are mixed with dependency lists in the
12073 nodes reachable from |dep_head|.
12074
12075 @ Here is a procedure that prints a dependency list in symbolic form.
12076 The second parameter should be either |dependent| or |mp_proto_dependent|,
12077 to indicate the scaling of the coefficients.
12078
12079 @<Declarations@>=
12080 static void mp_print_dependency (MP mp,pointer p, quarterword t);
12081
12082 @ @c
12083 void mp_print_dependency (MP mp,pointer p, quarterword t) {
12084   integer v; /* a coefficient */
12085   pointer pp,q; /* for list manipulation */
12086   pp=p;
12087   while (true) { 
12088     v=abs(value(p)); q=info(p);
12089     if ( q==null ) { /* the constant term */
12090       if ( (v!=0)||(p==pp) ) {
12091          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, xord('+'));
12092          mp_print_scaled(mp, value(p));
12093       }
12094       return;
12095     }
12096     @<Print the coefficient, unless it's $\pm1.0$@>;
12097     if ( type(q)!=mp_independent ) mp_confusion(mp, "dep");
12098 @:this can't happen dep}{\quad dep@>
12099     mp_print_variable_name(mp, q); v=value(q) % s_scale;
12100     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
12101     p=mp_link(p);
12102   }
12103 }
12104
12105 @ @<Print the coefficient, unless it's $\pm1.0$@>=
12106 if ( value(p)<0 ) mp_print_char(mp, xord('-'));
12107 else if ( p!=pp ) mp_print_char(mp, xord('+'));
12108 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
12109 if ( v!=unity ) mp_print_scaled(mp, v)
12110
12111 @ The maximum absolute value of a coefficient in a given dependency list
12112 is returned by the following simple function.
12113
12114 @c 
12115 static fraction mp_max_coef (MP mp,pointer p) {
12116   fraction x; /* the maximum so far */
12117   x=0;
12118   while ( info(p)!=null ) {
12119     if ( abs(value(p))>x ) x=abs(value(p));
12120     p=mp_link(p);
12121   }
12122   return x;
12123 }
12124
12125 @ One of the main operations needed on dependency lists is to add a multiple
12126 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
12127 to dependency lists and |f| is a fraction.
12128
12129 If the coefficient of any independent variable becomes |coef_bound| or
12130 more, in absolute value, this procedure changes the type of that variable
12131 to `|independent_needing_fix|', and sets the global variable |fix_needed|
12132 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12133 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12134 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12135 2.3723$, the safer value 7/3 is taken as the threshold.)
12136
12137 The changes mentioned in the preceding paragraph are actually done only if
12138 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12139 it is |false| only when \MP\ is making a dependency list that will soon
12140 be equated to zero.
12141
12142 Several procedures that act on dependency lists, including |p_plus_fq|,
12143 set the global variable |dep_final| to the final (constant term) node of
12144 the dependency list that they produce.
12145
12146 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12147 @d independent_needing_fix 0
12148
12149 @<Glob...@>=
12150 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12151 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12152 pointer dep_final; /* location of the constant term and final link */
12153
12154 @ @<Set init...@>=
12155 mp->fix_needed=false; mp->watch_coefs=true;
12156
12157 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12158 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12159 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12160 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12161
12162 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12163
12164 The final link of the dependency list or proto-dependency list returned
12165 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12166 constant term of the result will be located in the same |mem| location
12167 as the original constant term of~|p|.
12168
12169 Coefficients of the result are assumed to be zero if they are less than
12170 a certain threshold. This compensates for inevitable rounding errors,
12171 and tends to make more variables `|known|'. The threshold is approximately
12172 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12173 proto-dependencies.
12174
12175 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12176 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12177 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12178 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12179
12180 @<Declarations@>=
12181 static pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12182                       pointer q, quarterword t, quarterword tt) ;
12183
12184 @ @c
12185 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12186                       pointer q, quarterword t, quarterword tt) {
12187   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12188   pointer r,s; /* for list manipulation */
12189   integer threshold; /* defines a neighborhood of zero */
12190   integer v; /* temporary register */
12191   if ( t==mp_dependent ) threshold=fraction_threshold;
12192   else threshold=scaled_threshold;
12193   r=temp_head; pp=info(p); qq=info(q);
12194   while (1) {
12195     if ( pp==qq ) {
12196       if ( pp==null ) {
12197        break;
12198       } else {
12199         @<Contribute a term from |p|, plus |f| times the
12200           corresponding term from |q|@>
12201       }
12202     } else if ( value(pp)<value(qq) ) {
12203       @<Contribute a term from |q|, multiplied by~|f|@>
12204     } else { 
12205      mp_link(r)=p; r=p; p=mp_link(p); pp=info(p);
12206     }
12207   }
12208   if ( t==mp_dependent )
12209     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12210   else  
12211     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12212   mp_link(r)=p; mp->dep_final=p; 
12213   return mp_link(temp_head);
12214 }
12215
12216 @ @<Contribute a term from |p|, plus |f|...@>=
12217
12218   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12219   else v=value(p)+mp_take_scaled(mp, f,value(q));
12220   value(p)=v; s=p; p=mp_link(p);
12221   if ( abs(v)<threshold ) {
12222     mp_free_node(mp, s,dep_node_size);
12223   } else {
12224     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12225       type(qq)=independent_needing_fix; mp->fix_needed=true;
12226     }
12227     mp_link(r)=s; r=s;
12228   };
12229   pp=info(p); q=mp_link(q); qq=info(q);
12230 }
12231
12232 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12233
12234   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12235   else v=mp_take_scaled(mp, f,value(q));
12236   if ( abs(v)>halfp(threshold) ) { 
12237     s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=v;
12238     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12239       type(qq)=independent_needing_fix; mp->fix_needed=true;
12240     }
12241     mp_link(r)=s; r=s;
12242   }
12243   q=mp_link(q); qq=info(q);
12244 }
12245
12246 @ It is convenient to have another subroutine for the special case
12247 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12248 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12249
12250 @c 
12251 static pointer mp_p_plus_q (MP mp,pointer p, pointer q, quarterword t) {
12252   pointer pp,qq; /* |info(p)| and |info(q)|, respectively */
12253   pointer r,s; /* for list manipulation */
12254   integer threshold; /* defines a neighborhood of zero */
12255   integer v; /* temporary register */
12256   if ( t==mp_dependent ) threshold=fraction_threshold;
12257   else threshold=scaled_threshold;
12258   r=temp_head; pp=info(p); qq=info(q);
12259   while (1) {
12260     if ( pp==qq ) {
12261       if ( pp==null ) {
12262         break;
12263       } else {
12264         @<Contribute a term from |p|, plus the
12265           corresponding term from |q|@>
12266       }
12267     } else { 
12268           if ( value(pp)<value(qq) ) {
12269         s=mp_get_node(mp, dep_node_size); info(s)=qq; value(s)=value(q);
12270         q=mp_link(q); qq=info(q); mp_link(r)=s; r=s;
12271       } else { 
12272         mp_link(r)=p; r=p; p=mp_link(p); pp=info(p);
12273       }
12274     }
12275   }
12276   value(p)=mp_slow_add(mp, value(p),value(q));
12277   mp_link(r)=p; mp->dep_final=p; 
12278   return mp_link(temp_head);
12279 }
12280
12281 @ @<Contribute a term from |p|, plus the...@>=
12282
12283   v=value(p)+value(q);
12284   value(p)=v; s=p; p=mp_link(p); pp=info(p);
12285   if ( abs(v)<threshold ) {
12286     mp_free_node(mp, s,dep_node_size);
12287   } else { 
12288     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12289       type(qq)=independent_needing_fix; mp->fix_needed=true;
12290     }
12291     mp_link(r)=s; r=s;
12292   }
12293   q=mp_link(q); qq=info(q);
12294 }
12295
12296 @ A somewhat simpler routine will multiply a dependency list
12297 by a given constant~|v|. The constant is either a |fraction| less than
12298 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12299 convert a dependency list to a proto-dependency list.
12300 Parameters |t0| and |t1| are the list types before and after;
12301 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12302 and |v_is_scaled=true|.
12303
12304 @c 
12305 static pointer mp_p_times_v (MP mp,pointer p, integer v, quarterword t0,
12306                          quarterword t1, boolean v_is_scaled) {
12307   pointer r,s; /* for list manipulation */
12308   integer w; /* tentative coefficient */
12309   integer threshold;
12310   boolean scaling_down;
12311   if ( t0!=t1 ) scaling_down=true; else scaling_down=(!v_is_scaled);
12312   if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12313   else threshold=half_scaled_threshold;
12314   r=temp_head;
12315   while ( info(p)!=null ) {    
12316     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12317     else w=mp_take_scaled(mp, v,value(p));
12318     if ( abs(w)<=threshold ) { 
12319       s=mp_link(p); mp_free_node(mp, p,dep_node_size); p=s;
12320     } else {
12321       if ( abs(w)>=coef_bound ) { 
12322         mp->fix_needed=true; type(info(p))=independent_needing_fix;
12323       }
12324       mp_link(r)=p; r=p; value(p)=w; p=mp_link(p);
12325     }
12326   }
12327   mp_link(r)=p;
12328   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12329   else value(p)=mp_take_fraction(mp, value(p),v);
12330   return mp_link(temp_head);
12331 }
12332
12333 @ Similarly, we sometimes need to divide a dependency list
12334 by a given |scaled| constant.
12335
12336 @<Declarations@>=
12337 static pointer mp_p_over_v (MP mp,pointer p, scaled v, quarterword 
12338   t0, quarterword t1) ;
12339
12340 @ @c
12341 pointer mp_p_over_v (MP mp,pointer p, scaled v, quarterword 
12342   t0, quarterword t1) {
12343   pointer r,s; /* for list manipulation */
12344   integer w; /* tentative coefficient */
12345   integer threshold;
12346   boolean scaling_down;
12347   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12348   if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12349   else threshold=half_scaled_threshold;
12350   r=temp_head;
12351   while ( info( p)!=null ) {
12352     if ( scaling_down ) {
12353       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12354       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12355     } else {
12356       w=mp_make_scaled(mp, value(p),v);
12357     }
12358     if ( abs(w)<=threshold ) {
12359       s=mp_link(p); mp_free_node(mp, p,dep_node_size); p=s;
12360     } else { 
12361       if ( abs(w)>=coef_bound ) {
12362          mp->fix_needed=true; type(info(p))=independent_needing_fix;
12363       }
12364       mp_link(r)=p; r=p; value(p)=w; p=mp_link(p);
12365     }
12366   }
12367   mp_link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12368   return mp_link(temp_head);
12369 }
12370
12371 @ Here's another utility routine for dependency lists. When an independent
12372 variable becomes dependent, we want to remove it from all existing
12373 dependencies. The |p_with_x_becoming_q| function computes the
12374 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12375
12376 This procedure has basically the same calling conventions as |p_plus_fq|:
12377 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12378 final link are inherited from~|p|; and the fourth parameter tells whether
12379 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12380 is not altered if |x| does not occur in list~|p|.
12381
12382 @c 
12383 static pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12384            pointer x, pointer q, quarterword t) {
12385   pointer r,s; /* for list manipulation */
12386   integer v; /* coefficient of |x| */
12387   integer sx; /* serial number of |x| */
12388   s=p; r=temp_head; sx=value(x);
12389   while ( value(info(s))>sx ) { r=s; s=mp_link(s); };
12390   if ( info(s)!=x ) { 
12391     return p;
12392   } else { 
12393     mp_link(temp_head)=p; mp_link(r)=mp_link(s); v=value(s);
12394     mp_free_node(mp, s,dep_node_size);
12395     return mp_p_plus_fq(mp, mp_link(temp_head),v,q,t,mp_dependent);
12396   }
12397 }
12398
12399 @ Here's a simple procedure that reports an error when a variable
12400 has just received a known value that's out of the required range.
12401
12402 @<Declarations@>=
12403 static void mp_val_too_big (MP mp,scaled x) ;
12404
12405 @ @c void mp_val_too_big (MP mp,scaled x) { 
12406   if ( mp->internal[mp_warning_check]>0 ) { 
12407     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, xord(')'));
12408 @.Value is too large@>
12409     help4("The equation I just processed has given some variable",
12410       "a value of 4096 or more. Continue and I'll try to cope",
12411       "with that big value; but it might be dangerous.",
12412       "(Set warningcheck:=0 to suppress this message.)");
12413     mp_error(mp);
12414   }
12415 }
12416
12417 @ When a dependent variable becomes known, the following routine
12418 removes its dependency list. Here |p| points to the variable, and
12419 |q| points to the dependency list (which is one node long).
12420
12421 @<Declarations@>=
12422 static void mp_make_known (MP mp,pointer p, pointer q) ;
12423
12424 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12425   int t; /* the previous type */
12426   prev_dep(mp_link(q))=prev_dep(p);
12427   mp_link(prev_dep(p))=mp_link(q); t=type(p);
12428   type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12429   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12430   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12431     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12432 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12433     mp_print_variable_name(mp, p); 
12434     mp_print_char(mp, xord('=')); mp_print_scaled(mp, value(p));
12435     mp_end_diagnostic(mp, false);
12436   }
12437   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12438     mp->cur_type=mp_known; mp->cur_exp=value(p);
12439     mp_free_node(mp, p,value_node_size);
12440   }
12441 }
12442
12443 @ The |fix_dependencies| routine is called into action when |fix_needed|
12444 has been triggered. The program keeps a list~|s| of independent variables
12445 whose coefficients must be divided by~4.
12446
12447 In unusual cases, this fixup process might reduce one or more coefficients
12448 to zero, so that a variable will become known more or less by default.
12449
12450 @<Declarations@>=
12451 static void mp_fix_dependencies (MP mp);
12452
12453 @ @c 
12454 static void mp_fix_dependencies (MP mp) {
12455   pointer p,q,r,s,t; /* list manipulation registers */
12456   pointer x; /* an independent variable */
12457   r=mp_link(dep_head); s=null;
12458   while ( r!=dep_head ){ 
12459     t=r;
12460     @<Run through the dependency list for variable |t|, fixing
12461       all nodes, and ending with final link~|q|@>;
12462     r=mp_link(q);
12463     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12464   }
12465   while ( s!=null ) { 
12466     p=mp_link(s); x=info(s); free_avail(s); s=p;
12467     type(x)=mp_independent; value(x)=value(x)+2;
12468   }
12469   mp->fix_needed=false;
12470 }
12471
12472 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12473
12474 @<Run through the dependency list for variable |t|...@>=
12475 r=value_loc(t); /* |mp_link(r)=dep_list(t)| */
12476 while (1) { 
12477   q=mp_link(r); x=info(q);
12478   if ( x==null ) break;
12479   if ( type(x)<=independent_being_fixed ) {
12480     if ( type(x)<independent_being_fixed ) {
12481       p=mp_get_avail(mp); mp_link(p)=s; s=p;
12482       info(s)=x; type(x)=independent_being_fixed;
12483     }
12484     value(q)=value(q) / 4;
12485     if ( value(q)==0 ) {
12486       mp_link(r)=mp_link(q); mp_free_node(mp, q,dep_node_size); q=r;
12487     }
12488   }
12489   r=q;
12490 }
12491
12492
12493 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12494 linking it into the list of all known dependencies. We assume that
12495 |dep_final| points to the final node of list~|p|.
12496
12497 @c 
12498 static void mp_new_dep (MP mp,pointer q, pointer p) {
12499   pointer r; /* what used to be the first dependency */
12500   dep_list(q)=p; prev_dep(q)=dep_head;
12501   r=mp_link(dep_head); mp_link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12502   mp_link(dep_head)=q;
12503 }
12504
12505 @ Here is one of the ways a dependency list gets started.
12506 The |const_dependency| routine produces a list that has nothing but
12507 a constant term.
12508
12509 @c static pointer mp_const_dependency (MP mp, scaled v) {
12510   mp->dep_final=mp_get_node(mp, dep_node_size);
12511   value(mp->dep_final)=v; info(mp->dep_final)=null;
12512   return mp->dep_final;
12513 }
12514
12515 @ And here's a more interesting way to start a dependency list from scratch:
12516 The parameter to |single_dependency| is the location of an
12517 independent variable~|x|, and the result is the simple dependency list
12518 `|x+0|'.
12519
12520 In the unlikely event that the given independent variable has been doubled so
12521 often that we can't refer to it with a nonzero coefficient,
12522 |single_dependency| returns the simple list `0'.  This case can be
12523 recognized by testing that the returned list pointer is equal to
12524 |dep_final|.
12525
12526 @c 
12527 static pointer mp_single_dependency (MP mp,pointer p) {
12528   pointer q; /* the new dependency list */
12529   integer m; /* the number of doublings */
12530   m=value(p) % s_scale;
12531   if ( m>28 ) {
12532     return mp_const_dependency(mp, 0);
12533   } else { 
12534     q=mp_get_node(mp, dep_node_size);
12535     value(q)=(integer)two_to_the(28-m); info(q)=p;
12536     mp_link(q)=mp_const_dependency(mp, 0);
12537     return q;
12538   }
12539 }
12540
12541 @ We sometimes need to make an exact copy of a dependency list.
12542
12543 @c 
12544 static pointer mp_copy_dep_list (MP mp,pointer p) {
12545   pointer q; /* the new dependency list */
12546   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12547   while (1) { 
12548     info(mp->dep_final)=info(p); value(mp->dep_final)=value(p);
12549     if ( info(mp->dep_final)==null ) break;
12550     mp_link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12551     mp->dep_final=mp_link(mp->dep_final); p=mp_link(p);
12552   }
12553   return q;
12554 }
12555
12556 @ But how do variables normally become known? Ah, now we get to the heart of the
12557 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12558 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12559 appears. It equates this list to zero, by choosing an independent variable
12560 with the largest coefficient and making it dependent on the others. The
12561 newly dependent variable is eliminated from all current dependencies,
12562 thereby possibly making other dependent variables known.
12563
12564 The given list |p| is, of course, totally destroyed by all this processing.
12565
12566 @c 
12567 static void mp_linear_eq (MP mp, pointer p, quarterword t) {
12568   pointer q,r,s; /* for link manipulation */
12569   pointer x; /* the variable that loses its independence */
12570   integer n; /* the number of times |x| had been halved */
12571   integer v; /* the coefficient of |x| in list |p| */
12572   pointer prev_r; /* lags one step behind |r| */
12573   pointer final_node; /* the constant term of the new dependency list */
12574   integer w; /* a tentative coefficient */
12575    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12576   x=info(q); n=value(x) % s_scale;
12577   @<Divide list |p| by |-v|, removing node |q|@>;
12578   if ( mp->internal[mp_tracing_equations]>0 ) {
12579     @<Display the new dependency@>;
12580   }
12581   @<Simplify all existing dependencies by substituting for |x|@>;
12582   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12583   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12584 }
12585
12586 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12587 q=p; r=mp_link(p); v=value(q);
12588 while ( info(r)!=null ) { 
12589   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12590   r=mp_link(r);
12591 }
12592
12593 @ Here we want to change the coefficients from |scaled| to |fraction|,
12594 except in the constant term. In the common case of a trivial equation
12595 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12596
12597 @<Divide list |p| by |-v|, removing node |q|@>=
12598 s=temp_head; mp_link(s)=p; r=p;
12599 do { 
12600   if ( r==q ) {
12601     mp_link(s)=mp_link(r); mp_free_node(mp, r,dep_node_size);
12602   } else  { 
12603     w=mp_make_fraction(mp, value(r),v);
12604     if ( abs(w)<=half_fraction_threshold ) {
12605       mp_link(s)=mp_link(r); mp_free_node(mp, r,dep_node_size);
12606     } else { 
12607       value(r)=-w; s=r;
12608     }
12609   }
12610   r=mp_link(s);
12611 } while (info(r)!=null);
12612 if ( t==mp_proto_dependent ) {
12613   value(r)=-mp_make_scaled(mp, value(r),v);
12614 } else if ( v!=-fraction_one ) {
12615   value(r)=-mp_make_fraction(mp, value(r),v);
12616 }
12617 final_node=r; p=mp_link(temp_head)
12618
12619 @ @<Display the new dependency@>=
12620 if ( mp_interesting(mp, x) ) {
12621   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12622   mp_print_variable_name(mp, x);
12623 @:]]]\#\#_}{\.{\#\#}@>
12624   w=n;
12625   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12626   mp_print_char(mp, xord('=')); mp_print_dependency(mp, p,mp_dependent); 
12627   mp_end_diagnostic(mp, false);
12628 }
12629
12630 @ @<Simplify all existing dependencies by substituting for |x|@>=
12631 prev_r=dep_head; r=mp_link(dep_head);
12632 while ( r!=dep_head ) {
12633   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,type(r));
12634   if ( info(q)==null ) {
12635     mp_make_known(mp, r,q);
12636   } else { 
12637     dep_list(r)=q;
12638     do {  q=mp_link(q); } while (info(q)!=null);
12639     prev_r=q;
12640   }
12641   r=mp_link(prev_r);
12642 }
12643
12644 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12645 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12646 if ( info(p)==null ) {
12647   type(x)=mp_known;
12648   value(x)=value(p);
12649   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12650   mp_free_node(mp, p,dep_node_size);
12651   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12652     mp->cur_exp=value(x); mp->cur_type=mp_known;
12653     mp_free_node(mp, x,value_node_size);
12654   }
12655 } else { 
12656   type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12657   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12658 }
12659
12660 @ @<Divide list |p| by $2^n$@>=
12661
12662   s=temp_head; mp_link(temp_head)=p; r=p;
12663   do {  
12664     if ( n>30 ) w=0;
12665     else w=value(r) / two_to_the(n);
12666     if ( (abs(w)<=half_fraction_threshold)&&(info(r)!=null) ) {
12667       mp_link(s)=mp_link(r);
12668       mp_free_node(mp, r,dep_node_size);
12669     } else { 
12670       value(r)=w; s=r;
12671     }
12672     r=mp_link(s);
12673   } while (info(s)!=null);
12674   p=mp_link(temp_head);
12675 }
12676
12677 @ The |check_mem| procedure, which is used only when \MP\ is being
12678 debugged, makes sure that the current dependency lists are well formed.
12679
12680 @<Check the list of linear dependencies@>=
12681 q=dep_head; p=mp_link(q);
12682 while ( p!=dep_head ) {
12683   if ( prev_dep(p)!=q ) {
12684     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12685 @.Bad PREVDEP...@>
12686   }
12687   p=dep_list(p);
12688   while (1) {
12689     r=info(p); q=p; p=mp_link(q);
12690     if ( r==null ) break;
12691     if ( value(info(p))>=value(r) ) {
12692       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12693 @.Out of order...@>
12694     }
12695   }
12696 }
12697
12698 @* \[25] Dynamic nonlinear equations.
12699 Variables of numeric type are maintained by the general scheme of
12700 independent, dependent, and known values that we have just studied;
12701 and the components of pair and transform variables are handled in the
12702 same way. But \MP\ also has five other types of values: \&{boolean},
12703 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12704
12705 Equations are allowed between nonlinear quantities, but only in a
12706 simple form. Two variables that haven't yet been assigned values are
12707 either equal to each other, or they're not.
12708
12709 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12710 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12711 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12712 |null| (which means that no other variables are equivalent to this one), or
12713 it points to another variable of the same undefined type. The pointers in the
12714 latter case form a cycle of nodes, which we shall call a ``ring.''
12715 Rings of undefined variables may include capsules, which arise as
12716 intermediate results within expressions or as \&{expr} parameters to macros.
12717
12718 When one member of a ring receives a value, the same value is given to
12719 all the other members. In the case of paths and pictures, this implies
12720 making separate copies of a potentially large data structure; users should
12721 restrain their enthusiasm for such generality, unless they have lots and
12722 lots of memory space.
12723
12724 @ The following procedure is called when a capsule node is being
12725 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12726
12727 @c 
12728 static pointer mp_new_ring_entry (MP mp,pointer p) {
12729   pointer q; /* the new capsule node */
12730   q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
12731   type(q)=type(p);
12732   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12733   value(p)=q;
12734   return q;
12735 }
12736
12737 @ Conversely, we might delete a capsule or a variable before it becomes known.
12738 The following procedure simply detaches a quantity from its ring,
12739 without recycling the storage.
12740
12741 @<Declarations@>=
12742 static void mp_ring_delete (MP mp,pointer p);
12743
12744 @ @c
12745 void mp_ring_delete (MP mp,pointer p) {
12746   pointer q; 
12747   q=value(p);
12748   if ( q!=null ) if ( q!=p ){ 
12749     while ( value(q)!=p ) q=value(q);
12750     value(q)=value(p);
12751   }
12752 }
12753
12754 @ Eventually there might be an equation that assigns values to all of the
12755 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12756 propagation of values.
12757
12758 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12759 value, it will soon be recycled.
12760
12761 @c 
12762 static void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12763   quarterword t; /* the type of ring |p| */
12764   pointer q,r; /* link manipulation registers */
12765   t=type(p)-unknown_tag; q=value(p);
12766   if ( flush_p ) type(p)=mp_vacuous; else p=q;
12767   do {  
12768     r=value(q); type(q)=t;
12769     switch (t) {
12770     case mp_boolean_type: value(q)=v; break;
12771     case mp_string_type: value(q)=v; add_str_ref(v); break;
12772     case mp_pen_type: value(q)=copy_pen(v); break;
12773     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12774     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12775     } /* there ain't no more cases */
12776     q=r;
12777   } while (q!=p);
12778 }
12779
12780 @ If two members of rings are equated, and if they have the same type,
12781 the |ring_merge| procedure is called on to make them equivalent.
12782
12783 @c 
12784 static void mp_ring_merge (MP mp,pointer p, pointer q) {
12785   pointer r; /* traverses one list */
12786   r=value(p);
12787   while ( r!=p ) {
12788     if ( r==q ) {
12789       @<Exclaim about a redundant equation@>;
12790       return;
12791     };
12792     r=value(r);
12793   }
12794   r=value(p); value(p)=value(q); value(q)=r;
12795 }
12796
12797 @ @<Exclaim about a redundant equation@>=
12798
12799   print_err("Redundant equation");
12800 @.Redundant equation@>
12801   help2("I already knew that this equation was true.",
12802         "But perhaps no harm has been done; let's continue.");
12803   mp_put_get_error(mp);
12804 }
12805
12806 @* \[26] Introduction to the syntactic routines.
12807 Let's pause a moment now and try to look at the Big Picture.
12808 The \MP\ program consists of three main parts: syntactic routines,
12809 semantic routines, and output routines. The chief purpose of the
12810 syntactic routines is to deliver the user's input to the semantic routines,
12811 while parsing expressions and locating operators and operands. The
12812 semantic routines act as an interpreter responding to these operators,
12813 which may be regarded as commands. And the output routines are
12814 periodically called on to produce compact font descriptions that can be
12815 used for typesetting or for making interim proof drawings. We have
12816 discussed the basic data structures and many of the details of semantic
12817 operations, so we are good and ready to plunge into the part of \MP\ that
12818 actually controls the activities.
12819
12820 Our current goal is to come to grips with the |get_next| procedure,
12821 which is the keystone of \MP's input mechanism. Each call of |get_next|
12822 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12823 representing the next input token.
12824 $$\vbox{\halign{#\hfil\cr
12825   \hbox{|cur_cmd| denotes a command code from the long list of codes
12826    given earlier;}\cr
12827   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12828   \hbox{|cur_sym| is the hash address of the symbolic token that was
12829    just scanned,}\cr
12830   \hbox{\qquad or zero in the case of a numeric or string
12831    or capsule token.}\cr}}$$
12832 Underlying this external behavior of |get_next| is all the machinery
12833 necessary to convert from character files to tokens. At a given time we
12834 may be only partially finished with the reading of several files (for
12835 which \&{input} was specified), and partially finished with the expansion
12836 of some user-defined macros and/or some macro parameters, and partially
12837 finished reading some text that the user has inserted online,
12838 and so on. When reading a character file, the characters must be
12839 converted to tokens; comments and blank spaces must
12840 be removed, numeric and string tokens must be evaluated.
12841
12842 To handle these situations, which might all be present simultaneously,
12843 \MP\ uses various stacks that hold information about the incomplete
12844 activities, and there is a finite state control for each level of the
12845 input mechanism. These stacks record the current state of an implicitly
12846 recursive process, but the |get_next| procedure is not recursive.
12847
12848 @<Glob...@>=
12849 integer cur_cmd; /* current command set by |get_next| */
12850 integer cur_mod; /* operand of current command */
12851 halfword cur_sym; /* hash address of current symbol */
12852
12853 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12854 command code and its modifier.
12855 It consists of a rather tedious sequence of print
12856 commands, and most of it is essentially an inverse to the |primitive|
12857 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12858 all of this procedure appears elsewhere in the program, together with the
12859 corresponding |primitive| calls.
12860
12861 @<Declarations@>=
12862 static void mp_print_cmd_mod (MP mp,integer c, integer m) ;
12863
12864 @ @c
12865 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12866  switch (c) {
12867   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12868   default: mp_print(mp, "[unknown command code!]"); break;
12869   }
12870 }
12871
12872 @ Here is a procedure that displays a given command in braces, in the
12873 user's transcript file.
12874
12875 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12876
12877 @c 
12878 static void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12879   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12880   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, xord('}'));
12881   mp_end_diagnostic(mp, false);
12882 }
12883
12884 @* \[27] Input stacks and states.
12885 The state of \MP's input mechanism appears in the input stack, whose
12886 entries are records with five fields, called |index|, |start|, |loc|,
12887 |limit|, and |name|. The top element of this stack is maintained in a
12888 global variable for which no subscripting needs to be done; the other
12889 elements of the stack appear in an array. Hence the stack is declared thus:
12890
12891 @<Types...@>=
12892 typedef struct {
12893   quarterword index_field;
12894   halfword start_field, loc_field, limit_field, name_field;
12895 } in_state_record;
12896
12897 @ @<Glob...@>=
12898 in_state_record *input_stack;
12899 integer input_ptr; /* first unused location of |input_stack| */
12900 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12901 in_state_record cur_input; /* the ``top'' input state */
12902 int stack_size; /* maximum number of simultaneous input sources */
12903
12904 @ @<Allocate or initialize ...@>=
12905 mp->stack_size = 300;
12906 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12907
12908 @ @<Dealloc variables@>=
12909 xfree(mp->input_stack);
12910
12911 @ We've already defined the special variable |loc==cur_input.loc_field|
12912 in our discussion of basic input-output routines. The other components of
12913 |cur_input| are defined in the same way:
12914
12915 @d iindex mp->cur_input.index_field /* reference for buffer information */
12916 @d start mp->cur_input.start_field /* starting position in |buffer| */
12917 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12918 @d name mp->cur_input.name_field /* name of the current file */
12919
12920 @ Let's look more closely now at the five control variables
12921 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12922 assuming that \MP\ is reading a line of characters that have been input
12923 from some file or from the user's terminal. There is an array called
12924 |buffer| that acts as a stack of all lines of characters that are
12925 currently being read from files, including all lines on subsidiary
12926 levels of the input stack that are not yet completed. \MP\ will return to
12927 the other lines when it is finished with the present input file.
12928
12929 (Incidentally, on a machine with byte-oriented addressing, it would be
12930 appropriate to combine |buffer| with the |str_pool| array,
12931 letting the buffer entries grow downward from the top of the string pool
12932 and checking that these two tables don't bump into each other.)
12933
12934 The line we are currently working on begins in position |start| of the
12935 buffer; the next character we are about to read is |buffer[loc]|; and
12936 |limit| is the location of the last character present. We always have
12937 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12938 that the end of a line is easily sensed.
12939
12940 The |name| variable is a string number that designates the name of
12941 the current file, if we are reading an ordinary text file.  Special codes
12942 |is_term..max_spec_src| indicate other sources of input text.
12943
12944 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12945 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12946 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12947 @d max_spec_src is_scantok
12948
12949 @ Additional information about the current line is available via the
12950 |index| variable, which counts how many lines of characters are present
12951 in the buffer below the current level. We have |index=0| when reading
12952 from the terminal and prompting the user for each line; then if the user types,
12953 e.g., `\.{input figs}', we will have |index=1| while reading
12954 the file \.{figs.mp}. However, it does not follow that |index| is the
12955 same as the input stack pointer, since many of the levels on the input
12956 stack may come from token lists and some |index| values may correspond
12957 to \.{MPX} files that are not currently on the stack.
12958
12959 The global variable |in_open| is equal to the highest |index| value counting
12960 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12961 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12962 when we are not reading a token list.
12963
12964 If we are not currently reading from the terminal,
12965 we are reading from the file variable |input_file[index]|. We use
12966 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12967 and |cur_file| as an abbreviation for |input_file[index]|.
12968
12969 When \MP\ is not reading from the terminal, the global variable |line| contains
12970 the line number in the current file, for use in error messages. More precisely,
12971 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12972 the line number for each file in the |input_file| array.
12973
12974 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12975 array so that the name doesn't get lost when the file is temporarily removed
12976 from the input stack.
12977 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12978 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12979 Since this is not an \.{MPX} file, we have
12980 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12981 This |name| field is set to |finished| when |input_file[k]| is completely
12982 read.
12983
12984 If more information about the input state is needed, it can be
12985 included in small arrays like those shown here. For example,
12986 the current page or segment number in the input file might be put
12987 into a variable |page|, that is really a macro for the current entry
12988 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12989 by analogy with |line_stack|.
12990 @^system dependencies@>
12991
12992 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12993 @d cur_file mp->input_file[iindex] /* the current |void *| variable */
12994 @d line mp->line_stack[iindex] /* current line number in the current source file */
12995 @d in_name mp->iname_stack[iindex] /* a string used to construct \.{MPX} file names */
12996 @d in_area mp->iarea_stack[iindex] /* another string for naming \.{MPX} files */
12997 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12998 @d mpx_reading (mp->mpx_name[iindex]>absent)
12999   /* when reading a file, is it an \.{MPX} file? */
13000 @d mpx_finished 0
13001   /* |name_field| value when the corresponding \.{MPX} file is finished */
13002
13003 @<Glob...@>=
13004 integer in_open; /* the number of lines in the buffer, less one */
13005 unsigned int open_parens; /* the number of open text files */
13006 void  * *input_file ;
13007 integer *line_stack ; /* the line number for each file */
13008 char *  *iname_stack; /* used for naming \.{MPX} files */
13009 char *  *iarea_stack; /* used for naming \.{MPX} files */
13010 halfword*mpx_name  ;
13011
13012 @ @<Allocate or ...@>=
13013 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
13014 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
13015 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
13016 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
13017 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
13018 {
13019   int k;
13020   for (k=0;k<=mp->max_in_open;k++) {
13021     mp->iname_stack[k] =NULL;
13022     mp->iarea_stack[k] =NULL;
13023   }
13024 }
13025
13026 @ @<Dealloc variables@>=
13027 {
13028   int l;
13029   for (l=0;l<=mp->max_in_open;l++) {
13030     xfree(mp->iname_stack[l]);
13031     xfree(mp->iarea_stack[l]);
13032   }
13033 }
13034 xfree(mp->input_file);
13035 xfree(mp->line_stack);
13036 xfree(mp->iname_stack);
13037 xfree(mp->iarea_stack);
13038 xfree(mp->mpx_name);
13039
13040
13041 @ However, all this discussion about input state really applies only to the
13042 case that we are inputting from a file. There is another important case,
13043 namely when we are currently getting input from a token list. In this case
13044 |iindex>max_in_open|, and the conventions about the other state variables
13045 are different:
13046
13047 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
13048 the node that will be read next. If |loc=null|, the token list has been
13049 fully read.
13050
13051 \yskip\hang|start| points to the first node of the token list; this node
13052 may or may not contain a reference count, depending on the type of token
13053 list involved.
13054
13055 \yskip\hang|token_type|, which takes the place of |iindex| in the
13056 discussion above, is a code number that explains what kind of token list
13057 is being scanned.
13058
13059 \yskip\hang|name| points to the |eqtb| address of the control sequence
13060 being expanded, if the current token list is a macro not defined by
13061 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
13062 can be deduced by looking at their first two parameters.
13063
13064 \yskip\hang|param_start|, which takes the place of |limit|, tells where
13065 the parameters of the current macro or loop text begin in the |param_stack|.
13066
13067 \yskip\noindent The |token_type| can take several values, depending on
13068 where the current token list came from:
13069
13070 \yskip
13071 \indent|forever_text|, if the token list being scanned is the body of
13072 a \&{forever} loop;
13073
13074 \indent|loop_text|, if the token list being scanned is the body of
13075 a \&{for} or \&{forsuffixes} loop;
13076
13077 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
13078
13079 \indent|backed_up|, if the token list being scanned has been inserted as
13080 `to be read again'.
13081
13082 \indent|inserted|, if the token list being scanned has been inserted as
13083 part of error recovery;
13084
13085 \indent|macro|, if the expansion of a user-defined symbolic token is being
13086 scanned.
13087
13088 \yskip\noindent
13089 The token list begins with a reference count if and only if |token_type=
13090 macro|.
13091 @^reference counts@>
13092
13093 @d token_type iindex /* type of current token list */
13094 @d token_state (iindex>(int)mp->max_in_open) /* are we scanning a token list? */
13095 @d file_state (iindex<=(int)mp->max_in_open) /* are we scanning a file line? */
13096 @d param_start limit /* base of macro parameters in |param_stack| */
13097 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
13098 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
13099 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
13100 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
13101 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
13102 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
13103
13104 @ The |param_stack| is an auxiliary array used to hold pointers to the token
13105 lists for parameters at the current level and subsidiary levels of input.
13106 This stack grows at a different rate from the others.
13107
13108 @<Glob...@>=
13109 pointer *param_stack;  /* token list pointers for parameters */
13110 integer param_ptr; /* first unused entry in |param_stack| */
13111 integer max_param_stack;  /* largest value of |param_ptr| */
13112
13113 @ @<Allocate or initialize ...@>=
13114 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
13115
13116 @ @<Dealloc variables@>=
13117 xfree(mp->param_stack);
13118
13119 @ Notice that the |line| isn't valid when |token_state| is true because it
13120 depends on |iindex|.  If we really need to know the line number for the
13121 topmost file in the iindex stack we use the following function.  If a page
13122 number or other information is needed, this routine should be modified to
13123 compute it as well.
13124 @^system dependencies@>
13125
13126 @<Declarations@>=
13127 static integer mp_true_line (MP mp) ;
13128
13129 @ @c
13130 integer mp_true_line (MP mp) {
13131   int k; /* an index into the input stack */
13132   if ( file_state && (name>max_spec_src) ) {
13133     return line;
13134   } else { 
13135     k=mp->input_ptr;
13136     while ((k>0) &&
13137            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
13138             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
13139       decr(k);
13140     }
13141     return (k>0 ? mp->line_stack[(k-1)] : 0 );
13142   }
13143 }
13144
13145 @ Thus, the ``current input state'' can be very complicated indeed; there
13146 can be many levels and each level can arise in a variety of ways. The
13147 |show_context| procedure, which is used by \MP's error-reporting routine to
13148 print out the current input state on all levels down to the most recent
13149 line of characters from an input file, illustrates most of these conventions.
13150 The global variable |file_ptr| contains the lowest level that was
13151 displayed by this procedure.
13152
13153 @<Glob...@>=
13154 integer file_ptr; /* shallowest level shown by |show_context| */
13155
13156 @ The status at each level is indicated by printing two lines, where the first
13157 line indicates what was read so far and the second line shows what remains
13158 to be read. The context is cropped, if necessary, so that the first line
13159 contains at most |half_error_line| characters, and the second contains
13160 at most |error_line|. Non-current input levels whose |token_type| is
13161 `|backed_up|' are shown only if they have not been fully read.
13162
13163 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13164   unsigned old_setting; /* saved |selector| setting */
13165   @<Local variables for formatting calculations@>
13166   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13167   /* store current state */
13168   while (1) { 
13169     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13170     @<Display the current context@>;
13171     if ( file_state )
13172       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13173     decr(mp->file_ptr);
13174   }
13175   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13176 }
13177
13178 @ @<Display the current context@>=
13179 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13180    (token_type!=backed_up) || (loc!=null) ) {
13181     /* we omit backed-up token lists that have already been read */
13182   mp->tally=0; /* get ready to count characters */
13183   old_setting=mp->selector;
13184   if ( file_state ) {
13185     @<Print location of current line@>;
13186     @<Pseudoprint the line@>;
13187   } else { 
13188     @<Print type of token list@>;
13189     @<Pseudoprint the token list@>;
13190   }
13191   mp->selector=old_setting; /* stop pseudoprinting */
13192   @<Print two lines using the tricky pseudoprinted information@>;
13193 }
13194
13195 @ This routine should be changed, if necessary, to give the best possible
13196 indication of where the current line resides in the input file.
13197 For example, on some systems it is best to print both a page and line number.
13198 @^system dependencies@>
13199
13200 @<Print location of current line@>=
13201 if ( name>max_spec_src ) {
13202   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13203 } else if ( terminal_input ) {
13204   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13205   else mp_print_nl(mp, "<insert>");
13206 } else if ( name==is_scantok ) {
13207   mp_print_nl(mp, "<scantokens>");
13208 } else {
13209   mp_print_nl(mp, "<read>");
13210 }
13211 mp_print_char(mp, xord(' '))
13212
13213 @ Can't use case statement here because the |token_type| is not
13214 a constant expression.
13215
13216 @<Print type of token list@>=
13217 {
13218   if(token_type==forever_text) {
13219     mp_print_nl(mp, "<forever> ");
13220   } else if (token_type==loop_text) {
13221     @<Print the current loop value@>;
13222   } else if (token_type==parameter) {
13223     mp_print_nl(mp, "<argument> "); 
13224   } else if (token_type==backed_up) { 
13225     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13226     else mp_print_nl(mp, "<to be read again> ");
13227   } else if (token_type==inserted) {
13228     mp_print_nl(mp, "<inserted text> ");
13229   } else if (token_type==macro) {
13230     mp_print_ln(mp);
13231     if ( name!=null ) mp_print_text(name);
13232     else @<Print the name of a \&{vardef}'d macro@>;
13233     mp_print(mp, "->");
13234   } else {
13235     mp_print_nl(mp, "?");/* this should never happen */
13236 @.?\relax@>
13237   }
13238 }
13239
13240 @ The parameter that corresponds to a loop text is either a token list
13241 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13242 We'll discuss capsules later; for now, all we need to know is that
13243 the |link| field in a capsule parameter is |void| and that
13244 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13245
13246 @<Print the current loop value@>=
13247 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13248   if ( p!=null ) {
13249     if ( mp_link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13250     else mp_show_token_list(mp, p,null,20,mp->tally);
13251   }
13252   mp_print(mp, ")> ");
13253 }
13254
13255 @ The first two parameters of a macro defined by \&{vardef} will be token
13256 lists representing the macro's prefix and ``at point.'' By putting these
13257 together, we get the macro's full name.
13258
13259 @<Print the name of a \&{vardef}'d macro@>=
13260 { p=mp->param_stack[param_start];
13261   if ( p==null ) {
13262     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13263   } else { 
13264     q=p;
13265     while ( mp_link(q)!=null ) q=mp_link(q);
13266     mp_link(q)=mp->param_stack[param_start+1];
13267     mp_show_token_list(mp, p,null,20,mp->tally);
13268     mp_link(q)=null;
13269   }
13270 }
13271
13272 @ Now it is necessary to explain a little trick. We don't want to store a long
13273 string that corresponds to a token list, because that string might take up
13274 lots of memory; and we are printing during a time when an error message is
13275 being given, so we dare not do anything that might overflow one of \MP's
13276 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13277 that stores characters into a buffer of length |error_line|, where character
13278 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13279 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13280 |tally:=0| and |trick_count:=1000000|; then when we reach the
13281 point where transition from line 1 to line 2 should occur, we
13282 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13283 tally+1+error_line-half_error_line)|. At the end of the
13284 pseudoprinting, the values of |first_count|, |tally|, and
13285 |trick_count| give us all the information we need to print the two lines,
13286 and all of the necessary text is in |trick_buf|.
13287
13288 Namely, let |l| be the length of the descriptive information that appears
13289 on the first line. The length of the context information gathered for that
13290 line is |k=first_count|, and the length of the context information
13291 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13292 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13293 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13294 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13295 and print `\.{...}' followed by
13296 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13297 where subscripts of |trick_buf| are circular modulo |error_line|. The
13298 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13299 unless |n+m>error_line|; in the latter case, further cropping is done.
13300 This is easier to program than to explain.
13301
13302 @<Local variables for formatting...@>=
13303 int i; /* index into |buffer| */
13304 integer l; /* length of descriptive information on line 1 */
13305 integer m; /* context information gathered for line 2 */
13306 int n; /* length of line 1 */
13307 integer p; /* starting or ending place in |trick_buf| */
13308 integer q; /* temporary index */
13309
13310 @ The following code tells the print routines to gather
13311 the desired information.
13312
13313 @d begin_pseudoprint { 
13314   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13315   mp->trick_count=1000000;
13316 }
13317 @d set_trick_count {
13318   mp->first_count=mp->tally;
13319   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13320   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13321 }
13322
13323 @ And the following code uses the information after it has been gathered.
13324
13325 @<Print two lines using the tricky pseudoprinted information@>=
13326 if ( mp->trick_count==1000000 ) set_trick_count;
13327   /* |set_trick_count| must be performed */
13328 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13329 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13330 if ( l+mp->first_count<=mp->half_error_line ) {
13331   p=0; n=l+mp->first_count;
13332 } else  { 
13333   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13334   n=mp->half_error_line;
13335 }
13336 for (q=p;q<=mp->first_count-1;q++) {
13337   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13338 }
13339 mp_print_ln(mp);
13340 for (q=1;q<=n;q++) {
13341   mp_print_char(mp, xord(' ')); /* print |n| spaces to begin line~2 */
13342 }
13343 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13344 else p=mp->first_count+(mp->error_line-n-3);
13345 for (q=mp->first_count;q<=p-1;q++) {
13346   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13347 }
13348 if ( m+n>mp->error_line ) mp_print(mp, "...")
13349
13350 @ But the trick is distracting us from our current goal, which is to
13351 understand the input state. So let's concentrate on the data structures that
13352 are being pseudoprinted as we finish up the |show_context| procedure.
13353
13354 @<Pseudoprint the line@>=
13355 begin_pseudoprint;
13356 if ( limit>0 ) {
13357   for (i=start;i<=limit-1;i++) {
13358     if ( i==loc ) set_trick_count;
13359     mp_print_str(mp, mp->buffer[i]);
13360   }
13361 }
13362
13363 @ @<Pseudoprint the token list@>=
13364 begin_pseudoprint;
13365 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13366 else mp_show_macro(mp, start,loc,100000)
13367
13368 @ Here is the missing piece of |show_token_list| that is activated when the
13369 token beginning line~2 is about to be shown:
13370
13371 @<Do magic computation@>=set_trick_count
13372
13373 @* \[28] Maintaining the input stacks.
13374 The following subroutines change the input status in commonly needed ways.
13375
13376 First comes |push_input|, which stores the current state and creates a
13377 new level (having, initially, the same properties as the old).
13378
13379 @d push_input  { /* enter a new input level, save the old */
13380   if ( mp->input_ptr>mp->max_in_stack ) {
13381     mp->max_in_stack=mp->input_ptr;
13382     if ( mp->input_ptr==mp->stack_size ) {
13383       int l = (mp->stack_size+(mp->stack_size/4));
13384       XREALLOC(mp->input_stack, l, in_state_record);
13385       mp->stack_size = l;
13386     }         
13387   }
13388   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13389   incr(mp->input_ptr);
13390 }
13391
13392 @ And of course what goes up must come down.
13393
13394 @d pop_input { /* leave an input level, re-enter the old */
13395     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13396   }
13397
13398 @ Here is a procedure that starts a new level of token-list input, given
13399 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13400 set |name|, reset~|loc|, and increase the macro's reference count.
13401
13402 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13403
13404 @c 
13405 static void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13406   push_input; start=p; token_type=t;
13407   param_start=mp->param_ptr; loc=p;
13408 }
13409
13410 @ When a token list has been fully scanned, the following computations
13411 should be done as we leave that level of input.
13412 @^inner loop@>
13413
13414 @c 
13415 static void mp_end_token_list (MP mp) { /* leave a token-list input level */
13416   pointer p; /* temporary register */
13417   if ( token_type>=backed_up ) { /* token list to be deleted */
13418     if ( token_type<=inserted ) { 
13419       mp_flush_token_list(mp, start); goto DONE;
13420     } else {
13421       mp_delete_mac_ref(mp, start); /* update reference count */
13422     }
13423   }
13424   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13425     decr(mp->param_ptr);
13426     p=mp->param_stack[mp->param_ptr];
13427     if ( p!=null ) {
13428       if ( mp_link(p)==mp_void ) { /* it's an \&{expr} parameter */
13429         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13430       } else {
13431         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13432       }
13433     }
13434   }
13435 DONE: 
13436   pop_input; check_interrupt;
13437 }
13438
13439 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13440 token by the |cur_tok| routine.
13441 @^inner loop@>
13442
13443 @c @<Declare the procedure called |make_exp_copy|@>
13444 static pointer mp_cur_tok (MP mp) {
13445   pointer p; /* a new token node */
13446   quarterword save_type; /* |cur_type| to be restored */
13447   integer save_exp; /* |cur_exp| to be restored */
13448   if ( mp->cur_sym==0 ) {
13449     if ( mp->cur_cmd==capsule_token ) {
13450       save_type=mp->cur_type; save_exp=mp->cur_exp;
13451       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); mp_link(p)=null;
13452       mp->cur_type=save_type; mp->cur_exp=save_exp;
13453     } else { 
13454       p=mp_get_node(mp, token_node_size);
13455       value(p)=mp->cur_mod; name_type(p)=mp_token;
13456       if ( mp->cur_cmd==numeric_token ) type(p)=mp_known;
13457       else type(p)=mp_string_type;
13458     }
13459   } else { 
13460     fast_get_avail(p); info(p)=mp->cur_sym;
13461   }
13462   return p;
13463 }
13464
13465 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13466 seen. The |back_input| procedure takes care of this by putting the token
13467 just scanned back into the input stream, ready to be read again.
13468 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13469
13470 @<Declarations@>= 
13471 static void mp_back_input (MP mp);
13472
13473 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13474   pointer p; /* a token list of length one */
13475   p=mp_cur_tok(mp);
13476   while ( token_state &&(loc==null) ) 
13477     mp_end_token_list(mp); /* conserve stack space */
13478   back_list(p);
13479 }
13480
13481 @ The |back_error| routine is used when we want to restore or replace an
13482 offending token just before issuing an error message.  We disable interrupts
13483 during the call of |back_input| so that the help message won't be lost.
13484
13485 @ @c static void mp_back_error (MP mp) { /* back up one token and call |error| */
13486   mp->OK_to_interrupt=false; 
13487   mp_back_input(mp); 
13488   mp->OK_to_interrupt=true; mp_error(mp);
13489 }
13490 static void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13491   mp->OK_to_interrupt=false; 
13492   mp_back_input(mp); token_type=inserted;
13493   mp->OK_to_interrupt=true; mp_error(mp);
13494 }
13495
13496 @ The |begin_file_reading| procedure starts a new level of input for lines
13497 of characters to be read from a file, or as an insertion from the
13498 terminal. It does not take care of opening the file, nor does it set |loc|
13499 or |limit| or |line|.
13500 @^system dependencies@>
13501
13502 @c void mp_begin_file_reading (MP mp) { 
13503   if ( mp->in_open==mp->max_in_open ) 
13504     mp_overflow(mp, "text input levels",mp->max_in_open);
13505 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13506   if ( mp->first==mp->buf_size ) 
13507     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
13508   incr(mp->in_open); push_input; iindex=mp->in_open;
13509   mp->mpx_name[iindex]=absent;
13510   start=(halfword)mp->first;
13511   name=is_term; /* |terminal_input| is now |true| */
13512 }
13513
13514 @ Conversely, the variables must be downdated when such a level of input
13515 is finished.  Any associated \.{MPX} file must also be closed and popped
13516 off the file stack.
13517
13518 @c static void mp_end_file_reading (MP mp) { 
13519   if ( mp->in_open>iindex ) {
13520     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13521       mp_confusion(mp, "endinput");
13522 @:this can't happen endinput}{\quad endinput@>
13523     } else { 
13524       (mp->close_file)(mp,mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13525       delete_str_ref(mp->mpx_name[mp->in_open]);
13526       decr(mp->in_open);
13527     }
13528   }
13529   mp->first=(size_t)start;
13530   if ( iindex!=mp->in_open ) mp_confusion(mp, "endinput");
13531   if ( name>max_spec_src ) {
13532     (mp->close_file)(mp,cur_file);
13533     delete_str_ref(name);
13534     xfree(in_name); 
13535     xfree(in_area);
13536   }
13537   pop_input; decr(mp->in_open);
13538 }
13539
13540 @ Here is a function that tries to resume input from an \.{MPX} file already
13541 associated with the current input file.  It returns |false| if this doesn't
13542 work.
13543
13544 @c static boolean mp_begin_mpx_reading (MP mp) { 
13545   if ( mp->in_open!=iindex+1 ) {
13546      return false;
13547   } else { 
13548     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13549 @:this can't happen mpx}{\quad mpx@>
13550     if ( mp->first==mp->buf_size ) 
13551       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
13552     push_input; iindex=mp->in_open;
13553     start=(halfword)mp->first;
13554     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13555     @<Put an empty line in the input buffer@>;
13556     return true;
13557   }
13558 }
13559
13560 @ This procedure temporarily stops reading an \.{MPX} file.
13561
13562 @c static void mp_end_mpx_reading (MP mp) { 
13563   if ( mp->in_open!=iindex ) mp_confusion(mp, "mpx");
13564 @:this can't happen mpx}{\quad mpx@>
13565   if ( loc<limit ) {
13566     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13567   }
13568   mp->first=(size_t)start;
13569   pop_input;
13570 }
13571
13572 @ Here we enforce a restriction that simplifies the input stacks considerably.
13573 This should not inconvenience the user because \.{MPX} files are generated
13574 by an auxiliary program called \.{DVItoMP}.
13575
13576 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13577
13578 print_err("`mpxbreak' must be at the end of a line");
13579 help4("This file contains picture expressions for btex...etex",
13580   "blocks.  Such files are normally generated automatically",
13581   "but this one seems to be messed up.  I'm going to ignore",
13582   "the rest of this line.");
13583 mp_error(mp);
13584 }
13585
13586 @ In order to keep the stack from overflowing during a long sequence of
13587 inserted `\.{show}' commands, the following routine removes completed
13588 error-inserted lines from memory.
13589
13590 @c void mp_clear_for_error_prompt (MP mp) { 
13591   while ( file_state && terminal_input &&
13592     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13593   mp_print_ln(mp); clear_terminal;
13594 }
13595
13596 @ To get \MP's whole input mechanism going, we perform the following
13597 actions.
13598
13599 @<Initialize the input routines@>=
13600 { mp->input_ptr=0; mp->max_in_stack=0;
13601   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13602   mp->param_ptr=0; mp->max_param_stack=0;
13603   mp->first=1;
13604   start=1; iindex=0; line=0; name=is_term;
13605   mp->mpx_name[0]=absent;
13606   mp->force_eof=false;
13607   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13608   limit=(halfword)mp->last; mp->first=mp->last+1; 
13609   /* |init_terminal| has set |loc| and |last| */
13610 }
13611
13612 @* \[29] Getting the next token.
13613 The heart of \MP's input mechanism is the |get_next| procedure, which
13614 we shall develop in the next few sections of the program. Perhaps we
13615 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13616 eyes and mouth, reading the source files and gobbling them up. And it also
13617 helps \MP\ to regurgitate stored token lists that are to be processed again.
13618
13619 The main duty of |get_next| is to input one token and to set |cur_cmd|
13620 and |cur_mod| to that token's command code and modifier. Furthermore, if
13621 the input token is a symbolic token, that token's |hash| address
13622 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13623
13624 Underlying this simple description is a certain amount of complexity
13625 because of all the cases that need to be handled.
13626 However, the inner loop of |get_next| is reasonably short and fast.
13627
13628 @ Before getting into |get_next|, we need to consider a mechanism by which
13629 \MP\ helps keep errors from propagating too far. Whenever the program goes
13630 into a mode where it keeps calling |get_next| repeatedly until a certain
13631 condition is met, it sets |scanner_status| to some value other than |normal|.
13632 Then if an input file ends, or if an `\&{outer}' symbol appears,
13633 an appropriate error recovery will be possible.
13634
13635 The global variable |warning_info| helps in this error recovery by providing
13636 additional information. For example, |warning_info| might indicate the
13637 name of a macro whose replacement text is being scanned.
13638
13639 @d normal 0 /* |scanner_status| at ``quiet times'' */
13640 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13641 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13642 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13643 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13644 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13645 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13646 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13647
13648 @<Glob...@>=
13649 integer scanner_status; /* are we scanning at high speed? */
13650 integer warning_info; /* if so, what else do we need to know,
13651     in case an error occurs? */
13652
13653 @ @<Initialize the input routines@>=
13654 mp->scanner_status=normal;
13655
13656 @ The following subroutine
13657 is called when an `\&{outer}' symbolic token has been scanned or
13658 when the end of a file has been reached. These two cases are distinguished
13659 by |cur_sym|, which is zero at the end of a file.
13660
13661 @c
13662 static boolean mp_check_outer_validity (MP mp) {
13663   pointer p; /* points to inserted token list */
13664   if ( mp->scanner_status==normal ) {
13665     return true;
13666   } else if ( mp->scanner_status==tex_flushing ) {
13667     @<Check if the file has ended while flushing \TeX\ material and set the
13668       result value for |check_outer_validity|@>;
13669   } else { 
13670     mp->deletions_allowed=false;
13671     @<Back up an outer symbolic token so that it can be reread@>;
13672     if ( mp->scanner_status>skipping ) {
13673       @<Tell the user what has run away and try to recover@>;
13674     } else { 
13675       print_err("Incomplete if; all text was ignored after line ");
13676 @.Incomplete if...@>
13677       mp_print_int(mp, mp->warning_info);
13678       help3("A forbidden `outer' token occurred in skipped text.",
13679         "This kind of error happens when you say `if...' and forget",
13680         "the matching `fi'. I've inserted a `fi'; this might work.");
13681       if ( mp->cur_sym==0 ) 
13682         mp->help_line[2]="The file ended while I was skipping conditional text.";
13683       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13684     }
13685     mp->deletions_allowed=true; 
13686         return false;
13687   }
13688 }
13689
13690 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13691 if ( mp->cur_sym!=0 ) { 
13692    return true;
13693 } else { 
13694   mp->deletions_allowed=false;
13695   print_err("TeX mode didn't end; all text was ignored after line ");
13696   mp_print_int(mp, mp->warning_info);
13697   help2("The file ended while I was looking for the `etex' to",
13698         "finish this TeX material.  I've inserted `etex' now.");
13699   mp->cur_sym = frozen_etex;
13700   mp_ins_error(mp);
13701   mp->deletions_allowed=true;
13702   return false;
13703 }
13704
13705 @ @<Back up an outer symbolic token so that it can be reread@>=
13706 if ( mp->cur_sym!=0 ) {
13707   p=mp_get_avail(mp); info(p)=mp->cur_sym;
13708   back_list(p); /* prepare to read the symbolic token again */
13709 }
13710
13711 @ @<Tell the user what has run away...@>=
13712
13713   mp_runaway(mp); /* print the definition-so-far */
13714   if ( mp->cur_sym==0 ) {
13715     print_err("File ended");
13716 @.File ended while scanning...@>
13717   } else { 
13718     print_err("Forbidden token found");
13719 @.Forbidden token found...@>
13720   }
13721   mp_print(mp, " while scanning ");
13722   help4("I suspect you have forgotten an `enddef',",
13723     "causing me to read past where you wanted me to stop.",
13724     "I'll try to recover; but if the error is serious,",
13725     "you'd better type `E' or `X' now and fix your file.");
13726   switch (mp->scanner_status) {
13727     @<Complete the error message,
13728       and set |cur_sym| to a token that might help recover from the error@>
13729   } /* there are no other cases */
13730   mp_ins_error(mp);
13731 }
13732
13733 @ As we consider various kinds of errors, it is also appropriate to
13734 change the first line of the help message just given; |help_line[3]|
13735 points to the string that might be changed.
13736
13737 @<Complete the error message,...@>=
13738 case flushing: 
13739   mp_print(mp, "to the end of the statement");
13740   mp->help_line[3]="A previous error seems to have propagated,";
13741   mp->cur_sym=frozen_semicolon;
13742   break;
13743 case absorbing: 
13744   mp_print(mp, "a text argument");
13745   mp->help_line[3]="It seems that a right delimiter was left out,";
13746   if ( mp->warning_info==0 ) {
13747     mp->cur_sym=frozen_end_group;
13748   } else { 
13749     mp->cur_sym=frozen_right_delimiter;
13750     equiv(frozen_right_delimiter)=mp->warning_info;
13751   }
13752   break;
13753 case var_defining:
13754 case op_defining: 
13755   mp_print(mp, "the definition of ");
13756   if ( mp->scanner_status==op_defining ) 
13757      mp_print_text(mp->warning_info);
13758   else 
13759      mp_print_variable_name(mp, mp->warning_info);
13760   mp->cur_sym=frozen_end_def;
13761   break;
13762 case loop_defining: 
13763   mp_print(mp, "the text of a "); 
13764   mp_print_text(mp->warning_info);
13765   mp_print(mp, " loop");
13766   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13767   mp->cur_sym=frozen_end_for;
13768   break;
13769
13770 @ The |runaway| procedure displays the first part of the text that occurred
13771 when \MP\ began its special |scanner_status|, if that text has been saved.
13772
13773 @<Declarations@>=
13774 static void mp_runaway (MP mp) ;
13775
13776 @ @c
13777 void mp_runaway (MP mp) { 
13778   if ( mp->scanner_status>flushing ) { 
13779      mp_print_nl(mp, "Runaway ");
13780          switch (mp->scanner_status) { 
13781          case absorbing: mp_print(mp, "text?"); break;
13782          case var_defining: 
13783      case op_defining: mp_print(mp,"definition?"); break;
13784      case loop_defining: mp_print(mp, "loop?"); break;
13785      } /* there are no other cases */
13786      mp_print_ln(mp); 
13787      mp_show_token_list(mp, mp_link(hold_head),null,mp->error_line-10,0);
13788   }
13789 }
13790
13791 @ We need to mention a procedure that may be called by |get_next|.
13792
13793 @<Declarations@>= 
13794 static void mp_firm_up_the_line (MP mp);
13795
13796 @ And now we're ready to take the plunge into |get_next| itself.
13797 Note that the behavior depends on the |scanner_status| because percent signs
13798 and double quotes need to be passed over when skipping TeX material.
13799
13800 @c 
13801 void mp_get_next (MP mp) {
13802   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13803 @^inner loop@>
13804   /*restart*/ /* go here to get the next input token */
13805   /*exit*/ /* go here when the next input token has been got */
13806   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13807   /*found*/ /* go here when the end of a symbolic token has been found */
13808   /*switch*/ /* go here to branch on the class of an input character */
13809   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13810     /* go here at crucial stages when scanning a number */
13811   int k; /* an index into |buffer| */
13812   ASCII_code c; /* the current character in the buffer */
13813   int class; /* its class number */
13814   integer n,f; /* registers for decimal-to-binary conversion */
13815 RESTART: 
13816   mp->cur_sym=0;
13817   if ( file_state ) {
13818     @<Input from external file; |goto restart| if no input found,
13819     or |return| if a non-symbolic token is found@>;
13820   } else {
13821     @<Input from token list; |goto restart| if end of list or
13822       if a parameter needs to be expanded,
13823       or |return| if a non-symbolic token is found@>;
13824   }
13825 COMMON_ENDING: 
13826   @<Finish getting the symbolic token in |cur_sym|;
13827    |goto restart| if it is illegal@>;
13828 }
13829
13830 @ When a symbolic token is declared to be `\&{outer}', its command code
13831 is increased by |outer_tag|.
13832 @^inner loop@>
13833
13834 @<Finish getting the symbolic token in |cur_sym|...@>=
13835 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13836 if ( mp->cur_cmd>=outer_tag ) {
13837   if ( mp_check_outer_validity(mp) ) 
13838     mp->cur_cmd=mp->cur_cmd-outer_tag;
13839   else 
13840     goto RESTART;
13841 }
13842
13843 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13844 to have a special test for end-of-line.
13845 @^inner loop@>
13846
13847 @<Input from external file;...@>=
13848
13849 SWITCH: 
13850   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13851   switch (class) {
13852   case digit_class: goto START_NUMERIC_TOKEN; break;
13853   case period_class: 
13854     class=mp->char_class[mp->buffer[loc]];
13855     if ( class>period_class ) {
13856       goto SWITCH;
13857     } else if ( class<period_class ) { /* |class=digit_class| */
13858       n=0; goto START_DECIMAL_TOKEN;
13859     }
13860 @:. }{\..\ token@>
13861     break;
13862   case space_class: goto SWITCH; break;
13863   case percent_class: 
13864     if ( mp->scanner_status==tex_flushing ) {
13865       if ( loc<limit ) goto SWITCH;
13866     }
13867     @<Move to next line of file, or |goto restart| if there is no next line@>;
13868     check_interrupt;
13869     goto SWITCH;
13870     break;
13871   case string_class: 
13872     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13873     else @<Get a string token and |return|@>;
13874     break;
13875   case isolated_classes: 
13876     k=loc-1; goto FOUND; break;
13877   case invalid_class: 
13878     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13879     else @<Decry the invalid character and |goto restart|@>;
13880     break;
13881   default: break; /* letters, etc. */
13882   }
13883   k=loc-1;
13884   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13885   goto FOUND;
13886 START_NUMERIC_TOKEN:
13887   @<Get the integer part |n| of a numeric token;
13888     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13889 START_DECIMAL_TOKEN:
13890   @<Get the fraction part |f| of a numeric token@>;
13891 FIN_NUMERIC_TOKEN:
13892   @<Pack the numeric and fraction parts of a numeric token
13893     and |return|@>;
13894 FOUND: 
13895   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13896 }
13897
13898 @ We go to |restart| instead of to |SWITCH|, because we might enter
13899 |token_state| after the error has been dealt with
13900 (cf.\ |clear_for_error_prompt|).
13901
13902 @<Decry the invalid...@>=
13903
13904   print_err("Text line contains an invalid character");
13905 @.Text line contains...@>
13906   help2("A funny symbol that I can\'t read has just been input.",
13907         "Continue, and I'll forget that it ever happened.");
13908   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13909   goto RESTART;
13910 }
13911
13912 @ @<Get a string token and |return|@>=
13913
13914   if ( mp->buffer[loc]=='"' ) {
13915     mp->cur_mod=null_str;
13916   } else { 
13917     k=loc; mp->buffer[limit+1]=xord('"');
13918     do {  
13919      incr(loc);
13920     } while (mp->buffer[loc]!='"');
13921     if ( loc>limit ) {
13922       @<Decry the missing string delimiter and |goto restart|@>;
13923     }
13924     if ( loc==k+1 ) {
13925       mp->cur_mod=mp->buffer[k];
13926     } else { 
13927       str_room(loc-k);
13928       do {  
13929         append_char(mp->buffer[k]); incr(k);
13930       } while (k!=loc);
13931       mp->cur_mod=mp_make_string(mp);
13932     }
13933   }
13934   incr(loc); mp->cur_cmd=string_token; 
13935   return;
13936 }
13937
13938 @ We go to |restart| after this error message, not to |SWITCH|,
13939 because the |clear_for_error_prompt| routine might have reinstated
13940 |token_state| after |error| has finished.
13941
13942 @<Decry the missing string delimiter and |goto restart|@>=
13943
13944   loc=limit; /* the next character to be read on this line will be |"%"| */
13945   print_err("Incomplete string token has been flushed");
13946 @.Incomplete string token...@>
13947   help3("Strings should finish on the same line as they began.",
13948     "I've deleted the partial string; you might want to",
13949     "insert another by typing, e.g., `I\"new string\"'.");
13950   mp->deletions_allowed=false; mp_error(mp);
13951   mp->deletions_allowed=true; 
13952   goto RESTART;
13953 }
13954
13955 @ @<Get the integer part |n| of a numeric token...@>=
13956 n=c-'0';
13957 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13958   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13959   incr(loc);
13960 }
13961 if ( mp->buffer[loc]=='.' ) 
13962   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13963     goto DONE;
13964 f=0; 
13965 goto FIN_NUMERIC_TOKEN;
13966 DONE: incr(loc)
13967
13968 @ @<Get the fraction part |f| of a numeric token@>=
13969 k=0;
13970 do { 
13971   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13972     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13973   }
13974   incr(loc);
13975 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13976 f=mp_round_decimals(mp, k);
13977 if ( f==unity ) {
13978   incr(n); f=0;
13979 }
13980
13981 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13982 if ( n<32768 ) {
13983   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13984 } else if ( mp->scanner_status!=tex_flushing ) {
13985   print_err("Enormous number has been reduced");
13986 @.Enormous number...@>
13987   help2("I can\'t handle numbers bigger than 32767.99998;",
13988         "so I've changed your constant to that maximum amount.");
13989   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13990   mp->cur_mod=el_gordo;
13991 }
13992 mp->cur_cmd=numeric_token; return
13993
13994 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13995
13996   mp->cur_mod=n*unity+f;
13997   if ( mp->cur_mod>=fraction_one ) {
13998     if ( (mp->internal[mp_warning_check]>0) &&
13999          (mp->scanner_status!=tex_flushing) ) {
14000       print_err("Number is too large (");
14001       mp_print_scaled(mp, mp->cur_mod);
14002       mp_print_char(mp, xord(')'));
14003       help3("It is at least 4096. Continue and I'll try to cope",
14004       "with that big value; but it might be dangerous.",
14005       "(Set warningcheck:=0 to suppress this message.)");
14006       mp_error(mp);
14007     }
14008   }
14009 }
14010
14011 @ Let's consider now what happens when |get_next| is looking at a token list.
14012 @^inner loop@>
14013
14014 @<Input from token list;...@>=
14015 if ( loc>=mp->hi_mem_min ) { /* one-word token */
14016   mp->cur_sym=info(loc); loc=mp_link(loc); /* move to next */
14017   if ( mp->cur_sym>=expr_base ) {
14018     if ( mp->cur_sym>=suffix_base ) {
14019       @<Insert a suffix or text parameter and |goto restart|@>;
14020     } else { 
14021       mp->cur_cmd=capsule_token;
14022       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
14023       mp->cur_sym=0; return;
14024     }
14025   }
14026 } else if ( loc>null ) {
14027   @<Get a stored numeric or string or capsule token and |return|@>
14028 } else { /* we are done with this token list */
14029   mp_end_token_list(mp); goto RESTART; /* resume previous level */
14030 }
14031
14032 @ @<Insert a suffix or text parameter...@>=
14033
14034   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
14035   /* |param_size=text_base-suffix_base| */
14036   mp_begin_token_list(mp,
14037                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
14038                       parameter);
14039   goto RESTART;
14040 }
14041
14042 @ @<Get a stored numeric or string or capsule token...@>=
14043
14044   if ( name_type(loc)==mp_token ) {
14045     mp->cur_mod=value(loc);
14046     if ( type(loc)==mp_known ) {
14047       mp->cur_cmd=numeric_token;
14048     } else { 
14049       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
14050     }
14051   } else { 
14052     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
14053   };
14054   loc=mp_link(loc); return;
14055 }
14056
14057 @ All of the easy branches of |get_next| have now been taken care of.
14058 There is one more branch.
14059
14060 @<Move to next line of file, or |goto restart|...@>=
14061 if ( name>max_spec_src) {
14062   @<Read next line of file into |buffer|, or
14063     |goto restart| if the file has ended@>;
14064 } else { 
14065   if ( mp->input_ptr>0 ) {
14066      /* text was inserted during error recovery or by \&{scantokens} */
14067     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
14068   }
14069   if (mp->job_name == NULL && ( mp->selector<log_only || mp->selector>=write_file))  
14070     mp_open_log_file(mp);
14071   if ( mp->interaction>mp_nonstop_mode ) {
14072     if ( limit==start ) /* previous line was empty */
14073       mp_print_nl(mp, "(Please type a command or say `end')");
14074 @.Please type...@>
14075     mp_print_ln(mp); mp->first=(size_t)start;
14076     prompt_input("*"); /* input on-line into |buffer| */
14077 @.*\relax@>
14078     limit=(halfword)mp->last; mp->buffer[limit]=xord('%');
14079     mp->first=(size_t)(limit+1); loc=start;
14080   } else {
14081     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
14082 @.job aborted@>
14083     /* nonstop mode, which is intended for overnight batch processing,
14084        never waits for on-line input */
14085   }
14086 }
14087
14088 @ The global variable |force_eof| is normally |false|; it is set |true|
14089 by an \&{endinput} command.
14090
14091 @<Glob...@>=
14092 boolean force_eof; /* should the next \&{input} be aborted early? */
14093
14094 @ We must decrement |loc| in order to leave the buffer in a valid state
14095 when an error condition causes us to |goto restart| without calling
14096 |end_file_reading|.
14097
14098 @<Read next line of file into |buffer|, or
14099   |goto restart| if the file has ended@>=
14100
14101   incr(line); mp->first=(size_t)start;
14102   if ( ! mp->force_eof ) {
14103     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
14104       mp_firm_up_the_line(mp); /* this sets |limit| */
14105     else 
14106       mp->force_eof=true;
14107   };
14108   if ( mp->force_eof ) {
14109     mp->force_eof=false;
14110     decr(loc);
14111     if ( mpx_reading ) {
14112       @<Complain that the \.{MPX} file ended unexpectly; then set
14113         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
14114     } else { 
14115       mp_print_char(mp, xord(')')); decr(mp->open_parens);
14116       update_terminal; /* show user that file has been read */
14117       mp_end_file_reading(mp); /* resume previous level */
14118       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
14119       else goto RESTART;
14120     }
14121   }
14122   mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start; /* ready to read */
14123 }
14124
14125 @ We should never actually come to the end of an \.{MPX} file because such
14126 files should have an \&{mpxbreak} after the translation of the last
14127 \&{btex}$\,\ldots\,$\&{etex} block.
14128
14129 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
14130
14131   mp->mpx_name[iindex]=mpx_finished;
14132   print_err("mpx file ended unexpectedly");
14133   help4("The file had too few picture expressions for btex...etex",
14134     "blocks.  Such files are normally generated automatically",
14135     "but this one got messed up.  You might want to insert a",
14136     "picture expression now.");
14137   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
14138   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
14139 }
14140
14141 @ Sometimes we want to make it look as though we have just read a blank line
14142 without really doing so.
14143
14144 @<Put an empty line in the input buffer@>=
14145 mp->last=mp->first; limit=(halfword)mp->last; 
14146   /* simulate |input_ln| and |firm_up_the_line| */
14147 mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start
14148
14149 @ If the user has set the |mp_pausing| parameter to some positive value,
14150 and if nonstop mode has not been selected, each line of input is displayed
14151 on the terminal and the transcript file, followed by `\.{=>}'.
14152 \MP\ waits for a response. If the response is null (i.e., if nothing is
14153 typed except perhaps a few blank spaces), the original
14154 line is accepted as it stands; otherwise the line typed is
14155 used instead of the line in the file.
14156
14157 @c void mp_firm_up_the_line (MP mp) {
14158   size_t k; /* an index into |buffer| */
14159   limit=(halfword)mp->last;
14160   if ((!mp->noninteractive)   
14161       && (mp->internal[mp_pausing]>0 )
14162       && (mp->interaction>mp_nonstop_mode )) {
14163     wake_up_terminal; mp_print_ln(mp);
14164     if ( start<limit ) {
14165       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14166         mp_print_str(mp, mp->buffer[k]);
14167       } 
14168     }
14169     mp->first=(size_t)limit; prompt_input("=>"); /* wait for user response */
14170 @.=>@>
14171     if ( mp->last>mp->first ) {
14172       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14173         mp->buffer[k+start-mp->first]=mp->buffer[k];
14174       }
14175       limit=(halfword)(start+mp->last-mp->first);
14176     }
14177   }
14178 }
14179
14180 @* \[30] Dealing with \TeX\ material.
14181 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14182 features need to be implemented at a low level in the scanning process
14183 so that \MP\ can stay in synch with the a preprocessor that treats
14184 blocks of \TeX\ material as they occur in the input file without trying
14185 to expand \MP\ macros.  Thus we need a special version of |get_next|
14186 that does not expand macros and such but does handle \&{btex},
14187 \&{verbatimtex}, etc.
14188
14189 The special version of |get_next| is called |get_t_next|.  It works by flushing
14190 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14191 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14192 \&{btex}, and switching back when it sees \&{mpxbreak}.
14193
14194 @d btex_code 0
14195 @d verbatim_code 1
14196
14197 @ @<Put each...@>=
14198 mp_primitive(mp, "btex",start_tex,btex_code);
14199 @:btex_}{\&{btex} primitive@>
14200 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14201 @:verbatimtex_}{\&{verbatimtex} primitive@>
14202 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14203 @:etex_}{\&{etex} primitive@>
14204 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14205 @:mpx_break_}{\&{mpxbreak} primitive@>
14206
14207 @ @<Cases of |print_cmd...@>=
14208 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14209   else mp_print(mp, "verbatimtex"); break;
14210 case etex_marker: mp_print(mp, "etex"); break;
14211 case mpx_break: mp_print(mp, "mpxbreak"); break;
14212
14213 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14214 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14215 is encountered.
14216
14217 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14218
14219 @<Declarations@>=
14220 static void mp_start_mpx_input (MP mp);
14221
14222 @ @c 
14223 static void mp_t_next (MP mp) {
14224   int old_status; /* saves the |scanner_status| */
14225   integer old_info; /* saves the |warning_info| */
14226   while ( mp->cur_cmd<=max_pre_command ) {
14227     if ( mp->cur_cmd==mpx_break ) {
14228       if ( ! file_state || (mp->mpx_name[iindex]==absent) ) {
14229         @<Complain about a misplaced \&{mpxbreak}@>;
14230       } else { 
14231         mp_end_mpx_reading(mp); 
14232         goto TEX_FLUSH;
14233       }
14234     } else if ( mp->cur_cmd==start_tex ) {
14235       if ( token_state || (name<=max_spec_src) ) {
14236         @<Complain that we are not reading a file@>;
14237       } else if ( mpx_reading ) {
14238         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14239       } else if ( (mp->cur_mod!=verbatim_code)&&
14240                   (mp->mpx_name[iindex]!=mpx_finished) ) {
14241         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14242       } else {
14243         goto TEX_FLUSH;
14244       }
14245     } else {
14246        @<Complain about a misplaced \&{etex}@>;
14247     }
14248     goto COMMON_ENDING;
14249   TEX_FLUSH: 
14250     @<Flush the \TeX\ material@>;
14251   COMMON_ENDING: 
14252     mp_get_next(mp);
14253   }
14254 }
14255
14256 @ We could be in the middle of an operation such as skipping false conditional
14257 text when \TeX\ material is encountered, so we must be careful to save the
14258 |scanner_status|.
14259
14260 @<Flush the \TeX\ material@>=
14261 old_status=mp->scanner_status;
14262 old_info=mp->warning_info;
14263 mp->scanner_status=tex_flushing;
14264 mp->warning_info=line;
14265 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14266 mp->scanner_status=old_status;
14267 mp->warning_info=old_info
14268
14269 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14270 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14271 help4("This file contains picture expressions for btex...etex",
14272   "blocks.  Such files are normally generated automatically",
14273   "but this one seems to be messed up.  I'll just keep going",
14274   "and hope for the best.");
14275 mp_error(mp);
14276 }
14277
14278 @ @<Complain that we are not reading a file@>=
14279 { print_err("You can only use `btex' or `verbatimtex' in a file");
14280 help3("I'll have to ignore this preprocessor command because it",
14281   "only works when there is a file to preprocess.  You might",
14282   "want to delete everything up to the next `etex`.");
14283 mp_error(mp);
14284 }
14285
14286 @ @<Complain about a misplaced \&{mpxbreak}@>=
14287 { print_err("Misplaced mpxbreak");
14288 help2("I'll ignore this preprocessor command because it",
14289       "doesn't belong here");
14290 mp_error(mp);
14291 }
14292
14293 @ @<Complain about a misplaced \&{etex}@>=
14294 { print_err("Extra etex will be ignored");
14295 help1("There is no btex or verbatimtex for this to match");
14296 mp_error(mp);
14297 }
14298
14299 @* \[31] Scanning macro definitions.
14300 \MP\ has a variety of ways to tuck tokens away into token lists for later
14301 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14302 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14303 All such operations are handled by the routines in this part of the program.
14304
14305 The modifier part of each command code is zero for the ``ending delimiters''
14306 like \&{enddef} and \&{endfor}.
14307
14308 @d start_def 1 /* command modifier for \&{def} */
14309 @d var_def 2 /* command modifier for \&{vardef} */
14310 @d end_def 0 /* command modifier for \&{enddef} */
14311 @d start_forever 1 /* command modifier for \&{forever} */
14312 @d end_for 0 /* command modifier for \&{endfor} */
14313
14314 @<Put each...@>=
14315 mp_primitive(mp, "def",macro_def,start_def);
14316 @:def_}{\&{def} primitive@>
14317 mp_primitive(mp, "vardef",macro_def,var_def);
14318 @:var_def_}{\&{vardef} primitive@>
14319 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14320 @:primary_def_}{\&{primarydef} primitive@>
14321 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14322 @:secondary_def_}{\&{secondarydef} primitive@>
14323 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14324 @:tertiary_def_}{\&{tertiarydef} primitive@>
14325 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14326 @:end_def_}{\&{enddef} primitive@>
14327 @#
14328 mp_primitive(mp, "for",iteration,expr_base);
14329 @:for_}{\&{for} primitive@>
14330 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14331 @:for_suffixes_}{\&{forsuffixes} primitive@>
14332 mp_primitive(mp, "forever",iteration,start_forever);
14333 @:forever_}{\&{forever} primitive@>
14334 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14335 @:end_for_}{\&{endfor} primitive@>
14336
14337 @ @<Cases of |print_cmd...@>=
14338 case macro_def:
14339   if ( m<=var_def ) {
14340     if ( m==start_def ) mp_print(mp, "def");
14341     else if ( m<start_def ) mp_print(mp, "enddef");
14342     else mp_print(mp, "vardef");
14343   } else if ( m==secondary_primary_macro ) { 
14344     mp_print(mp, "primarydef");
14345   } else if ( m==tertiary_secondary_macro ) { 
14346     mp_print(mp, "secondarydef");
14347   } else { 
14348     mp_print(mp, "tertiarydef");
14349   }
14350   break;
14351 case iteration: 
14352   if ( m<=start_forever ) {
14353     if ( m==start_forever ) mp_print(mp, "forever"); 
14354     else mp_print(mp, "endfor");
14355   } else if ( m==expr_base ) {
14356     mp_print(mp, "for"); 
14357   } else { 
14358     mp_print(mp, "forsuffixes");
14359   }
14360   break;
14361
14362 @ Different macro-absorbing operations have different syntaxes, but they
14363 also have a lot in common. There is a list of special symbols that are to
14364 be replaced by parameter tokens; there is a special command code that
14365 ends the definition; the quotation conventions are identical.  Therefore
14366 it makes sense to have most of the work done by a single subroutine. That
14367 subroutine is called |scan_toks|.
14368
14369 The first parameter to |scan_toks| is the command code that will
14370 terminate scanning (either |macro_def| or |iteration|).
14371
14372 The second parameter, |subst_list|, points to a (possibly empty) list
14373 of two-word nodes whose |info| and |value| fields specify symbol tokens
14374 before and after replacement. The list will be returned to free storage
14375 by |scan_toks|.
14376
14377 The third parameter is simply appended to the token list that is built.
14378 And the final parameter tells how many of the special operations
14379 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14380 When such parameters are present, they are called \.{(SUFFIX0)},
14381 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14382
14383 @c static pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14384   subst_list, pointer tail_end, quarterword suffix_count) {
14385   pointer p; /* tail of the token list being built */
14386   pointer q; /* temporary for link management */
14387   integer balance; /* left delimiters minus right delimiters */
14388   p=hold_head; balance=1; mp_link(hold_head)=null;
14389   while (1) { 
14390     get_t_next;
14391     if ( mp->cur_sym>0 ) {
14392       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14393       if ( mp->cur_cmd==terminator ) {
14394         @<Adjust the balance; |break| if it's zero@>;
14395       } else if ( mp->cur_cmd==macro_special ) {
14396         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14397       }
14398     }
14399     mp_link(p)=mp_cur_tok(mp); p=mp_link(p);
14400   }
14401   mp_link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14402   return mp_link(hold_head);
14403 }
14404
14405 @ @<Substitute for |cur_sym|...@>=
14406
14407   q=subst_list;
14408   while ( q!=null ) {
14409     if ( info(q)==mp->cur_sym ) {
14410       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14411     }
14412     q=mp_link(q);
14413   }
14414 }
14415
14416 @ @<Adjust the balance; |break| if it's zero@>=
14417 if ( mp->cur_mod>0 ) {
14418   incr(balance);
14419 } else { 
14420   decr(balance);
14421   if ( balance==0 )
14422     break;
14423 }
14424
14425 @ Four commands are intended to be used only within macro texts: \&{quote},
14426 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14427 code called |macro_special|.
14428
14429 @d quote 0 /* |macro_special| modifier for \&{quote} */
14430 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14431 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14432 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14433
14434 @<Put each...@>=
14435 mp_primitive(mp, "quote",macro_special,quote);
14436 @:quote_}{\&{quote} primitive@>
14437 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14438 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14439 mp_primitive(mp, "@@",macro_special,macro_at);
14440 @:]]]\AT!_}{\.{\AT!} primitive@>
14441 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14442 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14443
14444 @ @<Cases of |print_cmd...@>=
14445 case macro_special: 
14446   switch (m) {
14447   case macro_prefix: mp_print(mp, "#@@"); break;
14448   case macro_at: mp_print_char(mp, xord('@@')); break;
14449   case macro_suffix: mp_print(mp, "@@#"); break;
14450   default: mp_print(mp, "quote"); break;
14451   }
14452   break;
14453
14454 @ @<Handle quoted...@>=
14455
14456   if ( mp->cur_mod==quote ) { get_t_next; } 
14457   else if ( mp->cur_mod<=suffix_count ) 
14458     mp->cur_sym=suffix_base-1+mp->cur_mod;
14459 }
14460
14461 @ Here is a routine that's used whenever a token will be redefined. If
14462 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14463 substituted; the latter is redefinable but essentially impossible to use,
14464 hence \MP's tables won't get fouled up.
14465
14466 @c static void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14467 RESTART: 
14468   get_t_next;
14469   if ( (mp->cur_sym==0)||(mp->cur_sym>(integer)frozen_inaccessible) ) {
14470     print_err("Missing symbolic token inserted");
14471 @.Missing symbolic token...@>
14472     help3("Sorry: You can\'t redefine a number, string, or expr.",
14473       "I've inserted an inaccessible symbol so that your",
14474       "definition will be completed without mixing me up too badly.");
14475     if ( mp->cur_sym>0 )
14476       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14477     else if ( mp->cur_cmd==string_token ) 
14478       delete_str_ref(mp->cur_mod);
14479     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14480   }
14481 }
14482
14483 @ Before we actually redefine a symbolic token, we need to clear away its
14484 former value, if it was a variable. The following stronger version of
14485 |get_symbol| does that.
14486
14487 @c static void mp_get_clear_symbol (MP mp) { 
14488   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14489 }
14490
14491 @ Here's another little subroutine; it checks that an equals sign
14492 or assignment sign comes along at the proper place in a macro definition.
14493
14494 @c static void mp_check_equals (MP mp) { 
14495   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14496      mp_missing_err(mp, "=");
14497 @.Missing `='@>
14498     help5("The next thing in this `def' should have been `=',",
14499           "because I've already looked at the definition heading.",
14500           "But don't worry; I'll pretend that an equals sign",
14501           "was present. Everything from here to `enddef'",
14502           "will be the replacement text of this macro.");
14503     mp_back_error(mp);
14504   }
14505 }
14506
14507 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14508 handled now that we have |scan_toks|.  In this case there are
14509 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14510 |expr_base| and |expr_base+1|).
14511
14512 @c static void mp_make_op_def (MP mp) {
14513   command_code m; /* the type of definition */
14514   pointer p,q,r; /* for list manipulation */
14515   m=mp->cur_mod;
14516   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14517   info(q)=mp->cur_sym; value(q)=expr_base;
14518   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14519   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14520   info(p)=mp->cur_sym; value(p)=expr_base+1; mp_link(p)=q;
14521   get_t_next; mp_check_equals(mp);
14522   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14523   r=mp_get_avail(mp); mp_link(q)=r; info(r)=general_macro;
14524   mp_link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14525   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14526   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14527 }
14528
14529 @ Parameters to macros are introduced by the keywords \&{expr},
14530 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14531
14532 @<Put each...@>=
14533 mp_primitive(mp, "expr",param_type,expr_base);
14534 @:expr_}{\&{expr} primitive@>
14535 mp_primitive(mp, "suffix",param_type,suffix_base);
14536 @:suffix_}{\&{suffix} primitive@>
14537 mp_primitive(mp, "text",param_type,text_base);
14538 @:text_}{\&{text} primitive@>
14539 mp_primitive(mp, "primary",param_type,primary_macro);
14540 @:primary_}{\&{primary} primitive@>
14541 mp_primitive(mp, "secondary",param_type,secondary_macro);
14542 @:secondary_}{\&{secondary} primitive@>
14543 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14544 @:tertiary_}{\&{tertiary} primitive@>
14545
14546 @ @<Cases of |print_cmd...@>=
14547 case param_type:
14548   if ( m>=expr_base ) {
14549     if ( m==expr_base ) mp_print(mp, "expr");
14550     else if ( m==suffix_base ) mp_print(mp, "suffix");
14551     else mp_print(mp, "text");
14552   } else if ( m<secondary_macro ) {
14553     mp_print(mp, "primary");
14554   } else if ( m==secondary_macro ) {
14555     mp_print(mp, "secondary");
14556   } else {
14557     mp_print(mp, "tertiary");
14558   }
14559   break;
14560
14561 @ Let's turn next to the more complex processing associated with \&{def}
14562 and \&{vardef}. When the following procedure is called, |cur_mod|
14563 should be either |start_def| or |var_def|.
14564
14565 @c 
14566 static void mp_scan_def (MP mp) {
14567   int m; /* the type of definition */
14568   int n; /* the number of special suffix parameters */
14569   int k; /* the total number of parameters */
14570   int c; /* the kind of macro we're defining */
14571   pointer r; /* parameter-substitution list */
14572   pointer q; /* tail of the macro token list */
14573   pointer p; /* temporary storage */
14574   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14575   pointer l_delim,r_delim; /* matching delimiters */
14576   m=mp->cur_mod; c=general_macro; mp_link(hold_head)=null;
14577   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14578   @<Scan the token or variable to be defined;
14579     set |n|, |scanner_status|, and |warning_info|@>;
14580   k=n;
14581   if ( mp->cur_cmd==left_delimiter ) {
14582     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14583   }
14584   if ( mp->cur_cmd==param_type ) {
14585     @<Absorb undelimited parameters, putting them into list |r|@>;
14586   }
14587   mp_check_equals(mp);
14588   p=mp_get_avail(mp); info(p)=c; mp_link(q)=p;
14589   @<Attach the replacement text to the tail of node |p|@>;
14590   mp->scanner_status=normal; mp_get_x_next(mp);
14591 }
14592
14593 @ We don't put `|frozen_end_group|' into the replacement text of
14594 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14595
14596 @<Attach the replacement text to the tail of node |p|@>=
14597 if ( m==start_def ) {
14598   mp_link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14599 } else { 
14600   q=mp_get_avail(mp); info(q)=mp->bg_loc; mp_link(p)=q;
14601   p=mp_get_avail(mp); info(p)=mp->eg_loc;
14602   mp_link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14603 }
14604 if ( mp->warning_info==bad_vardef ) 
14605   mp_flush_token_list(mp, value(bad_vardef))
14606
14607 @ @<Glob...@>=
14608 int bg_loc;
14609 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14610
14611 @ @<Scan the token or variable to be defined;...@>=
14612 if ( m==start_def ) {
14613   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14614   mp->scanner_status=op_defining; n=0;
14615   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14616 } else { 
14617   p=mp_scan_declared_variable(mp);
14618   mp_flush_variable(mp, equiv(info(p)),mp_link(p),true);
14619   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14620   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14621   mp->scanner_status=var_defining; n=2;
14622   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14623     n=3; get_t_next;
14624   }
14625   type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14626 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14627
14628 @ @<Change to `\.{a bad variable}'@>=
14629
14630   print_err("This variable already starts with a macro");
14631 @.This variable already...@>
14632   help2("After `vardef a' you can\'t say `vardef a.b'.",
14633         "So I'll have to discard this definition.");
14634   mp_error(mp); mp->warning_info=bad_vardef;
14635 }
14636
14637 @ @<Initialize table entries...@>=
14638 name_type(bad_vardef)=mp_root; mp_link(bad_vardef)=frozen_bad_vardef;
14639 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14640
14641 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14642 do {  
14643   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14644   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14645    base=mp->cur_mod;
14646   } else { 
14647     print_err("Missing parameter type; `expr' will be assumed");
14648 @.Missing parameter type@>
14649     help1("You should've had `expr' or `suffix' or `text' here.");
14650     mp_back_error(mp); base=expr_base;
14651   }
14652   @<Absorb parameter tokens for type |base|@>;
14653   mp_check_delimiter(mp, l_delim,r_delim);
14654   get_t_next;
14655 } while (mp->cur_cmd==left_delimiter)
14656
14657 @ @<Absorb parameter tokens for type |base|@>=
14658 do { 
14659   mp_link(q)=mp_get_avail(mp); q=mp_link(q); info(q)=base+k;
14660   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14661   value(p)=base+k; info(p)=mp->cur_sym;
14662   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14663 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14664   incr(k); mp_link(p)=r; r=p; get_t_next;
14665 } while (mp->cur_cmd==comma)
14666
14667 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14668
14669   p=mp_get_node(mp, token_node_size);
14670   if ( mp->cur_mod<expr_base ) {
14671     c=mp->cur_mod; value(p)=expr_base+k;
14672   } else { 
14673     value(p)=mp->cur_mod+k;
14674     if ( mp->cur_mod==expr_base ) c=expr_macro;
14675     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14676     else c=text_macro;
14677   }
14678   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14679   incr(k); mp_get_symbol(mp); info(p)=mp->cur_sym; mp_link(p)=r; r=p; get_t_next;
14680   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14681     c=of_macro; p=mp_get_node(mp, token_node_size);
14682     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14683     value(p)=expr_base+k; mp_get_symbol(mp); info(p)=mp->cur_sym;
14684     mp_link(p)=r; r=p; get_t_next;
14685   }
14686 }
14687
14688 @* \[32] Expanding the next token.
14689 Only a few command codes |<min_command| can possibly be returned by
14690 |get_t_next|; in increasing order, they are
14691 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14692 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14693
14694 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14695 like |get_t_next| except that it keeps getting more tokens until
14696 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14697 macros and removes conditionals or iterations or input instructions that
14698 might be present.
14699
14700 It follows that |get_x_next| might invoke itself recursively. In fact,
14701 there is massive recursion, since macro expansion can involve the
14702 scanning of arbitrarily complex expressions, which in turn involve
14703 macro expansion and conditionals, etc.
14704 @^recursion@>
14705
14706 Therefore it's necessary to declare a whole bunch of |forward|
14707 procedures at this point, and to insert some other procedures
14708 that will be invoked by |get_x_next|.
14709
14710 @<Declarations@>= 
14711 static void mp_scan_primary (MP mp);
14712 static void mp_scan_secondary (MP mp);
14713 static void mp_scan_tertiary (MP mp);
14714 static void mp_scan_expression (MP mp);
14715 static void mp_scan_suffix (MP mp);
14716 static void mp_get_boolean (MP mp);
14717 static void mp_pass_text (MP mp);
14718 static void mp_conditional (MP mp);
14719 static void mp_start_input (MP mp);
14720 static void mp_begin_iteration (MP mp);
14721 static void mp_resume_iteration (MP mp);
14722 static void mp_stop_iteration (MP mp);
14723
14724 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14725 when it has to do exotic expansion commands.
14726
14727 @c 
14728 static void mp_expand (MP mp) {
14729   pointer p; /* for list manipulation */
14730   size_t k; /* something that we hope is |<=buf_size| */
14731   pool_pointer j; /* index into |str_pool| */
14732   if ( mp->internal[mp_tracing_commands]>unity ) 
14733     if ( mp->cur_cmd!=defined_macro )
14734       show_cur_cmd_mod;
14735   switch (mp->cur_cmd)  {
14736   case if_test:
14737     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14738     break;
14739   case fi_or_else:
14740     @<Terminate the current conditional and skip to \&{fi}@>;
14741     break;
14742   case input:
14743     @<Initiate or terminate input from a file@>;
14744     break;
14745   case iteration:
14746     if ( mp->cur_mod==end_for ) {
14747       @<Scold the user for having an extra \&{endfor}@>;
14748     } else {
14749       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14750     }
14751     break;
14752   case repeat_loop: 
14753     @<Repeat a loop@>;
14754     break;
14755   case exit_test: 
14756     @<Exit a loop if the proper time has come@>;
14757     break;
14758   case relax: 
14759     break;
14760   case expand_after: 
14761     @<Expand the token after the next token@>;
14762     break;
14763   case scan_tokens: 
14764     @<Put a string into the input buffer@>;
14765     break;
14766   case defined_macro:
14767    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14768    break;
14769   }; /* there are no other cases */
14770 }
14771
14772 @ @<Scold the user...@>=
14773
14774   print_err("Extra `endfor'");
14775 @.Extra `endfor'@>
14776   help2("I'm not currently working on a for loop,",
14777         "so I had better not try to end anything.");
14778   mp_error(mp);
14779 }
14780
14781 @ The processing of \&{input} involves the |start_input| subroutine,
14782 which will be declared later; the processing of \&{endinput} is trivial.
14783
14784 @<Put each...@>=
14785 mp_primitive(mp, "input",input,0);
14786 @:input_}{\&{input} primitive@>
14787 mp_primitive(mp, "endinput",input,1);
14788 @:end_input_}{\&{endinput} primitive@>
14789
14790 @ @<Cases of |print_cmd_mod|...@>=
14791 case input: 
14792   if ( m==0 ) mp_print(mp, "input");
14793   else mp_print(mp, "endinput");
14794   break;
14795
14796 @ @<Initiate or terminate input...@>=
14797 if ( mp->cur_mod>0 ) mp->force_eof=true;
14798 else mp_start_input(mp)
14799
14800 @ We'll discuss the complicated parts of loop operations later. For now
14801 it suffices to know that there's a global variable called |loop_ptr|
14802 that will be |null| if no loop is in progress.
14803
14804 @<Repeat a loop@>=
14805 { while ( token_state &&(loc==null) ) 
14806     mp_end_token_list(mp); /* conserve stack space */
14807   if ( mp->loop_ptr==null ) {
14808     print_err("Lost loop");
14809 @.Lost loop@>
14810     help2("I'm confused; after exiting from a loop, I still seem",
14811           "to want to repeat it. I'll try to forget the problem.");
14812     mp_error(mp);
14813   } else {
14814     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14815   }
14816 }
14817
14818 @ @<Exit a loop if the proper time has come@>=
14819 { mp_get_boolean(mp);
14820   if ( mp->internal[mp_tracing_commands]>unity ) 
14821     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14822   if ( mp->cur_exp==true_code ) {
14823     if ( mp->loop_ptr==null ) {
14824       print_err("No loop is in progress");
14825 @.No loop is in progress@>
14826       help1("Why say `exitif' when there's nothing to exit from?");
14827       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14828     } else {
14829      @<Exit prematurely from an iteration@>;
14830     }
14831   } else if ( mp->cur_cmd!=semicolon ) {
14832     mp_missing_err(mp, ";");
14833 @.Missing `;'@>
14834     help2("After `exitif <boolean exp>' I expect to see a semicolon.",
14835           "I shall pretend that one was there."); mp_back_error(mp);
14836   }
14837 }
14838
14839 @ Here we use the fact that |forever_text| is the only |token_type| that
14840 is less than |loop_text|.
14841
14842 @<Exit prematurely...@>=
14843 { p=null;
14844   do {  
14845     if ( file_state ) {
14846       mp_end_file_reading(mp);
14847     } else { 
14848       if ( token_type<=loop_text ) p=start;
14849       mp_end_token_list(mp);
14850     }
14851   } while (p==null);
14852   if ( p!=info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14853 @.loop confusion@>
14854   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14855 }
14856
14857 @ @<Expand the token after the next token@>=
14858 { get_t_next;
14859   p=mp_cur_tok(mp); get_t_next;
14860   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14861   else mp_back_input(mp);
14862   back_list(p);
14863 }
14864
14865 @ @<Put a string into the input buffer@>=
14866 { mp_get_x_next(mp); mp_scan_primary(mp);
14867   if ( mp->cur_type!=mp_string_type ) {
14868     mp_disp_err(mp, null,"Not a string");
14869 @.Not a string@>
14870     help2("I'm going to flush this expression, since",
14871           "scantokens should be followed by a known string.");
14872     mp_put_get_flush_error(mp, 0);
14873   } else { 
14874     mp_back_input(mp);
14875     if ( length(mp->cur_exp)>0 )
14876        @<Pretend we're reading a new one-line file@>;
14877   }
14878 }
14879
14880 @ @<Pretend we're reading a new one-line file@>=
14881 { mp_begin_file_reading(mp); name=is_scantok;
14882   k=mp->first+length(mp->cur_exp);
14883   if ( k>=mp->max_buf_stack ) {
14884     while ( k>=mp->buf_size ) {
14885       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
14886     }
14887     mp->max_buf_stack=k+1;
14888   }
14889   j=mp->str_start[mp->cur_exp]; limit=(halfword)k;
14890   while ( mp->first<(size_t)limit ) {
14891     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14892   }
14893   mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start; 
14894   mp_flush_cur_exp(mp, 0);
14895 }
14896
14897 @ Here finally is |get_x_next|.
14898
14899 The expression scanning routines to be considered later
14900 communicate via the global quantities |cur_type| and |cur_exp|;
14901 we must be very careful to save and restore these quantities while
14902 macros are being expanded.
14903 @^inner loop@>
14904
14905 @<Declarations@>=
14906 static void mp_get_x_next (MP mp);
14907
14908 @ @c void mp_get_x_next (MP mp) {
14909   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14910   get_t_next;
14911   if ( mp->cur_cmd<min_command ) {
14912     save_exp=mp_stash_cur_exp(mp);
14913     do {  
14914       if ( mp->cur_cmd==defined_macro ) 
14915         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14916       else 
14917         mp_expand(mp);
14918       get_t_next;
14919      } while (mp->cur_cmd<min_command);
14920      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14921   }
14922 }
14923
14924 @ Now let's consider the |macro_call| procedure, which is used to start up
14925 all user-defined macros. Since the arguments to a macro might be expressions,
14926 |macro_call| is recursive.
14927 @^recursion@>
14928
14929 The first parameter to |macro_call| points to the reference count of the
14930 token list that defines the macro. The second parameter contains any
14931 arguments that have already been parsed (see below).  The third parameter
14932 points to the symbolic token that names the macro. If the third parameter
14933 is |null|, the macro was defined by \&{vardef}, so its name can be
14934 reconstructed from the prefix and ``at'' arguments found within the
14935 second parameter.
14936
14937 What is this second parameter? It's simply a linked list of one-word items,
14938 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14939 no arguments have been scanned yet; otherwise |info(arg_list)| points to
14940 the first scanned argument, and |mp_link(arg_list)| points to the list of
14941 further arguments (if any).
14942
14943 Arguments of type \&{expr} are so-called capsules, which we will
14944 discuss later when we concentrate on expressions; they can be
14945 recognized easily because their |link| field is |void|. Arguments of type
14946 \&{suffix} and \&{text} are token lists without reference counts.
14947
14948 @ After argument scanning is complete, the arguments are moved to the
14949 |param_stack|. (They can't be put on that stack any sooner, because
14950 the stack is growing and shrinking in unpredictable ways as more arguments
14951 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14952 the replacement text of the macro is placed at the top of the \MP's
14953 input stack, so that |get_t_next| will proceed to read it next.
14954
14955 @<Declarations@>=
14956 static void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14957                     pointer macro_name) ;
14958
14959 @ @c
14960 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14961                     pointer macro_name) {
14962   /* invokes a user-defined control sequence */
14963   pointer r; /* current node in the macro's token list */
14964   pointer p,q; /* for list manipulation */
14965   integer n; /* the number of arguments */
14966   pointer tail = 0; /* tail of the argument list */
14967   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14968   r=mp_link(def_ref); add_mac_ref(def_ref);
14969   if ( arg_list==null ) {
14970     n=0;
14971   } else {
14972    @<Determine the number |n| of arguments already supplied,
14973     and set |tail| to the tail of |arg_list|@>;
14974   }
14975   if ( mp->internal[mp_tracing_macros]>0 ) {
14976     @<Show the text of the macro being expanded, and the existing arguments@>;
14977   }
14978   @<Scan the remaining arguments, if any; set |r| to the first token
14979     of the replacement text@>;
14980   @<Feed the arguments and replacement text to the scanner@>;
14981 }
14982
14983 @ @<Show the text of the macro...@>=
14984 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14985 mp_print_macro_name(mp, arg_list,macro_name);
14986 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14987 mp_show_macro(mp, def_ref,null,100000);
14988 if ( arg_list!=null ) {
14989   n=0; p=arg_list;
14990   do {  
14991     q=info(p);
14992     mp_print_arg(mp, q,n,0);
14993     incr(n); p=mp_link(p);
14994   } while (p!=null);
14995 }
14996 mp_end_diagnostic(mp, false)
14997
14998
14999 @ @<Declarations@>=
15000 static void mp_print_macro_name (MP mp,pointer a, pointer n);
15001
15002 @ @c
15003 void mp_print_macro_name (MP mp,pointer a, pointer n) {
15004   pointer p,q; /* they traverse the first part of |a| */
15005   if ( n!=null ) {
15006     mp_print_text(n);
15007   } else  { 
15008     p=info(a);
15009     if ( p==null ) {
15010       mp_print_text(info(info(mp_link(a))));
15011     } else { 
15012       q=p;
15013       while ( mp_link(q)!=null ) q=mp_link(q);
15014       mp_link(q)=info(mp_link(a));
15015       mp_show_token_list(mp, p,null,1000,0);
15016       mp_link(q)=null;
15017     }
15018   }
15019 }
15020
15021 @ @<Declarations@>=
15022 static void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
15023
15024 @ @c
15025 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
15026   if ( mp_link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
15027   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
15028   else mp_print_nl(mp, "(TEXT");
15029   mp_print_int(mp, n); mp_print(mp, ")<-");
15030   if ( mp_link(q)==mp_void ) mp_print_exp(mp, q,1);
15031   else mp_show_token_list(mp, q,null,1000,0);
15032 }
15033
15034 @ @<Determine the number |n| of arguments already supplied...@>=
15035 {  
15036   n=1; tail=arg_list;
15037   while ( mp_link(tail)!=null ) { 
15038     incr(n); tail=mp_link(tail);
15039   }
15040 }
15041
15042 @ @<Scan the remaining arguments, if any; set |r|...@>=
15043 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
15044 while ( info(r)>=expr_base ) { 
15045   @<Scan the delimited argument represented by |info(r)|@>;
15046   r=mp_link(r);
15047 }
15048 if ( mp->cur_cmd==comma ) {
15049   print_err("Too many arguments to ");
15050 @.Too many arguments...@>
15051   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, xord(';'));
15052   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
15053 @.Missing `)'...@>
15054   mp_print(mp, "' has been inserted");
15055   help3("I'm going to assume that the comma I just read was a",
15056    "right delimiter, and then I'll begin expanding the macro.",
15057    "You might want to delete some tokens before continuing.");
15058   mp_error(mp);
15059 }
15060 if ( info(r)!=general_macro ) {
15061   @<Scan undelimited argument(s)@>;
15062 }
15063 r=mp_link(r)
15064
15065 @ At this point, the reader will find it advisable to review the explanation
15066 of token list format that was presented earlier, paying special attention to
15067 the conventions that apply only at the beginning of a macro's token list.
15068
15069 On the other hand, the reader will have to take the expression-parsing
15070 aspects of the following program on faith; we will explain |cur_type|
15071 and |cur_exp| later. (Several things in this program depend on each other,
15072 and it's necessary to jump into the circle somewhere.)
15073
15074 @<Scan the delimited argument represented by |info(r)|@>=
15075 if ( mp->cur_cmd!=comma ) {
15076   mp_get_x_next(mp);
15077   if ( mp->cur_cmd!=left_delimiter ) {
15078     print_err("Missing argument to ");
15079 @.Missing argument...@>
15080     mp_print_macro_name(mp, arg_list,macro_name);
15081     help3("That macro has more parameters than you thought.",
15082      "I'll continue by pretending that each missing argument",
15083      "is either zero or null.");
15084     if ( info(r)>=suffix_base ) {
15085       mp->cur_exp=null; mp->cur_type=mp_token_list;
15086     } else { 
15087       mp->cur_exp=0; mp->cur_type=mp_known;
15088     }
15089     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
15090     goto FOUND;
15091   }
15092   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
15093 }
15094 @<Scan the argument represented by |info(r)|@>;
15095 if ( mp->cur_cmd!=comma ) 
15096   @<Check that the proper right delimiter was present@>;
15097 FOUND:  
15098 @<Append the current expression to |arg_list|@>
15099
15100 @ @<Check that the proper right delim...@>=
15101 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15102   if ( info(mp_link(r))>=expr_base ) {
15103     mp_missing_err(mp, ",");
15104 @.Missing `,'@>
15105     help3("I've finished reading a macro argument and am about to",
15106       "read another; the arguments weren't delimited correctly.",
15107       "You might want to delete some tokens before continuing.");
15108     mp_back_error(mp); mp->cur_cmd=comma;
15109   } else { 
15110     mp_missing_err(mp, str(text(r_delim)));
15111 @.Missing `)'@>
15112     help2("I've gotten to the end of the macro parameter list.",
15113           "You might want to delete some tokens before continuing.");
15114     mp_back_error(mp);
15115   }
15116 }
15117
15118 @ A \&{suffix} or \&{text} parameter will have been scanned as
15119 a token list pointed to by |cur_exp|, in which case we will have
15120 |cur_type=token_list|.
15121
15122 @<Append the current expression to |arg_list|@>=
15123
15124   p=mp_get_avail(mp);
15125   if ( mp->cur_type==mp_token_list ) info(p)=mp->cur_exp;
15126   else info(p)=mp_stash_cur_exp(mp);
15127   if ( mp->internal[mp_tracing_macros]>0 ) {
15128     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,info(r)); 
15129     mp_end_diagnostic(mp, false);
15130   }
15131   if ( arg_list==null ) arg_list=p;
15132   else mp_link(tail)=p;
15133   tail=p; incr(n);
15134 }
15135
15136 @ @<Scan the argument represented by |info(r)|@>=
15137 if ( info(r)>=text_base ) {
15138   mp_scan_text_arg(mp, l_delim,r_delim);
15139 } else { 
15140   mp_get_x_next(mp);
15141   if ( info(r)>=suffix_base ) mp_scan_suffix(mp);
15142   else mp_scan_expression(mp);
15143 }
15144
15145 @ The parameters to |scan_text_arg| are either a pair of delimiters
15146 or zero; the latter case is for undelimited text arguments, which
15147 end with the first semicolon or \&{endgroup} or \&{end} that is not
15148 contained in a group.
15149
15150 @<Declarations@>=
15151 static void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
15152
15153 @ @c
15154 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15155   integer balance; /* excess of |l_delim| over |r_delim| */
15156   pointer p; /* list tail */
15157   mp->warning_info=l_delim; mp->scanner_status=absorbing;
15158   p=hold_head; balance=1; mp_link(hold_head)=null;
15159   while (1)  { 
15160     get_t_next;
15161     if ( l_delim==0 ) {
15162       @<Adjust the balance for an undelimited argument; |break| if done@>;
15163     } else {
15164           @<Adjust the balance for a delimited argument; |break| if done@>;
15165     }
15166     mp_link(p)=mp_cur_tok(mp); p=mp_link(p);
15167   }
15168   mp->cur_exp=mp_link(hold_head); mp->cur_type=mp_token_list;
15169   mp->scanner_status=normal;
15170 }
15171
15172 @ @<Adjust the balance for a delimited argument...@>=
15173 if ( mp->cur_cmd==right_delimiter ) { 
15174   if ( mp->cur_mod==l_delim ) { 
15175     decr(balance);
15176     if ( balance==0 ) break;
15177   }
15178 } else if ( mp->cur_cmd==left_delimiter ) {
15179   if ( mp->cur_mod==r_delim ) incr(balance);
15180 }
15181
15182 @ @<Adjust the balance for an undelimited...@>=
15183 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15184   if ( balance==1 ) { break; }
15185   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15186 } else if ( mp->cur_cmd==begin_group ) { 
15187   incr(balance); 
15188 }
15189
15190 @ @<Scan undelimited argument(s)@>=
15191
15192   if ( info(r)<text_macro ) {
15193     mp_get_x_next(mp);
15194     if ( info(r)!=suffix_macro ) {
15195       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15196     }
15197   }
15198   switch (info(r)) {
15199   case primary_macro:mp_scan_primary(mp); break;
15200   case secondary_macro:mp_scan_secondary(mp); break;
15201   case tertiary_macro:mp_scan_tertiary(mp); break;
15202   case expr_macro:mp_scan_expression(mp); break;
15203   case of_macro:
15204     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15205     break;
15206   case suffix_macro:
15207     @<Scan a suffix with optional delimiters@>;
15208     break;
15209   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15210   } /* there are no other cases */
15211   mp_back_input(mp); 
15212   @<Append the current expression to |arg_list|@>;
15213 }
15214
15215 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15216
15217   mp_scan_expression(mp); p=mp_get_avail(mp); info(p)=mp_stash_cur_exp(mp);
15218   if ( mp->internal[mp_tracing_macros]>0 ) { 
15219     mp_begin_diagnostic(mp); mp_print_arg(mp, info(p),n,0); 
15220     mp_end_diagnostic(mp, false);
15221   }
15222   if ( arg_list==null ) arg_list=p; else mp_link(tail)=p;
15223   tail=p;incr(n);
15224   if ( mp->cur_cmd!=of_token ) {
15225     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15226 @.Missing `of'@>
15227     mp_print_macro_name(mp, arg_list,macro_name);
15228     help1("I've got the first argument; will look now for the other.");
15229     mp_back_error(mp);
15230   }
15231   mp_get_x_next(mp); mp_scan_primary(mp);
15232 }
15233
15234 @ @<Scan a suffix with optional delimiters@>=
15235
15236   if ( mp->cur_cmd!=left_delimiter ) {
15237     l_delim=null;
15238   } else { 
15239     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15240   };
15241   mp_scan_suffix(mp);
15242   if ( l_delim!=null ) {
15243     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15244       mp_missing_err(mp, str(text(r_delim)));
15245 @.Missing `)'@>
15246       help2("I've gotten to the end of the macro parameter list.",
15247             "You might want to delete some tokens before continuing.");
15248       mp_back_error(mp);
15249     }
15250     mp_get_x_next(mp);
15251   }
15252 }
15253
15254 @ Before we put a new token list on the input stack, it is wise to clean off
15255 all token lists that have recently been depleted. Then a user macro that ends
15256 with a call to itself will not require unbounded stack space.
15257
15258 @<Feed the arguments and replacement text to the scanner@>=
15259 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15260 if ( mp->param_ptr+n>mp->max_param_stack ) {
15261   mp->max_param_stack=mp->param_ptr+n;
15262   if ( mp->max_param_stack>mp->param_size )
15263     mp_overflow(mp, "parameter stack size",mp->param_size);
15264 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15265 }
15266 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15267 if ( n>0 ) {
15268   p=arg_list;
15269   do {  
15270    mp->param_stack[mp->param_ptr]=info(p); incr(mp->param_ptr); p=mp_link(p);
15271   } while (p!=null);
15272   mp_flush_list(mp, arg_list);
15273 }
15274
15275 @ It's sometimes necessary to put a single argument onto |param_stack|.
15276 The |stack_argument| subroutine does this.
15277
15278 @c 
15279 static void mp_stack_argument (MP mp,pointer p) { 
15280   if ( mp->param_ptr==mp->max_param_stack ) {
15281     incr(mp->max_param_stack);
15282     if ( mp->max_param_stack>mp->param_size )
15283       mp_overflow(mp, "parameter stack size",mp->param_size);
15284 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15285   }
15286   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15287 }
15288
15289 @* \[33] Conditional processing.
15290 Let's consider now the way \&{if} commands are handled.
15291
15292 Conditions can be inside conditions, and this nesting has a stack
15293 that is independent of other stacks.
15294 Four global variables represent the top of the condition stack:
15295 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15296 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15297 the largest code of a |fi_or_else| command that is syntactically legal;
15298 and |if_line| is the line number at which the current conditional began.
15299
15300 If no conditions are currently in progress, the condition stack has the
15301 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15302 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15303 |link| fields of the first word contain |if_limit|, |cur_if|, and
15304 |cond_ptr| at the next level, and the second word contains the
15305 corresponding |if_line|.
15306
15307 @d if_node_size 2 /* number of words in stack entry for conditionals */
15308 @d if_line_field(A) mp->mem[(A)+1].cint
15309 @d if_code 1 /* code for \&{if} being evaluated */
15310 @d fi_code 2 /* code for \&{fi} */
15311 @d else_code 3 /* code for \&{else} */
15312 @d else_if_code 4 /* code for \&{elseif} */
15313
15314 @<Glob...@>=
15315 pointer cond_ptr; /* top of the condition stack */
15316 integer if_limit; /* upper bound on |fi_or_else| codes */
15317 quarterword cur_if; /* type of conditional being worked on */
15318 integer if_line; /* line where that conditional began */
15319
15320 @ @<Set init...@>=
15321 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15322
15323 @ @<Put each...@>=
15324 mp_primitive(mp, "if",if_test,if_code);
15325 @:if_}{\&{if} primitive@>
15326 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15327 @:fi_}{\&{fi} primitive@>
15328 mp_primitive(mp, "else",fi_or_else,else_code);
15329 @:else_}{\&{else} primitive@>
15330 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15331 @:else_if_}{\&{elseif} primitive@>
15332
15333 @ @<Cases of |print_cmd_mod|...@>=
15334 case if_test:
15335 case fi_or_else: 
15336   switch (m) {
15337   case if_code:mp_print(mp, "if"); break;
15338   case fi_code:mp_print(mp, "fi");  break;
15339   case else_code:mp_print(mp, "else"); break;
15340   default: mp_print(mp, "elseif"); break;
15341   }
15342   break;
15343
15344 @ Here is a procedure that ignores text until coming to an \&{elseif},
15345 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15346 nesting. After it has acted, |cur_mod| will indicate the token that
15347 was found.
15348
15349 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15350 makes the skipping process a bit simpler.
15351
15352 @c 
15353 void mp_pass_text (MP mp) {
15354   integer l = 0;
15355   mp->scanner_status=skipping;
15356   mp->warning_info=mp_true_line(mp);
15357   while (1)  { 
15358     get_t_next;
15359     if ( mp->cur_cmd<=fi_or_else ) {
15360       if ( mp->cur_cmd<fi_or_else ) {
15361         incr(l);
15362       } else { 
15363         if ( l==0 ) break;
15364         if ( mp->cur_mod==fi_code ) decr(l);
15365       }
15366     } else {
15367       @<Decrease the string reference count,
15368        if the current token is a string@>;
15369     }
15370   }
15371   mp->scanner_status=normal;
15372 }
15373
15374 @ @<Decrease the string reference count...@>=
15375 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15376
15377 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15378 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15379 condition has been evaluated, a colon will be inserted.
15380 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15381
15382 @<Push the condition stack@>=
15383 { p=mp_get_node(mp, if_node_size); mp_link(p)=mp->cond_ptr; type(p)=mp->if_limit;
15384   name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15385   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15386   mp->cur_if=if_code;
15387 }
15388
15389 @ @<Pop the condition stack@>=
15390 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15391   mp->cur_if=name_type(p); mp->if_limit=type(p); mp->cond_ptr=mp_link(p);
15392   mp_free_node(mp, p,if_node_size);
15393 }
15394
15395 @ Here's a procedure that changes the |if_limit| code corresponding to
15396 a given value of |cond_ptr|.
15397
15398 @c 
15399 static void mp_change_if_limit (MP mp,quarterword l, pointer p) {
15400   pointer q;
15401   if ( p==mp->cond_ptr ) {
15402     mp->if_limit=l; /* that's the easy case */
15403   } else  { 
15404     q=mp->cond_ptr;
15405     while (1) { 
15406       if ( q==null ) mp_confusion(mp, "if");
15407 @:this can't happen if}{\quad if@>
15408       if ( mp_link(q)==p ) { 
15409         type(q)=l; return;
15410       }
15411       q=mp_link(q);
15412     }
15413   }
15414 }
15415
15416 @ The user is supposed to put colons into the proper parts of conditional
15417 statements. Therefore, \MP\ has to check for their presence.
15418
15419 @c 
15420 static void mp_check_colon (MP mp) { 
15421   if ( mp->cur_cmd!=colon ) { 
15422     mp_missing_err(mp, ":");
15423 @.Missing `:'@>
15424     help2("There should've been a colon after the condition.",
15425           "I shall pretend that one was there.");
15426     mp_back_error(mp);
15427   }
15428 }
15429
15430 @ A condition is started when the |get_x_next| procedure encounters
15431 an |if_test| command; in that case |get_x_next| calls |conditional|,
15432 which is a recursive procedure.
15433 @^recursion@>
15434
15435 @c 
15436 void mp_conditional (MP mp) {
15437   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15438   int new_if_limit; /* future value of |if_limit| */
15439   pointer p; /* temporary register */
15440   @<Push the condition stack@>; 
15441   save_cond_ptr=mp->cond_ptr;
15442 RESWITCH: 
15443   mp_get_boolean(mp); new_if_limit=else_if_code;
15444   if ( mp->internal[mp_tracing_commands]>unity ) {
15445     @<Display the boolean value of |cur_exp|@>;
15446   }
15447 FOUND: 
15448   mp_check_colon(mp);
15449   if ( mp->cur_exp==true_code ) {
15450     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15451     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15452   };
15453   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15454 DONE: 
15455   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15456   if ( mp->cur_mod==fi_code ) {
15457     @<Pop the condition stack@>
15458   } else if ( mp->cur_mod==else_if_code ) {
15459     goto RESWITCH;
15460   } else  { 
15461     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15462     goto FOUND;
15463   }
15464 }
15465
15466 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15467 \&{else}: \\{bar} \&{fi}', the first \&{else}
15468 that we come to after learning that the \&{if} is false is not the
15469 \&{else} we're looking for. Hence the following curious logic is needed.
15470
15471 @<Skip to \&{elseif}...@>=
15472 while (1) { 
15473   mp_pass_text(mp);
15474   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15475   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15476 }
15477
15478
15479 @ @<Display the boolean value...@>=
15480 { mp_begin_diagnostic(mp);
15481   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15482   else mp_print(mp, "{false}");
15483   mp_end_diagnostic(mp, false);
15484 }
15485
15486 @ The processing of conditionals is complete except for the following
15487 code, which is actually part of |get_x_next|. It comes into play when
15488 \&{elseif}, \&{else}, or \&{fi} is scanned.
15489
15490 @<Terminate the current conditional and skip to \&{fi}@>=
15491 if ( mp->cur_mod>mp->if_limit ) {
15492   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15493     mp_missing_err(mp, ":");
15494 @.Missing `:'@>
15495     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15496   } else  { 
15497     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15498 @.Extra else@>
15499 @.Extra elseif@>
15500 @.Extra fi@>
15501     help1("I'm ignoring this; it doesn't match any if.");
15502     mp_error(mp);
15503   }
15504 } else  { 
15505   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15506   @<Pop the condition stack@>;
15507 }
15508
15509 @* \[34] Iterations.
15510 To bring our treatment of |get_x_next| to a close, we need to consider what
15511 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15512
15513 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15514 that are currently active. If |loop_ptr=null|, no loops are in progress;
15515 otherwise |info(loop_ptr)| points to the iterative text of the current
15516 (innermost) loop, and |mp_link(loop_ptr)| points to the data for any other
15517 loops that enclose the current one.
15518
15519 A loop-control node also has two other fields, called |loop_type| and
15520 |loop_list|, whose contents depend on the type of loop:
15521
15522 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15523 points to a list of one-word nodes whose |info| fields point to the
15524 remaining argument values of a suffix list and expression list.
15525
15526 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15527 `\&{forever}'.
15528
15529 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15530 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15531 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15532 progression.
15533
15534 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15535 header and |loop_list(loop_ptr)| points into the graphical object list for
15536 that edge header.
15537
15538 \yskip\noindent In the case of a progression node, the first word is not used
15539 because the link field of words in the dynamic memory area cannot be arbitrary.
15540
15541 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15542 @d loop_type(A) info(loop_list_loc((A))) /* the type of \&{for} loop */
15543 @d loop_list(A) mp_link(loop_list_loc((A))) /* the remaining list elements */
15544 @d loop_node_size 2 /* the number of words in a loop control node */
15545 @d progression_node_size 4 /* the number of words in a progression node */
15546 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15547 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15548 @d progression_flag (null+2)
15549   /* |loop_type| value when |loop_list| points to a progression node */
15550
15551 @<Glob...@>=
15552 pointer loop_ptr; /* top of the loop-control-node stack */
15553
15554 @ @<Set init...@>=
15555 mp->loop_ptr=null;
15556
15557 @ If the expressions that define an arithmetic progression in
15558 a \&{for} loop don't have known numeric values, the |bad_for|
15559 subroutine screams at the user.
15560
15561 @c 
15562 static void mp_bad_for (MP mp, const char * s) {
15563   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15564 @.Improper...replaced by 0@>
15565   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15566   help4("When you say `for x=a step b until c',",
15567     "the initial value `a' and the step size `b'",
15568     "and the final value `c' must have known numeric values.",
15569     "I'm zeroing this one. Proceed, with fingers crossed.");
15570   mp_put_get_flush_error(mp, 0);
15571 }
15572
15573 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15574 has just been scanned. (This code requires slight familiarity with
15575 expression-parsing routines that we have not yet discussed; but it seems
15576 to belong in the present part of the program, even though the original author
15577 didn't write it until later. The reader may wish to come back to it.)
15578
15579 @c void mp_begin_iteration (MP mp) {
15580   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15581   halfword n; /* hash address of the current symbol */
15582   pointer s; /* the new loop-control node */
15583   pointer p; /* substitution list for |scan_toks| */
15584   pointer q;  /* link manipulation register */
15585   pointer pp; /* a new progression node */
15586   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15587   if ( m==start_forever ){ 
15588     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15589   } else { 
15590     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15591     info(p)=mp->cur_sym; value(p)=m;
15592     mp_get_x_next(mp);
15593     if ( mp->cur_cmd==within_token ) {
15594       @<Set up a picture iteration@>;
15595     } else { 
15596       @<Check for the |"="| or |":="| in a loop header@>;
15597       @<Scan the values to be used in the loop@>;
15598     }
15599   }
15600   @<Check for the presence of a colon@>;
15601   @<Scan the loop text and put it on the loop control stack@>;
15602   mp_resume_iteration(mp);
15603 }
15604
15605 @ @<Check for the |"="| or |":="| in a loop header@>=
15606 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15607   mp_missing_err(mp, "=");
15608 @.Missing `='@>
15609   help3("The next thing in this loop should have been `=' or `:='.",
15610     "But don't worry; I'll pretend that an equals sign",
15611     "was present, and I'll look for the values next.");
15612   mp_back_error(mp);
15613 }
15614
15615 @ @<Check for the presence of a colon@>=
15616 if ( mp->cur_cmd!=colon ) { 
15617   mp_missing_err(mp, ":");
15618 @.Missing `:'@>
15619   help3("The next thing in this loop should have been a `:'.",
15620     "So I'll pretend that a colon was present;",
15621     "everything from here to `endfor' will be iterated.");
15622   mp_back_error(mp);
15623 }
15624
15625 @ We append a special |frozen_repeat_loop| token in place of the
15626 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15627 at the proper time to cause the loop to be repeated.
15628
15629 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15630 he will be foiled by the |get_symbol| routine, which keeps frozen
15631 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15632 token, so it won't be lost accidentally.)
15633
15634 @ @<Scan the loop text...@>=
15635 q=mp_get_avail(mp); info(q)=frozen_repeat_loop;
15636 mp->scanner_status=loop_defining; mp->warning_info=n;
15637 info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15638 mp_link(s)=mp->loop_ptr; mp->loop_ptr=s
15639
15640 @ @<Initialize table...@>=
15641 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15642 text(frozen_repeat_loop)=intern(" ENDFOR");
15643
15644 @ The loop text is inserted into \MP's scanning apparatus by the
15645 |resume_iteration| routine.
15646
15647 @c void mp_resume_iteration (MP mp) {
15648   pointer p,q; /* link registers */
15649   p=loop_type(mp->loop_ptr);
15650   if ( p==progression_flag ) { 
15651     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15652     mp->cur_exp=value(p);
15653     if ( @<The arithmetic progression has ended@> ) {
15654       mp_stop_iteration(mp);
15655       return;
15656     }
15657     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15658     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15659   } else if ( p==null ) { 
15660     p=loop_list(mp->loop_ptr);
15661     if ( p==null ) {
15662       mp_stop_iteration(mp);
15663       return;
15664     }
15665     loop_list(mp->loop_ptr)=mp_link(p); q=info(p); free_avail(p);
15666   } else if ( p==mp_void ) { 
15667     mp_begin_token_list(mp, info(mp->loop_ptr),forever_text); return;
15668   } else {
15669     @<Make |q| a capsule containing the next picture component from
15670       |loop_list(loop_ptr)| or |goto not_found|@>;
15671   }
15672   mp_begin_token_list(mp, info(mp->loop_ptr),loop_text);
15673   mp_stack_argument(mp, q);
15674   if ( mp->internal[mp_tracing_commands]>unity ) {
15675      @<Trace the start of a loop@>;
15676   }
15677   return;
15678 NOT_FOUND:
15679   mp_stop_iteration(mp);
15680 }
15681
15682 @ @<The arithmetic progression has ended@>=
15683 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15684  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15685
15686 @ @<Trace the start of a loop@>=
15687
15688   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15689 @.loop value=n@>
15690   if ( (q!=null)&&(mp_link(q)==mp_void) ) mp_print_exp(mp, q,1);
15691   else mp_show_token_list(mp, q,null,50,0);
15692   mp_print_char(mp, xord('}')); mp_end_diagnostic(mp, false);
15693 }
15694
15695 @ @<Make |q| a capsule containing the next picture component from...@>=
15696 { q=loop_list(mp->loop_ptr);
15697   if ( q==null ) goto NOT_FOUND;
15698   skip_component(q) goto NOT_FOUND;
15699   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15700   mp_init_bbox(mp, mp->cur_exp);
15701   mp->cur_type=mp_picture_type;
15702   loop_list(mp->loop_ptr)=q;
15703   q=mp_stash_cur_exp(mp);
15704 }
15705
15706 @ A level of loop control disappears when |resume_iteration| has decided
15707 not to resume, or when an \&{exitif} construction has removed the loop text
15708 from the input stack.
15709
15710 @c void mp_stop_iteration (MP mp) {
15711   pointer p,q; /* the usual */
15712   p=loop_type(mp->loop_ptr);
15713   if ( p==progression_flag )  {
15714     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15715   } else if ( p==null ){ 
15716     q=loop_list(mp->loop_ptr);
15717     while ( q!=null ) {
15718       p=info(q);
15719       if ( p!=null ) {
15720         if ( mp_link(p)==mp_void ) { /* it's an \&{expr} parameter */
15721           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15722         } else {
15723           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15724         }
15725       }
15726       p=q; q=mp_link(q); free_avail(p);
15727     }
15728   } else if ( p>progression_flag ) {
15729     delete_edge_ref(p);
15730   }
15731   p=mp->loop_ptr; mp->loop_ptr=mp_link(p); mp_flush_token_list(mp, info(p));
15732   mp_free_node(mp, p,loop_node_size);
15733 }
15734
15735 @ Now that we know all about loop control, we can finish up
15736 the missing portion of |begin_iteration| and we'll be done.
15737
15738 The following code is performed after the `\.=' has been scanned in
15739 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15740 (if |m=suffix_base|).
15741
15742 @<Scan the values to be used in the loop@>=
15743 loop_type(s)=null; q=loop_list_loc(s); mp_link(q)=null; /* |mp_link(q)=loop_list(s)| */
15744 do {  
15745   mp_get_x_next(mp);
15746   if ( m!=expr_base ) {
15747     mp_scan_suffix(mp);
15748   } else { 
15749     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15750           goto CONTINUE;
15751     mp_scan_expression(mp);
15752     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15753       @<Prepare for step-until construction and |break|@>;
15754     }
15755     mp->cur_exp=mp_stash_cur_exp(mp);
15756   }
15757   mp_link(q)=mp_get_avail(mp); q=mp_link(q); 
15758   info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15759 CONTINUE:
15760   ;
15761 } while (mp->cur_cmd==comma)
15762
15763 @ @<Prepare for step-until construction and |break|@>=
15764
15765   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15766   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15767   mp_get_x_next(mp); mp_scan_expression(mp);
15768   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15769   step_size(pp)=mp->cur_exp;
15770   if ( mp->cur_cmd!=until_token ) { 
15771     mp_missing_err(mp, "until");
15772 @.Missing `until'@>
15773     help2("I assume you meant to say `until' after `step'.",
15774           "So I'll look for the final value and colon next.");
15775     mp_back_error(mp);
15776   }
15777   mp_get_x_next(mp); mp_scan_expression(mp);
15778   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15779   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15780   loop_type(s)=progression_flag; 
15781   break;
15782 }
15783
15784 @ The last case is when we have just seen ``\&{within}'', and we need to
15785 parse a picture expression and prepare to iterate over it.
15786
15787 @<Set up a picture iteration@>=
15788 { mp_get_x_next(mp);
15789   mp_scan_expression(mp);
15790   @<Make sure the current expression is a known picture@>;
15791   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15792   q=mp_link(dummy_loc(mp->cur_exp));
15793   if ( q!= null ) 
15794     if ( is_start_or_stop(q) )
15795       if ( mp_skip_1component(mp, q)==null ) q=mp_link(q);
15796   loop_list(s)=q;
15797 }
15798
15799 @ @<Make sure the current expression is a known picture@>=
15800 if ( mp->cur_type!=mp_picture_type ) {
15801   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15802   help1("When you say `for x in p', p must be a known picture.");
15803   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15804   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15805 }
15806
15807 @* \[35] File names.
15808 It's time now to fret about file names.  Besides the fact that different
15809 operating systems treat files in different ways, we must cope with the
15810 fact that completely different naming conventions are used by different
15811 groups of people. The following programs show what is required for one
15812 particular operating system; similar routines for other systems are not
15813 difficult to devise.
15814 @^system dependencies@>
15815
15816 \MP\ assumes that a file name has three parts: the name proper; its
15817 ``extension''; and a ``file area'' where it is found in an external file
15818 system.  The extension of an input file is assumed to be
15819 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15820 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15821 metric files that describe characters in any fonts created by \MP; it is
15822 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15823 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15824 The file area can be arbitrary on input files, but files are usually
15825 output to the user's current area.  If an input file cannot be
15826 found on the specified area, \MP\ will look for it on a special system
15827 area; this special area is intended for commonly used input files.
15828
15829 Simple uses of \MP\ refer only to file names that have no explicit
15830 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15831 instead of `\.{input} \.{cmr10.new}'. Simple file
15832 names are best, because they make the \MP\ source files portable;
15833 whenever a file name consists entirely of letters and digits, it should be
15834 treated in the same way by all implementations of \MP. However, users
15835 need the ability to refer to other files in their environment, especially
15836 when responding to error messages concerning unopenable files; therefore
15837 we want to let them use the syntax that appears in their favorite
15838 operating system.
15839
15840 @ \MP\ uses the same conventions that have proved to be satisfactory for
15841 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15842 @^system dependencies@>
15843 the system-independent parts of \MP\ are expressed in terms
15844 of three system-dependent
15845 procedures called |begin_name|, |more_name|, and |end_name|. In
15846 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15847 the system-independent driver program does the operations
15848 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
15849 \,|end_name|.$$
15850 These three procedures communicate with each other via global variables.
15851 Afterwards the file name will appear in the string pool as three strings
15852 called |cur_name|\penalty10000\hskip-.05em,
15853 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15854 |""|), unless they were explicitly specified by the user.
15855
15856 Actually the situation is slightly more complicated, because \MP\ needs
15857 to know when the file name ends. The |more_name| routine is a function
15858 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15859 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15860 returns |false|; or, it returns |true| and $c_n$ is the last character
15861 on the current input line. In other words,
15862 |more_name| is supposed to return |true| unless it is sure that the
15863 file name has been completely scanned; and |end_name| is supposed to be able
15864 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15865 whether $|more_name|(c_n)$ returned |true| or |false|.
15866
15867 @<Glob...@>=
15868 char * cur_name; /* name of file just scanned */
15869 char * cur_area; /* file area just scanned, or \.{""} */
15870 char * cur_ext; /* file extension just scanned, or \.{""} */
15871
15872 @ It is easier to maintain reference counts if we assign initial values.
15873
15874 @<Set init...@>=
15875 mp->cur_name=xstrdup(""); 
15876 mp->cur_area=xstrdup(""); 
15877 mp->cur_ext=xstrdup("");
15878
15879 @ @<Dealloc variables@>=
15880 xfree(mp->cur_area);
15881 xfree(mp->cur_name);
15882 xfree(mp->cur_ext);
15883
15884 @ The file names we shall deal with for illustrative purposes have the
15885 following structure:  If the name contains `\.>' or `\.:', the file area
15886 consists of all characters up to and including the final such character;
15887 otherwise the file area is null.  If the remaining file name contains
15888 `\..', the file extension consists of all such characters from the first
15889 remaining `\..' to the end, otherwise the file extension is null.
15890 @^system dependencies@>
15891
15892 We can scan such file names easily by using two global variables that keep track
15893 of the occurrences of area and extension delimiters.  Note that these variables
15894 cannot be of type |pool_pointer| because a string pool compaction could occur
15895 while scanning a file name.
15896
15897 @<Glob...@>=
15898 integer area_delimiter;
15899   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15900 integer ext_delimiter; /* the relevant `\..', if any */
15901
15902 @ Here now is the first of the system-dependent routines for file name scanning.
15903 @^system dependencies@>
15904
15905 The file name length is limited to |file_name_size|. That is good, because
15906 in the current configuration we cannot call |mp_do_compaction| while a name 
15907 is being scanned, |mp->area_delimiter| and |mp->ext_delimiter| are direct
15908 offsets into |mp->str_pool|. I am not in a great hurry to fix this, because 
15909 calling |str_room()| just once is more efficient anyway. TODO.
15910
15911 @<Declarations@>=
15912 static void mp_begin_name (MP mp);
15913 static boolean mp_more_name (MP mp, ASCII_code c);
15914 static void mp_end_name (MP mp);
15915
15916 @ @c
15917 void mp_begin_name (MP mp) { 
15918   xfree(mp->cur_name); 
15919   xfree(mp->cur_area); 
15920   xfree(mp->cur_ext);
15921   mp->area_delimiter=-1; 
15922   mp->ext_delimiter=-1;
15923   str_room(file_name_size); 
15924 }
15925
15926 @ And here's the second.
15927 @^system dependencies@>
15928
15929 @c 
15930 boolean mp_more_name (MP mp, ASCII_code c) {
15931   if (c==' ') {
15932     return false;
15933   } else { 
15934     if ( (c=='>')||(c==':') ) { 
15935       mp->area_delimiter=mp->pool_ptr; 
15936       mp->ext_delimiter=-1;
15937     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15938       mp->ext_delimiter=mp->pool_ptr;
15939     }
15940     append_char(c); /* contribute |c| to the current string */
15941     return true;
15942   }
15943 }
15944
15945 @ The third.
15946 @^system dependencies@>
15947
15948 @d copy_pool_segment(A,B,C) { 
15949       A = xmalloc(C+1,sizeof(char)); 
15950       strncpy(A,(char *)(mp->str_pool+B),C);  
15951       A[C] = 0;}
15952
15953 @c
15954 void mp_end_name (MP mp) {
15955   pool_pointer s; /* length of area, name, and extension */
15956   unsigned int len;
15957   /* "my/w.mp" */
15958   s = mp->str_start[mp->str_ptr];
15959   if ( mp->area_delimiter<0 ) {    
15960     mp->cur_area=xstrdup("");
15961   } else {
15962     len = (unsigned)(mp->area_delimiter-s); 
15963     copy_pool_segment(mp->cur_area,s,len);
15964     s += len+1;
15965   }
15966   if ( mp->ext_delimiter<0 ) {
15967     mp->cur_ext=xstrdup("");
15968     len = (unsigned)(mp->pool_ptr-s); 
15969   } else {
15970     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(size_t)(mp->pool_ptr-mp->ext_delimiter));
15971     len = (unsigned)(mp->ext_delimiter-s);
15972   }
15973   copy_pool_segment(mp->cur_name,s,len);
15974   mp->pool_ptr=s; /* don't need this partial string */
15975 }
15976
15977 @ Conversely, here is a routine that takes three strings and prints a file
15978 name that might have produced them. (The routine is system dependent, because
15979 some operating systems put the file area last instead of first.)
15980 @^system dependencies@>
15981
15982 @<Basic printing...@>=
15983 static void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15984   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15985 }
15986
15987 @ Another system-dependent routine is needed to convert three internal
15988 \MP\ strings
15989 to the |name_of_file| value that is used to open files. The present code
15990 allows both lowercase and uppercase letters in the file name.
15991 @^system dependencies@>
15992
15993 @d append_to_name(A) { c=xord((int)(A)); 
15994   if ( k<file_name_size ) {
15995     mp->name_of_file[k]=(char)xchr(c);
15996     incr(k);
15997   }
15998 }
15999
16000 @ @c
16001 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) {
16002   integer k; /* number of positions filled in |name_of_file| */
16003   ASCII_code c; /* character being packed */
16004   const char *j; /* a character  index */
16005   k=0;
16006   assert(n!=NULL);
16007   if (a!=NULL) {
16008     for (j=a;*j!='\0';j++) { append_to_name(*j); }
16009   }
16010   for (j=n;*j!='\0';j++) { append_to_name(*j); }
16011   if (e!=NULL) {
16012     for (j=e;*j!='\0';j++) { append_to_name(*j); }
16013   }
16014   mp->name_of_file[k]=0;
16015   mp->name_length=k; 
16016 }
16017
16018 @ @<Internal library declarations@>=
16019 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) ;
16020
16021 @ @<Option variables@>=
16022 char *mem_name; /* for commandline */
16023
16024 @ @<Find constant sizes@>=
16025 mp->mem_name = xstrdup(opt->mem_name);
16026 if (mp->mem_name) {
16027   size_t l = strlen(mp->mem_name);
16028   if (l>4) {
16029     char *test = strstr(mp->mem_name,".mem");
16030     if (test == mp->mem_name+l-4) {
16031       *test = 0;
16032     }
16033   }
16034 }
16035
16036
16037 @ @<Dealloc variables@>=
16038 xfree(mp->mem_name);
16039
16040 @ This part of the program becomes active when a ``virgin'' \MP\ is
16041 trying to get going, just after the preliminary initialization, or
16042 when the user is substituting another mem file by typing `\.\&' after
16043 the initial `\.{**}' prompt.  The buffer contains the first line of
16044 input in |buffer[loc..(last-1)]|, where |loc<last| and |buffer[loc]<>""|.
16045
16046 @<Declarations@>=
16047 static boolean mp_open_mem_name (MP mp) ;
16048 static boolean mp_open_mem_file (MP mp) ;
16049
16050 @ @c
16051 boolean mp_open_mem_name (MP mp) {
16052   if (mp->mem_name!=NULL) {
16053     size_t l = strlen(mp->mem_name);
16054     char *s = xstrdup (mp->mem_name);
16055     if (l>4) {
16056       char *test = strstr(s,".mem");
16057       if (test == NULL || test != s+l-4) {
16058         s = xrealloc (s, l+5, 1);       
16059         strcat (s, ".mem");
16060       }
16061     } else {
16062       s = xrealloc (s, l+5, 1);
16063       strcat (s, ".mem");
16064     }
16065     mp->mem_file = (mp->open_file)(mp,s, "r", mp_filetype_memfile);
16066     xfree(s);
16067     if ( mp->mem_file ) return true;
16068   }
16069   return false;
16070 }
16071 boolean mp_open_mem_file (MP mp) {
16072   if (mp->mem_file != NULL)
16073     return true;
16074   if (mp_open_mem_name(mp)) 
16075     return true;
16076   if (mp_xstrcmp(mp->mem_name, "plain")) {
16077     wake_up_terminal;
16078     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
16079 @.Sorry, I can't find...@>
16080     update_terminal;
16081     /* now pull out all the stops: try for the system \.{plain} file */
16082     xfree(mp->mem_name);
16083     mp->mem_name = xstrdup("plain");
16084     if (mp_open_mem_name(mp))
16085       return true;
16086   }
16087   wake_up_terminal;
16088   wterm_ln("I can\'t find the PLAIN mem file!");
16089 @.I can't find PLAIN...@>
16090 @.plain@>
16091   return false;
16092 }
16093
16094 @ Operating systems often make it possible to determine the exact name (and
16095 possible version number) of a file that has been opened. The following routine,
16096 which simply makes a \MP\ string from the value of |name_of_file|, should
16097 ideally be changed to deduce the full name of file~|f|, which is the file
16098 most recently opened, if it is possible to do this.
16099 @^system dependencies@>
16100
16101 @<Declarations@>=
16102 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
16103 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
16104 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
16105
16106 @ @c 
16107 static str_number mp_make_name_string (MP mp) {
16108   int k; /* index into |name_of_file| */
16109   str_room(mp->name_length);
16110   for (k=0;k<mp->name_length;k++) {
16111     append_char(xord((int)mp->name_of_file[k]));
16112   }
16113   return mp_make_string(mp);
16114 }
16115
16116 @ Now let's consider the ``driver''
16117 routines by which \MP\ deals with file names
16118 in a system-independent manner.  First comes a procedure that looks for a
16119 file name in the input by taking the information from the input buffer.
16120 (We can't use |get_next|, because the conversion to tokens would
16121 destroy necessary information.)
16122
16123 This procedure doesn't allow semicolons or percent signs to be part of
16124 file names, because of other conventions of \MP.
16125 {\sl The {\logos METAFONT\/}book} doesn't
16126 use semicolons or percents immediately after file names, but some users
16127 no doubt will find it natural to do so; therefore system-dependent
16128 changes to allow such characters in file names should probably
16129 be made with reluctance, and only when an entire file name that
16130 includes special characters is ``quoted'' somehow.
16131 @^system dependencies@>
16132
16133 @c 
16134 static void mp_scan_file_name (MP mp) { 
16135   mp_begin_name(mp);
16136   while ( mp->buffer[loc]==' ' ) incr(loc);
16137   while (1) { 
16138     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
16139     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
16140     incr(loc);
16141   }
16142   mp_end_name(mp);
16143 }
16144
16145 @ Here is another version that takes its input from a string.
16146
16147 @<Declare subroutines for parsing file names@>=
16148 void mp_str_scan_file (MP mp,  str_number s) ;
16149
16150 @ @c
16151 void mp_str_scan_file (MP mp,  str_number s) {
16152   pool_pointer p,q; /* current position and stopping point */
16153   mp_begin_name(mp);
16154   p=mp->str_start[s]; q=str_stop(s);
16155   while ( p<q ){ 
16156     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16157     incr(p);
16158   }
16159   mp_end_name(mp);
16160 }
16161
16162 @ And one that reads from a |char*|.
16163
16164 @<Declare subroutines for parsing file names@>=
16165 extern void mp_ptr_scan_file (MP mp,  char *s);
16166
16167 @ @c
16168 void mp_ptr_scan_file (MP mp,  char *s) {
16169   char *p, *q; /* current position and stopping point */
16170   mp_begin_name(mp);
16171   p=s; q=p+strlen(s);
16172   while ( p<q ){ 
16173     if ( ! mp_more_name(mp, xord((int)(*p)))) break;
16174     p++;
16175   }
16176   mp_end_name(mp);
16177 }
16178
16179
16180 @ The global variable |job_name| contains the file name that was first
16181 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16182 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16183
16184 @<Glob...@>=
16185 boolean log_opened; /* has the transcript file been opened? */
16186 char *log_name; /* full name of the log file */
16187
16188 @ @<Option variables@>=
16189 char *job_name; /* principal file name */
16190
16191 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16192 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16193 except of course for a short time just after |job_name| has become nonzero.
16194
16195 @<Allocate or ...@>=
16196 mp->job_name=mp_xstrdup(mp, opt->job_name); 
16197 if (opt->noninteractive && opt->ini_version) {
16198   if (mp->job_name == NULL)
16199     mp->job_name=mp_xstrdup(mp,mp->mem_name); 
16200   if (mp->job_name != NULL) {
16201     size_t l = strlen(mp->job_name);
16202     if (l>4) {
16203       char *test = strstr(mp->job_name,".mem");
16204       if (test == mp->job_name+l-4)
16205         *test = 0;
16206     }
16207   }
16208 }
16209 mp->log_opened=false;
16210
16211 @ @<Dealloc variables@>=
16212 xfree(mp->job_name);
16213
16214 @ Here is a routine that manufactures the output file names, assuming that
16215 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16216 and |cur_ext|.
16217
16218 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16219
16220 @<Declarations@>=
16221 static void mp_pack_job_name (MP mp, const char *s) ;
16222
16223 @ @c 
16224 void mp_pack_job_name (MP mp, const char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16225   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16226   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16227   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16228   pack_cur_name;
16229 }
16230
16231 @ If some trouble arises when \MP\ tries to open a file, the following
16232 routine calls upon the user to supply another file name. Parameter~|s|
16233 is used in the error message to identify the type of file; parameter~|e|
16234 is the default extension if none is given. Upon exit from the routine,
16235 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16236 ready for another attempt at file opening.
16237
16238 @<Declarations@>=
16239 static void mp_prompt_file_name (MP mp, const char * s, const char * e) ;
16240
16241 @ @c void mp_prompt_file_name (MP mp, const char * s, const char * e) {
16242   size_t k; /* index into |buffer| */
16243   char * saved_cur_name;
16244   if ( mp->interaction==mp_scroll_mode ) 
16245         wake_up_terminal;
16246   if (strcmp(s,"input file name")==0) {
16247         print_err("I can\'t find file `");
16248 @.I can't find file x@>
16249   } else {
16250         print_err("I can\'t write on file `");
16251 @.I can't write on file x@>
16252   }
16253   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16254   mp_print(mp, "'.");
16255   if (strcmp(e,"")==0) 
16256         mp_show_context(mp);
16257   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16258 @.Please type...@>
16259   if (mp->noninteractive || mp->interaction<mp_scroll_mode )
16260     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16261 @.job aborted, file error...@>
16262   saved_cur_name = xstrdup(mp->cur_name);
16263   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16264   if (strcmp(mp->cur_ext,"")==0) 
16265         mp->cur_ext=xstrdup(e);
16266   if (strlen(mp->cur_name)==0) {
16267     mp->cur_name=saved_cur_name;
16268   } else {
16269     xfree(saved_cur_name);
16270   }
16271   pack_cur_name;
16272 }
16273
16274 @ @<Scan file name in the buffer@>=
16275
16276   mp_begin_name(mp); k=mp->first;
16277   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16278   while (1) { 
16279     if ( k==mp->last ) break;
16280     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16281     incr(k);
16282   }
16283   mp_end_name(mp);
16284 }
16285
16286 @ The |open_log_file| routine is used to open the transcript file and to help
16287 it catch up to what has previously been printed on the terminal.
16288
16289 @c void mp_open_log_file (MP mp) {
16290   unsigned old_setting; /* previous |selector| setting */
16291   int k; /* index into |months| and |buffer| */
16292   int l; /* end of first input line */
16293   integer m; /* the current month */
16294   const char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16295     /* abbreviations of month names */
16296   old_setting=mp->selector;
16297   if ( mp->job_name==NULL ) {
16298      mp->job_name=xstrdup("mpout");
16299   }
16300   mp_pack_job_name(mp,".log");
16301   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16302     @<Try to get a different log file name@>;
16303   }
16304   mp->log_name=xstrdup(mp->name_of_file);
16305   mp->selector=log_only; mp->log_opened=true;
16306   @<Print the banner line, including the date and time@>;
16307   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16308     /* make sure bottom level is in memory */
16309   if (!mp->noninteractive) {
16310     mp_print_nl(mp, "**");
16311 @.**@>
16312     l=mp->input_stack[0].limit_field-1; /* last position of first line */
16313     for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16314     mp_print_ln(mp); /* now the transcript file contains the first line of input */
16315   }
16316   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16317 }
16318
16319 @ @<Dealloc variables@>=
16320 xfree(mp->log_name);
16321
16322 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16323 unable to print error messages or even to |show_context|.
16324 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16325 routine will not be invoked because |log_opened| will be false.
16326
16327 The normal idea of |mp_batch_mode| is that nothing at all should be written
16328 on the terminal. However, in the unusual case that
16329 no log file could be opened, we make an exception and allow
16330 an explanatory message to be seen.
16331
16332 Incidentally, the program always refers to the log file as a `\.{transcript
16333 file}', because some systems cannot use the extension `\.{.log}' for
16334 this file.
16335
16336 @<Try to get a different log file name@>=
16337 {  
16338   mp->selector=term_only;
16339   mp_prompt_file_name(mp, "transcript file name",".log");
16340 }
16341
16342 @ @<Print the banner...@>=
16343
16344   wlog(mp->banner);
16345   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16346   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16347   mp_print_char(mp, xord(' '));
16348   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16349   for (k=3*m-3;k<3*m;k++) { wlog_chr((unsigned char)months[k]); }
16350   mp_print_char(mp, xord(' ')); 
16351   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16352   mp_print_char(mp, xord(' '));
16353   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16354   mp_print_dd(mp, m / 60); mp_print_char(mp, xord(':')); mp_print_dd(mp, m % 60);
16355 }
16356
16357 @ The |try_extension| function tries to open an input file determined by
16358 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16359 can't find the file in |cur_area| or the appropriate system area.
16360
16361 @c
16362 static boolean mp_try_extension (MP mp, const char *ext) { 
16363   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16364   in_name=xstrdup(mp->cur_name); 
16365   in_area=xstrdup(mp->cur_area);
16366   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16367     return true;
16368   } else { 
16369     mp_pack_file_name(mp, mp->cur_name,NULL,ext);
16370     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16371   }
16372 }
16373
16374 @ Let's turn now to the procedure that is used to initiate file reading
16375 when an `\.{input}' command is being processed.
16376
16377 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16378   char *fname = NULL;
16379   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16380   while (1) { 
16381     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16382     if ( strlen(mp->cur_ext)==0 ) {
16383       if ( mp_try_extension(mp, ".mp") ) break;
16384       else if ( mp_try_extension(mp, "") ) break;
16385       else if ( mp_try_extension(mp, ".mf") ) break;
16386       /* |else do_nothing; | */
16387     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16388       break;
16389     }
16390     mp_end_file_reading(mp); /* remove the level that didn't work */
16391     mp_prompt_file_name(mp, "input file name","");
16392   }
16393   name=mp_a_make_name_string(mp, cur_file);
16394   fname = xstrdup(mp->name_of_file);
16395   if ( mp->job_name==NULL ) {
16396     mp->job_name=xstrdup(mp->cur_name); 
16397     mp_open_log_file(mp);
16398   } /* |open_log_file| doesn't |show_context|, so |limit|
16399         and |loc| needn't be set to meaningful values yet */
16400   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16401   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, xord(' '));
16402   mp_print_char(mp, xord('(')); incr(mp->open_parens); mp_print(mp, fname); 
16403   xfree(fname);
16404   update_terminal;
16405   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16406   @<Read the first line of the new file@>;
16407 }
16408
16409 @ This code should be omitted if |a_make_name_string| returns something other
16410 than just a copy of its argument and the full file name is needed for opening
16411 \.{MPX} files or implementing the switch-to-editor option.
16412 @^system dependencies@>
16413
16414 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16415 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16416
16417 @ If the file is empty, it is considered to contain a single blank line,
16418 so there is no need to test the return value.
16419
16420 @<Read the first line...@>=
16421
16422   line=1;
16423   (void)mp_input_ln(mp, cur_file ); 
16424   mp_firm_up_the_line(mp);
16425   mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start;
16426 }
16427
16428 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16429 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16430 if ( token_state ) { 
16431   print_err("File names can't appear within macros");
16432 @.File names can't...@>
16433   help3("Sorry...I've converted what follows to tokens,",
16434     "possibly garbaging the name you gave.",
16435     "Please delete the tokens and insert the name again.");
16436   mp_error(mp);
16437 }
16438 if ( file_state ) {
16439   mp_scan_file_name(mp);
16440 } else { 
16441    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16442    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16443    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16444 }
16445
16446 @ The following simple routine starts reading the \.{MPX} file associated
16447 with the current input file.
16448
16449 @c void mp_start_mpx_input (MP mp) {
16450   char *origname = NULL; /* a copy of nameoffile */
16451   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16452   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16453     |goto not_found| if there is a problem@>;
16454   mp_begin_file_reading(mp);
16455   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16456     mp_end_file_reading(mp);
16457     goto NOT_FOUND;
16458   }
16459   name=mp_a_make_name_string(mp, cur_file);
16460   mp->mpx_name[iindex]=name; add_str_ref(name);
16461   @<Read the first line of the new file@>;
16462   xfree(origname);
16463   return;
16464 NOT_FOUND: 
16465     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16466   xfree(origname);
16467 }
16468
16469 @ This should ideally be changed to do whatever is necessary to create the
16470 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16471 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16472 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16473 completely different typesetting program if suitable postprocessor is
16474 available to perform the function of \.{DVItoMP}.)
16475 @^system dependencies@>
16476
16477 @ @<Exported types@>=
16478 typedef int (*mp_run_make_mpx_command)(MP mp, char *origname, char *mtxname);
16479
16480 @ @<Option variables@>=
16481 mp_run_make_mpx_command run_make_mpx;
16482
16483 @ @<Allocate or initialize ...@>=
16484 set_callback_option(run_make_mpx);
16485
16486 @ @<Declarations@>=
16487 static int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16488
16489 @ The default does nothing.
16490 @c 
16491 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16492   (void)mp;
16493   (void)origname;
16494   (void)mtxname;
16495   return false;
16496 }
16497
16498 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16499   |goto not_found| if there is a problem@>=
16500 origname = mp_xstrdup(mp,mp->name_of_file);
16501 *(origname+strlen(origname)-1)=0; /* drop the x */
16502 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16503   goto NOT_FOUND 
16504
16505 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16506 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16507 mp_print_nl(mp, ">> ");
16508 mp_print(mp, origname);
16509 mp_print_nl(mp, ">> ");
16510 mp_print(mp, mp->name_of_file);
16511 mp_print_nl(mp, "! Unable to make mpx file");
16512 help4("The two files given above are one of your source files",
16513   "and an auxiliary file I need to read to find out what your",
16514   "btex..etex blocks mean. If you don't know why I had trouble,",
16515   "try running it manually through MPtoTeX, TeX, and DVItoMP");
16516 succumb;
16517
16518 @ The last file-opening commands are for files accessed via the \&{readfrom}
16519 @:read_from_}{\&{readfrom} primitive@>
16520 operator and the \&{write} command.  Such files are stored in separate arrays.
16521 @:write_}{\&{write} primitive@>
16522
16523 @<Types in the outer block@>=
16524 typedef unsigned int readf_index; /* |0..max_read_files| */
16525 typedef unsigned int write_index;  /* |0..max_write_files| */
16526
16527 @ @<Glob...@>=
16528 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16529 void ** rd_file; /* \&{readfrom} files */
16530 char ** rd_fname; /* corresponding file name or 0 if file not open */
16531 readf_index read_files; /* number of valid entries in the above arrays */
16532 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16533 void ** wr_file; /* \&{write} files */
16534 char ** wr_fname; /* corresponding file name or 0 if file not open */
16535 write_index write_files; /* number of valid entries in the above arrays */
16536
16537 @ @<Allocate or initialize ...@>=
16538 mp->max_read_files=8;
16539 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16540 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16541 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16542 mp->max_write_files=8;
16543 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16544 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16545 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16546
16547
16548 @ This routine starts reading the file named by string~|s| without setting
16549 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16550 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16551
16552 @c 
16553 static boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16554   mp_ptr_scan_file(mp, s);
16555   pack_cur_name;
16556   mp_begin_file_reading(mp);
16557   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (int)(mp_filetype_text+n)) ) 
16558         goto NOT_FOUND;
16559   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16560     (mp->close_file)(mp,mp->rd_file[n]); 
16561         goto NOT_FOUND; 
16562   }
16563   mp->rd_fname[n]=xstrdup(s);
16564   return true;
16565 NOT_FOUND: 
16566   mp_end_file_reading(mp);
16567   return false;
16568 }
16569
16570 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16571
16572 @<Declarations@>=
16573 static void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16574
16575 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16576   mp_ptr_scan_file(mp, s);
16577   pack_cur_name;
16578   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (int)(mp_filetype_text+n)) )
16579     mp_prompt_file_name(mp, "file name for write output","");
16580   mp->wr_fname[n]=xstrdup(s);
16581 }
16582
16583
16584 @* \[36] Introduction to the parsing routines.
16585 We come now to the central nervous system that sparks many of \MP's activities.
16586 By evaluating expressions, from their primary constituents to ever larger
16587 subexpressions, \MP\ builds the structures that ultimately define complete
16588 pictures or fonts of type.
16589
16590 Four mutually recursive subroutines are involved in this process: We call them
16591 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16592 and |scan_expression|.}$$
16593 @^recursion@>
16594 Each of them is parameterless and begins with the first token to be scanned
16595 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16596 the value of the primary or secondary or tertiary or expression that was
16597 found will appear in the global variables |cur_type| and |cur_exp|. The
16598 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16599 and |cur_sym|.
16600
16601 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16602 backup mechanisms have been added in order to provide reasonable error
16603 recovery.
16604
16605 @<Glob...@>=
16606 quarterword cur_type; /* the type of the expression just found */
16607 integer cur_exp; /* the value of the expression just found */
16608
16609 @ @<Set init...@>=
16610 mp->cur_exp=0;
16611
16612 @ Many different kinds of expressions are possible, so it is wise to have
16613 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16614
16615 \smallskip\hang
16616 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16617 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16618 construction in which there was no expression before the \&{endgroup}.
16619 In this case |cur_exp| has some irrelevant value.
16620
16621 \smallskip\hang
16622 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16623 or |false_code|.
16624
16625 \smallskip\hang
16626 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16627 node that is in 
16628 a ring of equivalent booleans whose value has not yet been defined.
16629
16630 \smallskip\hang
16631 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16632 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16633 includes this particular reference.
16634
16635 \smallskip\hang
16636 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16637 node that is in
16638 a ring of equivalent strings whose value has not yet been defined.
16639
16640 \smallskip\hang
16641 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16642 else points to any of the nodes in this pen.  The pen may be polygonal or
16643 elliptical.
16644
16645 \smallskip\hang
16646 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16647 node that is in
16648 a ring of equivalent pens whose value has not yet been defined.
16649
16650 \smallskip\hang
16651 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16652 a path; nobody else points to this particular path. The control points of
16653 the path will have been chosen.
16654
16655 \smallskip\hang
16656 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16657 node that is in
16658 a ring of equivalent paths whose value has not yet been defined.
16659
16660 \smallskip\hang
16661 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16662 There may be other pointers to this particular set of edges.  The header node
16663 contains a reference count that includes this particular reference.
16664
16665 \smallskip\hang
16666 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16667 node that is in
16668 a ring of equivalent pictures whose value has not yet been defined.
16669
16670 \smallskip\hang
16671 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16672 capsule node. The |value| part of this capsule
16673 points to a transform node that contains six numeric values,
16674 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16675
16676 \smallskip\hang
16677 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16678 capsule node. The |value| part of this capsule
16679 points to a color node that contains three numeric values,
16680 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16681
16682 \smallskip\hang
16683 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16684 capsule node. The |value| part of this capsule
16685 points to a color node that contains four numeric values,
16686 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16687
16688 \smallskip\hang
16689 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16690 node whose type is |mp_pair_type|. The |value| part of this capsule
16691 points to a pair node that contains two numeric values,
16692 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16693
16694 \smallskip\hang
16695 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16696
16697 \smallskip\hang
16698 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16699 is |dependent|. The |dep_list| field in this capsule points to the associated
16700 dependency list.
16701
16702 \smallskip\hang
16703 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16704 capsule node. The |dep_list| field in this capsule
16705 points to the associated dependency list.
16706
16707 \smallskip\hang
16708 |cur_type=independent| means that |cur_exp| points to a capsule node
16709 whose type is |independent|. This somewhat unusual case can arise, for
16710 example, in the expression
16711 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16712
16713 \smallskip\hang
16714 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16715 tokens. 
16716
16717 \smallskip\noindent
16718 The possible settings of |cur_type| have been listed here in increasing
16719 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16720 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16721 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16722 |token_list|.
16723
16724 @ Capsules are two-word nodes that have a similar meaning
16725 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|,
16726 and their |type| field is one of the possibilities for |cur_type| listed above.
16727 Also |link<=void| in capsules that aren't part of a token list.
16728
16729 The |value| field of a capsule is, in most cases, the value that
16730 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16731 However, when |cur_exp| would point to a capsule,
16732 no extra layer of indirection is present; the |value|
16733 field is what would have been called |value(cur_exp)| if it had not been
16734 encapsulated.  Furthermore, if the type is |dependent| or
16735 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16736 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16737 always part of the general |dep_list| structure.
16738
16739 The |get_x_next| routine is careful not to change the values of |cur_type|
16740 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16741 call a macro, which might parse an expression, which might execute lots of
16742 commands in a group; hence it's possible that |cur_type| might change
16743 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16744 |known| or |independent|, during the time |get_x_next| is called. The
16745 programs below are careful to stash sensitive intermediate results in
16746 capsules, so that \MP's generality doesn't cause trouble.
16747
16748 Here's a procedure that illustrates these conventions. It takes
16749 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16750 and stashes them away in a
16751 capsule. It is not used when |cur_type=mp_token_list|.
16752 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16753 copy path lists or to update reference counts, etc.
16754
16755 The special link |mp_void| is put on the capsule returned by
16756 |stash_cur_exp|, because this procedure is used to store macro parameters
16757 that must be easily distinguishable from token lists.
16758
16759 @<Declare the stashing/unstashing routines@>=
16760 static pointer mp_stash_cur_exp (MP mp) {
16761   pointer p; /* the capsule that will be returned */
16762   switch (mp->cur_type) {
16763   case unknown_types:
16764   case mp_transform_type:
16765   case mp_color_type:
16766   case mp_pair_type:
16767   case mp_dependent:
16768   case mp_proto_dependent:
16769   case mp_independent: 
16770   case mp_cmykcolor_type:
16771     p=mp->cur_exp;
16772     break;
16773   default: 
16774     p=mp_get_node(mp, value_node_size); name_type(p)=mp_capsule;
16775     type(p)=mp->cur_type; value(p)=mp->cur_exp;
16776     break;
16777   }
16778   mp->cur_type=mp_vacuous; mp_link(p)=mp_void; 
16779   return p;
16780 }
16781
16782 @ The inverse of |stash_cur_exp| is the following procedure, which
16783 deletes an unnecessary capsule and puts its contents into |cur_type|
16784 and |cur_exp|.
16785
16786 The program steps of \MP\ can be divided into two categories: those in
16787 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16788 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16789 information or not. It's important not to ignore them when they're alive,
16790 and it's important not to pay attention to them when they're dead.
16791
16792 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16793 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16794 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16795 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16796 only when they are alive or dormant.
16797
16798 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16799 are alive or dormant. The \\{unstash} procedure assumes that they are
16800 dead or dormant; it resuscitates them.
16801
16802 @<Declare the stashing/unstashing...@>=
16803 static void mp_unstash_cur_exp (MP mp,pointer p) ;
16804
16805 @ @c
16806 void mp_unstash_cur_exp (MP mp,pointer p) { 
16807   mp->cur_type=type(p);
16808   switch (mp->cur_type) {
16809   case unknown_types:
16810   case mp_transform_type:
16811   case mp_color_type:
16812   case mp_pair_type:
16813   case mp_dependent: 
16814   case mp_proto_dependent:
16815   case mp_independent:
16816   case mp_cmykcolor_type: 
16817     mp->cur_exp=p;
16818     break;
16819   default:
16820     mp->cur_exp=value(p);
16821     mp_free_node(mp, p,value_node_size);
16822     break;
16823   }
16824 }
16825
16826 @ The following procedure prints the values of expressions in an
16827 abbreviated format. If its first parameter |p| is null, the value of
16828 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16829 containing the desired value. The second parameter controls the amount of
16830 output. If it is~0, dependency lists will be abbreviated to
16831 `\.{linearform}' unless they consist of a single term.  If it is greater
16832 than~1, complicated structures (pens, pictures, and paths) will be displayed
16833 in full.
16834 @.linearform@>
16835
16836 @<Declarations@>=
16837 @<Declare the procedure called |print_dp|@>
16838 @<Declare the stashing/unstashing routines@>
16839 static void mp_print_exp (MP mp,pointer p, quarterword verbosity) ;
16840
16841 @ @c
16842 void mp_print_exp (MP mp,pointer p, quarterword verbosity) {
16843   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16844   quarterword t; /* the type of the expression */
16845   pointer q; /* a big node being displayed */
16846   integer v=0; /* the value of the expression */
16847   if ( p!=null ) {
16848     restore_cur_exp=false;
16849   } else { 
16850     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16851   }
16852   t=type(p);
16853   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16854   @<Print an abbreviated value of |v| with format depending on |t|@>;
16855   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16856 }
16857
16858 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16859 switch (t) {
16860 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16861 case mp_boolean_type:
16862   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16863   break;
16864 case unknown_types: case mp_numeric_type:
16865   @<Display a variable that's been declared but not defined@>;
16866   break;
16867 case mp_string_type:
16868   mp_print_char(mp, xord('"')); mp_print_str(mp, v); mp_print_char(mp, xord('"'));
16869   break;
16870 case mp_pen_type: case mp_path_type: case mp_picture_type:
16871   @<Display a complex type@>;
16872   break;
16873 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16874   if ( v==null ) mp_print_type(mp, t);
16875   else @<Display a big node@>;
16876   break;
16877 case mp_known:mp_print_scaled(mp, v); break;
16878 case mp_dependent: case mp_proto_dependent:
16879   mp_print_dp(mp, t,v,verbosity);
16880   break;
16881 case mp_independent:mp_print_variable_name(mp, p); break;
16882 default: mp_confusion(mp, "exp"); break;
16883 @:this can't happen exp}{\quad exp@>
16884 }
16885
16886 @ @<Display a big node@>=
16887
16888   mp_print_char(mp, xord('(')); q=v+mp->big_node_size[t];
16889   do {  
16890     if ( type(v)==mp_known ) mp_print_scaled(mp, value(v));
16891     else if ( type(v)==mp_independent ) mp_print_variable_name(mp, v);
16892     else mp_print_dp(mp, type(v),dep_list(v),verbosity);
16893     v=v+2;
16894     if ( v!=q ) mp_print_char(mp, xord(','));
16895   } while (v!=q);
16896   mp_print_char(mp, xord(')'));
16897 }
16898
16899 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16900 in the log file only, unless the user has given a positive value to
16901 \\{tracingonline}.
16902
16903 @<Display a complex type@>=
16904 if ( verbosity<=1 ) {
16905   mp_print_type(mp, t);
16906 } else { 
16907   if ( mp->selector==term_and_log )
16908    if ( mp->internal[mp_tracing_online]<=0 ) {
16909     mp->selector=term_only;
16910     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16911     mp->selector=term_and_log;
16912   };
16913   switch (t) {
16914   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16915   case mp_path_type:mp_print_path(mp, v,"",false); break;
16916   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16917   } /* there are no other cases */
16918 }
16919
16920 @ @<Declare the procedure called |print_dp|@>=
16921 static void mp_print_dp (MP mp, quarterword t, pointer p, 
16922                   quarterword verbosity)  {
16923   pointer q; /* the node following |p| */
16924   q=mp_link(p);
16925   if ( (info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16926   else mp_print(mp, "linearform");
16927 }
16928
16929 @ The displayed name of a variable in a ring will not be a capsule unless
16930 the ring consists entirely of capsules.
16931
16932 @<Display a variable that's been declared but not defined@>=
16933 { mp_print_type(mp, t);
16934 if ( v!=null )
16935   { mp_print_char(mp, xord(' '));
16936   while ( (name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16937   mp_print_variable_name(mp, v);
16938   };
16939 }
16940
16941 @ When errors are detected during parsing, it is often helpful to
16942 display an expression just above the error message, using |exp_err|
16943 or |disp_err| instead of |print_err|.
16944
16945 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16946
16947 @<Declarations@>=
16948 static void mp_disp_err (MP mp,pointer p, const char *s) ;
16949
16950 @ @c
16951 void mp_disp_err (MP mp,pointer p, const char *s) { 
16952   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16953   mp_print_nl(mp, ">> ");
16954 @.>>@>
16955   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16956   if (strlen(s)>0) { 
16957     mp_print_nl(mp, "! "); mp_print(mp, s);
16958 @.!\relax@>
16959   }
16960 }
16961
16962 @ If |cur_type| and |cur_exp| contain relevant information that should
16963 be recycled, we will use the following procedure, which changes |cur_type|
16964 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16965 and |cur_exp| as either alive or dormant after this has been done,
16966 because |cur_exp| will not contain a pointer value.
16967
16968 @ @c 
16969 static void mp_flush_cur_exp (MP mp,scaled v) { 
16970   switch (mp->cur_type) {
16971   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16972   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16973     mp_recycle_value(mp, mp->cur_exp); 
16974     mp_free_node(mp, mp->cur_exp,value_node_size);
16975     break;
16976   case mp_string_type:
16977     delete_str_ref(mp->cur_exp); break;
16978   case mp_pen_type: case mp_path_type: 
16979     mp_toss_knot_list(mp, mp->cur_exp); break;
16980   case mp_picture_type:
16981     delete_edge_ref(mp->cur_exp); break;
16982   default: 
16983     break;
16984   }
16985   mp->cur_type=mp_known; mp->cur_exp=v;
16986 }
16987
16988 @ There's a much more general procedure that is capable of releasing
16989 the storage associated with any two-word value packet.
16990
16991 @<Declarations@>=
16992 static void mp_recycle_value (MP mp,pointer p) ;
16993
16994 @ @c 
16995 static void mp_recycle_value (MP mp,pointer p) {
16996   quarterword t; /* a type code */
16997   integer vv; /* another value */
16998   pointer q,r,s,pp; /* link manipulation registers */
16999   integer v=0; /* a value */
17000   t=type(p);
17001   if ( t<mp_dependent ) v=value(p);
17002   switch (t) {
17003   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
17004   case mp_numeric_type:
17005     break;
17006   case unknown_types:
17007     mp_ring_delete(mp, p); break;
17008   case mp_string_type:
17009     delete_str_ref(v); break;
17010   case mp_path_type: case mp_pen_type:
17011     mp_toss_knot_list(mp, v); break;
17012   case mp_picture_type:
17013     delete_edge_ref(v); break;
17014   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
17015   case mp_transform_type:
17016     @<Recycle a big node@>; break; 
17017   case mp_dependent: case mp_proto_dependent:
17018     @<Recycle a dependency list@>; break;
17019   case mp_independent:
17020     @<Recycle an independent variable@>; break;
17021   case mp_token_list: case mp_structured:
17022     mp_confusion(mp, "recycle"); break;
17023 @:this can't happen recycle}{\quad recycle@>
17024   case mp_unsuffixed_macro: case mp_suffixed_macro:
17025     mp_delete_mac_ref(mp, value(p)); break;
17026   } /* there are no other cases */
17027   type(p)=undefined;
17028 }
17029
17030 @ @<Recycle a big node@>=
17031 if ( v!=null ){ 
17032   q=v+mp->big_node_size[t];
17033   do {  
17034     q=q-2; mp_recycle_value(mp, q);
17035   } while (q!=v);
17036   mp_free_node(mp, v,mp->big_node_size[t]);
17037 }
17038
17039 @ @<Recycle a dependency list@>=
17040
17041   q=dep_list(p);
17042   while ( info(q)!=null ) q=mp_link(q);
17043   mp_link(prev_dep(p))=mp_link(q);
17044   prev_dep(mp_link(q))=prev_dep(p);
17045   mp_link(q)=null; mp_flush_node_list(mp, dep_list(p));
17046 }
17047
17048 @ When an independent variable disappears, it simply fades away, unless
17049 something depends on it. In the latter case, a dependent variable whose
17050 coefficient of dependence is maximal will take its place.
17051 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
17052 as part of his Ph.D. thesis (Stanford University, December 1982).
17053 @^Zabala Salelles, Ignacio Andr\'es@>
17054
17055 For example, suppose that variable $x$ is being recycled, and that the
17056 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
17057 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
17058 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
17059 we will print `\.{\#\#\# -2x=-y+a}'.
17060
17061 There's a slight complication, however: An independent variable $x$
17062 can occur both in dependency lists and in proto-dependency lists.
17063 This makes it necessary to be careful when deciding which coefficient
17064 is maximal.
17065
17066 Furthermore, this complication is not so slight when
17067 a proto-dependent variable is chosen to become independent. For example,
17068 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
17069 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
17070 large coefficient `50'.
17071
17072 In order to deal with these complications without wasting too much time,
17073 we shall link together the occurrences of~$x$ among all the linear
17074 dependencies, maintaining separate lists for the dependent and
17075 proto-dependent cases.
17076
17077 @<Recycle an independent variable@>=
17078
17079   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
17080   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
17081   q=mp_link(dep_head);
17082   while ( q!=dep_head ) { 
17083     s=value_loc(q); /* now |mp_link(s)=dep_list(q)| */
17084     while (1) { 
17085       r=mp_link(s);
17086       if ( info(r)==null ) break;
17087       if ( info(r)!=p ) { 
17088         s=r;
17089       } else  { 
17090         t=type(q); mp_link(s)=mp_link(r); info(r)=q;
17091         if ( abs(value(r))>mp->max_c[t] ) {
17092           @<Record a new maximum coefficient of type |t|@>;
17093         } else { 
17094           mp_link(r)=mp->max_link[t]; mp->max_link[t]=r;
17095         }
17096       }
17097     } 
17098     q=mp_link(r);
17099   }
17100   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
17101     @<Choose a dependent variable to take the place of the disappearing
17102     independent variable, and change all remaining dependencies
17103     accordingly@>;
17104   }
17105 }
17106
17107 @ The code for independency removal makes use of three two-word arrays.
17108
17109 @<Glob...@>=
17110 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
17111 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
17112 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
17113
17114 @ @<Record a new maximum coefficient...@>=
17115
17116   if ( mp->max_c[t]>0 ) {
17117     mp_link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17118   }
17119   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
17120 }
17121
17122 @ @<Choose a dependent...@>=
17123
17124   if ( (mp->max_c[mp_dependent] / 010000) >= mp->max_c[mp_proto_dependent] )
17125     t=mp_dependent;
17126   else 
17127     t=mp_proto_dependent;
17128   @<Determine the dependency list |s| to substitute for the independent
17129     variable~|p|@>;
17130   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
17131   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
17132     mp_link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17133   }
17134   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
17135   else { @<Substitute new proto-dependencies in place of |p|@>;}
17136   mp_flush_node_list(mp, s);
17137   if ( mp->fix_needed ) mp_fix_dependencies(mp);
17138   check_arith;
17139 }
17140
17141 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
17142 and |info(s)| points to the dependent variable~|pp| of type~|t| from
17143 whose dependency list we have removed node~|s|. We must reinsert
17144 node~|s| into the dependency list, with coefficient $-1.0$, and with
17145 |pp| as the new independent variable. Since |pp| will have a larger serial
17146 number than any other variable, we can put node |s| at the head of the
17147 list.
17148
17149 @<Determine the dep...@>=
17150 s=mp->max_ptr[t]; pp=info(s); v=value(s);
17151 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
17152 r=dep_list(pp); mp_link(s)=r;
17153 while ( info(r)!=null ) r=mp_link(r);
17154 q=mp_link(r); mp_link(r)=null;
17155 prev_dep(q)=prev_dep(pp); mp_link(prev_dep(pp))=q;
17156 new_indep(pp);
17157 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
17158 if ( mp->internal[mp_tracing_equations]>0 ) { 
17159   @<Show the transformed dependency@>; 
17160 }
17161
17162 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
17163 by the dependency list~|s|.
17164
17165 @<Show the transformed...@>=
17166 if ( mp_interesting(mp, p) ) {
17167   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
17168 @:]]]\#\#\#_}{\.{\#\#\#}@>
17169   if ( v>0 ) mp_print_char(mp, xord('-'));
17170   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17171   else vv=mp->max_c[mp_proto_dependent];
17172   if ( vv!=unity ) mp_print_scaled(mp, vv);
17173   mp_print_variable_name(mp, p);
17174   while ( value(p) % s_scale>0 ) {
17175     mp_print(mp, "*4"); value(p)=value(p)-2;
17176   }
17177   if ( t==mp_dependent ) mp_print_char(mp, xord('=')); else mp_print(mp, " = ");
17178   mp_print_dependency(mp, s,t);
17179   mp_end_diagnostic(mp, false);
17180 }
17181
17182 @ Finally, there are dependent and proto-dependent variables whose
17183 dependency lists must be brought up to date.
17184
17185 @<Substitute new dependencies...@>=
17186 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17187   r=mp->max_link[t];
17188   while ( r!=null ) {
17189     q=info(r);
17190     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17191      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17192     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17193     q=r; r=mp_link(r); mp_free_node(mp, q,dep_node_size);
17194   }
17195 }
17196
17197 @ @<Substitute new proto...@>=
17198 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17199   r=mp->max_link[t];
17200   while ( r!=null ) {
17201     q=info(r);
17202     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17203       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17204         mp->cur_type=mp_proto_dependent;
17205       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,
17206          mp_dependent,mp_proto_dependent);
17207       type(q)=mp_proto_dependent; 
17208       value(r)=mp_round_fraction(mp, value(r));
17209     }
17210     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17211        mp_make_scaled(mp, value(r),-v),s,
17212        mp_proto_dependent,mp_proto_dependent);
17213     if ( dep_list(q)==mp->dep_final ) 
17214        mp_make_known(mp, q,mp->dep_final);
17215     q=r; r=mp_link(r); mp_free_node(mp, q,dep_node_size);
17216   }
17217 }
17218
17219 @ Here are some routines that provide handy combinations of actions
17220 that are often needed during error recovery. For example,
17221 `|flush_error|' flushes the current expression, replaces it by
17222 a given value, and calls |error|.
17223
17224 Errors often are detected after an extra token has already been scanned.
17225 The `\\{put\_get}' routines put that token back before calling |error|;
17226 then they get it back again. (Or perhaps they get another token, if
17227 the user has changed things.)
17228
17229 @<Declarations@>=
17230 static void mp_flush_error (MP mp,scaled v);
17231 static void mp_put_get_error (MP mp);
17232 static void mp_put_get_flush_error (MP mp,scaled v) ;
17233
17234 @ @c
17235 void mp_flush_error (MP mp,scaled v) { 
17236   mp_error(mp); mp_flush_cur_exp(mp, v); 
17237 }
17238 void mp_put_get_error (MP mp) { 
17239   mp_back_error(mp); mp_get_x_next(mp); 
17240 }
17241 void mp_put_get_flush_error (MP mp,scaled v) { 
17242   mp_put_get_error(mp);
17243   mp_flush_cur_exp(mp, v); 
17244 }
17245
17246 @ A global variable |var_flag| is set to a special command code
17247 just before \MP\ calls |scan_expression|, if the expression should be
17248 treated as a variable when this command code immediately follows. For
17249 example, |var_flag| is set to |assignment| at the beginning of a
17250 statement, because we want to know the {\sl location\/} of a variable at
17251 the left of `\.{:=}', not the {\sl value\/} of that variable.
17252
17253 The |scan_expression| subroutine calls |scan_tertiary|,
17254 which calls |scan_secondary|, which calls |scan_primary|, which sets
17255 |var_flag:=0|. In this way each of the scanning routines ``knows''
17256 when it has been called with a special |var_flag|, but |var_flag| is
17257 usually zero.
17258
17259 A variable preceding a command that equals |var_flag| is converted to a
17260 token list rather than a value. Furthermore, an `\.{=}' sign following an
17261 expression with |var_flag=assignment| is not considered to be a relation
17262 that produces boolean expressions.
17263
17264
17265 @<Glob...@>=
17266 int var_flag; /* command that wants a variable */
17267
17268 @ @<Set init...@>=
17269 mp->var_flag=0;
17270
17271 @* \[37] Parsing primary expressions.
17272 The first parsing routine, |scan_primary|, is also the most complicated one,
17273 since it involves so many different cases. But each case---with one
17274 exception---is fairly simple by itself.
17275
17276 When |scan_primary| begins, the first token of the primary to be scanned
17277 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17278 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17279 earlier. If |cur_cmd| is not between |min_primary_command| and
17280 |max_primary_command|, inclusive, a syntax error will be signaled.
17281
17282 @<Declare the basic parsing subroutines@>=
17283 void mp_scan_primary (MP mp) {
17284   pointer p,q,r; /* for list manipulation */
17285   quarterword c; /* a primitive operation code */
17286   int my_var_flag; /* initial value of |my_var_flag| */
17287   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17288   @<Other local variables for |scan_primary|@>;
17289   my_var_flag=mp->var_flag; mp->var_flag=0;
17290 RESTART:
17291   check_arith;
17292   @<Supply diagnostic information, if requested@>;
17293   switch (mp->cur_cmd) {
17294   case left_delimiter:
17295     @<Scan a delimited primary@>; break;
17296   case begin_group:
17297     @<Scan a grouped primary@>; break;
17298   case string_token:
17299     @<Scan a string constant@>; break;
17300   case numeric_token:
17301     @<Scan a primary that starts with a numeric token@>; break;
17302   case nullary:
17303     @<Scan a nullary operation@>; break;
17304   case unary: case type_name: case cycle: case plus_or_minus:
17305     @<Scan a unary operation@>; break;
17306   case primary_binary:
17307     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17308   case str_op:
17309     @<Convert a suffix to a string@>; break;
17310   case internal_quantity:
17311     @<Scan an internal numeric quantity@>; break;
17312   case capsule_token:
17313     mp_make_exp_copy(mp, mp->cur_mod); break;
17314   case tag_token:
17315     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17316   default: 
17317     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17318 @.A primary expression...@>
17319   }
17320   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17321 DONE: 
17322   if ( mp->cur_cmd==left_bracket ) {
17323     if ( mp->cur_type>=mp_known ) {
17324       @<Scan a mediation construction@>;
17325     }
17326   }
17327 }
17328
17329
17330
17331 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17332
17333 @c 
17334 static void mp_bad_exp (MP mp, const char * s) {
17335   int save_flag;
17336   print_err(s); mp_print(mp, " expression can't begin with `");
17337   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17338   mp_print_char(mp, xord('\''));
17339   help4("I'm afraid I need some sort of value in order to continue,",
17340     "so I've tentatively inserted `0'. You may want to",
17341     "delete this zero and insert something else;",
17342     "see Chapter 27 of The METAFONTbook for an example.");
17343 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17344   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17345   mp->cur_mod=0; mp_ins_error(mp);
17346   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17347   mp->var_flag=save_flag;
17348 }
17349
17350 @ @<Supply diagnostic information, if requested@>=
17351 #ifdef DEBUG
17352 if ( mp->panicking ) mp_check_mem(mp, false);
17353 #endif
17354 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17355   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17356 }
17357
17358 @ @<Scan a delimited primary@>=
17359
17360   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17361   mp_get_x_next(mp); mp_scan_expression(mp);
17362   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17363     @<Scan the rest of a delimited set of numerics@>;
17364   } else {
17365     mp_check_delimiter(mp, l_delim,r_delim);
17366   }
17367 }
17368
17369 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17370 within a ``big node.''
17371
17372 @c 
17373 static void mp_stash_in (MP mp,pointer p) {
17374   pointer q; /* temporary register */
17375   type(p)=mp->cur_type;
17376   if ( mp->cur_type==mp_known ) {
17377     value(p)=mp->cur_exp;
17378   } else { 
17379     if ( mp->cur_type==mp_independent ) {
17380       @<Stash an independent |cur_exp| into a big node@>;
17381     } else { 
17382       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17383       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17384       mp_link(prev_dep(p))=p;
17385     }
17386     mp_free_node(mp, mp->cur_exp,value_node_size);
17387   }
17388   mp->cur_type=mp_vacuous;
17389 }
17390
17391 @ In rare cases the current expression can become |independent|. There
17392 may be many dependency lists pointing to such an independent capsule,
17393 so we can't simply move it into place within a big node. Instead,
17394 we copy it, then recycle it.
17395
17396 @ @<Stash an independent |cur_exp|...@>=
17397
17398   q=mp_single_dependency(mp, mp->cur_exp);
17399   if ( q==mp->dep_final ){ 
17400     type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17401   } else { 
17402     type(p)=mp_dependent; mp_new_dep(mp, p,q);
17403   }
17404   mp_recycle_value(mp, mp->cur_exp);
17405 }
17406
17407 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17408 are synonymous with |x_part_loc| and |y_part_loc|.
17409
17410 @<Scan the rest of a delimited set of numerics@>=
17411
17412 p=mp_stash_cur_exp(mp);
17413 mp_get_x_next(mp); mp_scan_expression(mp);
17414 @<Make sure the second part of a pair or color has a numeric type@>;
17415 q=mp_get_node(mp, value_node_size); name_type(q)=mp_capsule;
17416 if ( mp->cur_cmd==comma ) type(q)=mp_color_type;
17417 else type(q)=mp_pair_type;
17418 mp_init_big_node(mp, q); r=value(q);
17419 mp_stash_in(mp, y_part_loc(r));
17420 mp_unstash_cur_exp(mp, p);
17421 mp_stash_in(mp, x_part_loc(r));
17422 if ( mp->cur_cmd==comma ) {
17423   @<Scan the last of a triplet of numerics@>;
17424 }
17425 if ( mp->cur_cmd==comma ) {
17426   type(q)=mp_cmykcolor_type;
17427   mp_init_big_node(mp, q); t=value(q);
17428   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17429   value(cyan_part_loc(t))=value(red_part_loc(r));
17430   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17431   value(magenta_part_loc(t))=value(green_part_loc(r));
17432   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17433   value(yellow_part_loc(t))=value(blue_part_loc(r));
17434   mp_recycle_value(mp, r);
17435   r=t;
17436   @<Scan the last of a quartet of numerics@>;
17437 }
17438 mp_check_delimiter(mp, l_delim,r_delim);
17439 mp->cur_type=type(q);
17440 mp->cur_exp=q;
17441 }
17442
17443 @ @<Make sure the second part of a pair or color has a numeric type@>=
17444 if ( mp->cur_type<mp_known ) {
17445   exp_err("Nonnumeric ypart has been replaced by 0");
17446 @.Nonnumeric...replaced by 0@>
17447   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';",
17448     "but after finding a nice `a' I found a `b' that isn't",
17449     "of numeric type. So I've changed that part to zero.",
17450     "(The b that I didn't like appears above the error message.)");
17451   mp_put_get_flush_error(mp, 0);
17452 }
17453
17454 @ @<Scan the last of a triplet of numerics@>=
17455
17456   mp_get_x_next(mp); mp_scan_expression(mp);
17457   if ( mp->cur_type<mp_known ) {
17458     exp_err("Nonnumeric third part has been replaced by 0");
17459 @.Nonnumeric...replaced by 0@>
17460     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'",
17461       "isn't of numeric type. So I've changed that part to zero.",
17462       "(The c that I didn't like appears above the error message.)");
17463     mp_put_get_flush_error(mp, 0);
17464   }
17465   mp_stash_in(mp, blue_part_loc(r));
17466 }
17467
17468 @ @<Scan the last of a quartet of numerics@>=
17469
17470   mp_get_x_next(mp); mp_scan_expression(mp);
17471   if ( mp->cur_type<mp_known ) {
17472     exp_err("Nonnumeric blackpart has been replaced by 0");
17473 @.Nonnumeric...replaced by 0@>
17474     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't",
17475       "of numeric type. So I've changed that part to zero.",
17476       "(The k that I didn't like appears above the error message.)");
17477     mp_put_get_flush_error(mp, 0);
17478   }
17479   mp_stash_in(mp, black_part_loc(r));
17480 }
17481
17482 @ The local variable |group_line| keeps track of the line
17483 where a \&{begingroup} command occurred; this will be useful
17484 in an error message if the group doesn't actually end.
17485
17486 @<Other local variables for |scan_primary|@>=
17487 integer group_line; /* where a group began */
17488
17489 @ @<Scan a grouped primary@>=
17490
17491   group_line=mp_true_line(mp);
17492   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17493   save_boundary_item(p);
17494   do {  
17495     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17496   } while (mp->cur_cmd==semicolon);
17497   if ( mp->cur_cmd!=end_group ) {
17498     print_err("A group begun on line ");
17499 @.A group...never ended@>
17500     mp_print_int(mp, group_line);
17501     mp_print(mp, " never ended");
17502     help2("I saw a `begingroup' back there that hasn't been matched",
17503           "by `endgroup'. So I've inserted `endgroup' now.");
17504     mp_back_error(mp); mp->cur_cmd=end_group;
17505   }
17506   mp_unsave(mp); 
17507     /* this might change |cur_type|, if independent variables are recycled */
17508   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17509 }
17510
17511 @ @<Scan a string constant@>=
17512
17513   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17514 }
17515
17516 @ Later we'll come to procedures that perform actual operations like
17517 addition, square root, and so on; our purpose now is to do the parsing.
17518 But we might as well mention those future procedures now, so that the
17519 suspense won't be too bad:
17520
17521 \smallskip
17522 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17523 `\&{true}' or `\&{pencircle}');
17524
17525 \smallskip
17526 |do_unary(c)| applies a primitive operation to the current expression;
17527
17528 \smallskip
17529 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17530 and the current expression.
17531
17532 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17533
17534 @ @<Scan a unary operation@>=
17535
17536   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17537   mp_do_unary(mp, c); goto DONE;
17538 }
17539
17540 @ A numeric token might be a primary by itself, or it might be the
17541 numerator of a fraction composed solely of numeric tokens, or it might
17542 multiply the primary that follows (provided that the primary doesn't begin
17543 with a plus sign or a minus sign). The code here uses the facts that
17544 |max_primary_command=plus_or_minus| and
17545 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17546 than unity, we try to retain higher precision when we use it in scalar
17547 multiplication.
17548
17549 @<Other local variables for |scan_primary|@>=
17550 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17551
17552 @ @<Scan a primary that starts with a numeric token@>=
17553
17554   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17555   if ( mp->cur_cmd!=slash ) { 
17556     num=0; denom=0;
17557   } else { 
17558     mp_get_x_next(mp);
17559     if ( mp->cur_cmd!=numeric_token ) { 
17560       mp_back_input(mp);
17561       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17562       goto DONE;
17563     }
17564     num=mp->cur_exp; denom=mp->cur_mod;
17565     if ( denom==0 ) { @<Protest division by zero@>; }
17566     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17567     check_arith; mp_get_x_next(mp);
17568   }
17569   if ( mp->cur_cmd>=min_primary_command ) {
17570    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17571      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17572      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17573        mp_do_binary(mp, p,times);
17574      } else {
17575        mp_frac_mult(mp, num,denom);
17576        mp_free_node(mp, p,value_node_size);
17577      }
17578     }
17579   }
17580   goto DONE;
17581 }
17582
17583 @ @<Protest division...@>=
17584
17585   print_err("Division by zero");
17586 @.Division by zero@>
17587   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17588 }
17589
17590 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17591
17592   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17593   if ( mp->cur_cmd!=of_token ) {
17594     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17595     mp_print_cmd_mod(mp, primary_binary,c);
17596 @.Missing `of'@>
17597     help1("I've got the first argument; will look now for the other.");
17598     mp_back_error(mp);
17599   }
17600   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17601   mp_do_binary(mp, p,c); goto DONE;
17602 }
17603
17604 @ @<Convert a suffix to a string@>=
17605
17606   mp_get_x_next(mp); mp_scan_suffix(mp); 
17607   mp->old_setting=mp->selector; mp->selector=new_string;
17608   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17609   mp_flush_token_list(mp, mp->cur_exp);
17610   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17611   mp->cur_type=mp_string_type;
17612   goto DONE;
17613 }
17614
17615 @ If an internal quantity appears all by itself on the left of an
17616 assignment, we return a token list of length one, containing the address
17617 of the internal quantity plus |hash_end|. (This accords with the conventions
17618 of the save stack, as described earlier.)
17619
17620 @<Scan an internal...@>=
17621
17622   q=mp->cur_mod;
17623   if ( my_var_flag==assignment ) {
17624     mp_get_x_next(mp);
17625     if ( mp->cur_cmd==assignment ) {
17626       mp->cur_exp=mp_get_avail(mp);
17627       info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17628       goto DONE;
17629     }
17630     mp_back_input(mp);
17631   }
17632   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17633 }
17634
17635 @ The most difficult part of |scan_primary| has been saved for last, since
17636 it was necessary to build up some confidence first. We can now face the task
17637 of scanning a variable.
17638
17639 As we scan a variable, we build a token list containing the relevant
17640 names and subscript values, simultaneously following along in the
17641 ``collective'' structure to see if we are actually dealing with a macro
17642 instead of a value.
17643
17644 The local variables |pre_head| and |post_head| will point to the beginning
17645 of the prefix and suffix lists; |tail| will point to the end of the list
17646 that is currently growing.
17647
17648 Another local variable, |tt|, contains partial information about the
17649 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17650 relation |tt=type(q)| will always hold. If |tt=undefined|, the routine
17651 doesn't bother to update its information about type. And if
17652 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17653
17654 @ @<Other local variables for |scan_primary|@>=
17655 pointer pre_head,post_head,tail;
17656   /* prefix and suffix list variables */
17657 quarterword tt; /* approximation to the type of the variable-so-far */
17658 pointer t; /* a token */
17659 pointer macro_ref = 0; /* reference count for a suffixed macro */
17660
17661 @ @<Scan a variable primary...@>=
17662
17663   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17664   while (1) { 
17665     t=mp_cur_tok(mp); mp_link(tail)=t;
17666     if ( tt!=undefined ) {
17667        @<Find the approximate type |tt| and corresponding~|q|@>;
17668       if ( tt>=mp_unsuffixed_macro ) {
17669         @<Either begin an unsuffixed macro call or
17670           prepare for a suffixed one@>;
17671       }
17672     }
17673     mp_get_x_next(mp); tail=t;
17674     if ( mp->cur_cmd==left_bracket ) {
17675       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17676     }
17677     if ( mp->cur_cmd>max_suffix_token ) break;
17678     if ( mp->cur_cmd<min_suffix_token ) break;
17679   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17680   @<Handle unusual cases that masquerade as variables, and |goto restart|
17681     or |goto done| if appropriate;
17682     otherwise make a copy of the variable and |goto done|@>;
17683 }
17684
17685 @ @<Either begin an unsuffixed macro call or...@>=
17686
17687   mp_link(tail)=null;
17688   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17689     post_head=mp_get_avail(mp); tail=post_head; mp_link(tail)=t;
17690     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17691   } else {
17692     @<Set up unsuffixed macro call and |goto restart|@>;
17693   }
17694 }
17695
17696 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17697
17698   mp_get_x_next(mp); mp_scan_expression(mp);
17699   if ( mp->cur_cmd!=right_bracket ) {
17700     @<Put the left bracket and the expression back to be rescanned@>;
17701   } else { 
17702     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17703     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17704   }
17705 }
17706
17707 @ The left bracket that we thought was introducing a subscript might have
17708 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17709 So we don't issue an error message at this point; but we do want to back up
17710 so as to avoid any embarrassment about our incorrect assumption.
17711
17712 @<Put the left bracket and the expression back to be rescanned@>=
17713
17714   mp_back_input(mp); /* that was the token following the current expression */
17715   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17716   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17717 }
17718
17719 @ Here's a routine that puts the current expression back to be read again.
17720
17721 @c 
17722 static void mp_back_expr (MP mp) {
17723   pointer p; /* capsule token */
17724   p=mp_stash_cur_exp(mp); mp_link(p)=null; back_list(p);
17725 }
17726
17727 @ Unknown subscripts lead to the following error message.
17728
17729 @c 
17730 static void mp_bad_subscript (MP mp) { 
17731   exp_err("Improper subscript has been replaced by zero");
17732 @.Improper subscript...@>
17733   help3("A bracketed subscript must have a known numeric value;",
17734     "unfortunately, what I found was the value that appears just",
17735     "above this error message. So I'll try a zero subscript.");
17736   mp_flush_error(mp, 0);
17737 }
17738
17739 @ Every time we call |get_x_next|, there's a chance that the variable we've
17740 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17741 into the variable structure; we need to start searching from the root each time.
17742
17743 @<Find the approximate type |tt| and corresponding~|q|@>=
17744 @^inner loop@>
17745
17746   p=mp_link(pre_head); q=info(p); tt=undefined;
17747   if ( eq_type(q) % outer_tag==tag_token ) {
17748     q=equiv(q);
17749     if ( q==null ) goto DONE2;
17750     while (1) { 
17751       p=mp_link(p);
17752       if ( p==null ) {
17753         tt=type(q); goto DONE2;
17754       };
17755       if ( type(q)!=mp_structured ) goto DONE2;
17756       q=mp_link(attr_head(q)); /* the |collective_subscript| attribute */
17757       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17758         do {  q=mp_link(q); } while (! (attr_loc(q)>=info(p)));
17759         if ( attr_loc(q)>info(p) ) goto DONE2;
17760       }
17761     }
17762   }
17763 DONE2:
17764   ;
17765 }
17766
17767 @ How do things stand now? Well, we have scanned an entire variable name,
17768 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17769 |cur_sym| represent the token that follows. If |post_head=null|, a
17770 token list for this variable name starts at |mp_link(pre_head)|, with all
17771 subscripts evaluated. But if |post_head<>null|, the variable turned out
17772 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17773 |post_head| is the head of a token list containing both `\.{\AT!}' and
17774 the suffix.
17775
17776 Our immediate problem is to see if this variable still exists. (Variable
17777 structures can change drastically whenever we call |get_x_next|; users
17778 aren't supposed to do this, but the fact that it is possible means that
17779 we must be cautious.)
17780
17781 The following procedure prints an error message when a variable
17782 unexpectedly disappears. Its help message isn't quite right for
17783 our present purposes, but we'll be able to fix that up.
17784
17785 @c 
17786 static void mp_obliterated (MP mp,pointer q) { 
17787   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17788   mp_print(mp, " has been obliterated");
17789 @.Variable...obliterated@>
17790   help5("It seems you did a nasty thing---probably by accident,",
17791      "but nevertheless you nearly hornswoggled me...",
17792      "While I was evaluating the right-hand side of this",
17793      "command, something happened, and the left-hand side",
17794      "is no longer a variable! So I won't change anything.");
17795 }
17796
17797 @ If the variable does exist, we also need to check
17798 for a few other special cases before deciding that a plain old ordinary
17799 variable has, indeed, been scanned.
17800
17801 @<Handle unusual cases that masquerade as variables...@>=
17802 if ( post_head!=null ) {
17803   @<Set up suffixed macro call and |goto restart|@>;
17804 }
17805 q=mp_link(pre_head); free_avail(pre_head);
17806 if ( mp->cur_cmd==my_var_flag ) { 
17807   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17808 }
17809 p=mp_find_variable(mp, q);
17810 if ( p!=null ) {
17811   mp_make_exp_copy(mp, p);
17812 } else { 
17813   mp_obliterated(mp, q);
17814   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17815   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17816   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17817   mp_put_get_flush_error(mp, 0);
17818 }
17819 mp_flush_node_list(mp, q); 
17820 goto DONE
17821
17822 @ The only complication associated with macro calling is that the prefix
17823 and ``at'' parameters must be packaged in an appropriate list of lists.
17824
17825 @<Set up unsuffixed macro call and |goto restart|@>=
17826
17827   p=mp_get_avail(mp); info(pre_head)=mp_link(pre_head); mp_link(pre_head)=p;
17828   info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17829   mp_get_x_next(mp); 
17830   goto RESTART;
17831 }
17832
17833 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17834 we don't care, because we have reserved a pointer (|macro_ref|) to its
17835 token list.
17836
17837 @<Set up suffixed macro call and |goto restart|@>=
17838
17839   mp_back_input(mp); p=mp_get_avail(mp); q=mp_link(post_head);
17840   info(pre_head)=mp_link(pre_head); mp_link(pre_head)=post_head;
17841   info(post_head)=q; mp_link(post_head)=p; info(p)=mp_link(q); mp_link(q)=null;
17842   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17843   mp_get_x_next(mp); goto RESTART;
17844 }
17845
17846 @ Our remaining job is simply to make a copy of the value that has been
17847 found. Some cases are harder than others, but complexity arises solely
17848 because of the multiplicity of possible cases.
17849
17850 @<Declare the procedure called |make_exp_copy|@>=
17851 @<Declare subroutines needed by |make_exp_copy|@>
17852 static void mp_make_exp_copy (MP mp,pointer p) {
17853   pointer q,r,t; /* registers for list manipulation */
17854 RESTART: 
17855   mp->cur_type=type(p);
17856   switch (mp->cur_type) {
17857   case mp_vacuous: case mp_boolean_type: case mp_known:
17858     mp->cur_exp=value(p); break;
17859   case unknown_types:
17860     mp->cur_exp=mp_new_ring_entry(mp, p);
17861     break;
17862   case mp_string_type: 
17863     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17864     break;
17865   case mp_picture_type:
17866     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17867     break;
17868   case mp_pen_type:
17869     mp->cur_exp=copy_pen(value(p));
17870     break; 
17871   case mp_path_type:
17872     mp->cur_exp=mp_copy_path(mp, value(p));
17873     break;
17874   case mp_transform_type: case mp_color_type: 
17875   case mp_cmykcolor_type: case mp_pair_type:
17876     @<Copy the big node |p|@>;
17877     break;
17878   case mp_dependent: case mp_proto_dependent:
17879     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17880     break;
17881   case mp_numeric_type: 
17882     new_indep(p); goto RESTART;
17883     break;
17884   case mp_independent: 
17885     q=mp_single_dependency(mp, p);
17886     if ( q==mp->dep_final ){ 
17887       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,dep_node_size);
17888     } else { 
17889       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17890     }
17891     break;
17892   default: 
17893     mp_confusion(mp, "copy");
17894 @:this can't happen copy}{\quad copy@>
17895     break;
17896   }
17897 }
17898
17899 @ The |encapsulate| subroutine assumes that |dep_final| is the
17900 tail of dependency list~|p|.
17901
17902 @<Declare subroutines needed by |make_exp_copy|@>=
17903 static void mp_encapsulate (MP mp,pointer p) { 
17904   mp->cur_exp=mp_get_node(mp, value_node_size); type(mp->cur_exp)=mp->cur_type;
17905   name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17906 }
17907
17908 @ The most tedious case arises when the user refers to a
17909 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17910 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17911 or |known|.
17912
17913 @<Copy the big node |p|@>=
17914
17915   if ( value(p)==null ) 
17916     mp_init_big_node(mp, p);
17917   t=mp_get_node(mp, value_node_size); name_type(t)=mp_capsule; type(t)=mp->cur_type;
17918   mp_init_big_node(mp, t);
17919   q=value(p)+mp->big_node_size[mp->cur_type]; 
17920   r=value(t)+mp->big_node_size[mp->cur_type];
17921   do {  
17922     q=q-2; r=r-2; mp_install(mp, r,q);
17923   } while (q!=value(p));
17924   mp->cur_exp=t;
17925 }
17926
17927 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17928 a big node that will be part of a capsule.
17929
17930 @<Declare subroutines needed by |make_exp_copy|@>=
17931 static void mp_install (MP mp,pointer r, pointer q) {
17932   pointer p; /* temporary register */
17933   if ( type(q)==mp_known ){ 
17934     value(r)=value(q); type(r)=mp_known;
17935   } else  if ( type(q)==mp_independent ) {
17936     p=mp_single_dependency(mp, q);
17937     if ( p==mp->dep_final ) {
17938       type(r)=mp_known; value(r)=0; mp_free_node(mp, p,dep_node_size);
17939     } else  { 
17940       type(r)=mp_dependent; mp_new_dep(mp, r,p);
17941     }
17942   } else {
17943     type(r)=type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17944   }
17945 }
17946
17947 @ Expressions of the form `\.{a[b,c]}' are converted into
17948 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17949 provided that \.a is numeric.
17950
17951 @<Scan a mediation...@>=
17952
17953   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17954   if ( mp->cur_cmd!=comma ) {
17955     @<Put the left bracket and the expression back...@>;
17956     mp_unstash_cur_exp(mp, p);
17957   } else { 
17958     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17959     if ( mp->cur_cmd!=right_bracket ) {
17960       mp_missing_err(mp, "]");
17961 @.Missing `]'@>
17962       help3("I've scanned an expression of the form `a[b,c',",
17963       "so a right bracket should have come next.",
17964       "I shall pretend that one was there.");
17965       mp_back_error(mp);
17966     }
17967     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17968     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17969     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17970   }
17971 }
17972
17973 @ Here is a comparatively simple routine that is used to scan the
17974 \&{suffix} parameters of a macro.
17975
17976 @<Declare the basic parsing subroutines@>=
17977 static void mp_scan_suffix (MP mp) {
17978   pointer h,t; /* head and tail of the list being built */
17979   pointer p; /* temporary register */
17980   h=mp_get_avail(mp); t=h;
17981   while (1) { 
17982     if ( mp->cur_cmd==left_bracket ) {
17983       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17984     }
17985     if ( mp->cur_cmd==numeric_token ) {
17986       p=mp_new_num_tok(mp, mp->cur_mod);
17987     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17988        p=mp_get_avail(mp); info(p)=mp->cur_sym;
17989     } else {
17990       break;
17991     }
17992     mp_link(t)=p; t=p; mp_get_x_next(mp);
17993   }
17994   mp->cur_exp=mp_link(h); free_avail(h); mp->cur_type=mp_token_list;
17995 }
17996
17997 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17998
17999   mp_get_x_next(mp); mp_scan_expression(mp);
18000   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
18001   if ( mp->cur_cmd!=right_bracket ) {
18002      mp_missing_err(mp, "]");
18003 @.Missing `]'@>
18004     help3("I've seen a `[' and a subscript value, in a suffix,",
18005       "so a right bracket should have come next.",
18006       "I shall pretend that one was there.");
18007     mp_back_error(mp);
18008   }
18009   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
18010 }
18011
18012 @* \[38] Parsing secondary and higher expressions.
18013
18014 After the intricacies of |scan_primary|\kern-1pt,
18015 the |scan_secondary| routine is
18016 refreshingly simple. It's not trivial, but the operations are relatively
18017 straightforward; the main difficulty is, again, that expressions and data
18018 structures might change drastically every time we call |get_x_next|, so a
18019 cautious approach is mandatory. For example, a macro defined by
18020 \&{primarydef} might have disappeared by the time its second argument has
18021 been scanned; we solve this by increasing the reference count of its token
18022 list, so that the macro can be called even after it has been clobbered.
18023
18024 @<Declare the basic parsing subroutines@>=
18025 static void mp_scan_secondary (MP mp) {
18026   pointer p; /* for list manipulation */
18027   halfword c,d; /* operation codes or modifiers */
18028   pointer mac_name; /* token defined with \&{primarydef} */
18029 RESTART:
18030   if ((mp->cur_cmd<min_primary_command)||
18031       (mp->cur_cmd>max_primary_command) )
18032     mp_bad_exp(mp, "A secondary");
18033 @.A secondary expression...@>
18034   mp_scan_primary(mp);
18035 CONTINUE: 
18036   if ( mp->cur_cmd<=max_secondary_command &&
18037        mp->cur_cmd>=min_secondary_command ) {
18038     p=mp_stash_cur_exp(mp); 
18039     c=mp->cur_mod; d=mp->cur_cmd;
18040     if ( d==secondary_primary_macro ) { 
18041       mac_name=mp->cur_sym; 
18042       add_mac_ref(c);
18043     }
18044     mp_get_x_next(mp); 
18045     mp_scan_primary(mp);
18046     if ( d!=secondary_primary_macro ) {
18047       mp_do_binary(mp, p,c);
18048     } else { 
18049       mp_back_input(mp); 
18050       mp_binary_mac(mp, p,c,mac_name);
18051       decr(ref_count(c)); 
18052       mp_get_x_next(mp); 
18053       goto RESTART;
18054     }
18055     goto CONTINUE;
18056   }
18057 }
18058
18059 @ The following procedure calls a macro that has two parameters,
18060 |p| and |cur_exp|.
18061
18062 @c 
18063 static void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
18064   pointer q,r; /* nodes in the parameter list */
18065   q=mp_get_avail(mp); r=mp_get_avail(mp); mp_link(q)=r;
18066   info(q)=p; info(r)=mp_stash_cur_exp(mp);
18067   mp_macro_call(mp, c,q,n);
18068 }
18069
18070 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
18071
18072 @<Declare the basic parsing subroutines@>=
18073 static void mp_scan_tertiary (MP mp) {
18074   pointer p; /* for list manipulation */
18075   halfword c,d; /* operation codes or modifiers */
18076   pointer mac_name; /* token defined with \&{secondarydef} */
18077 RESTART:
18078   if ((mp->cur_cmd<min_primary_command)||
18079       (mp->cur_cmd>max_primary_command) )
18080     mp_bad_exp(mp, "A tertiary");
18081 @.A tertiary expression...@>
18082   mp_scan_secondary(mp);
18083 CONTINUE: 
18084   if ( mp->cur_cmd<=max_tertiary_command ) {
18085     if ( mp->cur_cmd>=min_tertiary_command ) {
18086       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18087       if ( d==tertiary_secondary_macro ) { 
18088         mac_name=mp->cur_sym; add_mac_ref(c);
18089       };
18090       mp_get_x_next(mp); mp_scan_secondary(mp);
18091       if ( d!=tertiary_secondary_macro ) {
18092         mp_do_binary(mp, p,c);
18093       } else { 
18094         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18095         decr(ref_count(c)); mp_get_x_next(mp); 
18096         goto RESTART;
18097       }
18098       goto CONTINUE;
18099     }
18100   }
18101 }
18102
18103 @ Finally we reach the deepest level in our quartet of parsing routines.
18104 This one is much like the others; but it has an extra complication from
18105 paths, which materialize here.
18106
18107 @d continue_path 25 /* a label inside of |scan_expression| */
18108 @d finish_path 26 /* another */
18109
18110 @<Declare the basic parsing subroutines@>=
18111 static void mp_scan_expression (MP mp) {
18112   pointer p,q,r,pp,qq; /* for list manipulation */
18113   halfword c,d; /* operation codes or modifiers */
18114   int my_var_flag; /* initial value of |var_flag| */
18115   pointer mac_name; /* token defined with \&{tertiarydef} */
18116   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
18117   scaled x,y; /* explicit coordinates or tension at a path join */
18118   int t; /* knot type following a path join */
18119   t=0; y=0; x=0;
18120   my_var_flag=mp->var_flag; mac_name=null;
18121 RESTART:
18122   if ((mp->cur_cmd<min_primary_command)||
18123       (mp->cur_cmd>max_primary_command) )
18124     mp_bad_exp(mp, "An");
18125 @.An expression...@>
18126   mp_scan_tertiary(mp);
18127 CONTINUE: 
18128   if ( mp->cur_cmd<=max_expression_command )
18129     if ( mp->cur_cmd>=min_expression_command ) {
18130       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
18131         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18132         if ( d==expression_tertiary_macro ) {
18133           mac_name=mp->cur_sym; add_mac_ref(c);
18134         }
18135         if ( (d<ampersand)||((d==ampersand)&&
18136              ((type(p)==mp_pair_type)||(type(p)==mp_path_type))) ) {
18137           @<Scan a path construction operation;
18138             but |return| if |p| has the wrong type@>;
18139         } else { 
18140           mp_get_x_next(mp); mp_scan_tertiary(mp);
18141           if ( d!=expression_tertiary_macro ) {
18142             mp_do_binary(mp, p,c);
18143           } else  { 
18144             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18145             decr(ref_count(c)); mp_get_x_next(mp); 
18146             goto RESTART;
18147           }
18148         }
18149         goto CONTINUE;
18150      }
18151   }
18152 }
18153
18154 @ The reader should review the data structure conventions for paths before
18155 hoping to understand the next part of this code.
18156
18157 @<Scan a path construction operation...@>=
18158
18159   cycle_hit=false;
18160   @<Convert the left operand, |p|, into a partial path ending at~|q|;
18161     but |return| if |p| doesn't have a suitable type@>;
18162 CONTINUE_PATH: 
18163   @<Determine the path join parameters;
18164     but |goto finish_path| if there's only a direction specifier@>;
18165   if ( mp->cur_cmd==cycle ) {
18166     @<Get ready to close a cycle@>;
18167   } else { 
18168     mp_scan_tertiary(mp);
18169     @<Convert the right operand, |cur_exp|,
18170       into a partial path from |pp| to~|qq|@>;
18171   }
18172   @<Join the partial paths and reset |p| and |q| to the head and tail
18173     of the result@>;
18174   if ( mp->cur_cmd>=min_expression_command )
18175     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18176 FINISH_PATH:
18177   @<Choose control points for the path and put the result into |cur_exp|@>;
18178 }
18179
18180 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18181
18182   mp_unstash_cur_exp(mp, p);
18183   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18184   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18185   else return;
18186   q=p;
18187   while ( mp_link(q)!=p ) q=mp_link(q);
18188   if ( mp_left_type(p)!=mp_endpoint ) { /* open up a cycle */
18189     r=mp_copy_knot(mp, p); mp_link(q)=r; q=r;
18190   }
18191   mp_left_type(p)=mp_open; mp_right_type(q)=mp_open;
18192 }
18193
18194 @ A pair of numeric values is changed into a knot node for a one-point path
18195 when \MP\ discovers that the pair is part of a path.
18196
18197 @c 
18198 static pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18199   pointer q; /* the new node */
18200   q=mp_get_node(mp, knot_node_size); mp_left_type(q)=mp_endpoint;
18201   mp_right_type(q)=mp_endpoint; mp_originator(q)=mp_metapost_user; mp_link(q)=q;
18202   mp_known_pair(mp); mp_x_coord(q)=mp->cur_x; mp_y_coord(q)=mp->cur_y;
18203   return q;
18204 }
18205
18206 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18207 of the current expression, assuming that the current expression is a
18208 pair of known numerics. Unknown components are zeroed, and the
18209 current expression is flushed.
18210
18211 @<Declarations@>=
18212 static void mp_known_pair (MP mp);
18213
18214 @ @c
18215 void mp_known_pair (MP mp) {
18216   pointer p; /* the pair node */
18217   if ( mp->cur_type!=mp_pair_type ) {
18218     exp_err("Undefined coordinates have been replaced by (0,0)");
18219 @.Undefined coordinates...@>
18220     help5("I need x and y numbers for this part of the path.",
18221        "The value I found (see above) was no good;",
18222        "so I'll try to keep going by using zero instead.",
18223        "(Chapter 27 of The METAFONTbook explains that",
18224 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18225        "you might want to type `I ??" "?' now.)");
18226     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18227   } else { 
18228     p=value(mp->cur_exp);
18229      @<Make sure that both |x| and |y| parts of |p| are known;
18230        copy them into |cur_x| and |cur_y|@>;
18231     mp_flush_cur_exp(mp, 0);
18232   }
18233 }
18234
18235 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18236 if ( type(x_part_loc(p))==mp_known ) {
18237   mp->cur_x=value(x_part_loc(p));
18238 } else { 
18239   mp_disp_err(mp, x_part_loc(p),
18240     "Undefined x coordinate has been replaced by 0");
18241 @.Undefined coordinates...@>
18242   help5("I need a `known' x value for this part of the path.",
18243     "The value I found (see above) was no good;",
18244     "so I'll try to keep going by using zero instead.",
18245     "(Chapter 27 of The METAFONTbook explains that",
18246 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18247     "you might want to type `I ??" "?' now.)");
18248   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18249 }
18250 if ( type(y_part_loc(p))==mp_known ) {
18251   mp->cur_y=value(y_part_loc(p));
18252 } else { 
18253   mp_disp_err(mp, y_part_loc(p),
18254     "Undefined y coordinate has been replaced by 0");
18255   help5("I need a `known' y value for this part of the path.",
18256     "The value I found (see above) was no good;",
18257     "so I'll try to keep going by using zero instead.",
18258     "(Chapter 27 of The METAFONTbook explains that",
18259     "you might want to type `I ??" "?' now.)");
18260   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18261 }
18262
18263 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18264
18265 @<Determine the path join parameters...@>=
18266 if ( mp->cur_cmd==left_brace ) {
18267   @<Put the pre-join direction information into node |q|@>;
18268 }
18269 d=mp->cur_cmd;
18270 if ( d==path_join ) {
18271   @<Determine the tension and/or control points@>;
18272 } else if ( d!=ampersand ) {
18273   goto FINISH_PATH;
18274 }
18275 mp_get_x_next(mp);
18276 if ( mp->cur_cmd==left_brace ) {
18277   @<Put the post-join direction information into |x| and |t|@>;
18278 } else if ( mp_right_type(q)!=mp_explicit ) {
18279   t=mp_open; x=0;
18280 }
18281
18282 @ The |scan_direction| subroutine looks at the directional information
18283 that is enclosed in braces, and also scans ahead to the following character.
18284 A type code is returned, either |open| (if the direction was $(0,0)$),
18285 or |curl| (if the direction was a curl of known value |cur_exp|), or
18286 |given| (if the direction is given by the |angle| value that now
18287 appears in |cur_exp|).
18288
18289 There's nothing difficult about this subroutine, but the program is rather
18290 lengthy because a variety of potential errors need to be nipped in the bud.
18291
18292 @c 
18293 static quarterword mp_scan_direction (MP mp) {
18294   int t; /* the type of information found */
18295   scaled x; /* an |x| coordinate */
18296   mp_get_x_next(mp);
18297   if ( mp->cur_cmd==curl_command ) {
18298      @<Scan a curl specification@>;
18299   } else {
18300     @<Scan a given direction@>;
18301   }
18302   if ( mp->cur_cmd!=right_brace ) {
18303     mp_missing_err(mp, "}");
18304 @.Missing `\char`\}'@>
18305     help3("I've scanned a direction spec for part of a path,",
18306       "so a right brace should have come next.",
18307       "I shall pretend that one was there.");
18308     mp_back_error(mp);
18309   }
18310   mp_get_x_next(mp); 
18311   return t;
18312 }
18313
18314 @ @<Scan a curl specification@>=
18315 { mp_get_x_next(mp); mp_scan_expression(mp);
18316 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18317   exp_err("Improper curl has been replaced by 1");
18318 @.Improper curl@>
18319   help1("A curl must be a known, nonnegative number.");
18320   mp_put_get_flush_error(mp, unity);
18321 }
18322 t=mp_curl;
18323 }
18324
18325 @ @<Scan a given direction@>=
18326 { mp_scan_expression(mp);
18327   if ( mp->cur_type>mp_pair_type ) {
18328     @<Get given directions separated by commas@>;
18329   } else {
18330     mp_known_pair(mp);
18331   }
18332   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18333   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18334 }
18335
18336 @ @<Get given directions separated by commas@>=
18337
18338   if ( mp->cur_type!=mp_known ) {
18339     exp_err("Undefined x coordinate has been replaced by 0");
18340 @.Undefined coordinates...@>
18341     help5("I need a `known' x value for this part of the path.",
18342       "The value I found (see above) was no good;",
18343       "so I'll try to keep going by using zero instead.",
18344       "(Chapter 27 of The METAFONTbook explains that",
18345 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18346       "you might want to type `I ??" "?' now.)");
18347     mp_put_get_flush_error(mp, 0);
18348   }
18349   x=mp->cur_exp;
18350   if ( mp->cur_cmd!=comma ) {
18351     mp_missing_err(mp, ",");
18352 @.Missing `,'@>
18353     help2("I've got the x coordinate of a path direction;",
18354           "will look for the y coordinate next.");
18355     mp_back_error(mp);
18356   }
18357   mp_get_x_next(mp); mp_scan_expression(mp);
18358   if ( mp->cur_type!=mp_known ) {
18359      exp_err("Undefined y coordinate has been replaced by 0");
18360     help5("I need a `known' y value for this part of the path.",
18361       "The value I found (see above) was no good;",
18362       "so I'll try to keep going by using zero instead.",
18363       "(Chapter 27 of The METAFONTbook explains that",
18364       "you might want to type `I ??" "?' now.)");
18365     mp_put_get_flush_error(mp, 0);
18366   }
18367   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18368 }
18369
18370 @ At this point |mp_right_type(q)| is usually |open|, but it may have been
18371 set to some other value by a previous operation. We must maintain
18372 the value of |mp_right_type(q)| in cases such as
18373 `\.{..\{curl2\}z\{0,0\}..}'.
18374
18375 @<Put the pre-join...@>=
18376
18377   t=mp_scan_direction(mp);
18378   if ( t!=mp_open ) {
18379     mp_right_type(q)=t; right_given(q)=mp->cur_exp;
18380     if ( mp_left_type(q)==mp_open ) {
18381       mp_left_type(q)=t; left_given(q)=mp->cur_exp;
18382     } /* note that |left_given(q)=left_curl(q)| */
18383   }
18384 }
18385
18386 @ Since |left_tension| and |mp_left_y| share the same position in knot nodes,
18387 and since |left_given| is similarly equivalent to |mp_left_x|, we use
18388 |x| and |y| to hold the given direction and tension information when
18389 there are no explicit control points.
18390
18391 @<Put the post-join...@>=
18392
18393   t=mp_scan_direction(mp);
18394   if ( mp_right_type(q)!=mp_explicit ) x=mp->cur_exp;
18395   else t=mp_explicit; /* the direction information is superfluous */
18396 }
18397
18398 @ @<Determine the tension and/or...@>=
18399
18400   mp_get_x_next(mp);
18401   if ( mp->cur_cmd==tension ) {
18402     @<Set explicit tensions@>;
18403   } else if ( mp->cur_cmd==controls ) {
18404     @<Set explicit control points@>;
18405   } else  { 
18406     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18407     goto DONE;
18408   };
18409   if ( mp->cur_cmd!=path_join ) {
18410      mp_missing_err(mp, "..");
18411 @.Missing `..'@>
18412     help1("A path join command should end with two dots.");
18413     mp_back_error(mp);
18414   }
18415 DONE:
18416   ;
18417 }
18418
18419 @ @<Set explicit tensions@>=
18420
18421   mp_get_x_next(mp); y=mp->cur_cmd;
18422   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18423   mp_scan_primary(mp);
18424   @<Make sure that the current expression is a valid tension setting@>;
18425   if ( y==at_least ) negate(mp->cur_exp);
18426   right_tension(q)=mp->cur_exp;
18427   if ( mp->cur_cmd==and_command ) {
18428     mp_get_x_next(mp); y=mp->cur_cmd;
18429     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18430     mp_scan_primary(mp);
18431     @<Make sure that the current expression is a valid tension setting@>;
18432     if ( y==at_least ) negate(mp->cur_exp);
18433   }
18434   y=mp->cur_exp;
18435 }
18436
18437 @ @d min_tension three_quarter_unit
18438
18439 @<Make sure that the current expression is a valid tension setting@>=
18440 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18441   exp_err("Improper tension has been set to 1");
18442 @.Improper tension@>
18443   help1("The expression above should have been a number >=3/4.");
18444   mp_put_get_flush_error(mp, unity);
18445 }
18446
18447 @ @<Set explicit control points@>=
18448
18449   mp_right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18450   mp_known_pair(mp); mp_right_x(q)=mp->cur_x; mp_right_y(q)=mp->cur_y;
18451   if ( mp->cur_cmd!=and_command ) {
18452     x=mp_right_x(q); y=mp_right_y(q);
18453   } else { 
18454     mp_get_x_next(mp); mp_scan_primary(mp);
18455     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18456   }
18457 }
18458
18459 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18460
18461   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18462   else pp=mp->cur_exp;
18463   qq=pp;
18464   while ( mp_link(qq)!=pp ) qq=mp_link(qq);
18465   if ( mp_left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18466     r=mp_copy_knot(mp, pp); mp_link(qq)=r; qq=r;
18467   }
18468   mp_left_type(pp)=mp_open; mp_right_type(qq)=mp_open;
18469 }
18470
18471 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18472 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18473 shouldn't have length zero.
18474
18475 @<Get ready to close a cycle@>=
18476
18477   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18478   if ( d==ampersand ) if ( p==q ) {
18479     d=path_join; right_tension(q)=unity; y=unity;
18480   }
18481 }
18482
18483 @ @<Join the partial paths and reset |p| and |q|...@>=
18484
18485 if ( d==ampersand ) {
18486   if ( (mp_x_coord(q)!=mp_x_coord(pp))||(mp_y_coord(q)!=mp_y_coord(pp)) ) {
18487     print_err("Paths don't touch; `&' will be changed to `..'");
18488 @.Paths don't touch@>
18489     help3("When you join paths `p&q', the ending point of p",
18490       "must be exactly equal to the starting point of q.",
18491       "So I'm going to pretend that you said `p..q' instead.");
18492     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18493   }
18494 }
18495 @<Plug an opening in |mp_right_type(pp)|, if possible@>;
18496 if ( d==ampersand ) {
18497   @<Splice independent paths together@>;
18498 } else  { 
18499   @<Plug an opening in |mp_right_type(q)|, if possible@>;
18500   mp_link(q)=pp; mp_left_y(pp)=y;
18501   if ( t!=mp_open ) { mp_left_x(pp)=x; mp_left_type(pp)=t;  };
18502 }
18503 q=qq;
18504 }
18505
18506 @ @<Plug an opening in |mp_right_type(q)|...@>=
18507 if ( mp_right_type(q)==mp_open ) {
18508   if ( (mp_left_type(q)==mp_curl)||(mp_left_type(q)==mp_given) ) {
18509     mp_right_type(q)=mp_left_type(q); right_given(q)=left_given(q);
18510   }
18511 }
18512
18513 @ @<Plug an opening in |mp_right_type(pp)|...@>=
18514 if ( mp_right_type(pp)==mp_open ) {
18515   if ( (t==mp_curl)||(t==mp_given) ) {
18516     mp_right_type(pp)=t; right_given(pp)=x;
18517   }
18518 }
18519
18520 @ @<Splice independent paths together@>=
18521
18522   if ( mp_left_type(q)==mp_open ) if ( mp_right_type(q)==mp_open ) {
18523     mp_left_type(q)=mp_curl; left_curl(q)=unity;
18524   }
18525   if ( mp_right_type(pp)==mp_open ) if ( t==mp_open ) {
18526     mp_right_type(pp)=mp_curl; right_curl(pp)=unity;
18527   }
18528   mp_right_type(q)=mp_right_type(pp); mp_link(q)=mp_link(pp);
18529   mp_right_x(q)=mp_right_x(pp); mp_right_y(q)=mp_right_y(pp);
18530   mp_free_node(mp, pp,knot_node_size);
18531   if ( qq==pp ) qq=q;
18532 }
18533
18534 @ @<Choose control points for the path...@>=
18535 if ( cycle_hit ) { 
18536   if ( d==ampersand ) p=q;
18537 } else  { 
18538   mp_left_type(p)=mp_endpoint;
18539   if ( mp_right_type(p)==mp_open ) { 
18540     mp_right_type(p)=mp_curl; right_curl(p)=unity;
18541   }
18542   mp_right_type(q)=mp_endpoint;
18543   if ( mp_left_type(q)==mp_open ) { 
18544     mp_left_type(q)=mp_curl; left_curl(q)=unity;
18545   }
18546   mp_link(q)=p;
18547 }
18548 mp_make_choices(mp, p);
18549 mp->cur_type=mp_path_type; mp->cur_exp=p
18550
18551 @ Finally, we sometimes need to scan an expression whose value is
18552 supposed to be either |true_code| or |false_code|.
18553
18554 @<Declare the basic parsing subroutines@>=
18555 static void mp_get_boolean (MP mp) { 
18556   mp_get_x_next(mp); mp_scan_expression(mp);
18557   if ( mp->cur_type!=mp_boolean_type ) {
18558     exp_err("Undefined condition will be treated as `false'");
18559 @.Undefined condition...@>
18560     help2("The expression shown above should have had a definite",
18561           "true-or-false value. I'm changing it to `false'.");
18562     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18563   }
18564 }
18565
18566 @* \[39] Doing the operations.
18567 The purpose of parsing is primarily to permit people to avoid piles of
18568 parentheses. But the real work is done after the structure of an expression
18569 has been recognized; that's when new expressions are generated. We
18570 turn now to the guts of \MP, which handles individual operators that
18571 have come through the parsing mechanism.
18572
18573 We'll start with the easy ones that take no operands, then work our way
18574 up to operators with one and ultimately two arguments. In other words,
18575 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18576 that are invoked periodically by the expression scanners.
18577
18578 First let's make sure that all of the primitive operators are in the
18579 hash table. Although |scan_primary| and its relatives made use of the
18580 \\{cmd} code for these operators, the \\{do} routines base everything
18581 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18582 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18583
18584 @<Put each...@>=
18585 mp_primitive(mp, "true",nullary,true_code);
18586 @:true_}{\&{true} primitive@>
18587 mp_primitive(mp, "false",nullary,false_code);
18588 @:false_}{\&{false} primitive@>
18589 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18590 @:null_picture_}{\&{nullpicture} primitive@>
18591 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18592 @:null_pen_}{\&{nullpen} primitive@>
18593 mp_primitive(mp, "jobname",nullary,job_name_op);
18594 @:job_name_}{\&{jobname} primitive@>
18595 mp_primitive(mp, "readstring",nullary,read_string_op);
18596 @:read_string_}{\&{readstring} primitive@>
18597 mp_primitive(mp, "pencircle",nullary,pen_circle);
18598 @:pen_circle_}{\&{pencircle} primitive@>
18599 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18600 @:normal_deviate_}{\&{normaldeviate} primitive@>
18601 mp_primitive(mp, "readfrom",unary,read_from_op);
18602 @:read_from_}{\&{readfrom} primitive@>
18603 mp_primitive(mp, "closefrom",unary,close_from_op);
18604 @:close_from_}{\&{closefrom} primitive@>
18605 mp_primitive(mp, "odd",unary,odd_op);
18606 @:odd_}{\&{odd} primitive@>
18607 mp_primitive(mp, "known",unary,known_op);
18608 @:known_}{\&{known} primitive@>
18609 mp_primitive(mp, "unknown",unary,unknown_op);
18610 @:unknown_}{\&{unknown} primitive@>
18611 mp_primitive(mp, "not",unary,not_op);
18612 @:not_}{\&{not} primitive@>
18613 mp_primitive(mp, "decimal",unary,decimal);
18614 @:decimal_}{\&{decimal} primitive@>
18615 mp_primitive(mp, "reverse",unary,reverse);
18616 @:reverse_}{\&{reverse} primitive@>
18617 mp_primitive(mp, "makepath",unary,make_path_op);
18618 @:make_path_}{\&{makepath} primitive@>
18619 mp_primitive(mp, "makepen",unary,make_pen_op);
18620 @:make_pen_}{\&{makepen} primitive@>
18621 mp_primitive(mp, "oct",unary,oct_op);
18622 @:oct_}{\&{oct} primitive@>
18623 mp_primitive(mp, "hex",unary,hex_op);
18624 @:hex_}{\&{hex} primitive@>
18625 mp_primitive(mp, "ASCII",unary,ASCII_op);
18626 @:ASCII_}{\&{ASCII} primitive@>
18627 mp_primitive(mp, "char",unary,char_op);
18628 @:char_}{\&{char} primitive@>
18629 mp_primitive(mp, "length",unary,length_op);
18630 @:length_}{\&{length} primitive@>
18631 mp_primitive(mp, "turningnumber",unary,turning_op);
18632 @:turning_number_}{\&{turningnumber} primitive@>
18633 mp_primitive(mp, "xpart",unary,x_part);
18634 @:x_part_}{\&{xpart} primitive@>
18635 mp_primitive(mp, "ypart",unary,y_part);
18636 @:y_part_}{\&{ypart} primitive@>
18637 mp_primitive(mp, "xxpart",unary,xx_part);
18638 @:xx_part_}{\&{xxpart} primitive@>
18639 mp_primitive(mp, "xypart",unary,xy_part);
18640 @:xy_part_}{\&{xypart} primitive@>
18641 mp_primitive(mp, "yxpart",unary,yx_part);
18642 @:yx_part_}{\&{yxpart} primitive@>
18643 mp_primitive(mp, "yypart",unary,yy_part);
18644 @:yy_part_}{\&{yypart} primitive@>
18645 mp_primitive(mp, "redpart",unary,red_part);
18646 @:red_part_}{\&{redpart} primitive@>
18647 mp_primitive(mp, "greenpart",unary,green_part);
18648 @:green_part_}{\&{greenpart} primitive@>
18649 mp_primitive(mp, "bluepart",unary,blue_part);
18650 @:blue_part_}{\&{bluepart} primitive@>
18651 mp_primitive(mp, "cyanpart",unary,cyan_part);
18652 @:cyan_part_}{\&{cyanpart} primitive@>
18653 mp_primitive(mp, "magentapart",unary,magenta_part);
18654 @:magenta_part_}{\&{magentapart} primitive@>
18655 mp_primitive(mp, "yellowpart",unary,yellow_part);
18656 @:yellow_part_}{\&{yellowpart} primitive@>
18657 mp_primitive(mp, "blackpart",unary,black_part);
18658 @:black_part_}{\&{blackpart} primitive@>
18659 mp_primitive(mp, "greypart",unary,grey_part);
18660 @:grey_part_}{\&{greypart} primitive@>
18661 mp_primitive(mp, "colormodel",unary,color_model_part);
18662 @:color_model_part_}{\&{colormodel} primitive@>
18663 mp_primitive(mp, "fontpart",unary,font_part);
18664 @:font_part_}{\&{fontpart} primitive@>
18665 mp_primitive(mp, "textpart",unary,text_part);
18666 @:text_part_}{\&{textpart} primitive@>
18667 mp_primitive(mp, "pathpart",unary,path_part);
18668 @:path_part_}{\&{pathpart} primitive@>
18669 mp_primitive(mp, "penpart",unary,pen_part);
18670 @:pen_part_}{\&{penpart} primitive@>
18671 mp_primitive(mp, "dashpart",unary,dash_part);
18672 @:dash_part_}{\&{dashpart} primitive@>
18673 mp_primitive(mp, "sqrt",unary,sqrt_op);
18674 @:sqrt_}{\&{sqrt} primitive@>
18675 mp_primitive(mp, "mexp",unary,mp_m_exp_op);
18676 @:m_exp_}{\&{mexp} primitive@>
18677 mp_primitive(mp, "mlog",unary,mp_m_log_op);
18678 @:m_log_}{\&{mlog} primitive@>
18679 mp_primitive(mp, "sind",unary,sin_d_op);
18680 @:sin_d_}{\&{sind} primitive@>
18681 mp_primitive(mp, "cosd",unary,cos_d_op);
18682 @:cos_d_}{\&{cosd} primitive@>
18683 mp_primitive(mp, "floor",unary,floor_op);
18684 @:floor_}{\&{floor} primitive@>
18685 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18686 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18687 mp_primitive(mp, "charexists",unary,char_exists_op);
18688 @:char_exists_}{\&{charexists} primitive@>
18689 mp_primitive(mp, "fontsize",unary,font_size);
18690 @:font_size_}{\&{fontsize} primitive@>
18691 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18692 @:ll_corner_}{\&{llcorner} primitive@>
18693 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18694 @:lr_corner_}{\&{lrcorner} primitive@>
18695 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18696 @:ul_corner_}{\&{ulcorner} primitive@>
18697 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18698 @:ur_corner_}{\&{urcorner} primitive@>
18699 mp_primitive(mp, "arclength",unary,arc_length);
18700 @:arc_length_}{\&{arclength} primitive@>
18701 mp_primitive(mp, "angle",unary,angle_op);
18702 @:angle_}{\&{angle} primitive@>
18703 mp_primitive(mp, "cycle",cycle,cycle_op);
18704 @:cycle_}{\&{cycle} primitive@>
18705 mp_primitive(mp, "stroked",unary,stroked_op);
18706 @:stroked_}{\&{stroked} primitive@>
18707 mp_primitive(mp, "filled",unary,filled_op);
18708 @:filled_}{\&{filled} primitive@>
18709 mp_primitive(mp, "textual",unary,textual_op);
18710 @:textual_}{\&{textual} primitive@>
18711 mp_primitive(mp, "clipped",unary,clipped_op);
18712 @:clipped_}{\&{clipped} primitive@>
18713 mp_primitive(mp, "bounded",unary,bounded_op);
18714 @:bounded_}{\&{bounded} primitive@>
18715 mp_primitive(mp, "+",plus_or_minus,plus);
18716 @:+ }{\.{+} primitive@>
18717 mp_primitive(mp, "-",plus_or_minus,minus);
18718 @:- }{\.{-} primitive@>
18719 mp_primitive(mp, "*",secondary_binary,times);
18720 @:* }{\.{*} primitive@>
18721 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18722 @:/ }{\.{/} primitive@>
18723 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18724 @:++_}{\.{++} primitive@>
18725 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18726 @:+-+_}{\.{+-+} primitive@>
18727 mp_primitive(mp, "or",tertiary_binary,or_op);
18728 @:or_}{\&{or} primitive@>
18729 mp_primitive(mp, "and",and_command,and_op);
18730 @:and_}{\&{and} primitive@>
18731 mp_primitive(mp, "<",expression_binary,less_than);
18732 @:< }{\.{<} primitive@>
18733 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18734 @:<=_}{\.{<=} primitive@>
18735 mp_primitive(mp, ">",expression_binary,greater_than);
18736 @:> }{\.{>} primitive@>
18737 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18738 @:>=_}{\.{>=} primitive@>
18739 mp_primitive(mp, "=",equals,equal_to);
18740 @:= }{\.{=} primitive@>
18741 mp_primitive(mp, "<>",expression_binary,unequal_to);
18742 @:<>_}{\.{<>} primitive@>
18743 mp_primitive(mp, "substring",primary_binary,substring_of);
18744 @:substring_}{\&{substring} primitive@>
18745 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18746 @:subpath_}{\&{subpath} primitive@>
18747 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18748 @:direction_time_}{\&{directiontime} primitive@>
18749 mp_primitive(mp, "point",primary_binary,point_of);
18750 @:point_}{\&{point} primitive@>
18751 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18752 @:precontrol_}{\&{precontrol} primitive@>
18753 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18754 @:postcontrol_}{\&{postcontrol} primitive@>
18755 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18756 @:pen_offset_}{\&{penoffset} primitive@>
18757 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18758 @:arc_time_of_}{\&{arctime} primitive@>
18759 mp_primitive(mp, "mpversion",nullary,mp_version);
18760 @:mp_verison_}{\&{mpversion} primitive@>
18761 mp_primitive(mp, "&",ampersand,concatenate);
18762 @:!!!}{\.{\&} primitive@>
18763 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18764 @:rotated_}{\&{rotated} primitive@>
18765 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18766 @:slanted_}{\&{slanted} primitive@>
18767 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18768 @:scaled_}{\&{scaled} primitive@>
18769 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18770 @:shifted_}{\&{shifted} primitive@>
18771 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18772 @:transformed_}{\&{transformed} primitive@>
18773 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18774 @:x_scaled_}{\&{xscaled} primitive@>
18775 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18776 @:y_scaled_}{\&{yscaled} primitive@>
18777 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18778 @:z_scaled_}{\&{zscaled} primitive@>
18779 mp_primitive(mp, "infont",secondary_binary,in_font);
18780 @:in_font_}{\&{infont} primitive@>
18781 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18782 @:intersection_times_}{\&{intersectiontimes} primitive@>
18783 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18784 @:envelope_}{\&{envelope} primitive@>
18785
18786 @ @<Cases of |print_cmd...@>=
18787 case nullary:
18788 case unary:
18789 case primary_binary:
18790 case secondary_binary:
18791 case tertiary_binary:
18792 case expression_binary:
18793 case cycle:
18794 case plus_or_minus:
18795 case slash:
18796 case ampersand:
18797 case equals:
18798 case and_command:
18799   mp_print_op(mp, m);
18800   break;
18801
18802 @ OK, let's look at the simplest \\{do} procedure first.
18803
18804 @c @<Declare nullary action procedure@>
18805 static void mp_do_nullary (MP mp,quarterword c) { 
18806   check_arith;
18807   if ( mp->internal[mp_tracing_commands]>two )
18808     mp_show_cmd_mod(mp, nullary,c);
18809   switch (c) {
18810   case true_code: case false_code: 
18811     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18812     break;
18813   case null_picture_code: 
18814     mp->cur_type=mp_picture_type;
18815     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18816     mp_init_edges(mp, mp->cur_exp);
18817     break;
18818   case null_pen_code: 
18819     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18820     break;
18821   case normal_deviate: 
18822     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18823     break;
18824   case pen_circle: 
18825     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18826     break;
18827   case job_name_op:  
18828     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18829     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18830     break;
18831   case mp_version: 
18832     mp->cur_type=mp_string_type; 
18833     mp->cur_exp=intern(metapost_version) ;
18834     break;
18835   case read_string_op:
18836     @<Read a string from the terminal@>;
18837     break;
18838   } /* there are no other cases */
18839   check_arith;
18840 }
18841
18842 @ @<Read a string...@>=
18843
18844   if (mp->noninteractive || mp->interaction<=mp_nonstop_mode )
18845     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18846   mp_begin_file_reading(mp); name=is_read;
18847   limit=start; prompt_input("");
18848   mp_finish_read(mp);
18849 }
18850
18851 @ @<Declare nullary action procedure@>=
18852 static void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18853   size_t k;
18854   str_room((int)mp->last-start);
18855   for (k=(size_t)start;k<=mp->last-1;k++) {
18856    append_char(mp->buffer[k]);
18857   }
18858   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18859   mp->cur_exp=mp_make_string(mp);
18860 }
18861
18862 @ Things get a bit more interesting when there's an operand. The
18863 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18864
18865 @c @<Declare unary action procedures@>
18866 static void mp_do_unary (MP mp,quarterword c) {
18867   pointer p,q,r; /* for list manipulation */
18868   integer x; /* a temporary register */
18869   check_arith;
18870   if ( mp->internal[mp_tracing_commands]>two )
18871     @<Trace the current unary operation@>;
18872   switch (c) {
18873   case plus:
18874     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18875     break;
18876   case minus:
18877     @<Negate the current expression@>;
18878     break;
18879   @<Additional cases of unary operators@>;
18880   } /* there are no other cases */
18881   check_arith;
18882 }
18883
18884 @ The |nice_pair| function returns |true| if both components of a pair
18885 are known.
18886
18887 @<Declare unary action procedures@>=
18888 static boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18889   if ( t==mp_pair_type ) {
18890     p=value(p);
18891     if ( type(x_part_loc(p))==mp_known )
18892       if ( type(y_part_loc(p))==mp_known )
18893         return true;
18894   }
18895   return false;
18896 }
18897
18898 @ The |nice_color_or_pair| function is analogous except that it also accepts
18899 fully known colors.
18900
18901 @<Declare unary action procedures@>=
18902 static boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18903   pointer q,r; /* for scanning the big node */
18904   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18905     return false;
18906   } else { 
18907     q=value(p);
18908     r=q+mp->big_node_size[type(p)];
18909     do {  
18910       r=r-2;
18911       if ( type(r)!=mp_known )
18912         return false;
18913     } while (r!=q);
18914     return true;
18915   }
18916 }
18917
18918 @ @<Declare unary action...@>=
18919 static void mp_print_known_or_unknown_type (MP mp,quarterword t, integer v) { 
18920   mp_print_char(mp, xord('('));
18921   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18922   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18923     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18924     mp_print_type(mp, t);
18925   }
18926   mp_print_char(mp, xord(')'));
18927 }
18928
18929 @ @<Declare unary action...@>=
18930 static void mp_bad_unary (MP mp,quarterword c) { 
18931   exp_err("Not implemented: "); mp_print_op(mp, c);
18932 @.Not implemented...@>
18933   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18934   help3("I'm afraid I don't know how to apply that operation to that",
18935     "particular type. Continue, and I'll simply return the",
18936     "argument (shown above) as the result of the operation.");
18937   mp_put_get_error(mp);
18938 }
18939
18940 @ @<Trace the current unary operation@>=
18941
18942   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18943   mp_print_op(mp, c); mp_print_char(mp, xord('('));
18944   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18945   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18946 }
18947
18948 @ Negation is easy except when the current expression
18949 is of type |independent|, or when it is a pair with one or more
18950 |independent| components.
18951
18952 It is tempting to argue that the negative of an independent variable
18953 is an independent variable, hence we don't have to do anything when
18954 negating it. The fallacy is that other dependent variables pointing
18955 to the current expression must change the sign of their
18956 coefficients if we make no change to the current expression.
18957
18958 Instead, we work around the problem by copying the current expression
18959 and recycling it afterwards (cf.~the |stash_in| routine).
18960
18961 @<Negate the current expression@>=
18962 switch (mp->cur_type) {
18963 case mp_color_type:
18964 case mp_cmykcolor_type:
18965 case mp_pair_type:
18966 case mp_independent: 
18967   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18968   if ( mp->cur_type==mp_dependent ) {
18969     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18970   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18971     p=value(mp->cur_exp);
18972     r=p+mp->big_node_size[mp->cur_type];
18973     do {  
18974       r=r-2;
18975       if ( type(r)==mp_known ) negate(value(r));
18976       else mp_negate_dep_list(mp, dep_list(r));
18977     } while (r!=p);
18978   } /* if |cur_type=mp_known| then |cur_exp=0| */
18979   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18980   break;
18981 case mp_dependent:
18982 case mp_proto_dependent:
18983   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18984   break;
18985 case mp_known:
18986   negate(mp->cur_exp);
18987   break;
18988 default:
18989   mp_bad_unary(mp, minus);
18990   break;
18991 }
18992
18993 @ @<Declare unary action...@>=
18994 static void mp_negate_dep_list (MP mp,pointer p) { 
18995   while (1) { 
18996     negate(value(p));
18997     if ( info(p)==null ) return;
18998     p=mp_link(p);
18999   }
19000 }
19001
19002 @ @<Additional cases of unary operators@>=
19003 case not_op: 
19004   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
19005   else mp->cur_exp=true_code+false_code-mp->cur_exp;
19006   break;
19007
19008 @ @d three_sixty_units 23592960 /* that's |360*unity| */
19009 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
19010
19011 @<Additional cases of unary operators@>=
19012 case sqrt_op:
19013 case mp_m_exp_op:
19014 case mp_m_log_op:
19015 case sin_d_op:
19016 case cos_d_op:
19017 case floor_op:
19018 case  uniform_deviate:
19019 case odd_op:
19020 case char_exists_op:
19021   if ( mp->cur_type!=mp_known ) {
19022     mp_bad_unary(mp, c);
19023   } else {
19024     switch (c) {
19025     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
19026     case mp_m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
19027     case mp_m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
19028     case sin_d_op:
19029     case cos_d_op:
19030       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
19031       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
19032       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
19033       break;
19034     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
19035     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
19036     case odd_op: 
19037       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
19038       mp->cur_type=mp_boolean_type;
19039       break;
19040     case char_exists_op:
19041       @<Determine if a character has been shipped out@>;
19042       break;
19043     } /* there are no other cases */
19044   }
19045   break;
19046
19047 @ @<Additional cases of unary operators@>=
19048 case angle_op:
19049   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
19050     p=value(mp->cur_exp);
19051     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
19052     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
19053     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
19054   } else {
19055     mp_bad_unary(mp, angle_op);
19056   }
19057   break;
19058
19059 @ If the current expression is a pair, but the context wants it to
19060 be a path, we call |pair_to_path|.
19061
19062 @<Declare unary action...@>=
19063 static void mp_pair_to_path (MP mp) { 
19064   mp->cur_exp=mp_new_knot(mp); 
19065   mp->cur_type=mp_path_type;
19066 }
19067
19068
19069 @d pict_color_type(A) ((mp_link(dummy_loc(mp->cur_exp))!=null) &&
19070                        (has_color(mp_link(dummy_loc(mp->cur_exp)))) &&
19071                        ((color_model(mp_link(dummy_loc(mp->cur_exp)))==A)
19072                         ||
19073                         ((color_model(mp_link(dummy_loc(mp->cur_exp)))==mp_uninitialized_model) &&
19074                         (mp->internal[mp_default_color_model]/unity)==(A))))
19075
19076 @<Additional cases of unary operators@>=
19077 case x_part:
19078 case y_part:
19079   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
19080     mp_take_part(mp, c);
19081   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19082   else mp_bad_unary(mp, c);
19083   break;
19084 case xx_part:
19085 case xy_part:
19086 case yx_part:
19087 case yy_part: 
19088   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
19089   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19090   else mp_bad_unary(mp, c);
19091   break;
19092 case red_part:
19093 case green_part:
19094 case blue_part: 
19095   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
19096   else if ( mp->cur_type==mp_picture_type ) {
19097     if pict_color_type(mp_rgb_model) mp_take_pict_part(mp, c);
19098     else mp_bad_color_part(mp, c);
19099   }
19100   else mp_bad_unary(mp, c);
19101   break;
19102 case cyan_part:
19103 case magenta_part:
19104 case yellow_part:
19105 case black_part: 
19106   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
19107   else if ( mp->cur_type==mp_picture_type ) {
19108     if pict_color_type(mp_cmyk_model) mp_take_pict_part(mp, c);
19109     else mp_bad_color_part(mp, c);
19110   }
19111   else mp_bad_unary(mp, c);
19112   break;
19113 case grey_part: 
19114   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
19115   else if ( mp->cur_type==mp_picture_type ) {
19116     if pict_color_type(mp_grey_model) mp_take_pict_part(mp, c);
19117     else mp_bad_color_part(mp, c);
19118   }
19119   else mp_bad_unary(mp, c);
19120   break;
19121 case color_model_part: 
19122   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19123   else mp_bad_unary(mp, c);
19124   break;
19125
19126 @ @<Declarations@>=
19127 static void mp_bad_color_part(MP mp, quarterword c);
19128
19129 @ @c
19130 static void mp_bad_color_part(MP mp, quarterword c) {
19131   pointer p; /* the big node */
19132   p=mp_link(dummy_loc(mp->cur_exp));
19133   exp_err("Wrong picture color model: "); mp_print_op(mp, c);
19134 @.Wrong picture color model...@>
19135   if (color_model(p)==mp_grey_model)
19136     mp_print(mp, " of grey object");
19137   else if (color_model(p)==mp_cmyk_model)
19138     mp_print(mp, " of cmyk object");
19139   else if (color_model(p)==mp_rgb_model)
19140     mp_print(mp, " of rgb object");
19141   else if (color_model(p)==mp_no_model) 
19142     mp_print(mp, " of marking object");
19143   else 
19144     mp_print(mp," of defaulted object");
19145   help3("You can only ask for the redpart, greenpart, bluepart of a rgb object,",
19146     "the cyanpart, magentapart, yellowpart or blackpart of a cmyk object, ",
19147     "or the greypart of a grey object. No mixing and matching, please.");
19148   mp_error(mp);
19149   if (c==black_part)
19150     mp_flush_cur_exp(mp,unity);
19151   else
19152     mp_flush_cur_exp(mp,0);
19153 }
19154
19155 @ In the following procedure, |cur_exp| points to a capsule, which points to
19156 a big node. We want to delete all but one part of the big node.
19157
19158 @<Declare unary action...@>=
19159 static void mp_take_part (MP mp,quarterword c) {
19160   pointer p; /* the big node */
19161   p=value(mp->cur_exp); value(temp_val)=p; type(temp_val)=mp->cur_type;
19162   mp_link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
19163   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
19164   mp_recycle_value(mp, temp_val);
19165 }
19166
19167 @ @<Initialize table entries...@>=
19168 name_type(temp_val)=mp_capsule;
19169
19170 @ @<Additional cases of unary operators@>=
19171 case font_part:
19172 case text_part:
19173 case path_part:
19174 case pen_part:
19175 case dash_part:
19176   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19177   else mp_bad_unary(mp, c);
19178   break;
19179
19180 @ @<Declarations@>=
19181 static void mp_scale_edges (MP mp);
19182
19183 @ @<Declare unary action...@>=
19184 static void mp_take_pict_part (MP mp,quarterword c) {
19185   pointer p; /* first graphical object in |cur_exp| */
19186   p=mp_link(dummy_loc(mp->cur_exp));
19187   if ( p!=null ) {
19188     switch (c) {
19189     case x_part: case y_part: case xx_part:
19190     case xy_part: case yx_part: case yy_part:
19191       if ( type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19192       else goto NOT_FOUND;
19193       break;
19194     case red_part: case green_part: case blue_part:
19195       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19196       else goto NOT_FOUND;
19197       break;
19198     case cyan_part: case magenta_part: case yellow_part:
19199     case black_part:
19200       if ( has_color(p) ) {
19201         if ( color_model(p)==mp_uninitialized_model && c==black_part)
19202           mp_flush_cur_exp(mp, unity);
19203         else
19204           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19205       } else goto NOT_FOUND;
19206       break;
19207     case grey_part:
19208       if ( has_color(p) )
19209           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19210       else goto NOT_FOUND;
19211       break;
19212     case color_model_part:
19213       if ( has_color(p) ) {
19214         if ( color_model(p)==mp_uninitialized_model )
19215           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19216         else
19217           mp_flush_cur_exp(mp, color_model(p)*unity);
19218       } else goto NOT_FOUND;
19219       break;
19220     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19221     } /* all cases have been enumerated */
19222     return;
19223   };
19224 NOT_FOUND:
19225   @<Convert the current expression to a null value appropriate
19226     for |c|@>;
19227 }
19228
19229 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19230 case text_part: 
19231   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19232   else { 
19233     mp_flush_cur_exp(mp, text_p(p));
19234     add_str_ref(mp->cur_exp);
19235     mp->cur_type=mp_string_type;
19236     };
19237   break;
19238 case font_part: 
19239   if ( type(p)!=mp_text_code ) goto NOT_FOUND;
19240   else { 
19241     mp_flush_cur_exp(mp, rts(mp->font_name[font_n(p)])); 
19242     add_str_ref(mp->cur_exp);
19243     mp->cur_type=mp_string_type;
19244   };
19245   break;
19246 case path_part:
19247   if ( type(p)==mp_text_code ) goto NOT_FOUND;
19248   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19249 @:this can't happen pict}{\quad pict@>
19250   else { 
19251     mp_flush_cur_exp(mp, mp_copy_path(mp, path_p(p)));
19252     mp->cur_type=mp_path_type;
19253   }
19254   break;
19255 case pen_part: 
19256   if ( ! has_pen(p) ) goto NOT_FOUND;
19257   else {
19258     if ( pen_p(p)==null ) goto NOT_FOUND;
19259     else { mp_flush_cur_exp(mp, copy_pen(pen_p(p)));
19260       mp->cur_type=mp_pen_type;
19261     };
19262   }
19263   break;
19264 case dash_part: 
19265   if ( type(p)!=mp_stroked_code ) goto NOT_FOUND;
19266   else { if ( dash_p(p)==null ) goto NOT_FOUND;
19267     else { add_edge_ref(dash_p(p));
19268     mp->se_sf=dash_scale(p);
19269     mp->se_pic=dash_p(p);
19270     mp_scale_edges(mp);
19271     mp_flush_cur_exp(mp, mp->se_pic);
19272     mp->cur_type=mp_picture_type;
19273     };
19274   }
19275   break;
19276
19277 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19278 parameterless procedure even though it really takes two arguments and updates
19279 one of them.  Hence the following globals are needed.
19280
19281 @<Global...@>=
19282 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19283 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19284
19285 @ @<Convert the current expression to a null value appropriate...@>=
19286 switch (c) {
19287 case text_part: case font_part: 
19288   mp_flush_cur_exp(mp, null_str);
19289   mp->cur_type=mp_string_type;
19290   break;
19291 case path_part: 
19292   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19293   mp_left_type(mp->cur_exp)=mp_endpoint;
19294   mp_right_type(mp->cur_exp)=mp_endpoint;
19295   mp_link(mp->cur_exp)=mp->cur_exp;
19296   mp_x_coord(mp->cur_exp)=0;
19297   mp_y_coord(mp->cur_exp)=0;
19298   mp_originator(mp->cur_exp)=mp_metapost_user;
19299   mp->cur_type=mp_path_type;
19300   break;
19301 case pen_part: 
19302   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19303   mp->cur_type=mp_pen_type;
19304   break;
19305 case dash_part: 
19306   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19307   mp_init_edges(mp, mp->cur_exp);
19308   mp->cur_type=mp_picture_type;
19309   break;
19310 default: 
19311    mp_flush_cur_exp(mp, 0);
19312   break;
19313 }
19314
19315 @ @<Additional cases of unary...@>=
19316 case char_op: 
19317   if ( mp->cur_type!=mp_known ) { 
19318     mp_bad_unary(mp, char_op);
19319   } else { 
19320     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19321     mp->cur_type=mp_string_type;
19322     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19323   }
19324   break;
19325 case decimal: 
19326   if ( mp->cur_type!=mp_known ) {
19327      mp_bad_unary(mp, decimal);
19328   } else { 
19329     mp->old_setting=mp->selector; mp->selector=new_string;
19330     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19331     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19332   }
19333   break;
19334 case oct_op:
19335 case hex_op:
19336 case ASCII_op: 
19337   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19338   else mp_str_to_num(mp, c);
19339   break;
19340 case font_size: 
19341   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19342   else @<Find the design size of the font whose name is |cur_exp|@>;
19343   break;
19344
19345 @ @<Declare unary action...@>=
19346 static void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19347   integer n; /* accumulator */
19348   ASCII_code m; /* current character */
19349   pool_pointer k; /* index into |str_pool| */
19350   int b; /* radix of conversion */
19351   boolean bad_char; /* did the string contain an invalid digit? */
19352   if ( c==ASCII_op ) {
19353     if ( length(mp->cur_exp)==0 ) n=-1;
19354     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19355   } else { 
19356     if ( c==oct_op ) b=8; else b=16;
19357     n=0; bad_char=false;
19358     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19359       m=mp->str_pool[k];
19360       if ( (m>='0')&&(m<='9') ) m=m-'0';
19361       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19362       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19363       else  { bad_char=true; m=0; };
19364       if ( (int)m>=b ) { bad_char=true; m=0; };
19365       if ( n<32768 / b ) n=n*b+m; else n=32767;
19366     }
19367     @<Give error messages if |bad_char| or |n>=4096|@>;
19368   }
19369   mp_flush_cur_exp(mp, n*unity);
19370 }
19371
19372 @ @<Give error messages if |bad_char|...@>=
19373 if ( bad_char ) { 
19374   exp_err("String contains illegal digits");
19375 @.String contains illegal digits@>
19376   if ( c==oct_op ) {
19377     help1("I zeroed out characters that weren't in the range 0..7.");
19378   } else  {
19379     help1("I zeroed out characters that weren't hex digits.");
19380   }
19381   mp_put_get_error(mp);
19382 }
19383 if ( (n>4095) ) {
19384   if ( mp->internal[mp_warning_check]>0 ) {
19385     print_err("Number too large ("); 
19386     mp_print_int(mp, n); mp_print_char(mp, xord(')'));
19387 @.Number too large@>
19388     help2("I have trouble with numbers greater than 4095; watch out.",
19389            "(Set warningcheck:=0 to suppress this message.)");
19390     mp_put_get_error(mp);
19391   }
19392 }
19393
19394 @ The length operation is somewhat unusual in that it applies to a variety
19395 of different types of operands.
19396
19397 @<Additional cases of unary...@>=
19398 case length_op: 
19399   switch (mp->cur_type) {
19400   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19401   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19402   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19403   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19404   default: 
19405     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19406       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19407         value(x_part_loc(value(mp->cur_exp))),
19408         value(y_part_loc(value(mp->cur_exp)))));
19409     else mp_bad_unary(mp, c);
19410     break;
19411   }
19412   break;
19413
19414 @ @<Declare unary action...@>=
19415 static scaled mp_path_length (MP mp) { /* computes the length of the current path */
19416   scaled n; /* the path length so far */
19417   pointer p; /* traverser */
19418   p=mp->cur_exp;
19419   if ( mp_left_type(p)==mp_endpoint ) n=-unity; else n=0;
19420   do {  p=mp_link(p); n=n+unity; } while (p!=mp->cur_exp);
19421   return n;
19422 }
19423
19424 @ @<Declare unary action...@>=
19425 static scaled mp_pict_length (MP mp) { 
19426   /* counts interior components in picture |cur_exp| */
19427   scaled n; /* the count so far */
19428   pointer p; /* traverser */
19429   n=0;
19430   p=mp_link(dummy_loc(mp->cur_exp));
19431   if ( p!=null ) {
19432     if ( is_start_or_stop(p) )
19433       if ( mp_skip_1component(mp, p)==null ) p=mp_link(p);
19434     while ( p!=null )  { 
19435       skip_component(p) return n; 
19436       n=n+unity;   
19437     }
19438   }
19439   return n;
19440 }
19441
19442 @ Implement |turningnumber|
19443
19444 @<Additional cases of unary...@>=
19445 case turning_op:
19446   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19447   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19448   else if ( mp_left_type(mp->cur_exp)==mp_endpoint )
19449      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19450   else
19451     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19452   break;
19453
19454 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19455 argument is |origin|.
19456
19457 @<Declare unary action...@>=
19458 static angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19459   if ( (! ((xpar==0) && (ypar==0))) )
19460     return mp_n_arg(mp, xpar,ypar);
19461   return 0;
19462 }
19463
19464
19465 @ The actual turning number is (for the moment) computed in a C function
19466 that receives eight integers corresponding to the four controlling points,
19467 and returns a single angle.  Besides those, we have to account for discrete
19468 moves at the actual points.
19469
19470 @d mp_floor(a) ((a)>=0 ? (int)(a) : -(int)(-(a)))
19471 @d bezier_error (720*(256*256*16))+1
19472 @d mp_sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19473 @d mp_out(A) (double)((A)/(256*256*16))
19474 @d divisor (256*256)
19475 @d double2angle(a) (int)mp_floor(a*256.0*256.0*16.0)
19476
19477 @<Declare unary action...@>=
19478 static angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19479             integer CX,integer CY,integer DX,integer DY);
19480
19481 @ @c 
19482 static angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19483             integer CX,integer CY,integer DX,integer DY) {
19484   double a, b, c;
19485   integer deltax,deltay;
19486   double ax,ay,bx,by,cx,cy,dx,dy;
19487   angle xi = 0, xo = 0, xm = 0;
19488   double res = 0;
19489   ax=(double)(AX/divisor);  ay=(double)(AY/divisor);
19490   bx=(double)(BX/divisor);  by=(double)(BY/divisor);
19491   cx=(double)(CX/divisor);  cy=(double)(CY/divisor);
19492   dx=(double)(DX/divisor);  dy=(double)(DY/divisor);
19493
19494   deltax = (BX-AX); deltay = (BY-AY);
19495   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19496   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19497   xi = mp_an_angle(mp,deltax,deltay);
19498
19499   deltax = (CX-BX); deltay = (CY-BY);
19500   xm = mp_an_angle(mp,deltax,deltay);
19501
19502   deltax = (DX-CX); deltay = (DY-CY);
19503   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19504   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19505   xo = mp_an_angle(mp,deltax,deltay);
19506
19507   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19508   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19509   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19510
19511   if ((a==0)&&(c==0)) {
19512     res = (b==0 ?  0 :  (mp_out(xo)-mp_out(xi))); 
19513   } else if ((a==0)||(c==0)) {
19514     if ((mp_sign(b) == mp_sign(a)) || (mp_sign(b) == mp_sign(c))) {
19515       res = mp_out(xo)-mp_out(xi); /* ? */
19516       if (res<-180.0) 
19517         res += 360.0;
19518       else if (res>180.0)
19519         res -= 360.0;
19520     } else {
19521       res = mp_out(xo)-mp_out(xi); /* ? */
19522     }
19523   } else if ((mp_sign(a)*mp_sign(c))<0) {
19524     res = mp_out(xo)-mp_out(xi); /* ? */
19525       if (res<-180.0) 
19526         res += 360.0;
19527       else if (res>180.0)
19528         res -= 360.0;
19529   } else {
19530     if (mp_sign(a) == mp_sign(b)) {
19531       res = mp_out(xo)-mp_out(xi); /* ? */
19532       if (res<-180.0) 
19533         res += 360.0;
19534       else if (res>180.0)
19535         res -= 360.0;
19536     } else {
19537       if ((b*b) == (4*a*c)) {
19538         res = (double)bezier_error;
19539       } else if ((b*b) < (4*a*c)) {
19540         res = mp_out(xo)-mp_out(xi); /* ? */
19541         if (res<=0.0 &&res>-180.0) 
19542           res += 360.0;
19543         else if (res>=0.0 && res<180.0)
19544           res -= 360.0;
19545       } else {
19546         res = mp_out(xo)-mp_out(xi);
19547         if (res<-180.0) 
19548           res += 360.0;
19549         else if (res>180.0)
19550           res -= 360.0;
19551       }
19552     }
19553   }
19554   return double2angle(res);
19555 }
19556
19557 @
19558 @d p_nextnext mp_link(mp_link(p))
19559 @d p_next mp_link(p)
19560 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19561
19562 @<Declare unary action...@>=
19563 static scaled mp_new_turn_cycles (MP mp,pointer c) {
19564   angle res,ang; /*  the angles of intermediate results  */
19565   scaled turns;  /*  the turn counter  */
19566   pointer p;     /*  for running around the path  */
19567   integer xp,yp;   /*  coordinates of next point  */
19568   integer x,y;   /*  helper coordinates  */
19569   angle in_angle,out_angle;     /*  helper angles */
19570   unsigned old_setting; /* saved |selector| setting */
19571   res=0;
19572   turns= 0;
19573   p=c;
19574   old_setting = mp->selector; mp->selector=term_only;
19575   if ( mp->internal[mp_tracing_commands]>unity ) {
19576     mp_begin_diagnostic(mp);
19577     mp_print_nl(mp, "");
19578     mp_end_diagnostic(mp, false);
19579   }
19580   do { 
19581     xp = mp_x_coord(p_next); yp = mp_y_coord(p_next);
19582     ang  = mp_bezier_slope(mp,mp_x_coord(p), mp_y_coord(p), mp_right_x(p), mp_right_y(p),
19583              mp_left_x(p_next), mp_left_y(p_next), xp, yp);
19584     if ( ang>seven_twenty_deg ) {
19585       print_err("Strange path");
19586       mp_error(mp);
19587       mp->selector=old_setting;
19588       return 0;
19589     }
19590     res  = res + ang;
19591     if ( res > one_eighty_deg ) {
19592       res = res - three_sixty_deg;
19593       turns = turns + unity;
19594     }
19595     if ( res <= -one_eighty_deg ) {
19596       res = res + three_sixty_deg;
19597       turns = turns - unity;
19598     }
19599     /*  incoming angle at next point  */
19600     x = mp_left_x(p_next);  y = mp_left_y(p_next);
19601     if ( (xp==x)&&(yp==y) ) { x = mp_right_x(p);  y = mp_right_y(p);  };
19602     if ( (xp==x)&&(yp==y) ) { x = mp_x_coord(p);  y = mp_y_coord(p);  };
19603     in_angle = mp_an_angle(mp, xp - x, yp - y);
19604     /*  outgoing angle at next point  */
19605     x = mp_right_x(p_next);  y = mp_right_y(p_next);
19606     if ( (xp==x)&&(yp==y) ) { x = mp_left_x(p_nextnext);  y = mp_left_y(p_nextnext);  };
19607     if ( (xp==x)&&(yp==y) ) { x = mp_x_coord(p_nextnext); y = mp_y_coord(p_nextnext); };
19608     out_angle = mp_an_angle(mp, x - xp, y- yp);
19609     ang  = (out_angle - in_angle);
19610     reduce_angle(ang);
19611     if ( ang!=0 ) {
19612       res  = res + ang;
19613       if ( res >= one_eighty_deg ) {
19614         res = res - three_sixty_deg;
19615         turns = turns + unity;
19616       };
19617       if ( res <= -one_eighty_deg ) {
19618         res = res + three_sixty_deg;
19619         turns = turns - unity;
19620       };
19621     };
19622     p = mp_link(p);
19623   } while (p!=c);
19624   mp->selector=old_setting;
19625   return turns;
19626 }
19627
19628
19629 @ This code is based on Bogus\l{}av Jackowski's
19630 |emergency_turningnumber| macro, with some minor changes by Taco
19631 Hoekwater. The macro code looked more like this:
19632 {\obeylines
19633 vardef turning\_number primary p =
19634 ~~save res, ang, turns;
19635 ~~res := 0;
19636 ~~if length p <= 2:
19637 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19638 ~~else:
19639 ~~~~for t = 0 upto length p-1 :
19640 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19641 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19642 ~~~~~~if angc > 180: angc := angc - 360; fi;
19643 ~~~~~~if angc < -180: angc := angc + 360; fi;
19644 ~~~~~~res  := res + angc;
19645 ~~~~endfor;
19646 ~~res/360
19647 ~~fi
19648 enddef;}
19649 The general idea is to calculate only the sum of the angles of
19650 straight lines between the points, of a path, not worrying about cusps
19651 or self-intersections in the segments at all. If the segment is not
19652 well-behaved, the result is not necesarily correct. But the old code
19653 was not always correct either, and worse, it sometimes failed for
19654 well-behaved paths as well. All known bugs that were triggered by the
19655 original code no longer occur with this code, and it runs roughly 3
19656 times as fast because the algorithm is much simpler.
19657
19658 @ It is possible to overflow the return value of the |turn_cycles|
19659 function when the path is sufficiently long and winding, but I am not
19660 going to bother testing for that. In any case, it would only return
19661 the looped result value, which is not a big problem.
19662
19663 The macro code for the repeat loop was a bit nicer to look
19664 at than the pascal code, because it could use |point -1 of p|. In
19665 pascal, the fastest way to loop around the path is not to look
19666 backward once, but forward twice. These defines help hide the trick.
19667
19668 @d p_to mp_link(mp_link(p))
19669 @d p_here mp_link(p)
19670 @d p_from p
19671
19672 @<Declare unary action...@>=
19673 static scaled mp_turn_cycles (MP mp,pointer c) {
19674   angle res,ang; /*  the angles of intermediate results  */
19675   scaled turns;  /*  the turn counter  */
19676   pointer p;     /*  for running around the path  */
19677   res=0;  turns= 0; p=c;
19678   do { 
19679     ang  = mp_an_angle (mp, mp_x_coord(p_to) - mp_x_coord(p_here), 
19680                             mp_y_coord(p_to) - mp_y_coord(p_here))
19681         - mp_an_angle (mp, mp_x_coord(p_here) - mp_x_coord(p_from), 
19682                            mp_y_coord(p_here) - mp_y_coord(p_from));
19683     reduce_angle(ang);
19684     res  = res + ang;
19685     if ( res >= three_sixty_deg )  {
19686       res = res - three_sixty_deg;
19687       turns = turns + unity;
19688     };
19689     if ( res <= -three_sixty_deg ) {
19690       res = res + three_sixty_deg;
19691       turns = turns - unity;
19692     };
19693     p = mp_link(p);
19694   } while (p!=c);
19695   return turns;
19696 }
19697
19698 @ @<Declare unary action...@>=
19699 static scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19700   scaled nval,oval;
19701   scaled saved_t_o; /* tracing\_online saved  */
19702   if ( (mp_link(c)==c)||(mp_link(mp_link(c))==c) ) {
19703     if ( mp_an_angle (mp, mp_x_coord(c) - mp_right_x(c),  mp_y_coord(c) - mp_right_y(c)) > 0 )
19704       return unity;
19705     else
19706       return -unity;
19707   } else {
19708     nval = mp_new_turn_cycles(mp, c);
19709     oval = mp_turn_cycles(mp, c);
19710     if ( nval!=oval ) {
19711       saved_t_o=mp->internal[mp_tracing_online];
19712       mp->internal[mp_tracing_online]=unity;
19713       mp_begin_diagnostic(mp);
19714       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19715                        " The current computed value is ");
19716       mp_print_scaled(mp, nval);
19717       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19718       mp_print_scaled(mp, oval);
19719       mp_end_diagnostic(mp, false);
19720       mp->internal[mp_tracing_online]=saved_t_o;
19721     }
19722     return nval;
19723   }
19724 }
19725
19726 @ @d type_range(A,B) { 
19727   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19728     mp_flush_cur_exp(mp, true_code);
19729   else mp_flush_cur_exp(mp, false_code);
19730   mp->cur_type=mp_boolean_type;
19731   }
19732 @d type_test(A) { 
19733   if ( mp->cur_type==(A) ) mp_flush_cur_exp(mp, true_code);
19734   else mp_flush_cur_exp(mp, false_code);
19735   mp->cur_type=mp_boolean_type;
19736   }
19737
19738 @<Additional cases of unary operators@>=
19739 case mp_boolean_type: 
19740   type_range(mp_boolean_type,mp_unknown_boolean); break;
19741 case mp_string_type: 
19742   type_range(mp_string_type,mp_unknown_string); break;
19743 case mp_pen_type: 
19744   type_range(mp_pen_type,mp_unknown_pen); break;
19745 case mp_path_type: 
19746   type_range(mp_path_type,mp_unknown_path); break;
19747 case mp_picture_type: 
19748   type_range(mp_picture_type,mp_unknown_picture); break;
19749 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19750 case mp_pair_type: 
19751   type_test(c); break;
19752 case mp_numeric_type: 
19753   type_range(mp_known,mp_independent); break;
19754 case known_op: case unknown_op: 
19755   mp_test_known(mp, c); break;
19756
19757 @ @<Declare unary action procedures@>=
19758 static void mp_test_known (MP mp,quarterword c) {
19759   int b; /* is the current expression known? */
19760   pointer p,q; /* locations in a big node */
19761   b=false_code;
19762   switch (mp->cur_type) {
19763   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19764   case mp_pen_type: case mp_path_type: case mp_picture_type:
19765   case mp_known: 
19766     b=true_code;
19767     break;
19768   case mp_transform_type:
19769   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19770     p=value(mp->cur_exp);
19771     q=p+mp->big_node_size[mp->cur_type];
19772     do {  
19773       q=q-2;
19774       if ( type(q)!=mp_known ) 
19775        goto DONE;
19776     } while (q!=p);
19777     b=true_code;
19778   DONE:  
19779     break;
19780   default: 
19781     break;
19782   }
19783   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19784   else mp_flush_cur_exp(mp, true_code+false_code-b);
19785   mp->cur_type=mp_boolean_type;
19786 }
19787
19788 @ @<Additional cases of unary operators@>=
19789 case cycle_op: 
19790   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19791   else if ( mp_left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19792   else mp_flush_cur_exp(mp, false_code);
19793   mp->cur_type=mp_boolean_type;
19794   break;
19795
19796 @ @<Additional cases of unary operators@>=
19797 case arc_length: 
19798   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19799   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19800   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19801   break;
19802
19803 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19804 object |type|.
19805 @^data structure assumptions@>
19806
19807 @<Additional cases of unary operators@>=
19808 case filled_op:
19809 case stroked_op:
19810 case textual_op:
19811 case clipped_op:
19812 case bounded_op:
19813   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19814   else if ( mp_link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19815   else if ( type(mp_link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19816     mp_flush_cur_exp(mp, true_code);
19817   else mp_flush_cur_exp(mp, false_code);
19818   mp->cur_type=mp_boolean_type;
19819   break;
19820
19821 @ @<Additional cases of unary operators@>=
19822 case make_pen_op: 
19823   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19824   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19825   else { 
19826     mp->cur_type=mp_pen_type;
19827     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19828   };
19829   break;
19830 case make_path_op: 
19831   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19832   else  { 
19833     mp->cur_type=mp_path_type;
19834     mp_make_path(mp, mp->cur_exp);
19835   };
19836   break;
19837 case reverse: 
19838   if ( mp->cur_type==mp_path_type ) {
19839     p=mp_htap_ypoc(mp, mp->cur_exp);
19840     if ( mp_right_type(p)==mp_endpoint ) p=mp_link(p);
19841     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19842   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19843   else mp_bad_unary(mp, reverse);
19844   break;
19845
19846 @ The |pair_value| routine changes the current expression to a
19847 given ordered pair of values.
19848
19849 @<Declare unary action procedures@>=
19850 static void mp_pair_value (MP mp,scaled x, scaled y) {
19851   pointer p; /* a pair node */
19852   p=mp_get_node(mp, value_node_size); 
19853   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19854   type(p)=mp_pair_type; name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19855   p=value(p);
19856   type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19857   type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19858 }
19859
19860 @ @<Additional cases of unary operators@>=
19861 case ll_corner_op: 
19862   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19863   else mp_pair_value(mp, minx,miny);
19864   break;
19865 case lr_corner_op: 
19866   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19867   else mp_pair_value(mp, maxx,miny);
19868   break;
19869 case ul_corner_op: 
19870   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19871   else mp_pair_value(mp, minx,maxy);
19872   break;
19873 case ur_corner_op: 
19874   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19875   else mp_pair_value(mp, maxx,maxy);
19876   break;
19877
19878 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19879 box of the current expression.  The boolean result is |false| if the expression
19880 has the wrong type.
19881
19882 @<Declare unary action procedures@>=
19883 static boolean mp_get_cur_bbox (MP mp) { 
19884   switch (mp->cur_type) {
19885   case mp_picture_type: 
19886     mp_set_bbox(mp, mp->cur_exp,true);
19887     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19888       minx=0; maxx=0; miny=0; maxy=0;
19889     } else { 
19890       minx=minx_val(mp->cur_exp);
19891       maxx=maxx_val(mp->cur_exp);
19892       miny=miny_val(mp->cur_exp);
19893       maxy=maxy_val(mp->cur_exp);
19894     }
19895     break;
19896   case mp_path_type: 
19897     mp_path_bbox(mp, mp->cur_exp);
19898     break;
19899   case mp_pen_type: 
19900     mp_pen_bbox(mp, mp->cur_exp);
19901     break;
19902   default: 
19903     return false;
19904   }
19905   return true;
19906 }
19907
19908 @ @<Additional cases of unary operators@>=
19909 case read_from_op:
19910 case close_from_op: 
19911   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19912   else mp_do_read_or_close(mp,c);
19913   break;
19914
19915 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19916 a line from the file or to close the file.
19917
19918 @<Declare unary action procedures@>=
19919 static void mp_do_read_or_close (MP mp,quarterword c) {
19920   readf_index n,n0; /* indices for searching |rd_fname| */
19921   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19922     call |start_read_input| and |goto found| or |not_found|@>;
19923   mp_begin_file_reading(mp);
19924   name=is_read;
19925   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19926     goto FOUND;
19927   mp_end_file_reading(mp);
19928 NOT_FOUND:
19929   @<Record the end of file and set |cur_exp| to a dummy value@>;
19930   return;
19931 CLOSE_FILE:
19932   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19933   return;
19934 FOUND:
19935   mp_flush_cur_exp(mp, 0);
19936   mp_finish_read(mp);
19937 }
19938
19939 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19940 |rd_fname|.
19941
19942 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19943 {   
19944   char *fn;
19945   n=mp->read_files;
19946   n0=mp->read_files;
19947   fn = str(mp->cur_exp);
19948   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19949     if ( n>0 ) {
19950       decr(n);
19951     } else if ( c==close_from_op ) {
19952       goto CLOSE_FILE;
19953     } else {
19954       if ( n0==mp->read_files ) {
19955         if ( mp->read_files<mp->max_read_files ) {
19956           incr(mp->read_files);
19957         } else {
19958           void **rd_file;
19959           char **rd_fname;
19960               readf_index l,k;
19961           l = mp->max_read_files + (mp->max_read_files/4);
19962           rd_file = xmalloc((l+1), sizeof(void *));
19963           rd_fname = xmalloc((l+1), sizeof(char *));
19964               for (k=0;k<=l;k++) {
19965             if (k<=mp->max_read_files) {
19966                   rd_file[k]=mp->rd_file[k]; 
19967               rd_fname[k]=mp->rd_fname[k];
19968             } else {
19969               rd_file[k]=0; 
19970               rd_fname[k]=NULL;
19971             }
19972           }
19973               xfree(mp->rd_file); xfree(mp->rd_fname);
19974           mp->max_read_files = l;
19975           mp->rd_file = rd_file;
19976           mp->rd_fname = rd_fname;
19977         }
19978       }
19979       n=n0;
19980       if ( mp_start_read_input(mp,fn,n) ) 
19981         goto FOUND;
19982       else 
19983         goto NOT_FOUND;
19984     }
19985     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19986   } 
19987   if ( c==close_from_op ) { 
19988     (mp->close_file)(mp,mp->rd_file[n]); 
19989     goto NOT_FOUND; 
19990   }
19991 }
19992
19993 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19994 xfree(mp->rd_fname[n]);
19995 mp->rd_fname[n]=NULL;
19996 if ( n==mp->read_files-1 ) mp->read_files=n;
19997 if ( c==close_from_op ) 
19998   goto CLOSE_FILE;
19999 mp_flush_cur_exp(mp, mp->eof_line);
20000 mp->cur_type=mp_string_type
20001
20002 @ The string denoting end-of-file is a one-byte string at position zero, by definition
20003
20004 @<Glob...@>=
20005 str_number eof_line;
20006
20007 @ @<Set init...@>=
20008 mp->eof_line=0;
20009
20010 @ Finally, we have the operations that combine a capsule~|p|
20011 with the current expression.
20012
20013 @d binary_return  { mp_finish_binary(mp, old_p, old_exp); return; }
20014
20015 @c @<Declare binary action procedures@>
20016 static void mp_finish_binary (MP mp, pointer old_p, pointer old_exp ){
20017   check_arith; 
20018   @<Recycle any sidestepped |independent| capsules@>;
20019 }
20020 static void mp_do_binary (MP mp,pointer p, quarterword c) {
20021   pointer q,r,rr; /* for list manipulation */
20022   pointer old_p,old_exp; /* capsules to recycle */
20023   integer v; /* for numeric manipulation */
20024   check_arith;
20025   if ( mp->internal[mp_tracing_commands]>two ) {
20026     @<Trace the current binary operation@>;
20027   }
20028   @<Sidestep |independent| cases in capsule |p|@>;
20029   @<Sidestep |independent| cases in the current expression@>;
20030   switch (c) {
20031   case plus: case minus:
20032     @<Add or subtract the current expression from |p|@>;
20033     break;
20034   @<Additional cases of binary operators@>;
20035   }; /* there are no other cases */
20036   mp_recycle_value(mp, p); 
20037   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
20038   mp_finish_binary(mp, old_p, old_exp);
20039 }
20040
20041 @ @<Declare binary action...@>=
20042 static void mp_bad_binary (MP mp,pointer p, quarterword c) { 
20043   mp_disp_err(mp, p,"");
20044   exp_err("Not implemented: ");
20045 @.Not implemented...@>
20046   if ( c>=min_of ) mp_print_op(mp, c);
20047   mp_print_known_or_unknown_type(mp, type(p),p);
20048   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
20049   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
20050   help3("I'm afraid I don't know how to apply that operation to that",
20051        "combination of types. Continue, and I'll return the second",
20052        "argument (see above) as the result of the operation.");
20053   mp_put_get_error(mp);
20054 }
20055 static void mp_bad_envelope_pen (MP mp) {
20056   mp_disp_err(mp, null,"");
20057   exp_err("Not implemented: envelope(elliptical pen)of(path)");
20058 @.Not implemented...@>
20059   help3("I'm afraid I don't know how to apply that operation to that",
20060        "combination of types. Continue, and I'll return the second",
20061        "argument (see above) as the result of the operation.");
20062   mp_put_get_error(mp);
20063 }
20064
20065 @ @<Trace the current binary operation@>=
20066
20067   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
20068   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
20069   mp_print_char(mp,xord(')')); mp_print_op(mp,c); mp_print_char(mp,xord('('));
20070   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
20071   mp_end_diagnostic(mp, false);
20072 }
20073
20074 @ Several of the binary operations are potentially complicated by the
20075 fact that |independent| values can sneak into capsules. For example,
20076 we've seen an instance of this difficulty in the unary operation
20077 of negation. In order to reduce the number of cases that need to be
20078 handled, we first change the two operands (if necessary)
20079 to rid them of |independent| components. The original operands are
20080 put into capsules called |old_p| and |old_exp|, which will be
20081 recycled after the binary operation has been safely carried out.
20082
20083 @<Recycle any sidestepped |independent| capsules@>=
20084 if ( old_p!=null ) { 
20085   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
20086 }
20087 if ( old_exp!=null ) {
20088   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
20089 }
20090
20091 @ A big node is considered to be ``tarnished'' if it contains at least one
20092 independent component. We will define a simple function called `|tarnished|'
20093 that returns |null| if and only if its argument is not tarnished.
20094
20095 @<Sidestep |independent| cases in capsule |p|@>=
20096 switch (type(p)) {
20097 case mp_transform_type:
20098 case mp_color_type:
20099 case mp_cmykcolor_type:
20100 case mp_pair_type: 
20101   old_p=mp_tarnished(mp, p);
20102   break;
20103 case mp_independent: old_p=mp_void; break;
20104 default: old_p=null; break;
20105 }
20106 if ( old_p!=null ) {
20107   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
20108   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20109 }
20110
20111 @ @<Sidestep |independent| cases in the current expression@>=
20112 switch (mp->cur_type) {
20113 case mp_transform_type:
20114 case mp_color_type:
20115 case mp_cmykcolor_type:
20116 case mp_pair_type: 
20117   old_exp=mp_tarnished(mp, mp->cur_exp);
20118   break;
20119 case mp_independent:old_exp=mp_void; break;
20120 default: old_exp=null; break;
20121 }
20122 if ( old_exp!=null ) {
20123   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20124 }
20125
20126 @ @<Declare binary action...@>=
20127 static pointer mp_tarnished (MP mp,pointer p) {
20128   pointer q; /* beginning of the big node */
20129   pointer r; /* current position in the big node */
20130   q=value(p); r=q+mp->big_node_size[type(p)];
20131   do {  
20132    r=r-2;
20133    if ( type(r)==mp_independent ) return mp_void; 
20134   } while (r!=q);
20135   return null;
20136 }
20137
20138 @ @<Add or subtract the current expression from |p|@>=
20139 if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20140   mp_bad_binary(mp, p,c);
20141 } else  {
20142   if ((mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20143     mp_add_or_subtract(mp, p,null,c);
20144   } else {
20145     if ( mp->cur_type!=type(p) )  {
20146       mp_bad_binary(mp, p,c);
20147     } else { 
20148       q=value(p); r=value(mp->cur_exp);
20149       rr=r+mp->big_node_size[mp->cur_type];
20150       while ( r<rr ) { 
20151         mp_add_or_subtract(mp, q,r,c);
20152         q=q+2; r=r+2;
20153       }
20154     }
20155   }
20156 }
20157
20158 @ The first argument to |add_or_subtract| is the location of a value node
20159 in a capsule or pair node that will soon be recycled. The second argument
20160 is either a location within a pair or transform node of |cur_exp|,
20161 or it is null (which means that |cur_exp| itself should be the second
20162 argument).  The third argument is either |plus| or |minus|.
20163
20164 The sum or difference of the numeric quantities will replace the second
20165 operand.  Arithmetic overflow may go undetected; users aren't supposed to
20166 be monkeying around with really big values.
20167 @^overflow in arithmetic@>
20168
20169 @<Declare binary action...@>=
20170 @<Declare the procedure called |dep_finish|@>
20171 static void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20172   quarterword s,t; /* operand types */
20173   pointer r; /* list traverser */
20174   integer v; /* second operand value */
20175   if ( q==null ) { 
20176     t=mp->cur_type;
20177     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20178   } else { 
20179     t=type(q);
20180     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20181   }
20182   if ( t==mp_known ) {
20183     if ( c==minus ) negate(v);
20184     if ( type(p)==mp_known ) {
20185       v=mp_slow_add(mp, value(p),v);
20186       if ( q==null ) mp->cur_exp=v; else value(q)=v;
20187       return;
20188     }
20189     @<Add a known value to the constant term of |dep_list(p)|@>;
20190   } else  { 
20191     if ( c==minus ) mp_negate_dep_list(mp, v);
20192     @<Add operand |p| to the dependency list |v|@>;
20193   }
20194 }
20195
20196 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20197 r=dep_list(p);
20198 while ( info(r)!=null ) r=mp_link(r);
20199 value(r)=mp_slow_add(mp, value(r),v);
20200 if ( q==null ) {
20201   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=type(p);
20202   name_type(q)=mp_capsule;
20203 }
20204 dep_list(q)=dep_list(p); type(q)=type(p);
20205 prev_dep(q)=prev_dep(p); mp_link(prev_dep(p))=q;
20206 type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20207
20208 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20209 nice to retain the extra accuracy of |fraction| coefficients.
20210 But we have to handle both kinds, and mixtures too.
20211
20212 @<Add operand |p| to the dependency list |v|@>=
20213 if ( type(p)==mp_known ) {
20214   @<Add the known |value(p)| to the constant term of |v|@>;
20215 } else { 
20216   s=type(p); r=dep_list(p);
20217   if ( t==mp_dependent ) {
20218     if ( s==mp_dependent ) {
20219       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20220         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20221       } /* |fix_needed| will necessarily be false */
20222       t=mp_proto_dependent; 
20223       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20224     }
20225     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20226     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20227  DONE:  
20228     @<Output the answer, |v| (which might have become |known|)@>;
20229   }
20230
20231 @ @<Add the known |value(p)| to the constant term of |v|@>=
20232
20233   while ( info(v)!=null ) v=mp_link(v);
20234   value(v)=mp_slow_add(mp, value(p),value(v));
20235 }
20236
20237 @ @<Output the answer, |v| (which might have become |known|)@>=
20238 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20239 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20240
20241 @ Here's the current situation: The dependency list |v| of type |t|
20242 should either be put into the current expression (if |q=null|) or
20243 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20244 or |q|) formerly held a dependency list with the same
20245 final pointer as the list |v|.
20246
20247 @<Declare the procedure called |dep_finish|@>=
20248 static void mp_dep_finish (MP mp, pointer v, pointer q, quarterword t) {
20249   pointer p; /* the destination */
20250   scaled vv; /* the value, if it is |known| */
20251   if ( q==null ) p=mp->cur_exp; else p=q;
20252   dep_list(p)=v; type(p)=t;
20253   if ( info(v)==null ) { 
20254     vv=value(v);
20255     if ( q==null ) { 
20256       mp_flush_cur_exp(mp, vv);
20257     } else  { 
20258       mp_recycle_value(mp, p); type(q)=mp_known; value(q)=vv; 
20259     }
20260   } else if ( q==null ) {
20261     mp->cur_type=t;
20262   }
20263   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20264 }
20265
20266 @ Let's turn now to the six basic relations of comparison.
20267
20268 @<Additional cases of binary operators@>=
20269 case less_than: case less_or_equal: case greater_than:
20270 case greater_or_equal: case equal_to: case unequal_to:
20271   check_arith; /* at this point |arith_error| should be |false|? */
20272   if ( (mp->cur_type>mp_pair_type)&&(type(p)>mp_pair_type) ) {
20273     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20274   } else if ( mp->cur_type!=type(p) ) {
20275     mp_bad_binary(mp, p,c); goto DONE; 
20276   } else if ( mp->cur_type==mp_string_type ) {
20277     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20278   } else if ((mp->cur_type==mp_unknown_string)||
20279            (mp->cur_type==mp_unknown_boolean) ) {
20280     @<Check if unknowns have been equated@>;
20281   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20282     @<Reduce comparison of big nodes to comparison of scalars@>;
20283   } else if ( mp->cur_type==mp_boolean_type ) {
20284     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20285   } else { 
20286     mp_bad_binary(mp, p,c); goto DONE;
20287   }
20288   @<Compare the current expression with zero@>;
20289 DONE:  
20290   mp->arith_error=false; /* ignore overflow in comparisons */
20291   break;
20292
20293 @ @<Compare the current expression with zero@>=
20294 if ( mp->cur_type!=mp_known ) {
20295   if ( mp->cur_type<mp_known ) {
20296     mp_disp_err(mp, p,"");
20297     help1("The quantities shown above have not been equated.")
20298   } else  {
20299     help2("Oh dear. I can\'t decide if the expression above is positive,",
20300           "negative, or zero. So this comparison test won't be `true'.");
20301   }
20302   exp_err("Unknown relation will be considered false");
20303 @.Unknown relation...@>
20304   mp_put_get_flush_error(mp, false_code);
20305 } else {
20306   switch (c) {
20307   case less_than: boolean_reset(mp->cur_exp<0); break;
20308   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20309   case greater_than: boolean_reset(mp->cur_exp>0); break;
20310   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20311   case equal_to: boolean_reset(mp->cur_exp==0); break;
20312   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20313   }; /* there are no other cases */
20314 }
20315 mp->cur_type=mp_boolean_type
20316
20317 @ When two unknown strings are in the same ring, we know that they are
20318 equal. Otherwise, we don't know whether they are equal or not, so we
20319 make no change.
20320
20321 @<Check if unknowns have been equated@>=
20322
20323   q=value(mp->cur_exp);
20324   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20325   if ( q==p ) mp_flush_cur_exp(mp, 0);
20326 }
20327
20328 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20329
20330   q=value(p); r=value(mp->cur_exp);
20331   rr=r+mp->big_node_size[mp->cur_type]-2;
20332   while (1) { mp_add_or_subtract(mp, q,r,minus);
20333     if ( type(r)!=mp_known ) break;
20334     if ( value(r)!=0 ) break;
20335     if ( r==rr ) break;
20336     q=q+2; r=r+2;
20337   }
20338   mp_take_part(mp, name_type(r)+x_part-mp_x_part_sector);
20339 }
20340
20341 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20342
20343 @<Additional cases of binary operators@>=
20344 case and_op:
20345 case or_op: 
20346   if ( (type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20347     mp_bad_binary(mp, p,c);
20348   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20349   break;
20350
20351 @ @<Additional cases of binary operators@>=
20352 case times: 
20353   if ( (mp->cur_type<mp_color_type)||(type(p)<mp_color_type) ) {
20354    mp_bad_binary(mp, p,times);
20355   } else if ( (mp->cur_type==mp_known)||(type(p)==mp_known) ) {
20356     @<Multiply when at least one operand is known@>;
20357   } else if ( (mp_nice_color_or_pair(mp, p,type(p))&&(mp->cur_type>mp_pair_type))
20358       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20359           (type(p)>mp_pair_type)) ) {
20360     mp_hard_times(mp, p); 
20361     binary_return;
20362   } else {
20363     mp_bad_binary(mp, p,times);
20364   }
20365   break;
20366
20367 @ @<Multiply when at least one operand is known@>=
20368
20369   if ( type(p)==mp_known ) {
20370     v=value(p); mp_free_node(mp, p,value_node_size); 
20371   } else {
20372     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20373   }
20374   if ( mp->cur_type==mp_known ) {
20375     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20376   } else if ( (mp->cur_type==mp_pair_type)||
20377               (mp->cur_type==mp_color_type)||
20378               (mp->cur_type==mp_cmykcolor_type) ) {
20379     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20380     do {  
20381        p=p-2; mp_dep_mult(mp, p,v,true);
20382     } while (p!=value(mp->cur_exp));
20383   } else {
20384     mp_dep_mult(mp, null,v,true);
20385   }
20386   binary_return;
20387 }
20388
20389 @ @<Declare binary action...@>=
20390 static void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20391   pointer q; /* the dependency list being multiplied by |v| */
20392   quarterword s,t; /* its type, before and after */
20393   if ( p==null ) {
20394     q=mp->cur_exp;
20395   } else if ( type(p)!=mp_known ) {
20396     q=p;
20397   } else { 
20398     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20399     else value(p)=mp_take_fraction(mp, value(p),v);
20400     return;
20401   };
20402   t=type(q); q=dep_list(q); s=t;
20403   if ( t==mp_dependent ) if ( v_is_scaled )
20404     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20405       t=mp_proto_dependent;
20406   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20407   mp_dep_finish(mp, q,p,t);
20408 }
20409
20410 @ Here is a routine that is similar to |times|; but it is invoked only
20411 internally, when |v| is a |fraction| whose magnitude is at most~1,
20412 and when |cur_type>=mp_color_type|.
20413
20414 @c 
20415 static void mp_frac_mult (MP mp,scaled n, scaled d) {
20416   /* multiplies |cur_exp| by |n/d| */
20417   pointer p; /* a pair node */
20418   pointer old_exp; /* a capsule to recycle */
20419   fraction v; /* |n/d| */
20420   if ( mp->internal[mp_tracing_commands]>two ) {
20421     @<Trace the fraction multiplication@>;
20422   }
20423   switch (mp->cur_type) {
20424   case mp_transform_type:
20425   case mp_color_type:
20426   case mp_cmykcolor_type:
20427   case mp_pair_type:
20428    old_exp=mp_tarnished(mp, mp->cur_exp);
20429    break;
20430   case mp_independent: old_exp=mp_void; break;
20431   default: old_exp=null; break;
20432   }
20433   if ( old_exp!=null ) { 
20434      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20435   }
20436   v=mp_make_fraction(mp, n,d);
20437   if ( mp->cur_type==mp_known ) {
20438     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20439   } else if ( mp->cur_type<=mp_pair_type ) { 
20440     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20441     do {  
20442       p=p-2;
20443       mp_dep_mult(mp, p,v,false);
20444     } while (p!=value(mp->cur_exp));
20445   } else {
20446     mp_dep_mult(mp, null,v,false);
20447   }
20448   if ( old_exp!=null ) {
20449     mp_recycle_value(mp, old_exp); 
20450     mp_free_node(mp, old_exp,value_node_size);
20451   }
20452 }
20453
20454 @ @<Trace the fraction multiplication@>=
20455
20456   mp_begin_diagnostic(mp); 
20457   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,xord('/'));
20458   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20459   mp_print(mp,")}");
20460   mp_end_diagnostic(mp, false);
20461 }
20462
20463 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20464
20465 @<Declare binary action procedures@>=
20466 static void mp_hard_times (MP mp,pointer p) {
20467   pointer q; /* a copy of the dependent variable |p| */
20468   pointer r; /* a component of the big node for the nice color or pair */
20469   scaled v; /* the known value for |r| */
20470   if ( type(p)<=mp_pair_type ) { 
20471      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20472   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20473   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20474   while (1) { 
20475     r=r-2;
20476     v=value(r);
20477     type(r)=type(p);
20478     if ( r==value(mp->cur_exp) ) 
20479       break;
20480     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20481     mp_dep_mult(mp, r,v,true);
20482   }
20483   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20484   mp_link(prev_dep(p))=r;
20485   mp_free_node(mp, p,value_node_size);
20486   mp_dep_mult(mp, r,v,true);
20487 }
20488
20489 @ @<Additional cases of binary operators@>=
20490 case over: 
20491   if ( (mp->cur_type!=mp_known)||(type(p)<mp_color_type) ) {
20492     mp_bad_binary(mp, p,over);
20493   } else { 
20494     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20495     if ( v==0 ) {
20496       @<Squeal about division by zero@>;
20497     } else { 
20498       if ( mp->cur_type==mp_known ) {
20499         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20500       } else if ( mp->cur_type<=mp_pair_type ) { 
20501         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20502         do {  
20503           p=p-2;  mp_dep_div(mp, p,v);
20504         } while (p!=value(mp->cur_exp));
20505       } else {
20506         mp_dep_div(mp, null,v);
20507       }
20508     }
20509     binary_return;
20510   }
20511   break;
20512
20513 @ @<Declare binary action...@>=
20514 static void mp_dep_div (MP mp,pointer p, scaled v) {
20515   pointer q; /* the dependency list being divided by |v| */
20516   quarterword s,t; /* its type, before and after */
20517   if ( p==null ) q=mp->cur_exp;
20518   else if ( type(p)!=mp_known ) q=p;
20519   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20520   t=type(q); q=dep_list(q); s=t;
20521   if ( t==mp_dependent )
20522     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20523       t=mp_proto_dependent;
20524   q=mp_p_over_v(mp, q,v,s,t); 
20525   mp_dep_finish(mp, q,p,t);
20526 }
20527
20528 @ @<Squeal about division by zero@>=
20529
20530   exp_err("Division by zero");
20531 @.Division by zero@>
20532   help2("You're trying to divide the quantity shown above the error",
20533         "message by zero. I'm going to divide it by one instead.");
20534   mp_put_get_error(mp);
20535 }
20536
20537 @ @<Additional cases of binary operators@>=
20538 case pythag_add:
20539 case pythag_sub: 
20540    if ( (mp->cur_type==mp_known)&&(type(p)==mp_known) ) {
20541      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20542      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20543    } else mp_bad_binary(mp, p,c);
20544    break;
20545
20546 @ The next few sections of the program deal with affine transformations
20547 of coordinate data.
20548
20549 @<Additional cases of binary operators@>=
20550 case rotated_by: case slanted_by:
20551 case scaled_by: case shifted_by: case transformed_by:
20552 case x_scaled: case y_scaled: case z_scaled:
20553   if ( type(p)==mp_path_type ) { 
20554     path_trans(c,p); binary_return;
20555   } else if ( type(p)==mp_pen_type ) { 
20556     pen_trans(c,p);
20557     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20558       /* rounding error could destroy convexity */
20559     binary_return;
20560   } else if ( (type(p)==mp_pair_type)||(type(p)==mp_transform_type) ) {
20561     mp_big_trans(mp, p,c);
20562   } else if ( type(p)==mp_picture_type ) {
20563     mp_do_edges_trans(mp, p,c); binary_return;
20564   } else {
20565     mp_bad_binary(mp, p,c);
20566   }
20567   break;
20568
20569 @ Let |c| be one of the eight transform operators. The procedure call
20570 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20571 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20572 change at all if |c=transformed_by|.)
20573
20574 Then, if all components of the resulting transform are |known|, they are
20575 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20576 and |cur_exp| is changed to the known value zero.
20577
20578 @<Declare binary action...@>=
20579 static void mp_set_up_trans (MP mp,quarterword c) {
20580   pointer p,q,r; /* list manipulation registers */
20581   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20582     @<Put the current transform into |cur_exp|@>;
20583   }
20584   @<If the current transform is entirely known, stash it in global variables;
20585     otherwise |return|@>;
20586 }
20587
20588 @ @<Glob...@>=
20589 scaled txx;
20590 scaled txy;
20591 scaled tyx;
20592 scaled tyy;
20593 scaled tx;
20594 scaled ty; /* current transform coefficients */
20595
20596 @ @<Put the current transform...@>=
20597
20598   p=mp_stash_cur_exp(mp); 
20599   mp->cur_exp=mp_id_transform(mp); 
20600   mp->cur_type=mp_transform_type;
20601   q=value(mp->cur_exp);
20602   switch (c) {
20603   @<For each of the eight cases, change the relevant fields of |cur_exp|
20604     and |goto done|;
20605     but do nothing if capsule |p| doesn't have the appropriate type@>;
20606   }; /* there are no other cases */
20607   mp_disp_err(mp, p,"Improper transformation argument");
20608 @.Improper transformation argument@>
20609   help3("The expression shown above has the wrong type,",
20610        "so I can\'t transform anything using it.",
20611        "Proceed, and I'll omit the transformation.");
20612   mp_put_get_error(mp);
20613 DONE: 
20614   mp_recycle_value(mp, p); 
20615   mp_free_node(mp, p,value_node_size);
20616 }
20617
20618 @ @<If the current transform is entirely known, ...@>=
20619 q=value(mp->cur_exp); r=q+transform_node_size;
20620 do {  
20621   r=r-2;
20622   if ( type(r)!=mp_known ) return;
20623 } while (r!=q);
20624 mp->txx=value(xx_part_loc(q));
20625 mp->txy=value(xy_part_loc(q));
20626 mp->tyx=value(yx_part_loc(q));
20627 mp->tyy=value(yy_part_loc(q));
20628 mp->tx=value(x_part_loc(q));
20629 mp->ty=value(y_part_loc(q));
20630 mp_flush_cur_exp(mp, 0)
20631
20632 @ @<For each of the eight cases...@>=
20633 case rotated_by:
20634   if ( type(p)==mp_known )
20635     @<Install sines and cosines, then |goto done|@>;
20636   break;
20637 case slanted_by:
20638   if ( type(p)>mp_pair_type ) { 
20639    mp_install(mp, xy_part_loc(q),p); goto DONE;
20640   };
20641   break;
20642 case scaled_by:
20643   if ( type(p)>mp_pair_type ) { 
20644     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20645     goto DONE;
20646   };
20647   break;
20648 case shifted_by:
20649   if ( type(p)==mp_pair_type ) {
20650     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20651     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20652   };
20653   break;
20654 case x_scaled:
20655   if ( type(p)>mp_pair_type ) {
20656     mp_install(mp, xx_part_loc(q),p); goto DONE;
20657   };
20658   break;
20659 case y_scaled:
20660   if ( type(p)>mp_pair_type ) {
20661     mp_install(mp, yy_part_loc(q),p); goto DONE;
20662   };
20663   break;
20664 case z_scaled:
20665   if ( type(p)==mp_pair_type )
20666     @<Install a complex multiplier, then |goto done|@>;
20667   break;
20668 case transformed_by:
20669   break;
20670   
20671
20672 @ @<Install sines and cosines, then |goto done|@>=
20673 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20674   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20675   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20676   value(xy_part_loc(q))=-value(yx_part_loc(q));
20677   value(yy_part_loc(q))=value(xx_part_loc(q));
20678   goto DONE;
20679 }
20680
20681 @ @<Install a complex multiplier, then |goto done|@>=
20682
20683   r=value(p);
20684   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20685   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20686   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20687   if ( type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20688   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20689   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20690   goto DONE;
20691 }
20692
20693 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20694 insists that the transformation be entirely known.
20695
20696 @<Declare binary action...@>=
20697 static void mp_set_up_known_trans (MP mp,quarterword c) { 
20698   mp_set_up_trans(mp, c);
20699   if ( mp->cur_type!=mp_known ) {
20700     exp_err("Transform components aren't all known");
20701 @.Transform components...@>
20702     help3("I'm unable to apply a partially specified transformation",
20703       "except to a fully known pair or transform.",
20704       "Proceed, and I'll omit the transformation.");
20705     mp_put_get_flush_error(mp, 0);
20706     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20707     mp->tx=0; mp->ty=0;
20708   }
20709 }
20710
20711 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20712 coordinates in locations |p| and~|q|.
20713
20714 @<Declare binary action...@>= 
20715 static void mp_trans (MP mp,pointer p, pointer q) {
20716   scaled v; /* the new |x| value */
20717   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20718   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20719   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20720   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20721   mp->mem[p].sc=v;
20722 }
20723
20724 @ The simplest transformation procedure applies a transform to all
20725 coordinates of a path.  The |path_trans(c)(p)| macro applies
20726 a transformation defined by |cur_exp| and the transform operator |c|
20727 to the path~|p|.
20728
20729 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20730                      mp_unstash_cur_exp(mp, (B)); 
20731                      mp_do_path_trans(mp, mp->cur_exp); }
20732
20733 @<Declare binary action...@>=
20734 static void mp_do_path_trans (MP mp,pointer p) {
20735   pointer q; /* list traverser */
20736   q=p;
20737   do { 
20738     if ( mp_left_type(q)!=mp_endpoint ) 
20739       mp_trans(mp, q+3,q+4); /* that's |mp_left_x| and |mp_left_y| */
20740     mp_trans(mp, q+1,q+2); /* that's |mp_x_coord| and |mp_y_coord| */
20741     if ( mp_right_type(q)!=mp_endpoint ) 
20742       mp_trans(mp, q+5,q+6); /* that's |mp_right_x| and |mp_right_y| */
20743 @^data structure assumptions@>
20744     q=mp_link(q);
20745   } while (q!=p);
20746 }
20747
20748 @ Transforming a pen is very similar, except that there are no |mp_left_type|
20749 and |mp_right_type| fields.
20750
20751 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20752                     mp_unstash_cur_exp(mp, (B)); 
20753                     mp_do_pen_trans(mp, mp->cur_exp); }
20754
20755 @<Declare binary action...@>=
20756 static void mp_do_pen_trans (MP mp,pointer p) {
20757   pointer q; /* list traverser */
20758   if ( pen_is_elliptical(p) ) {
20759     mp_trans(mp, p+3,p+4); /* that's |mp_left_x| and |mp_left_y| */
20760     mp_trans(mp, p+5,p+6); /* that's |mp_right_x| and |mp_right_y| */
20761   };
20762   q=p;
20763   do { 
20764     mp_trans(mp, q+1,q+2); /* that's |mp_x_coord| and |mp_y_coord| */
20765 @^data structure assumptions@>
20766     q=mp_link(q);
20767   } while (q!=p);
20768 }
20769
20770 @ The next transformation procedure applies to edge structures. It will do
20771 any transformation, but the results may be substandard if the picture contains
20772 text that uses downloaded bitmap fonts.  The binary action procedure is
20773 |do_edges_trans|, but we also need a function that just scales a picture.
20774 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20775 should be thought of as procedures that update an edge structure |h|, except
20776 that they have to return a (possibly new) structure because of the need to call
20777 |private_edges|.
20778
20779 @<Declare binary action...@>=
20780 static pointer mp_edges_trans (MP mp, pointer h) {
20781   pointer q; /* the object being transformed */
20782   pointer r,s; /* for list manipulation */
20783   scaled sx,sy; /* saved transformation parameters */
20784   scaled sqdet; /* square root of determinant for |dash_scale| */
20785   integer sgndet; /* sign of the determinant */
20786   scaled v; /* a temporary value */
20787   h=mp_private_edges(mp, h);
20788   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20789   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20790   if ( dash_list(h)!=null_dash ) {
20791     @<Try to transform the dash list of |h|@>;
20792   }
20793   @<Make the bounding box of |h| unknown if it can't be updated properly
20794     without scanning the whole structure@>;  
20795   q=mp_link(dummy_loc(h));
20796   while ( q!=null ) { 
20797     @<Transform graphical object |q|@>;
20798     q=mp_link(q);
20799   }
20800   return h;
20801 }
20802 static void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20803   mp_set_up_known_trans(mp, c);
20804   value(p)=mp_edges_trans(mp, value(p));
20805   mp_unstash_cur_exp(mp, p);
20806 }
20807 static void mp_scale_edges (MP mp) { 
20808   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20809   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20810   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20811 }
20812
20813 @ @<Try to transform the dash list of |h|@>=
20814 if ( (mp->txy!=0)||(mp->tyx!=0)||
20815      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20816   mp_flush_dash_list(mp, h);
20817 } else { 
20818   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20819   @<Scale the dash list by |txx| and shift it by |tx|@>;
20820   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20821 }
20822
20823 @ @<Reverse the dash list of |h|@>=
20824
20825   r=dash_list(h);
20826   dash_list(h)=null_dash;
20827   while ( r!=null_dash ) {
20828     s=r; r=mp_link(r);
20829     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20830     mp_link(s)=dash_list(h);
20831     dash_list(h)=s;
20832   }
20833 }
20834
20835 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20836 r=dash_list(h);
20837 while ( r!=null_dash ) {
20838   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20839   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20840   r=mp_link(r);
20841 }
20842
20843 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20844 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20845   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20846 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20847   mp_init_bbox(mp, h);
20848   goto DONE1;
20849 }
20850 if ( minx_val(h)<=maxx_val(h) ) {
20851   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20852    |(tx,ty)|@>;
20853 }
20854 DONE1:
20855
20856
20857
20858 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20859
20860   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20861   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20862 }
20863
20864 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20865 sum is similar.
20866
20867 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20868
20869   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20870   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20871   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20872   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20873   if ( mp->txx+mp->txy<0 ) {
20874     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20875   }
20876   if ( mp->tyx+mp->tyy<0 ) {
20877     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20878   }
20879 }
20880
20881 @ Now we ready for the main task of transforming the graphical objects in edge
20882 structure~|h|.
20883
20884 @<Transform graphical object |q|@>=
20885 switch (type(q)) {
20886 case mp_fill_code: case mp_stroked_code: 
20887   mp_do_path_trans(mp, path_p(q));
20888   @<Transform |pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20889   break;
20890 case mp_start_clip_code: case mp_start_bounds_code: 
20891   mp_do_path_trans(mp, path_p(q));
20892   break;
20893 case mp_text_code: 
20894   r=text_tx_loc(q);
20895   @<Transform the compact transformation starting at |r|@>;
20896   break;
20897 case mp_stop_clip_code: case mp_stop_bounds_code: 
20898   break;
20899 } /* there are no other cases */
20900
20901 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20902 The |dash_scale| has to be adjusted  to scale the dash lengths in |dash_p(q)|
20903 since the \ps\ output procedures will try to compensate for the transformation
20904 we are applying to |pen_p(q)|.  Since this compensation is based on the square
20905 root of the determinant, |sqdet| is the appropriate factor.
20906
20907 @<Transform |pen_p(q)|, making sure...@>=
20908 if ( pen_p(q)!=null ) {
20909   sx=mp->tx; sy=mp->ty;
20910   mp->tx=0; mp->ty=0;
20911   mp_do_pen_trans(mp, pen_p(q));
20912   if ( ((type(q)==mp_stroked_code)&&(dash_p(q)!=null)) )
20913     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20914   if ( ! pen_is_elliptical(pen_p(q)) )
20915     if ( sgndet<0 )
20916       pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, pen_p(q)),true); 
20917          /* this unreverses the pen */
20918   mp->tx=sx; mp->ty=sy;
20919 }
20920
20921 @ This uses the fact that transformations are stored in the order
20922 |(tx,ty,txx,txy,tyx,tyy)|.
20923 @^data structure assumptions@>
20924
20925 @<Transform the compact transformation starting at |r|@>=
20926 mp_trans(mp, r,r+1);
20927 sx=mp->tx; sy=mp->ty;
20928 mp->tx=0; mp->ty=0;
20929 mp_trans(mp, r+2,r+4);
20930 mp_trans(mp, r+3,r+5);
20931 mp->tx=sx; mp->ty=sy
20932
20933 @ The hard cases of transformation occur when big nodes are involved,
20934 and when some of their components are unknown.
20935
20936 @<Declare binary action...@>=
20937 @<Declare subroutines needed by |big_trans|@>
20938 static void mp_big_trans (MP mp,pointer p, quarterword c) {
20939   pointer q,r,pp,qq; /* list manipulation registers */
20940   quarterword s; /* size of a big node */
20941   s=mp->big_node_size[type(p)]; q=value(p); r=q+s;
20942   do {  
20943     r=r-2;
20944     if ( type(r)!=mp_known ) {
20945       @<Transform an unknown big node and |return|@>;
20946     }
20947   } while (r!=q);
20948   @<Transform a known big node@>;
20949 } /* node |p| will now be recycled by |do_binary| */
20950
20951 @ @<Transform an unknown big node and |return|@>=
20952
20953   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20954   r=value(mp->cur_exp);
20955   if ( mp->cur_type==mp_transform_type ) {
20956     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20957     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20958     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20959     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20960   }
20961   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20962   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20963   return;
20964 }
20965
20966 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20967 and let |q| point to a another value field. The |bilin1| procedure
20968 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20969
20970 @<Declare subroutines needed by |big_trans|@>=
20971 static void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20972                 scaled u, scaled delta) {
20973   pointer r; /* list traverser */
20974   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20975   if ( u!=0 ) {
20976     if ( type(q)==mp_known ) {
20977       delta+=mp_take_scaled(mp, value(q),u);
20978     } else { 
20979       @<Ensure that |type(p)=mp_proto_dependent|@>;
20980       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20981                                mp_proto_dependent,type(q));
20982     }
20983   }
20984   if ( type(p)==mp_known ) {
20985     value(p)+=delta;
20986   } else {
20987     r=dep_list(p);
20988     while ( info(r)!=null ) r=mp_link(r);
20989     delta+=value(r);
20990     if ( r!=dep_list(p) ) value(r)=delta;
20991     else { mp_recycle_value(mp, p); type(p)=mp_known; value(p)=delta; };
20992   }
20993   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20994 }
20995
20996 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20997 if ( type(p)!=mp_proto_dependent ) {
20998   if ( type(p)==mp_known ) 
20999     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
21000   else 
21001     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
21002                              mp_proto_dependent,true);
21003   type(p)=mp_proto_dependent;
21004 }
21005
21006 @ @<Transform a known big node@>=
21007 mp_set_up_trans(mp, c);
21008 if ( mp->cur_type==mp_known ) {
21009   @<Transform known by known@>;
21010 } else { 
21011   pp=mp_stash_cur_exp(mp); qq=value(pp);
21012   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
21013   if ( mp->cur_type==mp_transform_type ) {
21014     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
21015       value(xy_part_loc(q)),yx_part_loc(qq),null);
21016     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
21017       value(xx_part_loc(q)),yx_part_loc(qq),null);
21018     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
21019       value(yy_part_loc(q)),xy_part_loc(qq),null);
21020     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
21021       value(yx_part_loc(q)),xy_part_loc(qq),null);
21022   };
21023   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
21024     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
21025   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
21026     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
21027   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
21028 }
21029
21030 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
21031 at |dep_final|. The following procedure adds |v| times another
21032 numeric quantity to~|p|.
21033
21034 @<Declare subroutines needed by |big_trans|@>=
21035 static void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
21036   if ( type(r)==mp_known ) {
21037     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
21038   } else  { 
21039     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
21040                                                          mp_proto_dependent,type(r));
21041     if ( mp->fix_needed ) mp_fix_dependencies(mp);
21042   }
21043 }
21044
21045 @ The |bilin2| procedure is something like |bilin1|, but with known
21046 and unknown quantities reversed. Parameter |p| points to a value field
21047 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
21048 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
21049 unless it is |null| (which stands for zero). Location~|p| will be
21050 replaced by $p\cdot t+v\cdot u+q$.
21051
21052 @<Declare subroutines needed by |big_trans|@>=
21053 static void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
21054                 pointer u, pointer q) {
21055   scaled vv; /* temporary storage for |value(p)| */
21056   vv=value(p); type(p)=mp_proto_dependent;
21057   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
21058   if ( vv!=0 ) 
21059     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
21060   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
21061   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
21062   if ( dep_list(p)==mp->dep_final ) {
21063     vv=value(mp->dep_final); mp_recycle_value(mp, p);
21064     type(p)=mp_known; value(p)=vv;
21065   }
21066 }
21067
21068 @ @<Transform known by known@>=
21069
21070   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
21071   if ( mp->cur_type==mp_transform_type ) {
21072     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
21073     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
21074     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
21075     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
21076   }
21077   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
21078   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
21079 }
21080
21081 @ Finally, in |bilin3| everything is |known|.
21082
21083 @<Declare subroutines needed by |big_trans|@>=
21084 static void mp_bilin3 (MP mp,pointer p, scaled t, 
21085                scaled v, scaled u, scaled delta) { 
21086   if ( t!=unity )
21087     delta+=mp_take_scaled(mp, value(p),t);
21088   else 
21089     delta+=value(p);
21090   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
21091   else value(p)=delta;
21092 }
21093
21094 @ @<Additional cases of binary operators@>=
21095 case concatenate: 
21096   if ( (mp->cur_type==mp_string_type)&&(type(p)==mp_string_type) ) mp_cat(mp, p);
21097   else mp_bad_binary(mp, p,concatenate);
21098   break;
21099 case substring_of: 
21100   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_string_type) )
21101     mp_chop_string(mp, value(p));
21102   else mp_bad_binary(mp, p,substring_of);
21103   break;
21104 case subpath_of: 
21105   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21106   if ( mp_nice_pair(mp, p,type(p))&&(mp->cur_type==mp_path_type) )
21107     mp_chop_path(mp, value(p));
21108   else mp_bad_binary(mp, p,subpath_of);
21109   break;
21110
21111 @ @<Declare binary action...@>=
21112 static void mp_cat (MP mp,pointer p) {
21113   str_number a,b; /* the strings being concatenated */
21114   pool_pointer k; /* index into |str_pool| */
21115   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
21116   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
21117     append_char(mp->str_pool[k]);
21118   }
21119   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
21120     append_char(mp->str_pool[k]);
21121   }
21122   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
21123 }
21124
21125 @ @<Declare binary action...@>=
21126 static void mp_chop_string (MP mp,pointer p) {
21127   integer a, b; /* start and stop points */
21128   integer l; /* length of the original string */
21129   integer k; /* runs from |a| to |b| */
21130   str_number s; /* the original string */
21131   boolean reversed; /* was |a>b|? */
21132   a=mp_round_unscaled(mp, value(x_part_loc(p)));
21133   b=mp_round_unscaled(mp, value(y_part_loc(p)));
21134   if ( a<=b ) reversed=false;
21135   else  { reversed=true; k=a; a=b; b=k; };
21136   s=mp->cur_exp; l=length(s);
21137   if ( a<0 ) { 
21138     a=0;
21139     if ( b<0 ) b=0;
21140   }
21141   if ( b>l ) { 
21142     b=l;
21143     if ( a>l ) a=l;
21144   }
21145   str_room(b-a);
21146   if ( reversed ) {
21147     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
21148       append_char(mp->str_pool[k]);
21149     }
21150   } else  {
21151     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
21152       append_char(mp->str_pool[k]);
21153     }
21154   }
21155   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
21156 }
21157
21158 @ @<Declare binary action...@>=
21159 static void mp_chop_path (MP mp,pointer p) {
21160   pointer q; /* a knot in the original path */
21161   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21162   scaled a,b,k,l; /* indices for chopping */
21163   boolean reversed; /* was |a>b|? */
21164   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21165   if ( a<=b ) reversed=false;
21166   else  { reversed=true; k=a; a=b; b=k; };
21167   @<Dispense with the cases |a<0| and/or |b>l|@>;
21168   q=mp->cur_exp;
21169   while ( a>=unity ) {
21170     q=mp_link(q); a=a-unity; b=b-unity;
21171   }
21172   if ( b==a ) {
21173     @<Construct a path from |pp| to |qq| of length zero@>; 
21174   } else { 
21175     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
21176   }
21177   mp_left_type(pp)=mp_endpoint; mp_right_type(qq)=mp_endpoint; mp_link(qq)=pp;
21178   mp_toss_knot_list(mp, mp->cur_exp);
21179   if ( reversed ) {
21180     mp->cur_exp=mp_link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21181   } else {
21182     mp->cur_exp=pp;
21183   }
21184 }
21185
21186 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21187 if ( a<0 ) {
21188   if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
21189     a=0; if ( b<0 ) b=0;
21190   } else  {
21191     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21192   }
21193 }
21194 if ( b>l ) {
21195   if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
21196     b=l; if ( a>l ) a=l;
21197   } else {
21198     while ( a>=l ) { 
21199       a=a-l; b=b-l;
21200     }
21201   }
21202 }
21203
21204 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21205
21206   pp=mp_copy_knot(mp, q); qq=pp;
21207   do {  
21208     q=mp_link(q); rr=qq; qq=mp_copy_knot(mp, q); mp_link(rr)=qq; b=b-unity;
21209   } while (b>0);
21210   if ( a>0 ) {
21211     ss=pp; pp=mp_link(pp);
21212     mp_split_cubic(mp, ss,a*010000); pp=mp_link(ss);
21213     mp_free_node(mp, ss,knot_node_size);
21214     if ( rr==ss ) {
21215       b=mp_make_scaled(mp, b,unity-a); rr=pp;
21216     }
21217   }
21218   if ( b<0 ) {
21219     mp_split_cubic(mp, rr,(b+unity)*010000);
21220     mp_free_node(mp, qq,knot_node_size);
21221     qq=mp_link(rr);
21222   }
21223 }
21224
21225 @ @<Construct a path from |pp| to |qq| of length zero@>=
21226
21227   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=mp_link(q); };
21228   pp=mp_copy_knot(mp, q); qq=pp;
21229 }
21230
21231 @ @<Additional cases of binary operators@>=
21232 case point_of: case precontrol_of: case postcontrol_of: 
21233   if ( mp->cur_type==mp_pair_type )
21234      mp_pair_to_path(mp);
21235   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21236     mp_find_point(mp, value(p),c);
21237   else 
21238     mp_bad_binary(mp, p,c);
21239   break;
21240 case pen_offset_of: 
21241   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,type(p)) )
21242     mp_set_up_offset(mp, value(p));
21243   else 
21244     mp_bad_binary(mp, p,pen_offset_of);
21245   break;
21246 case direction_time_of: 
21247   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21248   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,type(p)) )
21249     mp_set_up_direction_time(mp, value(p));
21250   else 
21251     mp_bad_binary(mp, p,direction_time_of);
21252   break;
21253 case envelope_of:
21254   if ( (type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21255     mp_bad_binary(mp, p,envelope_of);
21256   else
21257     mp_set_up_envelope(mp, p);
21258   break;
21259
21260 @ @<Declare binary action...@>=
21261 static void mp_set_up_offset (MP mp,pointer p) { 
21262   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21263   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21264 }
21265 static void mp_set_up_direction_time (MP mp,pointer p) { 
21266   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21267   value(y_part_loc(p)),mp->cur_exp));
21268 }
21269 static void mp_set_up_envelope (MP mp,pointer p) {
21270   quarterword ljoin, lcap;
21271   scaled miterlim;
21272   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21273   /* TODO: accept elliptical pens for straight paths */
21274   if (pen_is_elliptical(value(p))) {
21275     mp_bad_envelope_pen(mp);
21276     mp->cur_exp = q;
21277     mp->cur_type = mp_path_type;
21278     return;
21279   }
21280   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21281   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21282   else ljoin=0;
21283   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21284   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21285   else lcap=0;
21286   if ( mp->internal[mp_miterlimit]<unity )
21287     miterlim=unity;
21288   else
21289     miterlim=mp->internal[mp_miterlimit];
21290   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21291   mp->cur_type = mp_path_type;
21292 }
21293
21294 @ @<Declare binary action...@>=
21295 static void mp_find_point (MP mp,scaled v, quarterword c) {
21296   pointer p; /* the path */
21297   scaled n; /* its length */
21298   p=mp->cur_exp;
21299   if ( mp_left_type(p)==mp_endpoint ) n=-unity; else n=0;
21300   do {  p=mp_link(p); n=n+unity; } while (p!=mp->cur_exp);
21301   if ( n==0 ) { 
21302     v=0; 
21303   } else if ( v<0 ) {
21304     if ( mp_left_type(p)==mp_endpoint ) v=0;
21305     else v=n-1-((-v-1) % n);
21306   } else if ( v>n ) {
21307     if ( mp_left_type(p)==mp_endpoint ) v=n;
21308     else v=v % n;
21309   }
21310   p=mp->cur_exp;
21311   while ( v>=unity ) { p=mp_link(p); v=v-unity;  };
21312   if ( v!=0 ) {
21313      @<Insert a fractional node by splitting the cubic@>;
21314   }
21315   @<Set the current expression to the desired path coordinates@>;
21316 }
21317
21318 @ @<Insert a fractional node...@>=
21319 { mp_split_cubic(mp, p,v*010000); p=mp_link(p); }
21320
21321 @ @<Set the current expression to the desired path coordinates...@>=
21322 switch (c) {
21323 case point_of: 
21324   mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21325   break;
21326 case precontrol_of: 
21327   if ( mp_left_type(p)==mp_endpoint ) mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21328   else mp_pair_value(mp, mp_left_x(p),mp_left_y(p));
21329   break;
21330 case postcontrol_of: 
21331   if ( mp_right_type(p)==mp_endpoint ) mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21332   else mp_pair_value(mp, mp_right_x(p),mp_right_y(p));
21333   break;
21334 } /* there are no other cases */
21335
21336 @ @<Additional cases of binary operators@>=
21337 case arc_time_of: 
21338   if ( mp->cur_type==mp_pair_type )
21339      mp_pair_to_path(mp);
21340   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_known) )
21341     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21342   else 
21343     mp_bad_binary(mp, p,c);
21344   break;
21345
21346 @ @<Additional cases of bin...@>=
21347 case intersect: 
21348   if ( type(p)==mp_pair_type ) {
21349     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21350     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21351   };
21352   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21353   if ( (mp->cur_type==mp_path_type)&&(type(p)==mp_path_type) ) {
21354     mp_path_intersection(mp, value(p),mp->cur_exp);
21355     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21356   } else {
21357     mp_bad_binary(mp, p,intersect);
21358   }
21359   break;
21360
21361 @ @<Additional cases of bin...@>=
21362 case in_font:
21363   if ( (mp->cur_type!=mp_string_type)||(type(p)!=mp_string_type)) 
21364     mp_bad_binary(mp, p,in_font);
21365   else { mp_do_infont(mp, p); binary_return; }
21366   break;
21367
21368 @ Function |new_text_node| owns the reference count for its second argument
21369 (the text string) but not its first (the font name).
21370
21371 @<Declare binary action...@>=
21372 static void mp_do_infont (MP mp,pointer p) {
21373   pointer q;
21374   q=mp_get_node(mp, edge_header_size);
21375   mp_init_edges(mp, q);
21376   mp_link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21377   obj_tail(q)=mp_link(obj_tail(q));
21378   mp_free_node(mp, p,value_node_size);
21379   mp_flush_cur_exp(mp, q);
21380   mp->cur_type=mp_picture_type;
21381 }
21382
21383 @* \[40] Statements and commands.
21384 The chief executive of \MP\ is the |do_statement| routine, which
21385 contains the master switch that causes all the various pieces of \MP\
21386 to do their things, in the right order.
21387
21388 In a sense, this is the grand climax of the program: It applies all the
21389 tools that we have worked so hard to construct. In another sense, this is
21390 the messiest part of the program: It necessarily refers to other pieces
21391 of code all over the place, so that a person can't fully understand what is
21392 going on without paging back and forth to be reminded of conventions that
21393 are defined elsewhere. We are now at the hub of the web.
21394
21395 The structure of |do_statement| itself is quite simple.  The first token
21396 of the statement is fetched using |get_x_next|.  If it can be the first
21397 token of an expression, we look for an equation, an assignment, or a
21398 title. Otherwise we use a \&{case} construction to branch at high speed to
21399 the appropriate routine for various and sundry other types of commands,
21400 each of which has an ``action procedure'' that does the necessary work.
21401
21402 The program uses the fact that
21403 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21404 to interpret a statement that starts with, e.g., `\&{string}',
21405 as a type declaration rather than a boolean expression.
21406
21407 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21408   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21409   if ( mp->cur_cmd>max_primary_command ) {
21410     @<Worry about bad statement@>;
21411   } else if ( mp->cur_cmd>max_statement_command ) {
21412     @<Do an equation, assignment, title, or
21413      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21414   } else {
21415     @<Do a statement that doesn't begin with an expression@>;
21416   }
21417   if ( mp->cur_cmd<semicolon )
21418     @<Flush unparsable junk that was found after the statement@>;
21419   mp->error_count=0;
21420 }
21421
21422 @ @<Declarations@>=
21423 @<Declare action procedures for use by |do_statement|@>
21424
21425 @ The only command codes |>max_primary_command| that can be present
21426 at the beginning of a statement are |semicolon| and higher; these
21427 occur when the statement is null.
21428
21429 @<Worry about bad statement@>=
21430
21431   if ( mp->cur_cmd<semicolon ) {
21432     print_err("A statement can't begin with `");
21433 @.A statement can't begin with x@>
21434     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, xord('\''));
21435     help5("I was looking for the beginning of a new statement.",
21436       "If you just proceed without changing anything, I'll ignore",
21437       "everything up to the next `;'. Please insert a semicolon",
21438       "now in front of anything that you don't want me to delete.",
21439       "(See Chapter 27 of The METAFONTbook for an example.)");
21440 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21441     mp_back_error(mp); mp_get_x_next(mp);
21442   }
21443 }
21444
21445 @ The help message printed here says that everything is flushed up to
21446 a semicolon, but actually the commands |end_group| and |stop| will
21447 also terminate a statement.
21448
21449 @<Flush unparsable junk that was found after the statement@>=
21450
21451   print_err("Extra tokens will be flushed");
21452 @.Extra tokens will be flushed@>
21453   help6("I've just read as much of that statement as I could fathom,",
21454         "so a semicolon should have been next. It's very puzzling...",
21455         "but I'll try to get myself back together, by ignoring",
21456         "everything up to the next `;'. Please insert a semicolon",
21457         "now in front of anything that you don't want me to delete.",
21458         "(See Chapter 27 of The METAFONTbook for an example.)");
21459 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21460   mp_back_error(mp); mp->scanner_status=flushing;
21461   do {  
21462     get_t_next;
21463     @<Decrease the string reference count...@>;
21464   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21465   mp->scanner_status=normal;
21466 }
21467
21468 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21469 |cur_type=mp_vacuous| unless the statement was simply an expression;
21470 in the latter case, |cur_type| and |cur_exp| should represent that
21471 expression.
21472
21473 @<Do a statement that doesn't...@>=
21474
21475   if ( mp->internal[mp_tracing_commands]>0 ) 
21476     show_cur_cmd_mod;
21477   switch (mp->cur_cmd ) {
21478   case type_name:mp_do_type_declaration(mp); break;
21479   case macro_def:
21480     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21481     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21482      break;
21483   @<Cases of |do_statement| that invoke particular commands@>;
21484   } /* there are no other cases */
21485   mp->cur_type=mp_vacuous;
21486 }
21487
21488 @ The most important statements begin with expressions.
21489
21490 @<Do an equation, assignment, title, or...@>=
21491
21492   mp->var_flag=assignment; mp_scan_expression(mp);
21493   if ( mp->cur_cmd<end_group ) {
21494     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21495     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21496     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21497     else if ( mp->cur_type!=mp_vacuous ){ 
21498       exp_err("Isolated expression");
21499 @.Isolated expression@>
21500       help3("I couldn't find an `=' or `:=' after the",
21501         "expression that is shown above this error message,",
21502         "so I guess I'll just ignore it and carry on.");
21503       mp_put_get_error(mp);
21504     }
21505     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21506   }
21507 }
21508
21509 @ @<Do a title@>=
21510
21511   if ( mp->internal[mp_tracing_titles]>0 ) {
21512     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21513   }
21514 }
21515
21516 @ Equations and assignments are performed by the pair of mutually recursive
21517 @^recursion@>
21518 routines |do_equation| and |do_assignment|. These routines are called when
21519 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21520 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21521 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21522 will be equal to the right-hand side (which will normally be equal
21523 to the left-hand side).
21524
21525 @<Declarations@>=
21526 @<Declare the procedure called |make_eq|@>
21527 static void mp_do_equation (MP mp) ;
21528
21529 @ @c
21530 void mp_do_equation (MP mp) {
21531   pointer lhs; /* capsule for the left-hand side */
21532   pointer p; /* temporary register */
21533   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21534   mp->var_flag=assignment; mp_scan_expression(mp);
21535   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21536   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21537   if ( mp->internal[mp_tracing_commands]>two ) 
21538     @<Trace the current equation@>;
21539   if ( mp->cur_type==mp_unknown_path ) if ( type(lhs)==mp_pair_type ) {
21540     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21541   }; /* in this case |make_eq| will change the pair to a path */
21542   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21543 }
21544
21545 @ And |do_assignment| is similar to |do_equation|:
21546
21547 @<Declarations@>=
21548 static void mp_do_assignment (MP mp);
21549
21550 @ @c
21551 void mp_do_assignment (MP mp) {
21552   pointer lhs; /* token list for the left-hand side */
21553   pointer p; /* where the left-hand value is stored */
21554   pointer q; /* temporary capsule for the right-hand value */
21555   if ( mp->cur_type!=mp_token_list ) { 
21556     exp_err("Improper `:=' will be changed to `='");
21557 @.Improper `:='@>
21558     help2("I didn't find a variable name at the left of the `:=',",
21559           "so I'm going to pretend that you said `=' instead.");
21560     mp_error(mp); mp_do_equation(mp);
21561   } else { 
21562     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21563     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21564     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21565     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21566     if ( mp->internal[mp_tracing_commands]>two ) 
21567       @<Trace the current assignment@>;
21568     if ( info(lhs)>hash_end ) {
21569       @<Assign the current expression to an internal variable@>;
21570     } else  {
21571       @<Assign the current expression to the variable |lhs|@>;
21572     }
21573     mp_flush_node_list(mp, lhs);
21574   }
21575 }
21576
21577 @ @<Trace the current equation@>=
21578
21579   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21580   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21581   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21582 }
21583
21584 @ @<Trace the current assignment@>=
21585
21586   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21587   if ( info(lhs)>hash_end ) 
21588      mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21589   else 
21590      mp_show_token_list(mp, lhs,null,1000,0);
21591   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21592   mp_print_char(mp, xord('}')); mp_end_diagnostic(mp, false);
21593 }
21594
21595 @ @<Assign the current expression to an internal variable@>=
21596 if ( mp->cur_type==mp_known )  {
21597   mp->internal[info(lhs)-(hash_end)]=mp->cur_exp;
21598 } else { 
21599   exp_err("Internal quantity `");
21600 @.Internal quantity...@>
21601   mp_print(mp, mp->int_name[info(lhs)-(hash_end)]);
21602   mp_print(mp, "' must receive a known value");
21603   help2("I can\'t set an internal quantity to anything but a known",
21604         "numeric value, so I'll have to ignore this assignment.");
21605   mp_put_get_error(mp);
21606 }
21607
21608 @ @<Assign the current expression to the variable |lhs|@>=
21609
21610   p=mp_find_variable(mp, lhs);
21611   if ( p!=null ) {
21612     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21613     mp_recycle_value(mp, p);
21614     type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21615     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21616   } else  { 
21617     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21618   }
21619 }
21620
21621
21622 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21623 a pointer to a capsule that is to be equated to the current expression.
21624
21625 @<Declare the procedure called |make_eq|@>=
21626 static void mp_make_eq (MP mp,pointer lhs) ;
21627
21628
21629
21630 @c void mp_make_eq (MP mp,pointer lhs) {
21631   quarterword t; /* type of the left-hand side */
21632   pointer p,q; /* pointers inside of big nodes */
21633   integer v=0; /* value of the left-hand side */
21634 RESTART: 
21635   t=type(lhs);
21636   if ( t<=mp_pair_type ) v=value(lhs);
21637   switch (t) {
21638   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21639     is incompatible with~|t|@>;
21640   } /* all cases have been listed */
21641   @<Announce that the equation cannot be performed@>;
21642 DONE:
21643   check_arith; mp_recycle_value(mp, lhs); 
21644   mp_free_node(mp, lhs,value_node_size);
21645 }
21646
21647 @ @<Announce that the equation cannot be performed@>=
21648 mp_disp_err(mp, lhs,""); 
21649 exp_err("Equation cannot be performed (");
21650 @.Equation cannot be performed@>
21651 if ( type(lhs)<=mp_pair_type ) mp_print_type(mp, type(lhs));
21652 else mp_print(mp, "numeric");
21653 mp_print_char(mp, xord('='));
21654 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21655 else mp_print(mp, "numeric");
21656 mp_print_char(mp, xord(')'));
21657 help2("I'm sorry, but I don't know how to make such things equal.",
21658       "(See the two expressions just above the error message.)");
21659 mp_put_get_error(mp)
21660
21661 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21662 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21663 case mp_path_type: case mp_picture_type:
21664   if ( mp->cur_type==t+unknown_tag ) { 
21665     mp_nonlinear_eq(mp, v,mp->cur_exp,false); 
21666     mp_unstash_cur_exp(mp, mp->cur_exp); goto DONE;
21667   } else if ( mp->cur_type==t ) {
21668     @<Report redundant or inconsistent equation and |goto done|@>;
21669   }
21670   break;
21671 case unknown_types:
21672   if ( mp->cur_type==t-unknown_tag ) { 
21673     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21674   } else if ( mp->cur_type==t ) { 
21675     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21676   } else if ( mp->cur_type==mp_pair_type ) {
21677     if ( t==mp_unknown_path ) { 
21678      mp_pair_to_path(mp); goto RESTART;
21679     };
21680   }
21681   break;
21682 case mp_transform_type: case mp_color_type:
21683 case mp_cmykcolor_type: case mp_pair_type:
21684   if ( mp->cur_type==t ) {
21685     @<Do multiple equations and |goto done|@>;
21686   }
21687   break;
21688 case mp_known: case mp_dependent:
21689 case mp_proto_dependent: case mp_independent:
21690   if ( mp->cur_type>=mp_known ) { 
21691     mp_try_eq(mp, lhs,null); goto DONE;
21692   };
21693   break;
21694 case mp_vacuous:
21695   break;
21696
21697 @ @<Report redundant or inconsistent equation and |goto done|@>=
21698
21699   if ( mp->cur_type<=mp_string_type ) {
21700     if ( mp->cur_type==mp_string_type ) {
21701       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21702         goto NOT_FOUND;
21703       }
21704     } else if ( v!=mp->cur_exp ) {
21705       goto NOT_FOUND;
21706     }
21707     @<Exclaim about a redundant equation@>; goto DONE;
21708   }
21709   print_err("Redundant or inconsistent equation");
21710 @.Redundant or inconsistent equation@>
21711   help2("An equation between already-known quantities can't help.",
21712         "But don't worry; continue and I'll just ignore it.");
21713   mp_put_get_error(mp); goto DONE;
21714 NOT_FOUND: 
21715   print_err("Inconsistent equation");
21716 @.Inconsistent equation@>
21717   help2("The equation I just read contradicts what was said before.",
21718         "But don't worry; continue and I'll just ignore it.");
21719   mp_put_get_error(mp); goto DONE;
21720 }
21721
21722 @ @<Do multiple equations and |goto done|@>=
21723
21724   p=v+mp->big_node_size[t]; 
21725   q=value(mp->cur_exp)+mp->big_node_size[t];
21726   do {  
21727     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21728   } while (p!=v);
21729   goto DONE;
21730 }
21731
21732 @ The first argument to |try_eq| is the location of a value node
21733 in a capsule that will soon be recycled. The second argument is
21734 either a location within a pair or transform node pointed to by
21735 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21736 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21737 but to equate the two operands.
21738
21739 @<Declarations@>=
21740 static void mp_try_eq (MP mp,pointer l, pointer r) ;
21741
21742
21743 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21744   pointer p; /* dependency list for right operand minus left operand */
21745   int t; /* the type of list |p| */
21746   pointer q; /* the constant term of |p| is here */
21747   pointer pp; /* dependency list for right operand */
21748   int tt; /* the type of list |pp| */
21749   boolean copied; /* have we copied a list that ought to be recycled? */
21750   @<Remove the left operand from its container, negate it, and
21751     put it into dependency list~|p| with constant term~|q|@>;
21752   @<Add the right operand to list |p|@>;
21753   if ( info(p)==null ) {
21754     @<Deal with redundant or inconsistent equation@>;
21755   } else { 
21756     mp_linear_eq(mp, p,t);
21757     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21758       if ( type(mp->cur_exp)==mp_known ) {
21759         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21760         mp_free_node(mp, pp,value_node_size);
21761       }
21762     }
21763   }
21764 }
21765
21766 @ @<Remove the left operand from its container, negate it, and...@>=
21767 t=type(l);
21768 if ( t==mp_known ) { 
21769   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21770 } else if ( t==mp_independent ) {
21771   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21772   q=mp->dep_final;
21773 } else { 
21774   p=dep_list(l); q=p;
21775   while (1) { 
21776     negate(value(q));
21777     if ( info(q)==null ) break;
21778     q=mp_link(q);
21779   }
21780   mp_link(prev_dep(l))=mp_link(q); prev_dep(mp_link(q))=prev_dep(l);
21781   type(l)=mp_known;
21782 }
21783
21784 @ @<Deal with redundant or inconsistent equation@>=
21785
21786   if ( abs(value(p))>64 ) { /* off by .001 or more */
21787     print_err("Inconsistent equation");
21788 @.Inconsistent equation@>
21789     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21790     mp_print_char(mp, xord(')'));
21791     help2("The equation I just read contradicts what was said before.",
21792           "But don't worry; continue and I'll just ignore it.");
21793     mp_put_get_error(mp);
21794   } else if ( r==null ) {
21795     @<Exclaim about a redundant equation@>;
21796   }
21797   mp_free_node(mp, p,dep_node_size);
21798 }
21799
21800 @ @<Add the right operand to list |p|@>=
21801 if ( r==null ) {
21802   if ( mp->cur_type==mp_known ) {
21803     value(q)=value(q)+mp->cur_exp; goto DONE1;
21804   } else { 
21805     tt=mp->cur_type;
21806     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21807     else pp=dep_list(mp->cur_exp);
21808   } 
21809 } else {
21810   if ( type(r)==mp_known ) {
21811     value(q)=value(q)+value(r); goto DONE1;
21812   } else { 
21813     tt=type(r);
21814     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21815     else pp=dep_list(r);
21816   }
21817 }
21818 if ( tt!=mp_independent ) copied=false;
21819 else  { copied=true; tt=mp_dependent; };
21820 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21821 if ( copied ) mp_flush_node_list(mp, pp);
21822 DONE1:
21823
21824 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21825 mp->watch_coefs=false;
21826 if ( t==tt ) {
21827   p=mp_p_plus_q(mp, p,pp,t);
21828 } else if ( t==mp_proto_dependent ) {
21829   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21830 } else { 
21831   q=p;
21832   while ( info(q)!=null ) {
21833     value(q)=mp_round_fraction(mp, value(q)); q=mp_link(q);
21834   }
21835   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21836 }
21837 mp->watch_coefs=true;
21838
21839 @ Our next goal is to process type declarations. For this purpose it's
21840 convenient to have a procedure that scans a $\langle\,$declared
21841 variable$\,\rangle$ and returns the corresponding token list. After the
21842 following procedure has acted, the token after the declared variable
21843 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21844 and~|cur_sym|.
21845
21846 @<Declarations@>=
21847 static pointer mp_scan_declared_variable (MP mp) ;
21848
21849 @ @c
21850 pointer mp_scan_declared_variable (MP mp) {
21851   pointer x; /* hash address of the variable's root */
21852   pointer h,t; /* head and tail of the token list to be returned */
21853   pointer l; /* hash address of left bracket */
21854   mp_get_symbol(mp); x=mp->cur_sym;
21855   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21856   h=mp_get_avail(mp); info(h)=x; t=h;
21857   while (1) { 
21858     mp_get_x_next(mp);
21859     if ( mp->cur_sym==0 ) break;
21860     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21861       if ( mp->cur_cmd==left_bracket ) {
21862         @<Descend past a collective subscript@>;
21863       } else {
21864         break;
21865       }
21866     }
21867     mp_link(t)=mp_get_avail(mp); t=mp_link(t); info(t)=mp->cur_sym;
21868   }
21869   if ( (eq_type(x)%outer_tag)!=tag_token ) mp_clear_symbol(mp, x,false);
21870   if ( equiv(x)==null ) mp_new_root(mp, x);
21871   return h;
21872 }
21873
21874 @ If the subscript isn't collective, we don't accept it as part of the
21875 declared variable.
21876
21877 @<Descend past a collective subscript@>=
21878
21879   l=mp->cur_sym; mp_get_x_next(mp);
21880   if ( mp->cur_cmd!=right_bracket ) {
21881     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21882   } else {
21883     mp->cur_sym=collective_subscript;
21884   }
21885 }
21886
21887 @ Type declarations are introduced by the following primitive operations.
21888
21889 @<Put each...@>=
21890 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21891 @:numeric_}{\&{numeric} primitive@>
21892 mp_primitive(mp, "string",type_name,mp_string_type);
21893 @:string_}{\&{string} primitive@>
21894 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21895 @:boolean_}{\&{boolean} primitive@>
21896 mp_primitive(mp, "path",type_name,mp_path_type);
21897 @:path_}{\&{path} primitive@>
21898 mp_primitive(mp, "pen",type_name,mp_pen_type);
21899 @:pen_}{\&{pen} primitive@>
21900 mp_primitive(mp, "picture",type_name,mp_picture_type);
21901 @:picture_}{\&{picture} primitive@>
21902 mp_primitive(mp, "transform",type_name,mp_transform_type);
21903 @:transform_}{\&{transform} primitive@>
21904 mp_primitive(mp, "color",type_name,mp_color_type);
21905 @:color_}{\&{color} primitive@>
21906 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21907 @:color_}{\&{rgbcolor} primitive@>
21908 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21909 @:color_}{\&{cmykcolor} primitive@>
21910 mp_primitive(mp, "pair",type_name,mp_pair_type);
21911 @:pair_}{\&{pair} primitive@>
21912
21913 @ @<Cases of |print_cmd...@>=
21914 case type_name: mp_print_type(mp, m); break;
21915
21916 @ Now we are ready to handle type declarations, assuming that a
21917 |type_name| has just been scanned.
21918
21919 @<Declare action procedures for use by |do_statement|@>=
21920 static void mp_do_type_declaration (MP mp) ;
21921
21922 @ @c
21923 void mp_do_type_declaration (MP mp) {
21924   quarterword t; /* the type being declared */
21925   pointer p; /* token list for a declared variable */
21926   pointer q; /* value node for the variable */
21927   if ( mp->cur_mod>=mp_transform_type ) 
21928     t=mp->cur_mod;
21929   else 
21930     t=mp->cur_mod+unknown_tag;
21931   do {  
21932     p=mp_scan_declared_variable(mp);
21933     mp_flush_variable(mp, equiv(info(p)),mp_link(p),false);
21934     q=mp_find_variable(mp, p);
21935     if ( q!=null ) { 
21936       type(q)=t; value(q)=null; 
21937     } else  { 
21938       print_err("Declared variable conflicts with previous vardef");
21939 @.Declared variable conflicts...@>
21940       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.",
21941             "Proceed, and I'll ignore the illegal redeclaration.");
21942       mp_put_get_error(mp);
21943     }
21944     mp_flush_list(mp, p);
21945     if ( mp->cur_cmd<comma ) {
21946       @<Flush spurious symbols after the declared variable@>;
21947     }
21948   } while (! end_of_statement);
21949 }
21950
21951 @ @<Flush spurious symbols after the declared variable@>=
21952
21953   print_err("Illegal suffix of declared variable will be flushed");
21954 @.Illegal suffix...flushed@>
21955   help5("Variables in declarations must consist entirely of",
21956     "names and collective subscripts, e.g., `x[]a'.",
21957     "Are you trying to use a reserved word in a variable name?",
21958     "I'm going to discard the junk I found here,",
21959     "up to the next comma or the end of the declaration.");
21960   if ( mp->cur_cmd==numeric_token )
21961     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21962   mp_put_get_error(mp); mp->scanner_status=flushing;
21963   do {  
21964     get_t_next;
21965     @<Decrease the string reference count...@>;
21966   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21967   mp->scanner_status=normal;
21968 }
21969
21970 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21971 until coming to the end of the user's program.
21972 Each execution of |do_statement| concludes with
21973 |cur_cmd=semicolon|, |end_group|, or |stop|.
21974
21975 @c 
21976 static void mp_main_control (MP mp) { 
21977   do {  
21978     mp_do_statement(mp);
21979     if ( mp->cur_cmd==end_group ) {
21980       print_err("Extra `endgroup'");
21981 @.Extra `endgroup'@>
21982       help2("I'm not currently working on a `begingroup',",
21983             "so I had better not try to end anything.");
21984       mp_flush_error(mp, 0);
21985     }
21986   } while (mp->cur_cmd!=stop);
21987 }
21988 int mp_run (MP mp) {
21989   if (mp->history < mp_fatal_error_stop ) {
21990     xfree(mp->jump_buf);
21991     mp->jump_buf = malloc(sizeof(jmp_buf));
21992     if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) 
21993       return mp->history;
21994     mp_main_control(mp); /* come to life */
21995     mp_final_cleanup(mp); /* prepare for death */
21996     mp_close_files_and_terminate(mp);
21997   }
21998   return mp->history;
21999 }
22000
22001 @ For |mp_execute|, we need to define a structure to store the
22002 redirected input and output. This structure holds the five relevant
22003 streams: the three informational output streams, the PostScript
22004 generation stream, and the input stream. These streams have many
22005 things in common, so it makes sense to give them their own structure
22006 definition. 
22007
22008 \item{fptr} is a virtual file pointer
22009 \item{data} is the data this stream holds
22010 \item{cur}  is a cursor pointing into |data| 
22011 \item{size} is the allocated length of the data stream
22012 \item{used} is the actual length of the data stream
22013
22014 There are small differences between input and output: |term_in| never
22015 uses |used|, whereas the other four never use |cur|.
22016
22017 @<Exported types@>= 
22018 typedef struct {
22019    void * fptr;
22020    char * data;
22021    char * cur;
22022    size_t size;
22023    size_t used;
22024 } mp_stream;
22025
22026 typedef struct {
22027     mp_stream term_out;
22028     mp_stream error_out;
22029     mp_stream log_out;
22030     mp_stream ps_out;
22031     mp_stream term_in;
22032     struct mp_edge_object *edges;
22033 } mp_run_data;
22034
22035 @ We need a function to clear an output stream, this is called at the
22036 beginning of |mp_execute|. We also need one for destroying an output
22037 stream, this is called just before a stream is (re)opened.
22038
22039 @c
22040 static void mp_reset_stream(mp_stream *str) {
22041    xfree(str->data); 
22042    str->cur = NULL;
22043    str->size = 0; 
22044    str->used = 0;
22045 }
22046 static void mp_free_stream(mp_stream *str) {
22047    xfree(str->fptr); 
22048    mp_reset_stream(str);
22049 }
22050
22051 @ @<Declarations@>=
22052 static void mp_reset_stream(mp_stream *str);
22053 static void mp_free_stream(mp_stream *str);
22054
22055 @ The global instance contains a pointer instead of the actual structure
22056 even though it is essentially static, because that makes it is easier to move 
22057 the object around.
22058
22059 @<Global ...@>=
22060 mp_run_data run_data;
22061
22062 @ Another type is needed: the indirection will overload some of the
22063 file pointer objects in the instance (but not all). For clarity, an
22064 indirect object is used that wraps a |FILE *|.
22065
22066 @<Types ... @>=
22067 typedef struct File {
22068     FILE *f;
22069 } File;
22070
22071 @ Here are all of the functions that need to be overloaded for |mp_execute|.
22072
22073 @<Declarations@>=
22074 static void *mplib_open_file(MP mp, const char *fname, const char *fmode, int ftype);
22075 static int mplib_get_char(void *f, mp_run_data * mplib_data);
22076 static void mplib_unget_char(void *f, mp_run_data * mplib_data, int c);
22077 static char *mplib_read_ascii_file(MP mp, void *ff, size_t * size);
22078 static void mplib_write_ascii_file(MP mp, void *ff, const char *s);
22079 static void mplib_read_binary_file(MP mp, void *ff, void **data, size_t * size);
22080 static void mplib_write_binary_file(MP mp, void *ff, void *s, size_t size);
22081 static void mplib_close_file(MP mp, void *ff);
22082 static int mplib_eof_file(MP mp, void *ff);
22083 static void mplib_flush_file(MP mp, void *ff);
22084 static void mplib_shipout_backend(MP mp, int h);
22085
22086 @ The |xmalloc(1,1)| calls make sure the stored indirection values are unique.
22087
22088 @d reset_stream(a)  do { 
22089         mp_reset_stream(&(a));
22090         if (!ff->f) {
22091           ff->f = xmalloc(1,1);
22092           (a).fptr = ff->f;
22093         } } while (0)
22094
22095 @c
22096
22097 static void *mplib_open_file(MP mp, const char *fname, const char *fmode, int ftype)
22098 {
22099     File *ff = xmalloc(1, sizeof(File));
22100     mp_run_data *run = mp_rundata(mp);
22101     ff->f = NULL;
22102     if (ftype == mp_filetype_terminal) {
22103         if (fmode[0] == 'r') {
22104             if (!ff->f) {
22105               ff->f = xmalloc(1,1);
22106               run->term_in.fptr = ff->f;
22107             }
22108         } else {
22109             reset_stream(run->term_out);
22110         }
22111     } else if (ftype == mp_filetype_error) {
22112         reset_stream(run->error_out);
22113     } else if (ftype == mp_filetype_log) {
22114         reset_stream(run->log_out);
22115     } else if (ftype == mp_filetype_postscript) {
22116         mp_free_stream(&(run->ps_out));
22117         ff->f = xmalloc(1,1);
22118         run->ps_out.fptr = ff->f;
22119     } else {
22120         char realmode[3];
22121         char *f = (mp->find_file)(mp, fname, fmode, ftype);
22122         if (f == NULL)
22123             return NULL;
22124         realmode[0] = *fmode;
22125         realmode[1] = 'b';
22126         realmode[2] = 0;
22127         ff->f = fopen(f, realmode);
22128         free(f);
22129         if ((fmode[0] == 'r') && (ff->f == NULL)) {
22130             free(ff);
22131             return NULL;
22132         }
22133     }
22134     return ff;
22135 }
22136
22137 static int mplib_get_char(void *f, mp_run_data * run)
22138 {
22139     int c;
22140     if (f == run->term_in.fptr && run->term_in.data != NULL) {
22141         if (run->term_in.size == 0) {
22142             if (run->term_in.cur  != NULL) {
22143                 run->term_in.cur = NULL;
22144             } else {
22145                 xfree(run->term_in.data);
22146             }
22147             c = EOF;
22148         } else {
22149             run->term_in.size--;
22150             c = *(run->term_in.cur)++;
22151         }
22152     } else {
22153         c = fgetc(f);
22154     }
22155     return c;
22156 }
22157
22158 static void mplib_unget_char(void *f, mp_run_data * run, int c)
22159 {
22160     if (f == run->term_in.fptr && run->term_in.cur != NULL) {
22161         run->term_in.size++;
22162         run->term_in.cur--;
22163     } else {
22164         ungetc(c, f);
22165     }
22166 }
22167
22168
22169 static char *mplib_read_ascii_file(MP mp, void *ff, size_t * size)
22170 {
22171     char *s = NULL;
22172     if (ff != NULL) {
22173         int c;
22174         size_t len = 0, lim = 128;
22175         mp_run_data *run = mp_rundata(mp);
22176         FILE *f = ((File *) ff)->f;
22177         if (f == NULL)
22178             return NULL;
22179         *size = 0;
22180         c = mplib_get_char(f, run);
22181         if (c == EOF)
22182             return NULL;
22183         s = malloc(lim);
22184         if (s == NULL)
22185             return NULL;
22186         while (c != EOF && c != '\n' && c != '\r') {
22187             if (len == lim) {
22188                 s = xrealloc(s, (lim + (lim >> 2)),1);
22189                 if (s == NULL)
22190                     return NULL;
22191                 lim += (lim >> 2);
22192             }
22193             s[len++] = c;
22194             c = mplib_get_char(f, run);
22195         }
22196         if (c == '\r') {
22197             c = mplib_get_char(f, run);
22198             if (c != EOF && c != '\n')
22199                 mplib_unget_char(f, run, c);
22200         }
22201         s[len] = 0;
22202         *size = len;
22203     }
22204     return s;
22205 }
22206
22207 static void mp_append_string (MP mp, mp_stream *a,const char *b) {
22208     size_t l = strlen(b);
22209     if ((a->used+l)>=a->size) {
22210         a->size += 256+(a->size)/5+l;
22211         a->data = xrealloc(a->data,a->size,1);
22212     }
22213     (void)strcpy(a->data+a->used,b);
22214     a->used += l;
22215 }
22216
22217
22218 static void mplib_write_ascii_file(MP mp, void *ff, const char *s)
22219 {
22220     if (ff != NULL) {
22221         void *f = ((File *) ff)->f;
22222         mp_run_data *run = mp_rundata(mp);
22223         if (f != NULL) {
22224             if (f == run->term_out.fptr) {
22225                 mp_append_string(mp,&(run->term_out), s);
22226             } else if (f == run->error_out.fptr) {
22227                 mp_append_string(mp,&(run->error_out), s);
22228             } else if (f == run->log_out.fptr) {
22229                 mp_append_string(mp,&(run->log_out), s);
22230             } else if (f == run->ps_out.fptr) {
22231                 mp_append_string(mp,&(run->ps_out), s);
22232             } else {
22233                 fprintf((FILE *) f, "%s", s);
22234             }
22235         }
22236     }
22237 }
22238
22239 static void mplib_read_binary_file(MP mp, void *ff, void **data, size_t * size)
22240 {
22241     (void) mp;
22242     if (ff != NULL) {
22243         size_t len = 0;
22244         FILE *f = ((File *) ff)->f;
22245         if (f != NULL)
22246             len = fread(*data, 1, *size, f);
22247         *size = len;
22248     }
22249 }
22250
22251 static void mplib_write_binary_file(MP mp, void *ff, void *s, size_t size)
22252 {
22253     (void) mp;
22254     if (ff != NULL) {
22255         FILE *f = ((File *) ff)->f;
22256         if (f != NULL)
22257             (void)fwrite(s, size, 1, f);
22258     }
22259 }
22260
22261 static void mplib_close_file(MP mp, void *ff)
22262 {
22263     if (ff != NULL) {
22264         mp_run_data *run = mp_rundata(mp);
22265         void *f = ((File *) ff)->f;
22266         if (f != NULL) {
22267           if (f != run->term_out.fptr
22268             && f != run->error_out.fptr
22269             && f != run->log_out.fptr
22270             && f != run->ps_out.fptr
22271             && f != run->term_in.fptr) {
22272             fclose(f);
22273           }
22274         }
22275         free(ff);
22276     }
22277 }
22278
22279 static int mplib_eof_file(MP mp, void *ff)
22280 {
22281     if (ff != NULL) {
22282         mp_run_data *run = mp_rundata(mp);
22283         FILE *f = ((File *) ff)->f;
22284         if (f == NULL)
22285             return 1;
22286         if (f == run->term_in.fptr && run->term_in.data != NULL) {
22287             return (run->term_in.size == 0);
22288         }
22289         return feof(f);
22290     }
22291     return 1;
22292 }
22293
22294 static void mplib_flush_file(MP mp, void *ff)
22295 {
22296     (void) mp;
22297     (void) ff;
22298     return;
22299 }
22300
22301 static void mplib_shipout_backend(MP mp, int h)
22302 {
22303     mp_edge_object *hh = mp_gr_export(mp, h);
22304     if (hh) {
22305         mp_run_data *run = mp_rundata(mp);
22306         if (run->edges==NULL) {
22307            run->edges = hh;
22308         } else {
22309            mp_edge_object *p = run->edges; 
22310            while (p->next!=NULL) { p = p->next; }
22311             p->next = hh;
22312         } 
22313     }
22314 }
22315
22316
22317 @ This is where we fill them all in.
22318 @<Prepare function pointers for non-interactive use@>=
22319 {
22320     mp->open_file         = mplib_open_file;
22321     mp->close_file        = mplib_close_file;
22322     mp->eof_file          = mplib_eof_file;
22323     mp->flush_file        = mplib_flush_file;
22324     mp->write_ascii_file  = mplib_write_ascii_file;
22325     mp->read_ascii_file   = mplib_read_ascii_file;
22326     mp->write_binary_file = mplib_write_binary_file;
22327     mp->read_binary_file  = mplib_read_binary_file;
22328     mp->shipout_backend   = mplib_shipout_backend;
22329 }
22330
22331 @ Perhaps this is the most important API function in the library.
22332
22333 @<Exported function ...@>=
22334 extern mp_run_data *mp_rundata (MP mp) ;
22335
22336 @ @c
22337 mp_run_data *mp_rundata (MP mp)  {
22338   return &(mp->run_data);
22339 }
22340
22341 @ @<Dealloc ...@>=
22342 mp_free_stream(&(mp->run_data.term_in));
22343 mp_free_stream(&(mp->run_data.term_out));
22344 mp_free_stream(&(mp->run_data.log_out));
22345 mp_free_stream(&(mp->run_data.error_out));
22346 mp_free_stream(&(mp->run_data.ps_out));
22347
22348 @ @<Finish non-interactive use@>=
22349 xfree(mp->term_out);
22350 xfree(mp->term_in);
22351 xfree(mp->err_out);
22352
22353 @ @<Start non-interactive work@>=
22354 @<Initialize the output routines@>;
22355 mp->input_ptr=0; mp->max_in_stack=0;
22356 mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
22357 mp->param_ptr=0; mp->max_param_stack=0;
22358 start = loc = iindex = 0; mp->first = 0;
22359 line=0; name=is_term;
22360 mp->mpx_name[0]=absent;
22361 mp->force_eof=false;
22362 t_open_in; 
22363 mp->scanner_status=normal;
22364 if (mp->mem_ident==NULL) {
22365   if ( ! mp_load_mem_file(mp) ) {
22366     (mp->close_file)(mp, mp->mem_file); 
22367      mp->history  = mp_fatal_error_stop;
22368      return mp->history;
22369   }
22370   (mp->close_file)(mp, mp->mem_file);
22371 }
22372 mp_fix_date_and_time(mp);
22373 if (mp->random_seed==0)
22374   mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
22375 mp_init_randoms(mp, mp->random_seed);
22376 @<Initialize the print |selector|...@>;
22377 mp_open_log_file(mp);
22378 mp_set_job_id(mp);
22379 mp_init_map_file(mp, mp->troff_mode);
22380 mp->history=mp_spotless; /* ready to go! */
22381 if (mp->troff_mode) {
22382   mp->internal[mp_gtroffmode]=unity; 
22383   mp->internal[mp_prologues]=unity; 
22384 }
22385 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
22386   mp->cur_sym=mp->start_sym; mp_back_input(mp);
22387 }
22388
22389 @ @c
22390 int mp_execute (MP mp, char *s, size_t l) {
22391   mp_reset_stream(&(mp->run_data.term_out));
22392   mp_reset_stream(&(mp->run_data.log_out));
22393   mp_reset_stream(&(mp->run_data.error_out));
22394   mp_reset_stream(&(mp->run_data.ps_out));
22395   if (mp->finished) {
22396       return mp->history;
22397   } else if (!mp->noninteractive) {
22398       mp->history = mp_fatal_error_stop ;
22399       return mp->history;
22400   }
22401   if (mp->history < mp_fatal_error_stop ) {
22402     xfree(mp->jump_buf);
22403     mp->jump_buf = malloc(sizeof(jmp_buf));
22404     if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) {   
22405        return mp->history; 
22406     }
22407     if (s==NULL) { /* this signals EOF */
22408       mp_final_cleanup(mp); /* prepare for death */
22409       mp_close_files_and_terminate(mp);
22410       return mp->history;
22411     } 
22412     mp->tally=0; 
22413     mp->term_offset=0; mp->file_offset=0; 
22414     /* Perhaps some sort of warning here when |data| is not 
22415      * yet exhausted would be nice ...  this happens after errors
22416      */
22417     if (mp->run_data.term_in.data)
22418       xfree(mp->run_data.term_in.data);
22419     mp->run_data.term_in.data = xstrdup(s);
22420     mp->run_data.term_in.cur = mp->run_data.term_in.data;
22421     mp->run_data.term_in.size = l;
22422     if (mp->run_state == 0) {
22423       mp->selector=term_only; 
22424       @<Start non-interactive work@>; 
22425     }
22426     mp->run_state =1;    
22427     (void)mp_input_ln(mp,mp->term_in);
22428     mp_firm_up_the_line(mp);    
22429     mp->buffer[limit]=xord('%');
22430     mp->first=(size_t)(limit+1); 
22431     loc=start;
22432         do {  
22433       mp_do_statement(mp);
22434     } while (mp->cur_cmd!=stop);
22435     mp_final_cleanup(mp); 
22436     mp_close_files_and_terminate(mp);
22437   }
22438   return mp->history;
22439 }
22440
22441 @ This function cleans up
22442 @c
22443 int mp_finish (MP mp) {
22444   int history = 0;
22445   if (mp->finished || mp->history >= mp_fatal_error_stop) {
22446     history = mp->history;
22447     mp_free(mp);
22448     return history;
22449   }
22450   xfree(mp->jump_buf);
22451   mp->jump_buf = malloc(sizeof(jmp_buf));
22452   if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) { 
22453     history = mp->history;
22454   } else {
22455     history = mp->history;
22456     mp_final_cleanup(mp); /* prepare for death */
22457   }
22458   mp_close_files_and_terminate(mp);
22459   mp_free(mp);
22460   return history;
22461 }
22462
22463 @ People may want to know the library version
22464 @c 
22465 char * mp_metapost_version (void) {
22466   return mp_strdup(metapost_version);
22467 }
22468
22469 @ @<Exported function headers@>=
22470 int mp_run (MP mp);
22471 int mp_execute (MP mp, char *s, size_t l);
22472 int mp_finish (MP mp);
22473 char * mp_metapost_version (void);
22474
22475 @ @<Put each...@>=
22476 mp_primitive(mp, "end",stop,0);
22477 @:end_}{\&{end} primitive@>
22478 mp_primitive(mp, "dump",stop,1);
22479 @:dump_}{\&{dump} primitive@>
22480
22481 @ @<Cases of |print_cmd...@>=
22482 case stop:
22483   if ( m==0 ) mp_print(mp, "end");
22484   else mp_print(mp, "dump");
22485   break;
22486
22487 @* \[41] Commands.
22488 Let's turn now to statements that are classified as ``commands'' because
22489 of their imperative nature. We'll begin with simple ones, so that it
22490 will be clear how to hook command processing into the |do_statement| routine;
22491 then we'll tackle the tougher commands.
22492
22493 Here's one of the simplest:
22494
22495 @<Cases of |do_statement|...@>=
22496 case mp_random_seed: mp_do_random_seed(mp);  break;
22497
22498 @ @<Declare action procedures for use by |do_statement|@>=
22499 static void mp_do_random_seed (MP mp) ;
22500
22501 @ @c void mp_do_random_seed (MP mp) { 
22502   mp_get_x_next(mp);
22503   if ( mp->cur_cmd!=assignment ) {
22504     mp_missing_err(mp, ":=");
22505 @.Missing `:='@>
22506     help1("Always say `randomseed:=<numeric expression>'.");
22507     mp_back_error(mp);
22508   };
22509   mp_get_x_next(mp); mp_scan_expression(mp);
22510   if ( mp->cur_type!=mp_known ) {
22511     exp_err("Unknown value will be ignored");
22512 @.Unknown value...ignored@>
22513     help2("Your expression was too random for me to handle,",
22514           "so I won't change the random seed just now.");
22515     mp_put_get_flush_error(mp, 0);
22516   } else {
22517    @<Initialize the random seed to |cur_exp|@>;
22518   }
22519 }
22520
22521 @ @<Initialize the random seed to |cur_exp|@>=
22522
22523   mp_init_randoms(mp, mp->cur_exp);
22524   if ( mp->selector>=log_only && mp->selector<write_file) {
22525     mp->old_setting=mp->selector; mp->selector=log_only;
22526     mp_print_nl(mp, "{randomseed:="); 
22527     mp_print_scaled(mp, mp->cur_exp); 
22528     mp_print_char(mp, xord('}'));
22529     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
22530   }
22531 }
22532
22533 @ And here's another simple one (somewhat different in flavor):
22534
22535 @<Cases of |do_statement|...@>=
22536 case mode_command: 
22537   mp_print_ln(mp); mp->interaction=mp->cur_mod;
22538   @<Initialize the print |selector| based on |interaction|@>;
22539   if ( mp->log_opened ) mp->selector=mp->selector+2;
22540   mp_get_x_next(mp);
22541   break;
22542
22543 @ @<Put each...@>=
22544 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
22545 @:mp_batch_mode_}{\&{batchmode} primitive@>
22546 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
22547 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
22548 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
22549 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
22550 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
22551 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
22552
22553 @ @<Cases of |print_cmd_mod|...@>=
22554 case mode_command: 
22555   switch (m) {
22556   case mp_batch_mode: mp_print(mp, "batchmode"); break;
22557   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
22558   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
22559   default: mp_print(mp, "errorstopmode"); break;
22560   }
22561   break;
22562
22563 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
22564
22565 @<Cases of |do_statement|...@>=
22566 case protection_command: mp_do_protection(mp); break;
22567
22568 @ @<Put each...@>=
22569 mp_primitive(mp, "inner",protection_command,0);
22570 @:inner_}{\&{inner} primitive@>
22571 mp_primitive(mp, "outer",protection_command,1);
22572 @:outer_}{\&{outer} primitive@>
22573
22574 @ @<Cases of |print_cmd...@>=
22575 case protection_command: 
22576   if ( m==0 ) mp_print(mp, "inner");
22577   else mp_print(mp, "outer");
22578   break;
22579
22580 @ @<Declare action procedures for use by |do_statement|@>=
22581 static void mp_do_protection (MP mp) ;
22582
22583 @ @c void mp_do_protection (MP mp) {
22584   int m; /* 0 to unprotect, 1 to protect */
22585   halfword t; /* the |eq_type| before we change it */
22586   m=mp->cur_mod;
22587   do {  
22588     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
22589     if ( m==0 ) { 
22590       if ( t>=outer_tag ) 
22591         eq_type(mp->cur_sym)=t-outer_tag;
22592     } else if ( t<outer_tag ) {
22593       eq_type(mp->cur_sym)=t+outer_tag;
22594     }
22595     mp_get_x_next(mp);
22596   } while (mp->cur_cmd==comma);
22597 }
22598
22599 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
22600 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
22601 declaration assigns the command code |left_delimiter| to `\.{(}' and
22602 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
22603 hash address of its mate.
22604
22605 @<Cases of |do_statement|...@>=
22606 case delimiters: mp_def_delims(mp); break;
22607
22608 @ @<Declare action procedures for use by |do_statement|@>=
22609 static void mp_def_delims (MP mp) ;
22610
22611 @ @c void mp_def_delims (MP mp) {
22612   pointer l_delim,r_delim; /* the new delimiter pair */
22613   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
22614   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
22615   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
22616   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
22617   mp_get_x_next(mp);
22618 }
22619
22620 @ Here is a procedure that is called when \MP\ has reached a point
22621 where some right delimiter is mandatory.
22622
22623 @<Declarations@>=
22624 static void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim);
22625
22626 @ @c
22627 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
22628   if ( mp->cur_cmd==right_delimiter ) 
22629     if ( mp->cur_mod==l_delim ) 
22630       return;
22631   if ( mp->cur_sym!=r_delim ) {
22632      mp_missing_err(mp, str(text(r_delim)));
22633 @.Missing `)'@>
22634     help2("I found no right delimiter to match a left one. So I've",
22635           "put one in, behind the scenes; this may fix the problem.");
22636     mp_back_error(mp);
22637   } else { 
22638     print_err("The token `"); mp_print_text(r_delim);
22639 @.The token...delimiter@>
22640     mp_print(mp, "' is no longer a right delimiter");
22641     help3("Strange: This token has lost its former meaning!",
22642       "I'll read it as a right delimiter this time;",
22643       "but watch out, I'll probably miss it later.");
22644     mp_error(mp);
22645   }
22646 }
22647
22648 @ The next four commands save or change the values associated with tokens.
22649
22650 @<Cases of |do_statement|...@>=
22651 case save_command: 
22652   do {  
22653     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22654   } while (mp->cur_cmd==comma);
22655   break;
22656 case interim_command: mp_do_interim(mp); break;
22657 case let_command: mp_do_let(mp); break;
22658 case new_internal: mp_do_new_internal(mp); break;
22659
22660 @ @<Declare action procedures for use by |do_statement|@>=
22661 static void mp_do_statement (MP mp);
22662 static void mp_do_interim (MP mp);
22663
22664 @ @c void mp_do_interim (MP mp) { 
22665   mp_get_x_next(mp);
22666   if ( mp->cur_cmd!=internal_quantity ) {
22667      print_err("The token `");
22668 @.The token...quantity@>
22669     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22670     else mp_print_text(mp->cur_sym);
22671     mp_print(mp, "' isn't an internal quantity");
22672     help1("Something like `tracingonline' should follow `interim'.");
22673     mp_back_error(mp);
22674   } else { 
22675     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22676   }
22677   mp_do_statement(mp);
22678 }
22679
22680 @ The following procedure is careful not to undefine the left-hand symbol
22681 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22682
22683 @<Declare action procedures for use by |do_statement|@>=
22684 static void mp_do_let (MP mp) ;
22685
22686 @ @c void mp_do_let (MP mp) {
22687   pointer l; /* hash location of the left-hand symbol */
22688   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22689   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22690      mp_missing_err(mp, "=");
22691 @.Missing `='@>
22692     help3("You should have said `let symbol = something'.",
22693       "But don't worry; I'll pretend that an equals sign",
22694       "was present. The next token I read will be `something'.");
22695     mp_back_error(mp);
22696   }
22697   mp_get_symbol(mp);
22698   switch (mp->cur_cmd) {
22699   case defined_macro: case secondary_primary_macro:
22700   case tertiary_secondary_macro: case expression_tertiary_macro: 
22701     add_mac_ref(mp->cur_mod);
22702     break;
22703   default: 
22704     break;
22705   }
22706   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22707   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22708   else equiv(l)=mp->cur_mod;
22709   mp_get_x_next(mp);
22710 }
22711
22712 @ @<Declarations@>=
22713 static void mp_grow_internals (MP mp, int l);
22714 static void mp_do_new_internal (MP mp) ;
22715
22716 @ @c
22717 void mp_grow_internals (MP mp, int l) {
22718   scaled *internal;
22719   char * *int_name; 
22720   int k;
22721   if ( hash_end+l>max_halfword ) {
22722     mp_confusion(mp, "out of memory space"); /* can't be reached */
22723   }
22724   int_name = xmalloc ((l+1),sizeof(char *));
22725   internal = xmalloc ((l+1),sizeof(scaled));
22726   for (k=0;k<=l; k++ ) { 
22727     if (k<=mp->max_internal) {
22728       internal[k]=mp->internal[k]; 
22729       int_name[k]=mp->int_name[k]; 
22730     } else {
22731       internal[k]=0; 
22732       int_name[k]=NULL; 
22733     }
22734   }
22735   xfree(mp->internal); xfree(mp->int_name);
22736   mp->int_name = int_name;
22737   mp->internal = internal;
22738   mp->max_internal = l;
22739 }
22740
22741 void mp_do_new_internal (MP mp) { 
22742   do {  
22743     if ( mp->int_ptr==mp->max_internal ) {
22744       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal/4)));
22745     }
22746     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22747     eq_type(mp->cur_sym)=internal_quantity; 
22748     equiv(mp->cur_sym)=mp->int_ptr;
22749     if(mp->int_name[mp->int_ptr]!=NULL)
22750       xfree(mp->int_name[mp->int_ptr]);
22751     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22752     mp->internal[mp->int_ptr]=0;
22753     mp_get_x_next(mp);
22754   } while (mp->cur_cmd==comma);
22755 }
22756
22757 @ @<Dealloc variables@>=
22758 for (k=0;k<=mp->max_internal;k++) {
22759    xfree(mp->int_name[k]);
22760 }
22761 xfree(mp->internal); 
22762 xfree(mp->int_name); 
22763
22764
22765 @ The various `\&{show}' commands are distinguished by modifier fields
22766 in the usual way.
22767
22768 @d show_token_code 0 /* show the meaning of a single token */
22769 @d show_stats_code 1 /* show current memory and string usage */
22770 @d show_code 2 /* show a list of expressions */
22771 @d show_var_code 3 /* show a variable and its descendents */
22772 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22773
22774 @<Put each...@>=
22775 mp_primitive(mp, "showtoken",show_command,show_token_code);
22776 @:show_token_}{\&{showtoken} primitive@>
22777 mp_primitive(mp, "showstats",show_command,show_stats_code);
22778 @:show_stats_}{\&{showstats} primitive@>
22779 mp_primitive(mp, "show",show_command,show_code);
22780 @:show_}{\&{show} primitive@>
22781 mp_primitive(mp, "showvariable",show_command,show_var_code);
22782 @:show_var_}{\&{showvariable} primitive@>
22783 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22784 @:show_dependencies_}{\&{showdependencies} primitive@>
22785
22786 @ @<Cases of |print_cmd...@>=
22787 case show_command: 
22788   switch (m) {
22789   case show_token_code:mp_print(mp, "showtoken"); break;
22790   case show_stats_code:mp_print(mp, "showstats"); break;
22791   case show_code:mp_print(mp, "show"); break;
22792   case show_var_code:mp_print(mp, "showvariable"); break;
22793   default: mp_print(mp, "showdependencies"); break;
22794   }
22795   break;
22796
22797 @ @<Cases of |do_statement|...@>=
22798 case show_command:mp_do_show_whatever(mp); break;
22799
22800 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22801 if it's |show_code|, complicated structures are abbreviated, otherwise
22802 they aren't.
22803
22804 @<Declare action procedures for use by |do_statement|@>=
22805 static void mp_do_show (MP mp) ;
22806
22807 @ @c void mp_do_show (MP mp) { 
22808   do {  
22809     mp_get_x_next(mp); mp_scan_expression(mp);
22810     mp_print_nl(mp, ">> ");
22811 @.>>@>
22812     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22813   } while (mp->cur_cmd==comma);
22814 }
22815
22816 @ @<Declare action procedures for use by |do_statement|@>=
22817 static void mp_disp_token (MP mp) ;
22818
22819 @ @c void mp_disp_token (MP mp) { 
22820   mp_print_nl(mp, "> ");
22821 @.>\relax@>
22822   if ( mp->cur_sym==0 ) {
22823     @<Show a numeric or string or capsule token@>;
22824   } else { 
22825     mp_print_text(mp->cur_sym); mp_print_char(mp, xord('='));
22826     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22827     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22828     if ( mp->cur_cmd==defined_macro ) {
22829       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22830     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22831 @^recursion@>
22832   }
22833 }
22834
22835 @ @<Show a numeric or string or capsule token@>=
22836
22837   if ( mp->cur_cmd==numeric_token ) {
22838     mp_print_scaled(mp, mp->cur_mod);
22839   } else if ( mp->cur_cmd==capsule_token ) {
22840     mp_print_capsule(mp,mp->cur_mod);
22841   } else  { 
22842     mp_print_char(mp, xord('"')); 
22843     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, xord('"'));
22844     delete_str_ref(mp->cur_mod);
22845   }
22846 }
22847
22848 @ The following cases of |print_cmd_mod| might arise in connection
22849 with |disp_token|, although they don't necessarily correspond to
22850 primitive tokens.
22851
22852 @<Cases of |print_cmd_...@>=
22853 case left_delimiter:
22854 case right_delimiter: 
22855   if ( c==left_delimiter ) mp_print(mp, "left");
22856   else mp_print(mp, "right");
22857   mp_print(mp, " delimiter that matches "); 
22858   mp_print_text(m);
22859   break;
22860 case tag_token:
22861   if ( m==null ) mp_print(mp, "tag");
22862    else mp_print(mp, "variable");
22863    break;
22864 case defined_macro: 
22865    mp_print(mp, "macro:");
22866    break;
22867 case secondary_primary_macro:
22868 case tertiary_secondary_macro:
22869 case expression_tertiary_macro:
22870   mp_print_cmd_mod(mp, macro_def,c); 
22871   mp_print(mp, "'d macro:");
22872   mp_print_ln(mp); mp_show_token_list(mp, mp_link(mp_link(m)),null,1000,0);
22873   break;
22874 case repeat_loop:
22875   mp_print(mp, "[repeat the loop]");
22876   break;
22877 case internal_quantity:
22878   mp_print(mp, mp->int_name[m]);
22879   break;
22880
22881 @ @<Declare action procedures for use by |do_statement|@>=
22882 static void mp_do_show_token (MP mp) ;
22883
22884 @ @c void mp_do_show_token (MP mp) { 
22885   do {  
22886     get_t_next; mp_disp_token(mp);
22887     mp_get_x_next(mp);
22888   } while (mp->cur_cmd==comma);
22889 }
22890
22891 @ @<Declare action procedures for use by |do_statement|@>=
22892 static void mp_do_show_stats (MP mp) ;
22893
22894 @ @c void mp_do_show_stats (MP mp) { 
22895   mp_print_nl(mp, "Memory usage ");
22896 @.Memory usage...@>
22897   mp_print_int(mp, mp->var_used); mp_print_char(mp, xord('&')); mp_print_int(mp, mp->dyn_used);
22898   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22899   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22900   mp_print_nl(mp, "String usage ");
22901   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22902   mp_print_char(mp, xord('&')); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22903   mp_print(mp, " (");
22904   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, xord('&'));
22905   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22906   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22907   mp_get_x_next(mp);
22908 }
22909
22910 @ Here's a recursive procedure that gives an abbreviated account
22911 of a variable, for use by |do_show_var|.
22912
22913 @<Declare action procedures for use by |do_statement|@>=
22914 static void mp_disp_var (MP mp,pointer p) ;
22915
22916 @ @c void mp_disp_var (MP mp,pointer p) {
22917   pointer q; /* traverses attributes and subscripts */
22918   int n; /* amount of macro text to show */
22919   if ( type(p)==mp_structured )  {
22920     @<Descend the structure@>;
22921   } else if ( type(p)>=mp_unsuffixed_macro ) {
22922     @<Display a variable macro@>;
22923   } else if ( type(p)!=undefined ){ 
22924     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22925     mp_print_char(mp, xord('='));
22926     mp_print_exp(mp, p,0);
22927   }
22928 }
22929
22930 @ @<Descend the structure@>=
22931
22932   q=attr_head(p);
22933   do {  mp_disp_var(mp, q); q=mp_link(q); } while (q!=end_attr);
22934   q=subscr_head(p);
22935   while ( name_type(q)==mp_subscr ) { 
22936     mp_disp_var(mp, q); q=mp_link(q);
22937   }
22938 }
22939
22940 @ @<Display a variable macro@>=
22941
22942   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22943   if ( type(p)>mp_unsuffixed_macro ) 
22944     mp_print(mp, "@@#"); /* |suffixed_macro| */
22945   mp_print(mp, "=macro:");
22946   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22947   else n=mp->max_print_line-mp->file_offset-15;
22948   mp_show_macro(mp, value(p),null,n);
22949 }
22950
22951 @ @<Declare action procedures for use by |do_statement|@>=
22952 static void mp_do_show_var (MP mp) ;
22953
22954 @ @c void mp_do_show_var (MP mp) { 
22955   do {  
22956     get_t_next;
22957     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22958       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22959       mp_disp_var(mp, mp->cur_mod); goto DONE;
22960     }
22961    mp_disp_token(mp);
22962   DONE:
22963    mp_get_x_next(mp);
22964   } while (mp->cur_cmd==comma);
22965 }
22966
22967 @ @<Declare action procedures for use by |do_statement|@>=
22968 static void mp_do_show_dependencies (MP mp) ;
22969
22970 @ @c void mp_do_show_dependencies (MP mp) {
22971   pointer p; /* link that runs through all dependencies */
22972   p=mp_link(dep_head);
22973   while ( p!=dep_head ) {
22974     if ( mp_interesting(mp, p) ) {
22975       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22976       if ( type(p)==mp_dependent ) mp_print_char(mp, xord('='));
22977       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22978       mp_print_dependency(mp, dep_list(p),type(p));
22979     }
22980     p=dep_list(p);
22981     while ( info(p)!=null ) p=mp_link(p);
22982     p=mp_link(p);
22983   }
22984   mp_get_x_next(mp);
22985 }
22986
22987 @ Finally we are ready for the procedure that governs all of the
22988 show commands.
22989
22990 @<Declare action procedures for use by |do_statement|@>=
22991 static void mp_do_show_whatever (MP mp) ;
22992
22993 @ @c void mp_do_show_whatever (MP mp) { 
22994   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22995   switch (mp->cur_mod) {
22996   case show_token_code:mp_do_show_token(mp); break;
22997   case show_stats_code:mp_do_show_stats(mp); break;
22998   case show_code:mp_do_show(mp); break;
22999   case show_var_code:mp_do_show_var(mp); break;
23000   case show_dependencies_code:mp_do_show_dependencies(mp); break;
23001   } /* there are no other cases */
23002   if ( mp->internal[mp_showstopping]>0 ){ 
23003     print_err("OK");
23004 @.OK@>
23005     if ( mp->interaction<mp_error_stop_mode ) { 
23006       help0; decr(mp->error_count);
23007     } else {
23008       help1("This isn't an error message; I'm just showing something.");
23009     }
23010     if ( mp->cur_cmd==semicolon ) mp_error(mp);
23011      else mp_put_get_error(mp);
23012   }
23013 }
23014
23015 @ The `\&{addto}' command needs the following additional primitives:
23016
23017 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
23018 @d contour_code 1 /* command modifier for `\&{contour}' */
23019 @d also_code 2 /* command modifier for `\&{also}' */
23020
23021 @ Pre and postscripts need two new identifiers:
23022
23023 @d with_pre_script 11
23024 @d with_post_script 13
23025
23026 @<Put each...@>=
23027 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
23028 @:double_path_}{\&{doublepath} primitive@>
23029 mp_primitive(mp, "contour",thing_to_add,contour_code);
23030 @:contour_}{\&{contour} primitive@>
23031 mp_primitive(mp, "also",thing_to_add,also_code);
23032 @:also_}{\&{also} primitive@>
23033 mp_primitive(mp, "withpen",with_option,mp_pen_type);
23034 @:with_pen_}{\&{withpen} primitive@>
23035 mp_primitive(mp, "dashed",with_option,mp_picture_type);
23036 @:dashed_}{\&{dashed} primitive@>
23037 mp_primitive(mp, "withprescript",with_option,with_pre_script);
23038 @:with_pre_script_}{\&{withprescript} primitive@>
23039 mp_primitive(mp, "withpostscript",with_option,with_post_script);
23040 @:with_post_script_}{\&{withpostscript} primitive@>
23041 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
23042 @:with_color_}{\&{withoutcolor} primitive@>
23043 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
23044 @:with_color_}{\&{withgreyscale} primitive@>
23045 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
23046 @:with_color_}{\&{withcolor} primitive@>
23047 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
23048 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
23049 @:with_color_}{\&{withrgbcolor} primitive@>
23050 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
23051 @:with_color_}{\&{withcmykcolor} primitive@>
23052
23053 @ @<Cases of |print_cmd...@>=
23054 case thing_to_add:
23055   if ( m==contour_code ) mp_print(mp, "contour");
23056   else if ( m==double_path_code ) mp_print(mp, "doublepath");
23057   else mp_print(mp, "also");
23058   break;
23059 case with_option:
23060   if ( m==mp_pen_type ) mp_print(mp, "withpen");
23061   else if ( m==with_pre_script ) mp_print(mp, "withprescript");
23062   else if ( m==with_post_script ) mp_print(mp, "withpostscript");
23063   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
23064   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
23065   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
23066   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
23067   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
23068   else mp_print(mp, "dashed");
23069   break;
23070
23071 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
23072 updates the list of graphical objects starting at |p|.  Each $\langle$with
23073 clause$\rangle$ updates all graphical objects whose |type| is compatible.
23074 Other objects are ignored.
23075
23076 @<Declare action procedures for use by |do_statement|@>=
23077 static void mp_scan_with_list (MP mp,pointer p) ;
23078
23079 @ @c void mp_scan_with_list (MP mp,pointer p) {
23080   quarterword t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
23081   pointer q; /* for list manipulation */
23082   unsigned old_setting; /* saved |selector| setting */
23083   pointer k; /* for finding the near-last item in a list  */
23084   str_number s; /* for string cleanup after combining  */
23085   pointer cp,pp,dp,ap,bp;
23086     /* objects being updated; |void| initially; |null| to suppress update */
23087   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
23088   k=0;
23089   while ( mp->cur_cmd==with_option ){ 
23090     t=mp->cur_mod;
23091     mp_get_x_next(mp);
23092     if ( t!=mp_no_model ) mp_scan_expression(mp);
23093     if (((t==with_pre_script)&&(mp->cur_type!=mp_string_type))||
23094      ((t==with_post_script)&&(mp->cur_type!=mp_string_type))||
23095      ((t==mp_uninitialized_model)&&
23096         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
23097           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
23098      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
23099      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
23100      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
23101      ((t==mp_pen_type)&&(mp->cur_type!=t))||
23102      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
23103       @<Complain about improper type@>;
23104     } else if ( t==mp_uninitialized_model ) {
23105       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23106       if ( cp!=null )
23107         @<Transfer a color from the current expression to object~|cp|@>;
23108       mp_flush_cur_exp(mp, 0);
23109     } else if ( t==mp_rgb_model ) {
23110       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23111       if ( cp!=null )
23112         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
23113       mp_flush_cur_exp(mp, 0);
23114     } else if ( t==mp_cmyk_model ) {
23115       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23116       if ( cp!=null )
23117         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
23118       mp_flush_cur_exp(mp, 0);
23119     } else if ( t==mp_grey_model ) {
23120       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23121       if ( cp!=null )
23122         @<Transfer a greyscale from the current expression to object~|cp|@>;
23123       mp_flush_cur_exp(mp, 0);
23124     } else if ( t==mp_no_model ) {
23125       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23126       if ( cp!=null )
23127         @<Transfer a noncolor from the current expression to object~|cp|@>;
23128     } else if ( t==mp_pen_type ) {
23129       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
23130       if ( pp!=null ) {
23131         if ( pen_p(pp)!=null ) mp_toss_knot_list(mp, pen_p(pp));
23132         pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
23133       }
23134     } else if ( t==with_pre_script ) {
23135       if ( ap==mp_void )
23136         ap=p;
23137       while ( (ap!=null)&&(! has_color(ap)) )
23138          ap=mp_link(ap);
23139       if ( ap!=null ) {
23140         if ( pre_script(ap)!=null ) { /*  build a new,combined string  */
23141           s=pre_script(ap);
23142           old_setting=mp->selector;
23143               mp->selector=new_string;
23144           str_room(length(pre_script(ap))+length(mp->cur_exp)+2);
23145               mp_print_str(mp, mp->cur_exp);
23146           append_char(13);  /* a forced \ps\ newline  */
23147           mp_print_str(mp, pre_script(ap));
23148           pre_script(ap)=mp_make_string(mp);
23149           delete_str_ref(s);
23150           mp->selector=old_setting;
23151         } else {
23152           pre_script(ap)=mp->cur_exp;
23153         }
23154         mp->cur_type=mp_vacuous;
23155       }
23156     } else if ( t==with_post_script ) {
23157       if ( bp==mp_void )
23158         k=p; 
23159       bp=k;
23160       while ( mp_link(k)!=null ) {
23161         k=mp_link(k);
23162         if ( has_color(k) ) bp=k;
23163       }
23164       if ( bp!=null ) {
23165          if ( post_script(bp)!=null ) {
23166            s=post_script(bp);
23167            old_setting=mp->selector;
23168                mp->selector=new_string;
23169            str_room(length(post_script(bp))+length(mp->cur_exp)+2);
23170            mp_print_str(mp, post_script(bp));
23171            append_char(13); /* a forced \ps\ newline  */
23172            mp_print_str(mp, mp->cur_exp);
23173            post_script(bp)=mp_make_string(mp);
23174            delete_str_ref(s);
23175            mp->selector=old_setting;
23176          } else {
23177            post_script(bp)=mp->cur_exp;
23178          }
23179          mp->cur_type=mp_vacuous;
23180        }
23181     } else { 
23182       if ( dp==mp_void ) {
23183         @<Make |dp| a stroked node in list~|p|@>;
23184       }
23185       if ( dp!=null ) {
23186         if ( dash_p(dp)!=null ) delete_edge_ref(dash_p(dp));
23187         dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
23188         dash_scale(dp)=unity;
23189         mp->cur_type=mp_vacuous;
23190       }
23191     }
23192   }
23193   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
23194     of the list@>;
23195 }
23196
23197 @ @<Complain about improper type@>=
23198 { exp_err("Improper type");
23199 @.Improper type@>
23200 help2("Next time say `withpen <known pen expression>';",
23201       "I'll ignore the bad `with' clause and look for another.");
23202 if ( t==with_pre_script )
23203   mp->help_line[1]="Next time say `withprescript <known string expression>';";
23204 else if ( t==with_post_script )
23205   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
23206 else if ( t==mp_picture_type )
23207   mp->help_line[1]="Next time say `dashed <known picture expression>';";
23208 else if ( t==mp_uninitialized_model )
23209   mp->help_line[1]="Next time say `withcolor <known color expression>';";
23210 else if ( t==mp_rgb_model )
23211   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
23212 else if ( t==mp_cmyk_model )
23213   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
23214 else if ( t==mp_grey_model )
23215   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
23216 mp_put_get_flush_error(mp, 0);
23217 }
23218
23219 @ Forcing the color to be between |0| and |unity| here guarantees that no
23220 picture will ever contain a color outside the legal range for \ps\ graphics.
23221
23222 @<Transfer a color from the current expression to object~|cp|@>=
23223 { if ( mp->cur_type==mp_color_type )
23224    @<Transfer a rgbcolor from the current expression to object~|cp|@>
23225 else if ( mp->cur_type==mp_cmykcolor_type )
23226    @<Transfer a cmykcolor from the current expression to object~|cp|@>
23227 else if ( mp->cur_type==mp_known )
23228    @<Transfer a greyscale from the current expression to object~|cp|@>
23229 else if ( mp->cur_exp==false_code )
23230    @<Transfer a noncolor from the current expression to object~|cp|@>;
23231 }
23232
23233 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
23234 { q=value(mp->cur_exp);
23235 cyan_val(cp)=0;
23236 magenta_val(cp)=0;
23237 yellow_val(cp)=0;
23238 black_val(cp)=0;
23239 red_val(cp)=value(red_part_loc(q));
23240 green_val(cp)=value(green_part_loc(q));
23241 blue_val(cp)=value(blue_part_loc(q));
23242 color_model(cp)=mp_rgb_model;
23243 if ( red_val(cp)<0 ) red_val(cp)=0;
23244 if ( green_val(cp)<0 ) green_val(cp)=0;
23245 if ( blue_val(cp)<0 ) blue_val(cp)=0;
23246 if ( red_val(cp)>unity ) red_val(cp)=unity;
23247 if ( green_val(cp)>unity ) green_val(cp)=unity;
23248 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
23249 }
23250
23251 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
23252 { q=value(mp->cur_exp);
23253 cyan_val(cp)=value(cyan_part_loc(q));
23254 magenta_val(cp)=value(magenta_part_loc(q));
23255 yellow_val(cp)=value(yellow_part_loc(q));
23256 black_val(cp)=value(black_part_loc(q));
23257 color_model(cp)=mp_cmyk_model;
23258 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
23259 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
23260 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
23261 if ( black_val(cp)<0 ) black_val(cp)=0;
23262 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
23263 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
23264 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
23265 if ( black_val(cp)>unity ) black_val(cp)=unity;
23266 }
23267
23268 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
23269 { q=mp->cur_exp;
23270 cyan_val(cp)=0;
23271 magenta_val(cp)=0;
23272 yellow_val(cp)=0;
23273 black_val(cp)=0;
23274 grey_val(cp)=q;
23275 color_model(cp)=mp_grey_model;
23276 if ( grey_val(cp)<0 ) grey_val(cp)=0;
23277 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
23278 }
23279
23280 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
23281 {
23282 cyan_val(cp)=0;
23283 magenta_val(cp)=0;
23284 yellow_val(cp)=0;
23285 black_val(cp)=0;
23286 grey_val(cp)=0;
23287 color_model(cp)=mp_no_model;
23288 }
23289
23290 @ @<Make |cp| a colored object in object list~|p|@>=
23291 { cp=p;
23292   while ( cp!=null ){ 
23293     if ( has_color(cp) ) break;
23294     cp=mp_link(cp);
23295   }
23296 }
23297
23298 @ @<Make |pp| an object in list~|p| that needs a pen@>=
23299 { pp=p;
23300   while ( pp!=null ) {
23301     if ( has_pen(pp) ) break;
23302     pp=mp_link(pp);
23303   }
23304 }
23305
23306 @ @<Make |dp| a stroked node in list~|p|@>=
23307 { dp=p;
23308   while ( dp!=null ) {
23309     if ( type(dp)==mp_stroked_code ) break;
23310     dp=mp_link(dp);
23311   }
23312 }
23313
23314 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
23315 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
23316 if ( pp>mp_void ) {
23317   @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
23318 }
23319 if ( dp>mp_void ) {
23320   @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>;
23321 }
23322
23323
23324 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
23325 { q=mp_link(cp);
23326   while ( q!=null ) { 
23327     if ( has_color(q) ) {
23328       red_val(q)=red_val(cp);
23329       green_val(q)=green_val(cp);
23330       blue_val(q)=blue_val(cp);
23331       black_val(q)=black_val(cp);
23332       color_model(q)=color_model(cp);
23333     }
23334     q=mp_link(q);
23335   }
23336 }
23337
23338 @ @<Copy |pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
23339 { q=mp_link(pp);
23340   while ( q!=null ) {
23341     if ( has_pen(q) ) {
23342       if ( pen_p(q)!=null ) mp_toss_knot_list(mp, pen_p(q));
23343       pen_p(q)=copy_pen(pen_p(pp));
23344     }
23345     q=mp_link(q);
23346   }
23347 }
23348
23349 @ @<Make stroked nodes linked to |dp| refer to |dash_p(dp)|@>=
23350 { q=mp_link(dp);
23351   while ( q!=null ) {
23352     if ( type(q)==mp_stroked_code ) {
23353       if ( dash_p(q)!=null ) delete_edge_ref(dash_p(q));
23354       dash_p(q)=dash_p(dp);
23355       dash_scale(q)=unity;
23356       if ( dash_p(q)!=null ) add_edge_ref(dash_p(q));
23357     }
23358     q=mp_link(q);
23359   }
23360 }
23361
23362 @ One of the things we need to do when we've parsed an \&{addto} or
23363 similar command is find the header of a supposed \&{picture} variable, given
23364 a token list for that variable.  Since the edge structure is about to be
23365 updated, we use |private_edges| to make sure that this is possible.
23366
23367 @<Declare action procedures for use by |do_statement|@>=
23368 static pointer mp_find_edges_var (MP mp, pointer t) ;
23369
23370 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
23371   pointer p;
23372   pointer cur_edges; /* the return value */
23373   p=mp_find_variable(mp, t); cur_edges=null;
23374   if ( p==null ) { 
23375     mp_obliterated(mp, t); mp_put_get_error(mp);
23376   } else if ( type(p)!=mp_picture_type )  { 
23377     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
23378 @.Variable x is the wrong type@>
23379     mp_print(mp, " is the wrong type ("); 
23380     mp_print_type(mp, type(p)); mp_print_char(mp, xord(')'));
23381     help2("I was looking for a \"known\" picture variable.",
23382           "So I'll not change anything just now."); 
23383     mp_put_get_error(mp);
23384   } else { 
23385     value(p)=mp_private_edges(mp, value(p));
23386     cur_edges=value(p);
23387   }
23388   mp_flush_node_list(mp, t);
23389   return cur_edges;
23390 }
23391
23392 @ @<Cases of |do_statement|...@>=
23393 case add_to_command: mp_do_add_to(mp); break;
23394 case bounds_command:mp_do_bounds(mp); break;
23395
23396 @ @<Put each...@>=
23397 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
23398 @:clip_}{\&{clip} primitive@>
23399 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
23400 @:set_bounds_}{\&{setbounds} primitive@>
23401
23402 @ @<Cases of |print_cmd...@>=
23403 case bounds_command: 
23404   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
23405   else mp_print(mp, "setbounds");
23406   break;
23407
23408 @ The following function parses the beginning of an \&{addto} or \&{clip}
23409 command: it expects a variable name followed by a token with |cur_cmd=sep|
23410 and then an expression.  The function returns the token list for the variable
23411 and stores the command modifier for the separator token in the global variable
23412 |last_add_type|.  We must be careful because this variable might get overwritten
23413 any time we call |get_x_next|.
23414
23415 @<Glob...@>=
23416 quarterword last_add_type;
23417   /* command modifier that identifies the last \&{addto} command */
23418
23419 @ @<Declare action procedures for use by |do_statement|@>=
23420 static pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
23421
23422 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
23423   pointer lhv; /* variable to add to left */
23424   quarterword add_type=0; /* value to be returned in |last_add_type| */
23425   lhv=null;
23426   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
23427   if ( mp->cur_type!=mp_token_list ) {
23428     @<Abandon edges command because there's no variable@>;
23429   } else  { 
23430     lhv=mp->cur_exp; add_type=mp->cur_mod;
23431     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
23432   }
23433   mp->last_add_type=add_type;
23434   return lhv;
23435 }
23436
23437 @ @<Abandon edges command because there's no variable@>=
23438 { exp_err("Not a suitable variable");
23439 @.Not a suitable variable@>
23440   help4("At this point I needed to see the name of a picture variable.",
23441     "(Or perhaps you have indeed presented me with one; I might",
23442     "have missed it, if it wasn't followed by the proper token.)",
23443     "So I'll not change anything just now.");
23444   mp_put_get_flush_error(mp, 0);
23445 }
23446
23447 @ Here is an example of how to use |start_draw_cmd|.
23448
23449 @<Declare action procedures for use by |do_statement|@>=
23450 static void mp_do_bounds (MP mp) ;
23451
23452 @ @c void mp_do_bounds (MP mp) {
23453   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
23454   pointer p; /* for list manipulation */
23455   integer m; /* initial value of |cur_mod| */
23456   m=mp->cur_mod;
23457   lhv=mp_start_draw_cmd(mp, to_token);
23458   if ( lhv!=null ) {
23459     lhe=mp_find_edges_var(mp, lhv);
23460     if ( lhe==null ) {
23461       mp_flush_cur_exp(mp, 0);
23462     } else if ( mp->cur_type!=mp_path_type ) {
23463       exp_err("Improper `clip'");
23464 @.Improper `addto'@>
23465       help2("This expression should have specified a known path.",
23466             "So I'll not change anything just now."); 
23467       mp_put_get_flush_error(mp, 0);
23468     } else if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
23469       @<Complain about a non-cycle@>;
23470     } else {
23471       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
23472     }
23473   }
23474 }
23475
23476 @ @<Complain about a non-cycle@>=
23477 { print_err("Not a cycle");
23478 @.Not a cycle@>
23479   help2("That contour should have ended with `..cycle' or `&cycle'.",
23480         "So I'll not change anything just now."); mp_put_get_error(mp);
23481 }
23482
23483 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
23484 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
23485   mp_link(p)=mp_link(dummy_loc(lhe));
23486   mp_link(dummy_loc(lhe))=p;
23487   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
23488   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
23489   type(p)=stop_type(m);
23490   mp_link(obj_tail(lhe))=p;
23491   obj_tail(lhe)=p;
23492   mp_init_bbox(mp, lhe);
23493 }
23494
23495 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
23496 cases to deal with.
23497
23498 @<Declare action procedures for use by |do_statement|@>=
23499 static void mp_do_add_to (MP mp) ;
23500
23501 @ @c void mp_do_add_to (MP mp) {
23502   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
23503   pointer p; /* the graphical object or list for |scan_with_list| to update */
23504   pointer e; /* an edge structure to be merged */
23505   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
23506   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
23507   if ( lhv!=null ) {
23508     if ( add_type==also_code ) {
23509       @<Make sure the current expression is a suitable picture and set |e| and |p|
23510        appropriately@>;
23511     } else {
23512       @<Create a graphical object |p| based on |add_type| and the current
23513         expression@>;
23514     }
23515     mp_scan_with_list(mp, p);
23516     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
23517   }
23518 }
23519
23520 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
23521 setting |e:=null| prevents anything from being added to |lhe|.
23522
23523 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
23524
23525   p=null; e=null;
23526   if ( mp->cur_type!=mp_picture_type ) {
23527     exp_err("Improper `addto'");
23528 @.Improper `addto'@>
23529     help2("This expression should have specified a known picture.",
23530           "So I'll not change anything just now."); 
23531     mp_put_get_flush_error(mp, 0);
23532   } else { 
23533     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
23534     p=mp_link(dummy_loc(e));
23535   }
23536 }
23537
23538 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
23539 attempts to add to the edge structure.
23540
23541 @<Create a graphical object |p| based on |add_type| and the current...@>=
23542 { e=null; p=null;
23543   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
23544   if ( mp->cur_type!=mp_path_type ) {
23545     exp_err("Improper `addto'");
23546 @.Improper `addto'@>
23547     help2("This expression should have specified a known path.",
23548           "So I'll not change anything just now."); 
23549     mp_put_get_flush_error(mp, 0);
23550   } else if ( add_type==contour_code ) {
23551     if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
23552       @<Complain about a non-cycle@>;
23553     } else { 
23554       p=mp_new_fill_node(mp, mp->cur_exp);
23555       mp->cur_type=mp_vacuous;
23556     }
23557   } else { 
23558     p=mp_new_stroked_node(mp, mp->cur_exp);
23559     mp->cur_type=mp_vacuous;
23560   }
23561 }
23562
23563 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
23564 lhe=mp_find_edges_var(mp, lhv);
23565 if ( lhe==null ) {
23566   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
23567   if ( e!=null ) delete_edge_ref(e);
23568 } else if ( add_type==also_code ) {
23569   if ( e!=null ) {
23570     @<Merge |e| into |lhe| and delete |e|@>;
23571   } else { 
23572     do_nothing;
23573   }
23574 } else if ( p!=null ) {
23575   mp_link(obj_tail(lhe))=p;
23576   obj_tail(lhe)=p;
23577   if ( add_type==double_path_code )
23578     if ( pen_p(p)==null ) 
23579       pen_p(p)=mp_get_pen_circle(mp, 0);
23580 }
23581
23582 @ @<Merge |e| into |lhe| and delete |e|@>=
23583 { if ( mp_link(dummy_loc(e))!=null ) {
23584     mp_link(obj_tail(lhe))=mp_link(dummy_loc(e));
23585     obj_tail(lhe)=obj_tail(e);
23586     obj_tail(e)=dummy_loc(e);
23587     mp_link(dummy_loc(e))=null;
23588     mp_flush_dash_list(mp, lhe);
23589   }
23590   mp_toss_edges(mp, e);
23591 }
23592
23593 @ @<Cases of |do_statement|...@>=
23594 case ship_out_command: mp_do_ship_out(mp); break;
23595
23596 @ @<Declare action procedures for use by |do_statement|@>=
23597 @<Declare the \ps\ output procedures@>
23598 static void mp_do_ship_out (MP mp) ;
23599
23600 @ @c void mp_do_ship_out (MP mp) {
23601   integer c; /* the character code */
23602   mp_get_x_next(mp); mp_scan_expression(mp);
23603   if ( mp->cur_type!=mp_picture_type ) {
23604     @<Complain that it's not a known picture@>;
23605   } else { 
23606     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
23607     if ( c<0 ) c=c+256;
23608     @<Store the width information for character code~|c|@>;
23609     mp_ship_out(mp, mp->cur_exp);
23610     mp_flush_cur_exp(mp, 0);
23611   }
23612 }
23613
23614 @ @<Complain that it's not a known picture@>=
23615
23616   exp_err("Not a known picture");
23617   help1("I can only output known pictures.");
23618   mp_put_get_flush_error(mp, 0);
23619 }
23620
23621 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
23622 |start_sym|.
23623
23624 @<Cases of |do_statement|...@>=
23625 case every_job_command: 
23626   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
23627   break;
23628
23629 @ @<Glob...@>=
23630 halfword start_sym; /* a symbolic token to insert at beginning of job */
23631
23632 @ @<Set init...@>=
23633 mp->start_sym=0;
23634
23635 @ Finally, we have only the ``message'' commands remaining.
23636
23637 @d message_code 0
23638 @d err_message_code 1
23639 @d err_help_code 2
23640 @d filename_template_code 3
23641 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
23642               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
23643               if ( f>g ) {
23644                 mp->pool_ptr = mp->pool_ptr - g;
23645                 while ( f>g ) {
23646                   mp_print_char(mp, xord('0'));
23647                   decr(f);
23648                   };
23649                 mp_print_int(mp, (A));
23650               };
23651               f = 0
23652
23653 @<Put each...@>=
23654 mp_primitive(mp, "message",message_command,message_code);
23655 @:message_}{\&{message} primitive@>
23656 mp_primitive(mp, "errmessage",message_command,err_message_code);
23657 @:err_message_}{\&{errmessage} primitive@>
23658 mp_primitive(mp, "errhelp",message_command,err_help_code);
23659 @:err_help_}{\&{errhelp} primitive@>
23660 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23661 @:filename_template_}{\&{filenametemplate} primitive@>
23662
23663 @ @<Cases of |print_cmd...@>=
23664 case message_command: 
23665   if ( m<err_message_code ) mp_print(mp, "message");
23666   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23667   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23668   else mp_print(mp, "errhelp");
23669   break;
23670
23671 @ @<Cases of |do_statement|...@>=
23672 case message_command: mp_do_message(mp); break;
23673
23674 @ @<Declare action procedures for use by |do_statement|@>=
23675 @<Declare a procedure called |no_string_err|@>
23676 static void mp_do_message (MP mp) ;
23677
23678
23679 @c void mp_do_message (MP mp) {
23680   int m; /* the type of message */
23681   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23682   if ( mp->cur_type!=mp_string_type )
23683     mp_no_string_err(mp, "A message should be a known string expression.");
23684   else {
23685     switch (m) {
23686     case message_code: 
23687       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23688       break;
23689     case err_message_code:
23690       @<Print string |cur_exp| as an error message@>;
23691       break;
23692     case err_help_code:
23693       @<Save string |cur_exp| as the |err_help|@>;
23694       break;
23695     case filename_template_code:
23696       @<Save the filename template@>;
23697       break;
23698     } /* there are no other cases */
23699   }
23700   mp_flush_cur_exp(mp, 0);
23701 }
23702
23703 @ @<Declare a procedure called |no_string_err|@>=
23704 static void mp_no_string_err (MP mp, const char *s) { 
23705    exp_err("Not a string");
23706 @.Not a string@>
23707   help1(s);
23708   mp_put_get_error(mp);
23709 }
23710
23711 @ The global variable |err_help| is zero when the user has most recently
23712 given an empty help string, or if none has ever been given.
23713
23714 @<Save string |cur_exp| as the |err_help|@>=
23715
23716   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23717   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23718   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23719 }
23720
23721 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23722 \&{errhelp}, we don't want to give a long help message each time. So we
23723 give a verbose explanation only once.
23724
23725 @<Glob...@>=
23726 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23727
23728 @ @<Set init...@>=mp->long_help_seen=false;
23729
23730 @ @<Print string |cur_exp| as an error message@>=
23731
23732   print_err(""); mp_print_str(mp, mp->cur_exp);
23733   if ( mp->err_help!=0 ) {
23734     mp->use_err_help=true;
23735   } else if ( mp->long_help_seen ) { 
23736     help1("(That was another `errmessage'.)") ; 
23737   } else  { 
23738    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23739     help4("This error message was generated by an `errmessage'",
23740      "command, so I can\'t give any explicit help.",
23741      "Pretend that you're Miss Marple: Examine all clues,",
23742 @^Marple, Jane@>
23743      "and deduce the truth by inspired guesses.");
23744   }
23745   mp_put_get_error(mp); mp->use_err_help=false;
23746 }
23747
23748 @ @<Cases of |do_statement|...@>=
23749 case write_command: mp_do_write(mp); break;
23750
23751 @ @<Declare action procedures for use by |do_statement|@>=
23752 static void mp_do_write (MP mp) ;
23753
23754 @ @c void mp_do_write (MP mp) {
23755   str_number t; /* the line of text to be written */
23756   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23757   unsigned old_setting; /* for saving |selector| during output */
23758   mp_get_x_next(mp);
23759   mp_scan_expression(mp);
23760   if ( mp->cur_type!=mp_string_type ) {
23761     mp_no_string_err(mp, "The text to be written should be a known string expression");
23762   } else if ( mp->cur_cmd!=to_token ) { 
23763     print_err("Missing `to' clause");
23764     help1("A write command should end with `to <filename>'");
23765     mp_put_get_error(mp);
23766   } else { 
23767     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23768     mp_get_x_next(mp);
23769     mp_scan_expression(mp);
23770     if ( mp->cur_type!=mp_string_type )
23771       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23772     else {
23773       @<Write |t| to the file named by |cur_exp|@>;
23774     }
23775     delete_str_ref(t);
23776   }
23777   mp_flush_cur_exp(mp, 0);
23778 }
23779
23780 @ @<Write |t| to the file named by |cur_exp|@>=
23781
23782   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23783     |cur_exp| must be inserted@>;
23784   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23785     @<Record the end of file on |wr_file[n]|@>;
23786   } else { 
23787     old_setting=mp->selector;
23788     mp->selector=n+write_file;
23789     mp_print_str(mp, t); mp_print_ln(mp);
23790     mp->selector = old_setting;
23791   }
23792 }
23793
23794 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23795 {
23796   char *fn = str(mp->cur_exp);
23797   n=mp->write_files;
23798   n0=mp->write_files;
23799   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23800     if ( n==0 ) { /* bottom reached */
23801           if ( n0==mp->write_files ) {
23802         if ( mp->write_files<mp->max_write_files ) {
23803           incr(mp->write_files);
23804         } else {
23805           void **wr_file;
23806           char **wr_fname;
23807               write_index l,k;
23808           l = mp->max_write_files + (mp->max_write_files/4);
23809           wr_file = xmalloc((l+1),sizeof(void *));
23810           wr_fname = xmalloc((l+1),sizeof(char *));
23811               for (k=0;k<=l;k++) {
23812             if (k<=mp->max_write_files) {
23813                   wr_file[k]=mp->wr_file[k]; 
23814               wr_fname[k]=mp->wr_fname[k];
23815             } else {
23816                   wr_file[k]=0; 
23817               wr_fname[k]=NULL;
23818             }
23819           }
23820               xfree(mp->wr_file); xfree(mp->wr_fname);
23821           mp->max_write_files = l;
23822           mp->wr_file = wr_file;
23823           mp->wr_fname = wr_fname;
23824         }
23825       }
23826       n=n0;
23827       mp_open_write_file(mp, fn ,n);
23828     } else { 
23829       decr(n);
23830           if ( mp->wr_fname[n]==NULL )  n0=n; 
23831     }
23832   }
23833 }
23834
23835 @ @<Record the end of file on |wr_file[n]|@>=
23836 { (mp->close_file)(mp,mp->wr_file[n]);
23837   xfree(mp->wr_fname[n]);
23838   if ( n==mp->write_files-1 ) mp->write_files=n;
23839 }
23840
23841
23842 @* \[42] Writing font metric data.
23843 \TeX\ gets its knowledge about fonts from font metric files, also called
23844 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23845 but other programs know about them too. One of \MP's duties is to
23846 write \.{TFM} files so that the user's fonts can readily be
23847 applied to typesetting.
23848 @:TFM files}{\.{TFM} files@>
23849 @^font metric files@>
23850
23851 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23852 Since the number of bytes is always a multiple of~4, we could
23853 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23854 byte interpretation. The format of \.{TFM} files was designed by
23855 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23856 @^Ramshaw, Lyle Harold@>
23857 of information in a compact but useful form.
23858
23859 @<Glob...@>=
23860 void * tfm_file; /* the font metric output goes here */
23861 char * metric_file_name; /* full name of the font metric file */
23862
23863 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23864 integers that give the lengths of the various subsequent portions
23865 of the file. These twelve integers are, in order:
23866 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23867 |lf|&length of the entire file, in words;\cr
23868 |lh|&length of the header data, in words;\cr
23869 |bc|&smallest character code in the font;\cr
23870 |ec|&largest character code in the font;\cr
23871 |nw|&number of words in the width table;\cr
23872 |nh|&number of words in the height table;\cr
23873 |nd|&number of words in the depth table;\cr
23874 |ni|&number of words in the italic correction table;\cr
23875 |nl|&number of words in the lig/kern table;\cr
23876 |nk|&number of words in the kern table;\cr
23877 |ne|&number of words in the extensible character table;\cr
23878 |np|&number of font parameter words.\cr}}$$
23879 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23880 |ne<=256|, and
23881 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23882 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23883 and as few as 0 characters (if |bc=ec+1|).
23884
23885 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23886 16 or more bits, the most significant bytes appear first in the file.
23887 This is called BigEndian order.
23888 @^BigEndian order@>
23889
23890 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23891 arrays.
23892
23893 The most important data type used here is a |fix_word|, which is
23894 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23895 quantity, with the two's complement of the entire word used to represent
23896 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23897 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23898 the smallest is $-2048$. We will see below, however, that all but two of
23899 the |fix_word| values must lie between $-16$ and $+16$.
23900
23901 @ The first data array is a block of header information, which contains
23902 general facts about the font. The header must contain at least two words,
23903 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23904 header information of use to other software routines might also be
23905 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23906 For example, 16 more words of header information are in use at the Xerox
23907 Palo Alto Research Center; the first ten specify the character coding
23908 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23909 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23910 last gives the ``face byte.''
23911
23912 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23913 the \.{GF} output file. This helps ensure consistency between files,
23914 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23915 should match the check sums on actual fonts that are used.  The actual
23916 relation between this check sum and the rest of the \.{TFM} file is not
23917 important; the check sum is simply an identification number with the
23918 property that incompatible fonts almost always have distinct check sums.
23919 @^check sum@>
23920
23921 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23922 font, in units of \TeX\ points. This number must be at least 1.0; it is
23923 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23924 font, i.e., a font that was designed to look best at a 10-point size,
23925 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23926 $\delta$ \.{pt}', the effect is to override the design size and replace it
23927 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23928 the font image by a factor of $\delta$ divided by the design size.  {\sl
23929 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23930 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23931 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23932 since many fonts have a design size equal to one em.  The other dimensions
23933 must be less than 16 design-size units in absolute value; thus,
23934 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23935 \.{TFM} file whose first byte might be something besides 0 or 255.
23936 @^design size@>
23937
23938 @ Next comes the |char_info| array, which contains one |char_info_word|
23939 per character. Each word in this part of the file contains six fields
23940 packed into four bytes as follows.
23941
23942 \yskip\hang first byte: |width_index| (8 bits)\par
23943 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23944   (4~bits)\par
23945 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23946   (2~bits)\par
23947 \hang fourth byte: |remainder| (8 bits)\par
23948 \yskip\noindent
23949 The actual width of a character is \\{width}|[width_index]|, in design-size
23950 units; this is a device for compressing information, since many characters
23951 have the same width. Since it is quite common for many characters
23952 to have the same height, depth, or italic correction, the \.{TFM} format
23953 imposes a limit of 16 different heights, 16 different depths, and
23954 64 different italic corrections.
23955
23956 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23957 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23958 value of zero.  The |width_index| should never be zero unless the
23959 character does not exist in the font, since a character is valid if and
23960 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23961
23962 @ The |tag| field in a |char_info_word| has four values that explain how to
23963 interpret the |remainder| field.
23964
23965 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23966 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23967 program starting at location |remainder| in the |lig_kern| array.\par
23968 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23969 characters of ascending sizes, and not the largest in the chain.  The
23970 |remainder| field gives the character code of the next larger character.\par
23971 \hang|tag=3| (|ext_tag|) means that this character code represents an
23972 extensible character, i.e., a character that is built up of smaller pieces
23973 so that it can be made arbitrarily large. The pieces are specified in
23974 |exten[remainder]|.\par
23975 \yskip\noindent
23976 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23977 unless they are used in special circumstances in math formulas. For example,
23978 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23979 operation looks for both |list_tag| and |ext_tag|.
23980
23981 @d no_tag 0 /* vanilla character */
23982 @d lig_tag 1 /* character has a ligature/kerning program */
23983 @d list_tag 2 /* character has a successor in a charlist */
23984 @d ext_tag 3 /* character is extensible */
23985
23986 @ The |lig_kern| array contains instructions in a simple programming language
23987 that explains what to do for special letter pairs. Each word in this array is a
23988 |lig_kern_command| of four bytes.
23989
23990 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23991   step if the byte is 128 or more, otherwise the next step is obtained by
23992   skipping this number of intervening steps.\par
23993 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23994   then perform the operation and stop, otherwise continue.''\par
23995 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23996   a kern step otherwise.\par
23997 \hang fourth byte: |remainder|.\par
23998 \yskip\noindent
23999 In a kern step, an
24000 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
24001 between the current character and |next_char|. This amount is
24002 often negative, so that the characters are brought closer together
24003 by kerning; but it might be positive.
24004
24005 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
24006 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
24007 |remainder| is inserted between the current character and |next_char|;
24008 then the current character is deleted if $b=0$, and |next_char| is
24009 deleted if $c=0$; then we pass over $a$~characters to reach the next
24010 current character (which may have a ligature/kerning program of its own).
24011
24012 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
24013 the |next_char| byte is the so-called right boundary character of this font;
24014 the value of |next_char| need not lie between |bc| and~|ec|.
24015 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
24016 there is a special ligature/kerning program for a left boundary character,
24017 beginning at location |256*op_byte+remainder|.
24018 The interpretation is that \TeX\ puts implicit boundary characters
24019 before and after each consecutive string of characters from the same font.
24020 These implicit characters do not appear in the output, but they can affect
24021 ligatures and kerning.
24022
24023 If the very first instruction of a character's |lig_kern| program has
24024 |skip_byte>128|, the program actually begins in location
24025 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
24026 arrays, because the first instruction must otherwise
24027 appear in a location |<=255|.
24028
24029 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
24030 the condition
24031 $$\hbox{|256*op_byte+remainder<nl|.}$$
24032 If such an instruction is encountered during
24033 normal program execution, it denotes an unconditional halt; no ligature
24034 command is performed.
24035
24036 @d stop_flag (128)
24037   /* value indicating `\.{STOP}' in a lig/kern program */
24038 @d kern_flag (128) /* op code for a kern step */
24039 @d skip_byte(A) mp->lig_kern[(A)].b0
24040 @d next_char(A) mp->lig_kern[(A)].b1
24041 @d op_byte(A) mp->lig_kern[(A)].b2
24042 @d rem_byte(A) mp->lig_kern[(A)].b3
24043
24044 @ Extensible characters are specified by an |extensible_recipe|, which
24045 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
24046 order). These bytes are the character codes of individual pieces used to
24047 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
24048 present in the built-up result. For example, an extensible vertical line is
24049 like an extensible bracket, except that the top and bottom pieces are missing.
24050
24051 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
24052 if the piece isn't present. Then the extensible characters have the form
24053 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
24054 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
24055 The width of the extensible character is the width of $R$; and the
24056 height-plus-depth is the sum of the individual height-plus-depths of the
24057 components used, since the pieces are butted together in a vertical list.
24058
24059 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
24060 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
24061 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
24062 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
24063
24064 @ The final portion of a \.{TFM} file is the |param| array, which is another
24065 sequence of |fix_word| values.
24066
24067 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
24068 to help position accents. For example, |slant=.25| means that when you go
24069 up one unit, you also go .25 units to the right. The |slant| is a pure
24070 number; it is the only |fix_word| other than the design size itself that is
24071 not scaled by the design size.
24072 @^design size@>
24073
24074 \hang|param[2]=space| is the normal spacing between words in text.
24075 Note that character 040 in the font need not have anything to do with
24076 blank spaces.
24077
24078 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
24079
24080 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
24081
24082 \hang|param[5]=x_height| is the size of one ex in the font; it is also
24083 the height of letters for which accents don't have to be raised or lowered.
24084
24085 \hang|param[6]=quad| is the size of one em in the font.
24086
24087 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
24088 ends of sentences.
24089
24090 \yskip\noindent
24091 If fewer than seven parameters are present, \TeX\ sets the missing parameters
24092 to zero.
24093
24094 @d slant_code 1
24095 @d space_code 2
24096 @d space_stretch_code 3
24097 @d space_shrink_code 4
24098 @d x_height_code 5
24099 @d quad_code 6
24100 @d extra_space_code 7
24101
24102 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
24103 information, and it does this all at once at the end of a job.
24104 In order to prepare for such frenetic activity, it squirrels away the
24105 necessary facts in various arrays as information becomes available.
24106
24107 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
24108 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
24109 |tfm_ital_corr|. Other information about a character (e.g., about
24110 its ligatures or successors) is accessible via the |char_tag| and
24111 |char_remainder| arrays. Other information about the font as a whole
24112 is kept in additional arrays called |header_byte|, |lig_kern|,
24113 |kern|, |exten|, and |param|.
24114
24115 @d max_tfm_int 32510
24116 @d undefined_label max_tfm_int /* an undefined local label */
24117
24118 @<Glob...@>=
24119 #define TFM_ITEMS 257
24120 eight_bits bc;
24121 eight_bits ec; /* smallest and largest character codes shipped out */
24122 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
24123 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
24124 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
24125 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
24126 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
24127 int char_tag[TFM_ITEMS]; /* |remainder| category */
24128 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
24129 char *header_byte; /* bytes of the \.{TFM} header */
24130 int header_last; /* last initialized \.{TFM} header byte */
24131 int header_size; /* size of the \.{TFM} header */
24132 four_quarters *lig_kern; /* the ligature/kern table */
24133 short nl; /* the number of ligature/kern steps so far */
24134 scaled *kern; /* distinct kerning amounts */
24135 short nk; /* the number of distinct kerns so far */
24136 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
24137 short ne; /* the number of extensible characters so far */
24138 scaled *param; /* \&{fontinfo} parameters */
24139 short np; /* the largest \&{fontinfo} parameter specified so far */
24140 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
24141 short skip_table[TFM_ITEMS]; /* local label status */
24142 boolean lk_started; /* has there been a lig/kern step in this command yet? */
24143 integer bchar; /* right boundary character */
24144 short bch_label; /* left boundary starting location */
24145 short ll;short lll; /* registers used for lig/kern processing */
24146 short label_loc[257]; /* lig/kern starting addresses */
24147 eight_bits label_char[257]; /* characters for |label_loc| */
24148 short label_ptr; /* highest position occupied in |label_loc| */
24149
24150 @ @<Allocate or initialize ...@>=
24151 mp->header_size = 128; /* just for init */
24152 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
24153
24154 @ @<Dealloc variables@>=
24155 xfree(mp->header_byte);
24156 xfree(mp->lig_kern);
24157 xfree(mp->kern);
24158 xfree(mp->param);
24159
24160 @ @<Set init...@>=
24161 for (k=0;k<= 255;k++ ) {
24162   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
24163   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
24164   mp->skip_table[k]=undefined_label;
24165 }
24166 memset(mp->header_byte,0,(size_t)mp->header_size);
24167 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
24168 mp->internal[mp_boundary_char]=-unity;
24169 mp->bch_label=undefined_label;
24170 mp->label_loc[0]=-1; mp->label_ptr=0;
24171
24172 @ @<Declarations@>=
24173 static scaled mp_tfm_check (MP mp,quarterword m) ;
24174
24175 @ @c
24176 static scaled mp_tfm_check (MP mp,quarterword m) {
24177   if ( abs(mp->internal[m])>=fraction_half ) {
24178     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
24179 @.Enormous charwd...@>
24180 @.Enormous chardp...@>
24181 @.Enormous charht...@>
24182 @.Enormous charic...@>
24183 @.Enormous designsize...@>
24184     mp_print(mp, " has been reduced");
24185     help1("Font metric dimensions must be less than 2048pt.");
24186     mp_put_get_error(mp);
24187     if ( mp->internal[m]>0 ) return (fraction_half-1);
24188     else return (1-fraction_half);
24189   } else {
24190     return mp->internal[m];
24191   }
24192 }
24193
24194 @ @<Store the width information for character code~|c|@>=
24195 if ( c<mp->bc ) mp->bc=(eight_bits)c;
24196 if ( c>mp->ec ) mp->ec=(eight_bits)c;
24197 mp->char_exists[c]=true;
24198 mp->tfm_width[c]=mp_tfm_check(mp,mp_char_wd);
24199 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
24200 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
24201 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
24202
24203 @ Now let's consider \MP's special \.{TFM}-oriented commands.
24204
24205 @<Cases of |do_statement|...@>=
24206 case tfm_command: mp_do_tfm_command(mp); break;
24207
24208 @ @d char_list_code 0
24209 @d lig_table_code 1
24210 @d extensible_code 2
24211 @d header_byte_code 3
24212 @d font_dimen_code 4
24213
24214 @<Put each...@>=
24215 mp_primitive(mp, "charlist",tfm_command,char_list_code);
24216 @:char_list_}{\&{charlist} primitive@>
24217 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
24218 @:lig_table_}{\&{ligtable} primitive@>
24219 mp_primitive(mp, "extensible",tfm_command,extensible_code);
24220 @:extensible_}{\&{extensible} primitive@>
24221 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
24222 @:header_byte_}{\&{headerbyte} primitive@>
24223 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
24224 @:font_dimen_}{\&{fontdimen} primitive@>
24225
24226 @ @<Cases of |print_cmd...@>=
24227 case tfm_command: 
24228   switch (m) {
24229   case char_list_code:mp_print(mp, "charlist"); break;
24230   case lig_table_code:mp_print(mp, "ligtable"); break;
24231   case extensible_code:mp_print(mp, "extensible"); break;
24232   case header_byte_code:mp_print(mp, "headerbyte"); break;
24233   default: mp_print(mp, "fontdimen"); break;
24234   }
24235   break;
24236
24237 @ @<Declare action procedures for use by |do_statement|@>=
24238 static eight_bits mp_get_code (MP mp) ;
24239
24240 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
24241   integer c; /* the code value found */
24242   mp_get_x_next(mp); mp_scan_expression(mp);
24243   if ( mp->cur_type==mp_known ) { 
24244     c=mp_round_unscaled(mp, mp->cur_exp);
24245     if ( c>=0 ) if ( c<256 ) return (eight_bits)c;
24246   } else if ( mp->cur_type==mp_string_type ) {
24247     if ( length(mp->cur_exp)==1 )  { 
24248       c=mp->str_pool[mp->str_start[mp->cur_exp]];
24249       return (eight_bits)c;
24250     }
24251   }
24252   exp_err("Invalid code has been replaced by 0");
24253 @.Invalid code...@>
24254   help2("I was looking for a number between 0 and 255, or for a",
24255         "string of length 1. Didn't find it; will use 0 instead.");
24256   mp_put_get_flush_error(mp, 0); c=0;
24257   return (eight_bits)c;
24258 }
24259
24260 @ @<Declare action procedures for use by |do_statement|@>=
24261 static void mp_set_tag (MP mp,halfword c, quarterword t, halfword r) ;
24262
24263 @ @c void mp_set_tag (MP mp,halfword c, quarterword t, halfword r) { 
24264   if ( mp->char_tag[c]==no_tag ) {
24265     mp->char_tag[c]=t; mp->char_remainder[c]=r;
24266     if ( t==lig_tag ){ 
24267       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
24268       mp->label_char[mp->label_ptr]=(eight_bits)c;
24269     }
24270   } else {
24271     @<Complain about a character tag conflict@>;
24272   }
24273 }
24274
24275 @ @<Complain about a character tag conflict@>=
24276
24277   print_err("Character ");
24278   if ( (c>' ')&&(c<127) ) mp_print_char(mp,xord(c));
24279   else if ( c==256 ) mp_print(mp, "||");
24280   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
24281   mp_print(mp, " is already ");
24282 @.Character c is already...@>
24283   switch (mp->char_tag[c]) {
24284   case lig_tag: mp_print(mp, "in a ligtable"); break;
24285   case list_tag: mp_print(mp, "in a charlist"); break;
24286   case ext_tag: mp_print(mp, "extensible"); break;
24287   } /* there are no other cases */
24288   help2("It's not legal to label a character more than once.",
24289         "So I'll not change anything just now.");
24290   mp_put_get_error(mp); 
24291 }
24292
24293 @ @<Declare action procedures for use by |do_statement|@>=
24294 static void mp_do_tfm_command (MP mp) ;
24295
24296 @ @c void mp_do_tfm_command (MP mp) {
24297   int c,cc; /* character codes */
24298   int k; /* index into the |kern| array */
24299   int j; /* index into |header_byte| or |param| */
24300   switch (mp->cur_mod) {
24301   case char_list_code: 
24302     c=mp_get_code(mp);
24303      /* we will store a list of character successors */
24304     while ( mp->cur_cmd==colon )   { 
24305       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
24306     };
24307     break;
24308   case lig_table_code: 
24309     if (mp->lig_kern==NULL) 
24310        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
24311     if (mp->kern==NULL) 
24312        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
24313     @<Store a list of ligature/kern steps@>;
24314     break;
24315   case extensible_code: 
24316     @<Define an extensible recipe@>;
24317     break;
24318   case header_byte_code: 
24319   case font_dimen_code: 
24320     c=mp->cur_mod; mp_get_x_next(mp);
24321     mp_scan_expression(mp);
24322     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
24323       exp_err("Improper location");
24324 @.Improper location@>
24325       help2("I was looking for a known, positive number.",
24326             "For safety's sake I'll ignore the present command.");
24327       mp_put_get_error(mp);
24328     } else  { 
24329       j=mp_round_unscaled(mp, mp->cur_exp);
24330       if ( mp->cur_cmd!=colon ) {
24331         mp_missing_err(mp, ":");
24332 @.Missing `:'@>
24333         help1("A colon should follow a headerbyte or fontinfo location.");
24334         mp_back_error(mp);
24335       }
24336       if ( c==header_byte_code ) { 
24337         @<Store a list of header bytes@>;
24338       } else {     
24339         if (mp->param==NULL) 
24340           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
24341         @<Store a list of font dimensions@>;
24342       }
24343     }
24344     break;
24345   } /* there are no other cases */
24346 }
24347
24348 @ @<Store a list of ligature/kern steps@>=
24349
24350   mp->lk_started=false;
24351 CONTINUE: 
24352   mp_get_x_next(mp);
24353   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
24354     @<Process a |skip_to| command and |goto done|@>;
24355   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
24356   else { mp_back_input(mp); c=mp_get_code(mp); };
24357   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
24358     @<Record a label in a lig/kern subprogram and |goto continue|@>;
24359   }
24360   if ( mp->cur_cmd==lig_kern_token ) { 
24361     @<Compile a ligature/kern command@>; 
24362   } else  { 
24363     print_err("Illegal ligtable step");
24364 @.Illegal ligtable step@>
24365     help1("I was looking for `=:' or `kern' here.");
24366     mp_back_error(mp); next_char(mp->nl)=qi(0); 
24367     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
24368     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
24369   }
24370   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
24371   incr(mp->nl);
24372   if ( mp->cur_cmd==comma ) goto CONTINUE;
24373   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
24374 }
24375 DONE:
24376
24377 @ @<Put each...@>=
24378 mp_primitive(mp, "=:",lig_kern_token,0);
24379 @:=:_}{\.{=:} primitive@>
24380 mp_primitive(mp, "=:|",lig_kern_token,1);
24381 @:=:/_}{\.{=:\char'174} primitive@>
24382 mp_primitive(mp, "=:|>",lig_kern_token,5);
24383 @:=:/>_}{\.{=:\char'174>} primitive@>
24384 mp_primitive(mp, "|=:",lig_kern_token,2);
24385 @:=:/_}{\.{\char'174=:} primitive@>
24386 mp_primitive(mp, "|=:>",lig_kern_token,6);
24387 @:=:/>_}{\.{\char'174=:>} primitive@>
24388 mp_primitive(mp, "|=:|",lig_kern_token,3);
24389 @:=:/_}{\.{\char'174=:\char'174} primitive@>
24390 mp_primitive(mp, "|=:|>",lig_kern_token,7);
24391 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
24392 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
24393 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
24394 mp_primitive(mp, "kern",lig_kern_token,128);
24395 @:kern_}{\&{kern} primitive@>
24396
24397 @ @<Cases of |print_cmd...@>=
24398 case lig_kern_token: 
24399   switch (m) {
24400   case 0:mp_print(mp, "=:"); break;
24401   case 1:mp_print(mp, "=:|"); break;
24402   case 2:mp_print(mp, "|=:"); break;
24403   case 3:mp_print(mp, "|=:|"); break;
24404   case 5:mp_print(mp, "=:|>"); break;
24405   case 6:mp_print(mp, "|=:>"); break;
24406   case 7:mp_print(mp, "|=:|>"); break;
24407   case 11:mp_print(mp, "|=:|>>"); break;
24408   default: mp_print(mp, "kern"); break;
24409   }
24410   break;
24411
24412 @ Local labels are implemented by maintaining the |skip_table| array,
24413 where |skip_table[c]| is either |undefined_label| or the address of the
24414 most recent lig/kern instruction that skips to local label~|c|. In the
24415 latter case, the |skip_byte| in that instruction will (temporarily)
24416 be zero if there were no prior skips to this label, or it will be the
24417 distance to the prior skip.
24418
24419 We may need to cancel skips that span more than 127 lig/kern steps.
24420
24421 @d cancel_skips(A) mp->ll=(A);
24422   do {  
24423     mp->lll=qo(skip_byte(mp->ll)); 
24424     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
24425   } while (mp->lll!=0)
24426 @d skip_error(A) { print_err("Too far to skip");
24427 @.Too far to skip@>
24428   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
24429   mp_error(mp); cancel_skips((A));
24430   }
24431
24432 @<Process a |skip_to| command and |goto done|@>=
24433
24434   c=mp_get_code(mp);
24435   if ( mp->nl-mp->skip_table[c]>128 ) {
24436     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
24437   }
24438   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
24439   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
24440   mp->skip_table[c]=mp->nl-1; goto DONE;
24441 }
24442
24443 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
24444
24445   if ( mp->cur_cmd==colon ) {
24446     if ( c==256 ) mp->bch_label=mp->nl;
24447     else mp_set_tag(mp, c,lig_tag,mp->nl);
24448   } else if ( mp->skip_table[c]<undefined_label ) {
24449     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
24450     do {  
24451       mp->lll=qo(skip_byte(mp->ll));
24452       if ( mp->nl-mp->ll>128 ) {
24453         skip_error(mp->ll); goto CONTINUE;
24454       }
24455       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
24456     } while (mp->lll!=0);
24457   }
24458   goto CONTINUE;
24459 }
24460
24461 @ @<Compile a ligature/kern...@>=
24462
24463   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
24464   if ( mp->cur_mod<128 ) { /* ligature op */
24465     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
24466   } else { 
24467     mp_get_x_next(mp); mp_scan_expression(mp);
24468     if ( mp->cur_type!=mp_known ) {
24469       exp_err("Improper kern");
24470 @.Improper kern@>
24471       help2("The amount of kern should be a known numeric value.",
24472             "I'm zeroing this one. Proceed, with fingers crossed.");
24473       mp_put_get_flush_error(mp, 0);
24474     }
24475     mp->kern[mp->nk]=mp->cur_exp;
24476     k=0; 
24477     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
24478     if ( k==mp->nk ) {
24479       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
24480       incr(mp->nk);
24481     }
24482     op_byte(mp->nl)=kern_flag+(k / 256);
24483     rem_byte(mp->nl)=qi((k % 256));
24484   }
24485   mp->lk_started=true;
24486 }
24487
24488 @ @d missing_extensible_punctuation(A) 
24489   { mp_missing_err(mp, (A));
24490 @.Missing `\char`\#'@>
24491   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
24492   }
24493
24494 @<Define an extensible recipe@>=
24495
24496   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
24497   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
24498   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
24499   ext_top(mp->ne)=qi(mp_get_code(mp));
24500   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24501   ext_mid(mp->ne)=qi(mp_get_code(mp));
24502   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24503   ext_bot(mp->ne)=qi(mp_get_code(mp));
24504   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24505   ext_rep(mp->ne)=qi(mp_get_code(mp));
24506   incr(mp->ne);
24507 }
24508
24509 @ The header could contain ASCII zeroes, so can't use |strdup|.
24510
24511 @<Store a list of header bytes@>=
24512 do {  
24513   if ( j>=mp->header_size ) {
24514     size_t l = (size_t)(mp->header_size + (mp->header_size/4));
24515     char *t = xmalloc(l,1);
24516     memset(t,0,l); 
24517     memcpy(t,mp->header_byte,(size_t)mp->header_size);
24518     xfree (mp->header_byte);
24519     mp->header_byte = t;
24520     mp->header_size = (int)l;
24521   }
24522   mp->header_byte[j]=(char)mp_get_code(mp); 
24523   incr(j); incr(mp->header_last);
24524 } while (mp->cur_cmd==comma)
24525
24526 @ @<Store a list of font dimensions@>=
24527 do {  
24528   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
24529   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
24530   mp_get_x_next(mp); mp_scan_expression(mp);
24531   if ( mp->cur_type!=mp_known ){ 
24532     exp_err("Improper font parameter");
24533 @.Improper font parameter@>
24534     help1("I'm zeroing this one. Proceed, with fingers crossed.");
24535     mp_put_get_flush_error(mp, 0);
24536   }
24537   mp->param[j]=mp->cur_exp; incr(j);
24538 } while (mp->cur_cmd==comma)
24539
24540 @ OK: We've stored all the data that is needed for the \.{TFM} file.
24541 All that remains is to output it in the correct format.
24542
24543 An interesting problem needs to be solved in this connection, because
24544 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
24545 and 64~italic corrections. If the data has more distinct values than
24546 this, we want to meet the necessary restrictions by perturbing the
24547 given values as little as possible.
24548
24549 \MP\ solves this problem in two steps. First the values of a given
24550 kind (widths, heights, depths, or italic corrections) are sorted;
24551 then the list of sorted values is perturbed, if necessary.
24552
24553 The sorting operation is facilitated by having a special node of
24554 essentially infinite |value| at the end of the current list.
24555
24556 @<Initialize table entries...@>=
24557 value(inf_val)=fraction_four;
24558
24559 @ Straight linear insertion is good enough for sorting, since the lists
24560 are usually not terribly long. As we work on the data, the current list
24561 will start at |mp_link(temp_head)| and end at |inf_val|; the nodes in this
24562 list will be in increasing order of their |value| fields.
24563
24564 Given such a list, the |sort_in| function takes a value and returns a pointer
24565 to where that value can be found in the list. The value is inserted in
24566 the proper place, if necessary.
24567
24568 At the time we need to do these operations, most of \MP's work has been
24569 completed, so we will have plenty of memory to play with. The value nodes
24570 that are allocated for sorting will never be returned to free storage.
24571
24572 @d clear_the_list mp_link(temp_head)=inf_val
24573
24574 @c 
24575 static pointer mp_sort_in (MP mp,scaled v) {
24576   pointer p,q,r; /* list manipulation registers */
24577   p=temp_head;
24578   while (1) { 
24579     q=mp_link(p);
24580     if ( v<=value(q) ) break;
24581     p=q;
24582   }
24583   if ( v<value(q) ) {
24584     r=mp_get_node(mp, value_node_size); value(r)=v; mp_link(r)=q; mp_link(p)=r;
24585   }
24586   return mp_link(p);
24587 }
24588
24589 @ Now we come to the interesting part, where we reduce the list if necessary
24590 until it has the required size. The |min_cover| routine is basic to this
24591 process; it computes the minimum number~|m| such that the values of the
24592 current sorted list can be covered by |m|~intervals of width~|d|. It
24593 also sets the global value |perturbation| to the smallest value $d'>d$
24594 such that the covering found by this algorithm would be different.
24595
24596 In particular, |min_cover(0)| returns the number of distinct values in the
24597 current list and sets |perturbation| to the minimum distance between
24598 adjacent values.
24599
24600 @c 
24601 static integer mp_min_cover (MP mp,scaled d) {
24602   pointer p; /* runs through the current list */
24603   scaled l; /* the least element covered by the current interval */
24604   integer m; /* lower bound on the size of the minimum cover */
24605   m=0; p=mp_link(temp_head); mp->perturbation=el_gordo;
24606   while ( p!=inf_val ){ 
24607     incr(m); l=value(p);
24608     do {  p=mp_link(p); } while (value(p)<=l+d);
24609     if ( value(p)-l<mp->perturbation ) 
24610       mp->perturbation=value(p)-l;
24611   }
24612   return m;
24613 }
24614
24615 @ @<Glob...@>=
24616 scaled perturbation; /* quantity related to \.{TFM} rounding */
24617 integer excess; /* the list is this much too long */
24618
24619 @ The smallest |d| such that a given list can be covered with |m| intervals
24620 is determined by the |threshold| routine, which is sort of an inverse
24621 to |min_cover|. The idea is to increase the interval size rapidly until
24622 finding the range, then to go sequentially until the exact borderline has
24623 been discovered.
24624
24625 @c 
24626 static scaled mp_threshold (MP mp,integer m) {
24627   scaled d; /* lower bound on the smallest interval size */
24628   mp->excess=mp_min_cover(mp, 0)-m;
24629   if ( mp->excess<=0 ) {
24630     return 0;
24631   } else  { 
24632     do {  
24633       d=mp->perturbation;
24634     } while (mp_min_cover(mp, d+d)>m);
24635     while ( mp_min_cover(mp, d)>m ) 
24636       d=mp->perturbation;
24637     return d;
24638   }
24639 }
24640
24641 @ The |skimp| procedure reduces the current list to at most |m| entries,
24642 by changing values if necessary. It also sets |info(p):=k| if |value(p)|
24643 is the |k|th distinct value on the resulting list, and it sets
24644 |perturbation| to the maximum amount by which a |value| field has
24645 been changed. The size of the resulting list is returned as the
24646 value of |skimp|.
24647
24648 @c 
24649 static integer mp_skimp (MP mp,integer m) {
24650   scaled d; /* the size of intervals being coalesced */
24651   pointer p,q,r; /* list manipulation registers */
24652   scaled l; /* the least value in the current interval */
24653   scaled v; /* a compromise value */
24654   d=mp_threshold(mp, m); mp->perturbation=0;
24655   q=temp_head; m=0; p=mp_link(temp_head);
24656   while ( p!=inf_val ) {
24657     incr(m); l=value(p); info(p)=m;
24658     if ( value(mp_link(p))<=l+d ) {
24659       @<Replace an interval of values by its midpoint@>;
24660     }
24661     q=p; p=mp_link(p);
24662   }
24663   return m;
24664 }
24665
24666 @ @<Replace an interval...@>=
24667
24668   do {  
24669     p=mp_link(p); info(p)=m;
24670     decr(mp->excess); if ( mp->excess==0 ) d=0;
24671   } while (value(mp_link(p))<=l+d);
24672   v=l+halfp(value(p)-l);
24673   if ( value(p)-v>mp->perturbation ) 
24674     mp->perturbation=value(p)-v;
24675   r=q;
24676   do {  
24677     r=mp_link(r); value(r)=v;
24678   } while (r!=p);
24679   mp_link(q)=p; /* remove duplicate values from the current list */
24680 }
24681
24682 @ A warning message is issued whenever something is perturbed by
24683 more than 1/16\thinspace pt.
24684
24685 @c 
24686 static void mp_tfm_warning (MP mp,quarterword m) { 
24687   mp_print_nl(mp, "(some "); 
24688   mp_print(mp, mp->int_name[m]);
24689 @.some charwds...@>
24690 @.some chardps...@>
24691 @.some charhts...@>
24692 @.some charics...@>
24693   mp_print(mp, " values had to be adjusted by as much as ");
24694   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24695 }
24696
24697 @ Here's an example of how we use these routines.
24698 The width data needs to be perturbed only if there are 256 distinct
24699 widths, but \MP\ must check for this case even though it is
24700 highly unusual.
24701
24702 An integer variable |k| will be defined when we use this code.
24703 The |dimen_head| array will contain pointers to the sorted
24704 lists of dimensions.
24705
24706 @<Massage the \.{TFM} widths@>=
24707 clear_the_list;
24708 for (k=mp->bc;k<=mp->ec;k++)  {
24709   if ( mp->char_exists[k] )
24710     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24711 }
24712 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=mp_link(temp_head);
24713 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24714
24715 @ @<Glob...@>=
24716 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24717
24718 @ Heights, depths, and italic corrections are different from widths
24719 not only because their list length is more severely restricted, but
24720 also because zero values do not need to be put into the lists.
24721
24722 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24723 clear_the_list;
24724 for (k=mp->bc;k<=mp->ec;k++) {
24725   if ( mp->char_exists[k] ) {
24726     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24727     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24728   }
24729 }
24730 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=mp_link(temp_head);
24731 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24732 clear_the_list;
24733 for (k=mp->bc;k<=mp->ec;k++) {
24734   if ( mp->char_exists[k] ) {
24735     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24736     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24737   }
24738 }
24739 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=mp_link(temp_head);
24740 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24741 clear_the_list;
24742 for (k=mp->bc;k<=mp->ec;k++) {
24743   if ( mp->char_exists[k] ) {
24744     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24745     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24746   }
24747 }
24748 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=mp_link(temp_head);
24749 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24750
24751 @ @<Initialize table entries...@>=
24752 value(zero_val)=0; info(zero_val)=0;
24753
24754 @ Bytes 5--8 of the header are set to the design size, unless the user has
24755 some crazy reason for specifying them differently.
24756 @^design size@>
24757
24758 Error messages are not allowed at the time this procedure is called,
24759 so a warning is printed instead.
24760
24761 The value of |max_tfm_dimen| is calculated so that
24762 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24763  < \\{three\_bytes}.$$
24764
24765 @d three_bytes 0100000000 /* $2^{24}$ */
24766
24767 @c 
24768 static void mp_fix_design_size (MP mp) {
24769   scaled d; /* the design size */
24770   d=mp->internal[mp_design_size];
24771   if ( (d<unity)||(d>=fraction_half) ) {
24772     if ( d!=0 )
24773       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24774 @.illegal design size...@>
24775     d=040000000; mp->internal[mp_design_size]=d;
24776   }
24777   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24778     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24779      mp->header_byte[4]=d / 04000000;
24780      mp->header_byte[5]=(d / 4096) % 256;
24781      mp->header_byte[6]=(d / 16) % 256;
24782      mp->header_byte[7]=(d % 16)*16;
24783   };
24784   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-1-mp->internal[mp_design_size] / 010000000;
24785   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24786 }
24787
24788 @ The |dimen_out| procedure computes a |fix_word| relative to the
24789 design size. If the data was out of range, it is corrected and the
24790 global variable |tfm_changed| is increased by~one.
24791
24792 @c 
24793 static integer mp_dimen_out (MP mp,scaled x) { 
24794   if ( abs(x)>mp->max_tfm_dimen ) {
24795     incr(mp->tfm_changed);
24796     if ( x>0 ) x=mp->max_tfm_dimen; else x=-mp->max_tfm_dimen;
24797   }
24798   x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24799   return x;
24800 }
24801
24802 @ @<Glob...@>=
24803 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24804 integer tfm_changed; /* the number of data entries that were out of bounds */
24805
24806 @ If the user has not specified any of the first four header bytes,
24807 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24808 from the |tfm_width| data relative to the design size.
24809 @^check sum@>
24810
24811 @c 
24812 static void mp_fix_check_sum (MP mp) {
24813   eight_bits k; /* runs through character codes */
24814   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24815   integer x;  /* hash value used in check sum computation */
24816   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24817        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24818     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24819     mp->header_byte[0]=(char)B1; mp->header_byte[1]=(char)B2;
24820     mp->header_byte[2]=(char)B3; mp->header_byte[3]=(char)B4; 
24821     return;
24822   }
24823 }
24824
24825 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24826 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24827 for (k=mp->bc;k<=mp->ec;k++) { 
24828   if ( mp->char_exists[k] ) {
24829     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24830     B1=(eight_bits)((B1+B1+x) % 255);
24831     B2=(eight_bits)((B2+B2+x) % 253);
24832     B3=(eight_bits)((B3+B3+x) % 251);
24833     B4=(eight_bits)((B4+B4+x) % 247);
24834   }
24835 }
24836
24837 @ Finally we're ready to actually write the \.{TFM} information.
24838 Here are some utility routines for this purpose.
24839
24840 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24841   unsigned char s=(unsigned char)(A); 
24842   (mp->write_binary_file)(mp,mp->tfm_file,(void *)&s,1); 
24843   } while (0)
24844
24845 @c 
24846 static void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24847   tfm_out(x / 256); tfm_out(x % 256);
24848 }
24849 static void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24850   if ( x>=0 ) tfm_out(x / three_bytes);
24851   else { 
24852     x=x+010000000000; /* use two's complement for negative values */
24853     x=x+010000000000;
24854     tfm_out((x / three_bytes) + 128);
24855   };
24856   x=x % three_bytes; tfm_out(x / unity);
24857   x=x % unity; tfm_out(x / 0400);
24858   tfm_out(x % 0400);
24859 }
24860 static void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24861   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24862   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24863 }
24864
24865 @ @<Finish the \.{TFM} file@>=
24866 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24867 mp_pack_job_name(mp, ".tfm");
24868 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24869   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24870 mp->metric_file_name=xstrdup(mp->name_of_file);
24871 @<Output the subfile sizes and header bytes@>;
24872 @<Output the character information bytes, then
24873   output the dimensions themselves@>;
24874 @<Output the ligature/kern program@>;
24875 @<Output the extensible character recipes and the font metric parameters@>;
24876   if ( mp->internal[mp_tracing_stats]>0 )
24877   @<Log the subfile sizes of the \.{TFM} file@>;
24878 mp_print_nl(mp, "Font metrics written on "); 
24879 mp_print(mp, mp->metric_file_name); mp_print_char(mp, xord('.'));
24880 @.Font metrics written...@>
24881 (mp->close_file)(mp,mp->tfm_file)
24882
24883 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24884 this code.
24885
24886 @<Output the subfile sizes and header bytes@>=
24887 k=mp->header_last;
24888 LH=(k+3) / 4; /* this is the number of header words */
24889 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24890 @<Compute the ligature/kern program offset and implant the
24891   left boundary label@>;
24892 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24893      +lk_offset+mp->nk+mp->ne+mp->np);
24894   /* this is the total number of file words that will be output */
24895 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24896 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24897 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24898 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24899 mp_tfm_two(mp, mp->np);
24900 for (k=0;k< 4*LH;k++)   { 
24901   tfm_out(mp->header_byte[k]);
24902 }
24903
24904 @ @<Output the character information bytes...@>=
24905 for (k=mp->bc;k<=mp->ec;k++) {
24906   if ( ! mp->char_exists[k] ) {
24907     mp_tfm_four(mp, 0);
24908   } else { 
24909     tfm_out(info(mp->tfm_width[k])); /* the width index */
24910     tfm_out((info(mp->tfm_height[k]))*16+info(mp->tfm_depth[k]));
24911     tfm_out((info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24912     tfm_out(mp->char_remainder[k]);
24913   };
24914 }
24915 mp->tfm_changed=0;
24916 for (k=1;k<=4;k++) { 
24917   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24918   while ( p!=inf_val ) {
24919     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=mp_link(p);
24920   }
24921 }
24922
24923
24924 @ We need to output special instructions at the beginning of the
24925 |lig_kern| array in order to specify the right boundary character
24926 and/or to handle starting addresses that exceed 255. The |label_loc|
24927 and |label_char| arrays have been set up to record all the
24928 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24929 \le|label_loc|[|label_ptr]|$.
24930
24931 @<Compute the ligature/kern program offset...@>=
24932 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24933 if ((mp->bchar<0)||(mp->bchar>255))
24934   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24935 else { mp->lk_started=true; lk_offset=1; };
24936 @<Find the minimum |lk_offset| and adjust all remainders@>;
24937 if ( mp->bch_label<undefined_label )
24938   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24939   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24940   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24941   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24942   }
24943
24944 @ @<Find the minimum |lk_offset|...@>=
24945 k=mp->label_ptr; /* pointer to the largest unallocated label */
24946 if ( mp->label_loc[k]+lk_offset>255 ) {
24947   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24948   do {  
24949     mp->char_remainder[mp->label_char[k]]=lk_offset;
24950     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24951        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24952     }
24953     incr(lk_offset); decr(k);
24954   } while (! (lk_offset+mp->label_loc[k]<256));
24955     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24956 }
24957 if ( lk_offset>0 ) {
24958   while ( k>0 ) {
24959     mp->char_remainder[mp->label_char[k]]
24960      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24961     decr(k);
24962   }
24963 }
24964
24965 @ @<Output the ligature/kern program@>=
24966 for (k=0;k<= 255;k++ ) {
24967   if ( mp->skip_table[k]<undefined_label ) {
24968      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24969 @.local label l:: was missing@>
24970     cancel_skips(mp->skip_table[k]);
24971   }
24972 }
24973 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24974   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24975 } else {
24976   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24977     mp->ll=mp->label_loc[mp->label_ptr];
24978     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24979     else { tfm_out(255); tfm_out(mp->bchar);   };
24980     mp_tfm_two(mp, mp->ll+lk_offset);
24981     do {  
24982       decr(mp->label_ptr);
24983     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24984   }
24985 }
24986 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24987 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24988
24989 @ @<Output the extensible character recipes...@>=
24990 for (k=0;k<=mp->ne-1;k++) 
24991   mp_tfm_qqqq(mp, mp->exten[k]);
24992 for (k=1;k<=mp->np;k++) {
24993   if ( k==1 ) {
24994     if ( abs(mp->param[1])<fraction_half ) {
24995       mp_tfm_four(mp, mp->param[1]*16);
24996     } else  { 
24997       incr(mp->tfm_changed);
24998       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24999       else mp_tfm_four(mp, -el_gordo);
25000     }
25001   } else {
25002     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
25003   }
25004 }
25005 if ( mp->tfm_changed>0 )  { 
25006   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
25007 @.a font metric dimension...@>
25008   else  { 
25009     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
25010 @.font metric dimensions...@>
25011     mp_print(mp, " font metric dimensions");
25012   }
25013   mp_print(mp, " had to be decreased)");
25014 }
25015
25016 @ @<Log the subfile sizes of the \.{TFM} file@>=
25017
25018   char s[200];
25019   wlog_ln(" ");
25020   if ( mp->bch_label<undefined_label ) decr(mp->nl);
25021   mp_snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
25022                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
25023   wlog_ln(s);
25024 }
25025
25026 @* \[43] Reading font metric data.
25027
25028 \MP\ isn't a typesetting program but it does need to find the bounding box
25029 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
25030 well as write them.
25031
25032 @<Glob...@>=
25033 void * tfm_infile;
25034
25035 @ All the width, height, and depth information is stored in an array called
25036 |font_info|.  This array is allocated sequentially and each font is stored
25037 as a series of |char_info| words followed by the width, height, and depth
25038 tables.  Since |font_name| entries are permanent, their |str_ref| values are
25039 set to |max_str_ref|.
25040
25041 @<Types...@>=
25042 typedef unsigned int font_number; /* |0..font_max| */
25043
25044 @ The |font_info| array is indexed via a group directory arrays.
25045 For example, the |char_info| data for character~|c| in font~|f| will be
25046 in |font_info[char_base[f]+c].qqqq|.
25047
25048 @<Glob...@>=
25049 font_number font_max; /* maximum font number for included text fonts */
25050 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
25051 memory_word *font_info; /* height, width, and depth data */
25052 char        **font_enc_name; /* encoding names, if any */
25053 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
25054 size_t      next_fmem; /* next unused entry in |font_info| */
25055 font_number last_fnum; /* last font number used so far */
25056 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
25057 char        **font_name;  /* name as specified in the \&{infont} command */
25058 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
25059 font_number last_ps_fnum; /* last valid |font_ps_name| index */
25060 eight_bits  *font_bc;
25061 eight_bits  *font_ec;  /* first and last character code */
25062 int         *char_base;  /* base address for |char_info| */
25063 int         *width_base; /* index for zeroth character width */
25064 int         *height_base; /* index for zeroth character height */
25065 int         *depth_base; /* index for zeroth character depth */
25066 pointer     *font_sizes;
25067
25068 @ @<Allocate or initialize ...@>=
25069 mp->font_mem_size = 10000; 
25070 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
25071 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
25072 mp->last_fnum = null_font;
25073
25074 @ @<Dealloc variables@>=
25075 for (k=1;k<=(int)mp->last_fnum;k++) {
25076   xfree(mp->font_enc_name[k]);
25077   xfree(mp->font_name[k]);
25078   xfree(mp->font_ps_name[k]);
25079 }
25080 xfree(mp->font_info);
25081 xfree(mp->font_enc_name);
25082 xfree(mp->font_ps_name_fixed);
25083 xfree(mp->font_dsize);
25084 xfree(mp->font_name);
25085 xfree(mp->font_ps_name);
25086 xfree(mp->font_bc);
25087 xfree(mp->font_ec);
25088 xfree(mp->char_base);
25089 xfree(mp->width_base);
25090 xfree(mp->height_base);
25091 xfree(mp->depth_base);
25092 xfree(mp->font_sizes);
25093
25094
25095 @c 
25096 void mp_reallocate_fonts (MP mp, font_number l) {
25097   font_number f;
25098   XREALLOC(mp->font_enc_name,      l, char *);
25099   XREALLOC(mp->font_ps_name_fixed, l, boolean);
25100   XREALLOC(mp->font_dsize,         l, scaled);
25101   XREALLOC(mp->font_name,          l, char *);
25102   XREALLOC(mp->font_ps_name,       l, char *);
25103   XREALLOC(mp->font_bc,            l, eight_bits);
25104   XREALLOC(mp->font_ec,            l, eight_bits);
25105   XREALLOC(mp->char_base,          l, int);
25106   XREALLOC(mp->width_base,         l, int);
25107   XREALLOC(mp->height_base,        l, int);
25108   XREALLOC(mp->depth_base,         l, int);
25109   XREALLOC(mp->font_sizes,         l, pointer);
25110   for (f=(mp->last_fnum+1);f<=l;f++) {
25111     mp->font_enc_name[f]=NULL;
25112     mp->font_ps_name_fixed[f] = false;
25113     mp->font_name[f]=NULL;
25114     mp->font_ps_name[f]=NULL;
25115     mp->font_sizes[f]=null;
25116   }
25117   mp->font_max = l;
25118 }
25119
25120 @ @<Internal library declarations@>=
25121 void mp_reallocate_fonts (MP mp, font_number l);
25122
25123
25124 @ A |null_font| containing no characters is useful for error recovery.  Its
25125 |font_name| entry starts out empty but is reset each time an erroneous font is
25126 found.  This helps to cut down on the number of duplicate error messages without
25127 wasting a lot of space.
25128
25129 @d null_font 0 /* the |font_number| for an empty font */
25130
25131 @<Set initial...@>=
25132 mp->font_dsize[null_font]=0;
25133 mp->font_bc[null_font]=1;
25134 mp->font_ec[null_font]=0;
25135 mp->char_base[null_font]=0;
25136 mp->width_base[null_font]=0;
25137 mp->height_base[null_font]=0;
25138 mp->depth_base[null_font]=0;
25139 mp->next_fmem=0;
25140 mp->last_fnum=null_font;
25141 mp->last_ps_fnum=null_font;
25142 mp->font_name[null_font]=(char *)"nullfont";
25143 mp->font_ps_name[null_font]=(char *)"";
25144 mp->font_ps_name_fixed[null_font] = false;
25145 mp->font_enc_name[null_font]=NULL;
25146 mp->font_sizes[null_font]=null;
25147
25148 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
25149 the |width index|; the |b1| field contains the height
25150 index; the |b2| fields contains the depth index, and the |b3| field used only
25151 for temporary storage. (It is used to keep track of which characters occur in
25152 an edge structure that is being shipped out.)
25153 The corresponding words in the width, height, and depth tables are stored as
25154 |scaled| values in units of \ps\ points.
25155
25156 With the macros below, the |char_info| word for character~|c| in font~|f| is
25157 |char_info(f,c)| and the width is
25158 $$\hbox{|char_width(f,char_info(f,c)).sc|.}$$
25159
25160 @d char_info(A,B) mp->font_info[mp->char_base[(A)]+(B)].qqqq
25161 @d char_width(A,B) mp->font_info[mp->width_base[(A)]+(B).b0].sc
25162 @d char_height(A,B) mp->font_info[mp->height_base[(A)]+(B).b1].sc
25163 @d char_depth(A,B) mp->font_info[mp->depth_base[(A)]+(B).b2].sc
25164 @d ichar_exists(A) ((A).b0>0)
25165
25166 @ When we have a font name and we don't know whether it has been loaded yet,
25167 we scan the |font_name| array before calling |read_font_info|.
25168
25169 @<Declarations@>=
25170 static font_number mp_find_font (MP mp, char *f) ;
25171
25172 @ @c
25173 font_number mp_find_font (MP mp, char *f) {
25174   font_number n;
25175   for (n=0;n<=mp->last_fnum;n++) {
25176     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
25177       mp_xfree(f);
25178       return n;
25179     }
25180   }
25181   n = mp_read_font_info(mp, f);
25182   mp_xfree(f);
25183   return n;
25184 }
25185
25186 @ This is an interface function for getting the width of character,
25187 as a double in ps units
25188
25189 @c double mp_get_char_dimension (MP mp, char *fname, int c, int t) {
25190   unsigned n;
25191   four_quarters cc;
25192   font_number f = 0;
25193   double w = -1.0;
25194   for (n=0;n<=mp->last_fnum;n++) {
25195     if (mp_xstrcmp(fname,mp->font_name[n])==0 ) {
25196       f = n;
25197       break;
25198     }
25199   }
25200   if (f==0)
25201     return 0.0;
25202   cc = char_info(f,c);
25203   if (! ichar_exists(cc) )
25204     return 0.0;
25205   if (t=='w')
25206     w = (double)char_width(f,cc);
25207   else if (t=='h')
25208     w = (double)char_height(f,cc);
25209   else if (t=='d')
25210     w = (double)char_depth(f,cc);
25211   return w/655.35*(72.27/72);
25212 }
25213
25214 @ @<Exported function ...@>=
25215 double mp_get_char_dimension (MP mp, char *fname, int n, int t);
25216
25217
25218 @ One simple application of |find_font| is the implementation of the |font_size|
25219 operator that gets the design size for a given font name.
25220
25221 @<Find the design size of the font whose name is |cur_exp|@>=
25222 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
25223
25224 @ If we discover that the font doesn't have a requested character, we omit it
25225 from the bounding box computation and expect the \ps\ interpreter to drop it.
25226 This routine issues a warning message if the user has asked for it.
25227
25228 @<Declarations@>=
25229 static void mp_lost_warning (MP mp,font_number f, pool_pointer k);
25230
25231 @ @c 
25232 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
25233   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
25234     mp_begin_diagnostic(mp);
25235     if ( mp->selector==log_only ) incr(mp->selector);
25236     mp_print_nl(mp, "Missing character: There is no ");
25237 @.Missing character@>
25238     mp_print_str(mp, mp->str_pool[k]); 
25239     mp_print(mp, " in font ");
25240     mp_print(mp, mp->font_name[f]); mp_print_char(mp, xord('!')); 
25241     mp_end_diagnostic(mp, false);
25242   }
25243 }
25244
25245 @ The whole purpose of saving the height, width, and depth information is to be
25246 able to find the bounding box of an item of text in an edge structure.  The
25247 |set_text_box| procedure takes a text node and adds this information.
25248
25249 @<Declarations@>=
25250 static void mp_set_text_box (MP mp,pointer p); 
25251
25252 @ @c 
25253 void mp_set_text_box (MP mp,pointer p) {
25254   font_number f; /* |font_n(p)| */
25255   ASCII_code bc,ec; /* range of valid characters for font |f| */
25256   pool_pointer k,kk; /* current character and character to stop at */
25257   four_quarters cc; /* the |char_info| for the current character */
25258   scaled h,d; /* dimensions of the current character */
25259   width_val(p)=0;
25260   height_val(p)=-el_gordo;
25261   depth_val(p)=-el_gordo;
25262   f=(font_number)font_n(p);
25263   bc=mp->font_bc[f];
25264   ec=mp->font_ec[f];
25265   kk=str_stop(text_p(p));
25266   k=mp->str_start[text_p(p)];
25267   while ( k<kk ) {
25268     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
25269   }
25270   @<Set the height and depth to zero if the bounding box is empty@>;
25271 }
25272
25273 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
25274
25275   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
25276     mp_lost_warning(mp, f,k);
25277   } else { 
25278     cc=char_info(f,mp->str_pool[k]);
25279     if ( ! ichar_exists(cc) ) {
25280       mp_lost_warning(mp, f,k);
25281     } else { 
25282       width_val(p)=width_val(p)+char_width(f,cc);
25283       h=char_height(f,cc);
25284       d=char_depth(f,cc);
25285       if ( h>height_val(p) ) height_val(p)=h;
25286       if ( d>depth_val(p) ) depth_val(p)=d;
25287     }
25288   }
25289   incr(k);
25290 }
25291
25292 @ Let's hope modern compilers do comparisons correctly when the difference would
25293 overflow.
25294
25295 @<Set the height and depth to zero if the bounding box is empty@>=
25296 if ( height_val(p)<-depth_val(p) ) { 
25297   height_val(p)=0;
25298   depth_val(p)=0;
25299 }
25300
25301 @ The new primitives fontmapfile and fontmapline.
25302
25303 @<Declare action procedures for use by |do_statement|@>=
25304 static void mp_do_mapfile (MP mp) ;
25305 static void mp_do_mapline (MP mp) ;
25306
25307 @ @c 
25308 static void mp_do_mapfile (MP mp) { 
25309   mp_get_x_next(mp); mp_scan_expression(mp);
25310   if ( mp->cur_type!=mp_string_type ) {
25311     @<Complain about improper map operation@>;
25312   } else {
25313     mp_map_file(mp,mp->cur_exp);
25314   }
25315 }
25316 static void mp_do_mapline (MP mp) { 
25317   mp_get_x_next(mp); mp_scan_expression(mp);
25318   if ( mp->cur_type!=mp_string_type ) {
25319      @<Complain about improper map operation@>;
25320   } else { 
25321      mp_map_line(mp,mp->cur_exp);
25322   }
25323 }
25324
25325 @ @<Complain about improper map operation@>=
25326
25327   exp_err("Unsuitable expression");
25328   help1("Only known strings can be map files or map lines.");
25329   mp_put_get_error(mp);
25330 }
25331
25332 @ To print |scaled| value to PDF output we need some subroutines to ensure
25333 accurary.
25334
25335 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
25336
25337 @<Glob...@>=
25338 scaled one_bp; /* scaled value corresponds to 1bp */
25339 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
25340 scaled one_hundred_inch; /* scaled value corresponds to 100in */
25341 integer ten_pow[10]; /* $10^0..10^9$ */
25342 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
25343
25344 @ @<Set init...@>=
25345 mp->one_bp = 65782; /* 65781.76 */
25346 mp->one_hundred_bp = 6578176;
25347 mp->one_hundred_inch = 473628672;
25348 mp->ten_pow[0] = 1;
25349 for (i = 1;i<= 9; i++ ) {
25350   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
25351 }
25352
25353 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
25354
25355 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
25356   scaled q,r;
25357   integer sign,i;
25358   sign = 1;
25359   if ( s < 0 ) { sign = -sign; s = -s; }
25360   if ( m < 0 ) { sign = -sign; m = -m; }
25361   if ( m == 0 )
25362     mp_confusion(mp, "arithmetic: divided by zero");
25363   else if ( m >= (max_integer / 10) )
25364     mp_confusion(mp, "arithmetic: number too big");
25365   q = s / m;
25366   r = s % m;
25367   for (i = 1;i<=dd;i++) {
25368     q = 10*q + (10*r) / m;
25369     r = (10*r) % m;
25370   }
25371   if ( 2*r >= m ) { incr(q); r = r - m; }
25372   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
25373   return (sign*q);
25374 }
25375
25376 @* \[44] Shipping pictures out.
25377 The |ship_out| procedure, to be described below, is given a pointer to
25378 an edge structure. Its mission is to output a file containing the \ps\
25379 description of an edge structure.
25380
25381 @ Each time an edge structure is shipped out we write a new \ps\ output
25382 file named according to the current \&{charcode}.
25383 @:char_code_}{\&{charcode} primitive@>
25384
25385 This is the only backend function that remains in the main |mpost.w| file. 
25386 There are just too many variable accesses needed for status reporting 
25387 etcetera to make it worthwile to move the code to |psout.w|.
25388
25389 @<Internal library declarations@>=
25390 void mp_open_output_file (MP mp) ;
25391
25392 @ @c 
25393 static char *mp_set_output_file_name (MP mp, integer c) {
25394   char *ss = NULL; /* filename extension proposal */  
25395   char *nn = NULL; /* temp string  for str() */
25396   unsigned old_setting; /* previous |selector| setting */
25397   pool_pointer i; /*  indexes into |filename_template|  */
25398   integer cc; /* a temporary integer for template building  */
25399   integer f,g=0; /* field widths */
25400   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25401   if ( mp->filename_template==0 ) {
25402     char *s; /* a file extension derived from |c| */
25403     if ( c<0 ) 
25404       s=xstrdup(".ps");
25405     else 
25406       @<Use |c| to compute the file extension |s|@>;
25407     mp_pack_job_name(mp, s);
25408     free(s);
25409     ss = xstrdup(mp->name_of_file);
25410   } else { /* initializations */
25411     str_number s, n; /* a file extension derived from |c| */
25412     old_setting=mp->selector; 
25413     mp->selector=new_string;
25414     f = 0;
25415     i = mp->str_start[mp->filename_template];
25416     n = null_str; /* initialize */
25417     while ( i<str_stop(mp->filename_template) ) {
25418        if ( mp->str_pool[i]=='%' ) {
25419       CONTINUE:
25420         incr(i);
25421         if ( i<str_stop(mp->filename_template) ) {
25422           if ( mp->str_pool[i]=='j' ) {
25423             mp_print(mp, mp->job_name);
25424           } else if ( mp->str_pool[i]=='d' ) {
25425              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
25426              print_with_leading_zeroes(cc);
25427           } else if ( mp->str_pool[i]=='m' ) {
25428              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
25429              print_with_leading_zeroes(cc);
25430           } else if ( mp->str_pool[i]=='y' ) {
25431              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
25432              print_with_leading_zeroes(cc);
25433           } else if ( mp->str_pool[i]=='H' ) {
25434              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
25435              print_with_leading_zeroes(cc);
25436           }  else if ( mp->str_pool[i]=='M' ) {
25437              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
25438              print_with_leading_zeroes(cc);
25439           } else if ( mp->str_pool[i]=='c' ) {
25440             if ( c<0 ) mp_print(mp, "ps");
25441             else print_with_leading_zeroes(c);
25442           } else if ( (mp->str_pool[i]>='0') && 
25443                       (mp->str_pool[i]<='9') ) {
25444             if ( (f<10)  )
25445               f = (f*10) + mp->str_pool[i]-'0';
25446             goto CONTINUE;
25447           } else {
25448             mp_print_str(mp, mp->str_pool[i]);
25449           }
25450         }
25451       } else {
25452         if ( mp->str_pool[i]=='.' )
25453           if (length(n)==0)
25454             n = mp_make_string(mp);
25455         mp_print_str(mp, mp->str_pool[i]);
25456       };
25457       incr(i);
25458     }
25459     s = mp_make_string(mp);
25460     mp->selector= old_setting;
25461     if (length(n)==0) {
25462        n=s;
25463        s=null_str;
25464     }
25465     ss = str(s);
25466     nn = str(n);
25467     mp_pack_file_name(mp, nn,"",ss);
25468     free(nn);
25469     delete_str_ref(n);
25470     delete_str_ref(s);
25471   }
25472   return ss;
25473 }
25474
25475 static char * mp_get_output_file_name (MP mp) {
25476   char *f;
25477   char *saved_name;  /* saved |name_of_file| */
25478   saved_name = xstrdup(mp->name_of_file);
25479   f = xstrdup(mp_set_output_file_name(mp, mp_round_unscaled(mp, mp->internal[mp_char_code])));
25480   mp_pack_file_name(mp, saved_name,NULL,NULL);
25481   free(saved_name);
25482   return f;
25483 }
25484
25485 void mp_open_output_file (MP mp) {
25486   char *ss; /* filename extension proposal */
25487   integer c; /* \&{charcode} rounded to the nearest integer */
25488   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25489   ss = mp_set_output_file_name(mp, c);
25490   while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
25491     mp_prompt_file_name(mp, "file name for output",ss);
25492   xfree(ss);
25493   @<Store the true output file name if appropriate@>;
25494 }
25495
25496 @ The file extension created here could be up to five characters long in
25497 extreme cases so it may have to be shortened on some systems.
25498 @^system dependencies@>
25499
25500 @<Use |c| to compute the file extension |s|@>=
25501
25502   s = xmalloc(7,1);
25503   mp_snprintf(s,7,".%i",(int)c);
25504 }
25505
25506 @ The user won't want to see all the output file names so we only save the
25507 first and last ones and a count of how many there were.  For this purpose
25508 files are ordered primarily by \&{charcode} and secondarily by order of
25509 creation.
25510 @:char_code_}{\&{charcode} primitive@>
25511
25512 @<Store the true output file name if appropriate@>=
25513 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
25514   mp->first_output_code=c;
25515   xfree(mp->first_file_name);
25516   mp->first_file_name=xstrdup(mp->name_of_file);
25517 }
25518 if ( c>=mp->last_output_code ) {
25519   mp->last_output_code=c;
25520   xfree(mp->last_file_name);
25521   mp->last_file_name=xstrdup(mp->name_of_file);
25522 }
25523
25524 @ @<Glob...@>=
25525 char * first_file_name;
25526 char * last_file_name; /* full file names */
25527 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25528 @:char_code_}{\&{charcode} primitive@>
25529 integer total_shipped; /* total number of |ship_out| operations completed */
25530
25531 @ @<Set init...@>=
25532 mp->first_file_name=xstrdup("");
25533 mp->last_file_name=xstrdup("");
25534 mp->first_output_code=32768;
25535 mp->last_output_code=-32768;
25536 mp->total_shipped=0;
25537
25538 @ @<Dealloc variables@>=
25539 xfree(mp->first_file_name);
25540 xfree(mp->last_file_name);
25541
25542 @ @<Begin the progress report for the output of picture~|c|@>=
25543 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25544 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, xord(' '));
25545 mp_print_char(mp, xord('['));
25546 if ( c>=0 ) mp_print_int(mp, c)
25547
25548 @ @<End progress report@>=
25549 mp_print_char(mp, xord(']'));
25550 update_terminal;
25551 incr(mp->total_shipped)
25552
25553 @ @<Explain what output files were written@>=
25554 if ( mp->total_shipped>0 ) { 
25555   mp_print_nl(mp, "");
25556   mp_print_int(mp, mp->total_shipped);
25557   if (mp->noninteractive) {
25558     mp_print(mp, " figure");
25559     if ( mp->total_shipped>1 ) mp_print_char(mp, xord('s'));
25560     mp_print(mp, " created.");
25561   } else {
25562     mp_print(mp, " output file");
25563     if ( mp->total_shipped>1 ) mp_print_char(mp, xord('s'));
25564     mp_print(mp, " written: ");
25565     mp_print(mp, mp->first_file_name);
25566     if ( mp->total_shipped>1 ) {
25567       if ( 31+strlen(mp->first_file_name)+
25568          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25569         mp_print_ln(mp);
25570       mp_print(mp, " .. ");
25571       mp_print(mp, mp->last_file_name);
25572     }
25573   }
25574 }
25575
25576 @ @<Internal library declarations@>=
25577 boolean mp_has_font_size(MP mp, font_number f );
25578
25579 @ @c 
25580 boolean mp_has_font_size(MP mp, font_number f ) {
25581   return (mp->font_sizes[f]!=null);
25582 }
25583
25584 @ The \&{special} command saves up lines of text to be printed during the next
25585 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25586
25587 @<Glob...@>=
25588 pointer last_pending; /* the last token in a list of pending specials */
25589
25590 @ @<Set init...@>=
25591 mp->last_pending=spec_head;
25592
25593 @ @<Cases of |do_statement|...@>=
25594 case special_command: 
25595   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25596   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25597   mp_do_mapline(mp);
25598   break;
25599
25600 @ @<Declare action procedures for use by |do_statement|@>=
25601 static void mp_do_special (MP mp) ;
25602
25603 @ @c void mp_do_special (MP mp) { 
25604   mp_get_x_next(mp); mp_scan_expression(mp);
25605   if ( mp->cur_type!=mp_string_type ) {
25606     @<Complain about improper special operation@>;
25607   } else { 
25608     mp_link(mp->last_pending)=mp_stash_cur_exp(mp);
25609     mp->last_pending=mp_link(mp->last_pending);
25610     mp_link(mp->last_pending)=null;
25611   }
25612 }
25613
25614 @ @<Complain about improper special operation@>=
25615
25616   exp_err("Unsuitable expression");
25617   help1("Only known strings are allowed for output as specials.");
25618   mp_put_get_error(mp);
25619 }
25620
25621 @ On the export side, we need an extra object type for special strings.
25622
25623 @<Graphical object codes@>=
25624 mp_special_code=8, 
25625
25626 @ @<Export pending specials@>=
25627 p=mp_link(spec_head);
25628 while ( p!=null ) {
25629   mp_special_object *tp;
25630   tp = (mp_special_object *)mp_new_graphic_object(mp,mp_special_code);  
25631   gr_pre_script(tp)  = str(value(p));
25632   if (hh->body==NULL) hh->body = (mp_graphic_object *)tp; 
25633   else gr_link(hp) = (mp_graphic_object *)tp;
25634   hp = (mp_graphic_object *)tp;
25635   p=mp_link(p);
25636 }
25637 mp_flush_token_list(mp, mp_link(spec_head));
25638 mp_link(spec_head)=null;
25639 mp->last_pending=spec_head
25640
25641 @ We are now ready for the main output procedure.  Note that the |selector|
25642 setting is saved in a global variable so that |begin_diagnostic| can access it.
25643
25644 @<Declare the \ps\ output procedures@>=
25645 static void mp_ship_out (MP mp, pointer h) ;
25646
25647 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25648
25649 @d export_color(q,p) 
25650   if ( color_model(p)==mp_uninitialized_model ) {
25651     gr_color_model(q)  = (unsigned char)(mp->internal[mp_default_color_model]/65536);
25652     gr_cyan_val(q)     = 0;
25653         gr_magenta_val(q)  = 0;
25654         gr_yellow_val(q)   = 0;
25655         gr_black_val(q)    = (gr_color_model(q)==mp_cmyk_model ? unity : 0);
25656   } else {
25657     gr_color_model(q)  = (unsigned char)color_model(p);
25658     gr_cyan_val(q)     = cyan_val(p);
25659     gr_magenta_val(q)  = magenta_val(p);
25660     gr_yellow_val(q)   = yellow_val(p);
25661     gr_black_val(q)    = black_val(p);
25662   }
25663
25664 @d export_scripts(q,p)
25665   if (pre_script(p)!=null)  gr_pre_script(q)   = str(pre_script(p));
25666   if (post_script(p)!=null) gr_post_script(q)  = str(post_script(p));
25667
25668 @c
25669 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25670   pointer p; /* the current graphical object */
25671   integer t; /* a temporary value */
25672   integer c; /* a rounded charcode */
25673   scaled d_width; /* the current pen width */
25674   mp_edge_object *hh; /* the first graphical object */
25675   mp_graphic_object *hq; /* something |hp| points to  */
25676   mp_text_object    *tt;
25677   mp_fill_object    *tf;
25678   mp_stroked_object *ts;
25679   mp_clip_object    *tc;
25680   mp_bounds_object  *tb;
25681   mp_graphic_object *hp = NULL; /* the current graphical object */
25682   mp_set_bbox(mp, h, true);
25683   hh = xmalloc(1,sizeof(mp_edge_object));
25684   hh->body = NULL;
25685   hh->next = NULL;
25686   hh->_parent = mp;
25687   hh->_minx = minx_val(h);
25688   hh->_miny = miny_val(h);
25689   hh->_maxx = maxx_val(h);
25690   hh->_maxy = maxy_val(h);
25691   hh->_filename = mp_get_output_file_name(mp);
25692   c = mp_round_unscaled(mp,mp->internal[mp_char_code]);
25693   hh->_charcode = c;
25694   hh->_width = mp->internal[mp_char_wd];
25695   hh->_height = mp->internal[mp_char_ht];
25696   hh->_depth = mp->internal[mp_char_dp];
25697   hh->_ital_corr = mp->internal[mp_char_ic];
25698   @<Export pending specials@>;
25699   p=mp_link(dummy_loc(h));
25700   while ( p!=null ) { 
25701     hq = mp_new_graphic_object(mp,type(p));
25702     switch (type(p)) {
25703     case mp_fill_code:
25704       tf = (mp_fill_object *)hq;
25705       gr_pen_p(tf)        = mp_export_knot_list(mp,pen_p(p));
25706       d_width = mp_get_pen_scale(mp, pen_p(p));
25707       if ((pen_p(p)==null) || pen_is_elliptical(pen_p(p)))  {
25708             gr_path_p(tf)       = mp_export_knot_list(mp,path_p(p));
25709       } else {
25710         pointer pc, pp;
25711         pc = mp_copy_path(mp, path_p(p));
25712         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25713         gr_path_p(tf)       = mp_export_knot_list(mp,pp);
25714         mp_toss_knot_list(mp, pp);
25715         pc = mp_htap_ypoc(mp, path_p(p));
25716         pp = mp_make_envelope(mp, pc, pen_p(p),ljoin_val(p),0,miterlim_val(p));
25717         gr_htap_p(tf)       = mp_export_knot_list(mp,pp);
25718         mp_toss_knot_list(mp, pp);
25719       }
25720       export_color(tf,p) ;
25721       export_scripts(tf,p);
25722       gr_ljoin_val(tf)    = (unsigned char)ljoin_val(p);
25723       gr_miterlim_val(tf) = miterlim_val(p);
25724       break;
25725     case mp_stroked_code:
25726       ts = (mp_stroked_object *)hq;
25727       gr_pen_p(ts)        = mp_export_knot_list(mp,pen_p(p));
25728       d_width = mp_get_pen_scale(mp, pen_p(p));
25729       if (pen_is_elliptical(pen_p(p)))  {
25730               gr_path_p(ts)       = mp_export_knot_list(mp,path_p(p));
25731       } else {
25732         pointer pc;
25733         pc=mp_copy_path(mp, path_p(p));
25734         t=lcap_val(p);
25735         if ( mp_left_type(pc)!=mp_endpoint ) { 
25736           mp_left_type(mp_insert_knot(mp, pc,mp_x_coord(pc),mp_y_coord(pc)))=mp_endpoint;
25737           mp_right_type(pc)=mp_endpoint;
25738           pc=mp_link(pc);
25739           t=1;
25740         }
25741         pc=mp_make_envelope(mp,pc,pen_p(p),ljoin_val(p),t,miterlim_val(p));
25742         gr_path_p(ts)       = mp_export_knot_list(mp,pc);
25743         mp_toss_knot_list(mp, pc);
25744       }
25745       export_color(ts,p) ;
25746       export_scripts(ts,p);
25747       gr_ljoin_val(ts)    = (unsigned char)ljoin_val(p);
25748       gr_miterlim_val(ts) = miterlim_val(p);
25749       gr_lcap_val(ts)     = (unsigned char)lcap_val(p);
25750       gr_dash_p(ts)       = mp_export_dashes(mp,p,&d_width);
25751       break;
25752     case mp_text_code:
25753       tt = (mp_text_object *)hq;
25754       gr_text_p(tt)       = str(text_p(p));
25755       gr_font_n(tt)       = (unsigned int)font_n(p);
25756       gr_font_name(tt)    = mp_xstrdup(mp,mp->font_name[font_n(p)]);
25757       gr_font_dsize(tt)   = (unsigned int)mp->font_dsize[font_n(p)];
25758       export_color(tt,p) ;
25759       export_scripts(tt,p);
25760       gr_width_val(tt)    = width_val(p);
25761       gr_height_val(tt)   = height_val(p);
25762       gr_depth_val(tt)    = depth_val(p);
25763       gr_tx_val(tt)       = tx_val(p);
25764       gr_ty_val(tt)       = ty_val(p);
25765       gr_txx_val(tt)      = txx_val(p);
25766       gr_txy_val(tt)      = txy_val(p);
25767       gr_tyx_val(tt)      = tyx_val(p);
25768       gr_tyy_val(tt)      = tyy_val(p);
25769       break;
25770     case mp_start_clip_code: 
25771       tc = (mp_clip_object *)hq;
25772       gr_path_p(tc) = mp_export_knot_list(mp,path_p(p));
25773       break;
25774     case mp_start_bounds_code:
25775       tb = (mp_bounds_object *)hq;
25776       gr_path_p(tb) = mp_export_knot_list(mp,path_p(p));
25777       break;
25778     case mp_stop_clip_code: 
25779     case mp_stop_bounds_code:
25780       /* nothing to do here */
25781       break;
25782     } 
25783     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25784     hp = hq;
25785     p=mp_link(p);
25786   }
25787   return hh;
25788 }
25789
25790 @ @<Declarations@>=
25791 static struct mp_edge_object *mp_gr_export(MP mp, int h);
25792
25793 @ This function is now nearly trivial.
25794
25795 @c
25796 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25797   integer c; /* \&{charcode} rounded to the nearest integer */
25798   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25799   @<Begin the progress report for the output of picture~|c|@>;
25800   (mp->shipout_backend) (mp, h);
25801   @<End progress report@>;
25802   if ( mp->internal[mp_tracing_output]>0 ) 
25803    mp_print_edges(mp, h," (just shipped out)",true);
25804 }
25805
25806 @ @<Declarations@>=
25807 static void mp_shipout_backend (MP mp, pointer h);
25808
25809 @ @c
25810 void mp_shipout_backend (MP mp, pointer h) {
25811   mp_edge_object *hh; /* the first graphical object */
25812   hh = mp_gr_export(mp,h);
25813   (void)mp_gr_ship_out (hh,
25814                  (mp->internal[mp_prologues]/65536),
25815                  (mp->internal[mp_procset]/65536), 
25816                  false);
25817   mp_gr_toss_objects(hh);
25818 }
25819
25820 @ @<Exported types@>=
25821 typedef void (*mp_backend_writer)(MP, int);
25822
25823 @ @<Option variables@>=
25824 mp_backend_writer shipout_backend;
25825
25826 @ Now that we've finished |ship_out|, let's look at the other commands
25827 by which a user can send things to the \.{GF} file.
25828
25829 @ @<Determine if a character has been shipped out@>=
25830
25831   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25832   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25833   boolean_reset(mp->char_exists[mp->cur_exp]);
25834   mp->cur_type=mp_boolean_type;
25835 }
25836
25837 @ @<Glob...@>=
25838 psout_data ps;
25839
25840 @ @<Allocate or initialize ...@>=
25841 mp_backend_initialize(mp);
25842
25843 @ @<Dealloc...@>=
25844 mp_backend_free(mp);
25845
25846
25847 @* \[45] Dumping and undumping the tables.
25848 After \.{INIMP} has seen a collection of macros, it
25849 can write all the necessary information on an auxiliary file so
25850 that production versions of \MP\ are able to initialize their
25851 memory at high speed. The present section of the program takes
25852 care of such output and input. We shall consider simultaneously
25853 the processes of storing and restoring,
25854 so that the inverse relation between them is clear.
25855 @.INIMP@>
25856
25857 The global variable |mem_ident| is a string that is printed right
25858 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25859 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25860 for example, `\.{(mem=plain 1990.4.14)}', showing the year,
25861 month, and day that the mem file was created. We have |mem_ident=0|
25862 before \MP's tables are loaded.
25863
25864 @<Glob...@>=
25865 char * mem_ident;
25866
25867 @ @<Set init...@>=
25868 mp->mem_ident=NULL;
25869
25870 @ @<Initialize table entries...@>=
25871 mp->mem_ident=xstrdup(" (INIMP)");
25872
25873 @ @<Declare act...@>=
25874 static void mp_store_mem_file (MP mp) ;
25875
25876 @ @c void mp_store_mem_file (MP mp) {
25877   integer k;  /* all-purpose index */
25878   pointer p,q; /* all-purpose pointers */
25879   integer x; /* something to dump */
25880   four_quarters w; /* four ASCII codes */
25881   memory_word WW;
25882   @<Create the |mem_ident|, open the mem file,
25883     and inform the user that dumping has begun@>;
25884   @<Dump constants for consistency check@>;
25885   @<Dump the string pool@>;
25886   @<Dump the dynamic memory@>;
25887   @<Dump the table of equivalents and the hash table@>;
25888   @<Dump a few more things and the closing check word@>;
25889   @<Close the mem file@>;
25890 }
25891
25892 @ Corresponding to the procedure that dumps a mem file, we also have a function
25893 that reads~one~in. The function returns |false| if the dumped mem is
25894 incompatible with the present \MP\ table sizes, etc.
25895
25896 @d too_small(A) { wake_up_terminal;
25897   wterm_ln("---! Must increase the "); wterm((A));
25898 @.Must increase the x@>
25899   goto OFF_BASE;
25900   }
25901
25902 @c 
25903 boolean mp_load_mem_file (MP mp) {
25904   integer k; /* all-purpose index */
25905   pointer p,q; /* all-purpose pointers */
25906   integer x; /* something undumped */
25907   str_number s; /* some temporary string */
25908   four_quarters w; /* four ASCII codes */
25909   memory_word WW;
25910   @<Undump the string pool@>;
25911   @<Undump the dynamic memory@>;
25912   @<Undump the table of equivalents and the hash table@>;
25913   @<Undump a few more things and the closing check word@>;
25914   return true; /* it worked! */
25915 OFF_BASE: 
25916   wake_up_terminal;
25917   wterm_ln("(Fatal mem file error; I'm stymied)\n");
25918 @.Fatal mem file error@>
25919    return false;
25920 }
25921
25922 @ @<Declarations@>=
25923 static boolean mp_load_mem_file (MP mp) ;
25924
25925 @ Mem files consist of |memory_word| items, and we use the following
25926 macros to dump words of different types:
25927
25928 @d dump_wd(A)   { WW=(A);       (mp->write_binary_file)(mp,mp->mem_file,&WW,sizeof(WW)); }
25929 @d dump_int(A)  { int cint=(A); (mp->write_binary_file)(mp,mp->mem_file,&cint,sizeof(cint)); }
25930 @d dump_hh(A)   { WW.hh=(A);    (mp->write_binary_file)(mp,mp->mem_file,&WW,sizeof(WW)); }
25931 @d dump_qqqq(A) { WW.qqqq=(A);  (mp->write_binary_file)(mp,mp->mem_file,&WW,sizeof(WW)); }
25932 @d dump_string(A) { dump_int((int)(strlen(A)+1));
25933                     (mp->write_binary_file)(mp,mp->mem_file,A,strlen(A)+1); }
25934
25935 @<Glob...@>=
25936 void * mem_file; /* for input or output of mem information */
25937
25938 @ The inverse macros are slightly more complicated, since we need to check
25939 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
25940 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
25941
25942 @d mgeti(A) do {
25943   size_t wanted = sizeof(A);
25944   void *A_ptr = &A;
25945   (mp->read_binary_file)(mp, mp->mem_file,&A_ptr,&wanted);
25946   if (wanted!=sizeof(A)) goto OFF_BASE;
25947 } while (0)
25948
25949 @d mgetw(A) do {
25950   size_t wanted = sizeof(A);
25951   void *A_ptr = &A;
25952   (mp->read_binary_file)(mp, mp->mem_file,&A_ptr,&wanted);
25953   if (wanted!=sizeof(A)) goto OFF_BASE;
25954 } while (0)
25955
25956 @d undump_wd(A)   { mgetw(WW); A=WW; }
25957 @d undump_int(A)  { int cint; mgeti(cint); A=cint; }
25958 @d undump_hh(A)   { mgetw(WW); A=WW.hh; }
25959 @d undump_qqqq(A) { mgetw(WW); A=WW.qqqq; }
25960 @d undump_strings(A,B,C) { 
25961    undump_int(x); if ( (x<(A)) || (x>(B)) ) goto OFF_BASE; else C=str(x); }
25962 @d undump(A,B,C) { undump_int(x); 
25963                    if ( (x<(A)) || (x>(int)(B)) ) goto OFF_BASE; else C=x; }
25964 @d undump_size(A,B,C,D) { undump_int(x);
25965                           if (x<(A)) goto OFF_BASE; 
25966                           if (x>(B)) too_small((C)); else D=x; }
25967 @d undump_string(A) { 
25968   size_t the_wanted; 
25969   void *the_string;
25970   integer XX=0; 
25971   undump_int(XX);
25972   the_wanted = (size_t)XX;
25973   the_string = xmalloc(XX,1);
25974   (mp->read_binary_file)(mp,mp->mem_file,&the_string,&the_wanted);
25975   A = (char *)the_string;
25976   if (the_wanted!=(size_t)XX) goto OFF_BASE;
25977 }
25978
25979 @ The next few sections of the program should make it clear how we use the
25980 dump/undump macros.
25981
25982 @<Dump constants for consistency check@>=
25983 x = metapost_magic; dump_int(x);
25984 dump_int(mp->mem_top);
25985 dump_int((integer)mp->hash_size);
25986 dump_int(mp->hash_prime)
25987 dump_int(mp->param_size);
25988 dump_int(mp->max_in_open);
25989
25990 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
25991 strings to the string pool; therefore \.{INIMP} and \MP\ will have
25992 the same strings. (And it is, of course, a good thing that they do.)
25993 @.WEB@>
25994 @^string pool@>
25995
25996 @<Undump constants for consistency check@>=
25997 undump_int(x); 
25998 if (x!=metapost_magic) goto OFF_BASE;
25999 undump_int(x); mp->mem_top = x;
26000 undump_int(x); mp->hash_size = (unsigned)x;
26001 undump_int(x); mp->hash_prime = x;
26002 undump_int(x); mp->param_size = x;
26003 undump_int(x); mp->max_in_open = x;
26004
26005 @ We do string pool compaction to avoid dumping unused strings.
26006
26007 @d dump_four_ASCII 
26008   w.b0=qi(mp->str_pool[k]); w.b1=qi(mp->str_pool[k+1]);
26009   w.b2=qi(mp->str_pool[k+2]); w.b3=qi(mp->str_pool[k+3]);
26010   dump_qqqq(w)
26011
26012 @<Dump the string pool@>=
26013 mp_do_compaction(mp, mp->pool_size);
26014 dump_int(mp->pool_ptr);
26015 dump_int(mp->max_str_ptr);
26016 dump_int(mp->str_ptr);
26017 k=0;
26018 while ( (mp->next_str[k]==k+1) && (k<=mp->max_str_ptr) ) 
26019   k++;
26020 dump_int(k);
26021 while ( k<=mp->max_str_ptr ) { 
26022   dump_int(mp->next_str[k]); incr(k);
26023 }
26024 k=0;
26025 while (1)  { 
26026   dump_int(mp->str_start[k]); /* TODO: valgrind warning here */
26027   if ( k==mp->str_ptr ) {
26028     break;
26029   } else { 
26030     k=mp->next_str[k]; 
26031   }
26032 }
26033 k=0;
26034 while (k+4<mp->pool_ptr ) {
26035   dump_four_ASCII; k=k+4; 
26036 }
26037 k=mp->pool_ptr-4; dump_four_ASCII;
26038 mp_print_ln(mp); mp_print(mp, "at most "); mp_print_int(mp, mp->max_str_ptr);
26039 mp_print(mp, " strings of total length ");
26040 mp_print_int(mp, mp->pool_ptr)
26041
26042 @ @d undump_four_ASCII 
26043   undump_qqqq(w);
26044   mp->str_pool[k]=(ASCII_code)qo(w.b0); mp->str_pool[k+1]=(ASCII_code)qo(w.b1);
26045   mp->str_pool[k+2]=(ASCII_code)qo(w.b2); mp->str_pool[k+3]=(ASCII_code)qo(w.b3)
26046
26047 @<Undump the string pool@>=
26048 undump_int(mp->pool_ptr);
26049 mp_reallocate_pool(mp, mp->pool_ptr) ;
26050 undump_int(mp->max_str_ptr);
26051 mp_reallocate_strings (mp,mp->max_str_ptr) ;
26052 undump(0,mp->max_str_ptr,mp->str_ptr);
26053 undump(0,mp->max_str_ptr+1,s);
26054 for (k=0;k<=s-1;k++) 
26055   mp->next_str[k]=k+1;
26056 for (k=s;k<=mp->max_str_ptr;k++) 
26057   undump(s+1,mp->max_str_ptr+1,mp->next_str[k]);
26058 mp->fixed_str_use=0;
26059 k=0;
26060 while (1) { 
26061   undump(0,mp->pool_ptr,mp->str_start[k]);
26062   if ( k==mp->str_ptr ) break;
26063   mp->str_ref[k]=max_str_ref;
26064   incr(mp->fixed_str_use);
26065   mp->last_fixed_str=k; k=mp->next_str[k];
26066 }
26067 k=0;
26068 while ( k+4<mp->pool_ptr ) { 
26069   undump_four_ASCII; k=k+4;
26070 }
26071 k=mp->pool_ptr-4; undump_four_ASCII;
26072 mp->init_str_use=mp->fixed_str_use; mp->init_pool_ptr=mp->pool_ptr;
26073 mp->max_pool_ptr=mp->pool_ptr;
26074 mp->strs_used_up=mp->fixed_str_use;
26075 mp->pool_in_use=mp->str_start[mp->str_ptr]; mp->strs_in_use=mp->fixed_str_use;
26076 mp->max_pl_used=mp->pool_in_use; mp->max_strs_used=mp->strs_in_use;
26077 mp->pact_count=0; mp->pact_chars=0; mp->pact_strs=0;
26078
26079 @ By sorting the list of available spaces in the variable-size portion of
26080 |mem|, we are usually able to get by without having to dump very much
26081 of the dynamic memory.
26082
26083 We recompute |var_used| and |dyn_used|, so that \.{INIMP} dumps valid
26084 information even when it has not been gathering statistics.
26085
26086 @<Dump the dynamic memory@>=
26087 mp_sort_avail(mp); mp->var_used=0;
26088 dump_int(mp->lo_mem_max); dump_int(mp->rover);
26089 p=0; q=mp->rover; x=0;
26090 do {  
26091   for (k=p;k<= q+1;k++) 
26092     dump_wd(mp->mem[k]);
26093   x=x+q+2-p; mp->var_used=mp->var_used+q-p;
26094   p=q+node_size(q); q=rmp_link(q);
26095 } while (q!=mp->rover);
26096 mp->var_used=mp->var_used+mp->lo_mem_max-p; 
26097 mp->dyn_used=mp->mem_end+1-mp->hi_mem_min;
26098 for (k=p;k<= mp->lo_mem_max;k++ ) 
26099   dump_wd(mp->mem[k]);
26100 x=x+mp->lo_mem_max+1-p;
26101 dump_int(mp->hi_mem_min); dump_int(mp->avail);
26102 for (k=mp->hi_mem_min;k<=mp->mem_end;k++ ) 
26103   dump_wd(mp->mem[k]);
26104 x=x+mp->mem_end+1-mp->hi_mem_min;
26105 p=mp->avail;
26106 while ( p!=null ) { 
26107   decr(mp->dyn_used); p=mp_link(p);
26108 }
26109 dump_int(mp->var_used); dump_int(mp->dyn_used);
26110 mp_print_ln(mp); mp_print_int(mp, x);
26111 mp_print(mp, " memory locations dumped; current usage is ");
26112 mp_print_int(mp, mp->var_used); mp_print_char(mp, xord('&')); mp_print_int(mp, mp->dyn_used)
26113
26114 @ @<Undump the dynamic memory@>=
26115 undump(lo_mem_stat_max+1000,hi_mem_stat_min-1,mp->lo_mem_max);
26116 undump(lo_mem_stat_max+1,mp->lo_mem_max,mp->rover);
26117 p=0; q=mp->rover;
26118 do {  
26119   for (k=p;k<= q+1; k++) 
26120     undump_wd(mp->mem[k]);
26121   p=q+node_size(q);
26122   if ( (p>mp->lo_mem_max)||((q>=rmp_link(q))&&(rmp_link(q)!=mp->rover)) ) 
26123     goto OFF_BASE;
26124   q=rmp_link(q);
26125 } while (q!=mp->rover);
26126 for (k=p;k<=mp->lo_mem_max;k++ ) 
26127   undump_wd(mp->mem[k]);
26128 undump(mp->lo_mem_max+1,hi_mem_stat_min,mp->hi_mem_min);
26129 undump(null,mp->mem_top,mp->avail); mp->mem_end=mp->mem_top;
26130 mp->last_pending=spec_head;
26131 for (k=mp->hi_mem_min;k<= mp->mem_end;k++) 
26132   undump_wd(mp->mem[k]);
26133 undump_int(mp->var_used); undump_int(mp->dyn_used)
26134
26135 @ A different scheme is used to compress the hash table, since its lower region
26136 is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output three
26137 words: |p|, |hash[p]|, and |eqtb[p]|. The hash table is, of course, densely
26138 packed for |p>=hash_used|, so the remaining entries are output in~a~block.
26139
26140 @<Dump the table of equivalents and the hash table@>=
26141 dump_int(mp->hash_used); 
26142 mp->st_count=frozen_inaccessible-1-mp->hash_used;
26143 for (p=1;p<=mp->hash_used;p++) {
26144   if ( text(p)!=0 ) {
26145      dump_int(p); dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]); incr(mp->st_count);
26146   }
26147 }
26148 for (p=mp->hash_used+1;p<=(int)hash_end;p++) {
26149   dump_hh(mp->hash[p]); dump_hh(mp->eqtb[p]);
26150 }
26151 dump_int(mp->st_count);
26152 mp_print_ln(mp); mp_print_int(mp, mp->st_count); mp_print(mp, " symbolic tokens")
26153
26154 @ @<Undump the table of equivalents and the hash table@>=
26155 undump(1,frozen_inaccessible,mp->hash_used); 
26156 p=0;
26157 do {  
26158   undump(p+1,mp->hash_used,p); 
26159   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26160 } while (p!=mp->hash_used);
26161 for (p=mp->hash_used+1;p<=(int)hash_end;p++ )  { 
26162   undump_hh(mp->hash[p]); undump_hh(mp->eqtb[p]);
26163 }
26164 undump_int(mp->st_count)
26165
26166 @ We have already printed a lot of statistics, so we set |mp_tracing_stats:=0|
26167 to prevent them appearing again.
26168
26169 @<Dump a few more things and the closing check word@>=
26170 dump_int(mp->max_internal);
26171 dump_int(mp->int_ptr);
26172 for (k=1;k<= mp->int_ptr;k++ ) { 
26173   dump_int(mp->internal[k]); 
26174   dump_string(mp->int_name[k]);
26175 }
26176 dump_int(mp->start_sym); 
26177 dump_int(mp->interaction); 
26178 dump_string(mp->mem_ident);
26179 dump_int(mp->bg_loc); dump_int(mp->eg_loc); dump_int(mp->serial_no); dump_int(69073);
26180 mp->internal[mp_tracing_stats]=0
26181
26182 @ @<Undump a few more things and the closing check word@>=
26183 undump_int(x);
26184 if (x>mp->max_internal) mp_grow_internals(mp,x);
26185 undump_int(mp->int_ptr);
26186 for (k=1;k<= mp->int_ptr;k++) { 
26187   undump_int(mp->internal[k]);
26188   undump_string(mp->int_name[k]);
26189 }
26190 undump(0,frozen_inaccessible,mp->start_sym);
26191 if (mp->interaction==mp_unspecified_mode) {
26192   undump(mp_unspecified_mode,mp_error_stop_mode,mp->interaction);
26193 } else {
26194   undump(mp_unspecified_mode,mp_error_stop_mode,x);
26195 }
26196 undump_string(mp->mem_ident);
26197 undump(1,hash_end,mp->bg_loc);
26198 undump(1,hash_end,mp->eg_loc);
26199 undump_int(mp->serial_no);
26200 undump_int(x); 
26201 if (x!=69073) goto OFF_BASE
26202
26203 @ @<Create the |mem_ident|...@>=
26204
26205   char *tmp = xmalloc(11,1);
26206   xfree(mp->mem_ident);
26207   mp->mem_ident = xmalloc(256,1);
26208   mp_snprintf(tmp,11,"%04d.%02d.%02d",
26209           (int)mp_round_unscaled(mp, mp->internal[mp_year]),
26210           (int)mp_round_unscaled(mp, mp->internal[mp_month]),
26211           (int)mp_round_unscaled(mp, mp->internal[mp_day]));
26212   mp_snprintf(mp->mem_ident,256," (mem=%s %s)",mp->job_name, tmp);
26213   xfree(tmp);
26214   mp_pack_job_name(mp, ".mem");
26215   while (! mp_w_open_out(mp, &mp->mem_file) )
26216     mp_prompt_file_name(mp, "mem file name", ".mem");
26217   mp_print_nl(mp, "Beginning to dump on file ");
26218 @.Beginning to dump...@>
26219   mp_print(mp, mp->name_of_file); 
26220   mp_print_nl(mp, mp->mem_ident);
26221 }
26222
26223 @ @<Dealloc variables@>=
26224 xfree(mp->mem_ident);
26225
26226 @ @<Close the mem file@>=
26227 (mp->close_file)(mp,mp->mem_file)
26228
26229 @* \[46] The main program.
26230 This is it: the part of \MP\ that executes all those procedures we have
26231 written.
26232
26233 Well---almost. We haven't put the parsing subroutines into the
26234 program yet; and we'd better leave space for a few more routines that may
26235 have been forgotten.
26236
26237 @c @<Declare the basic parsing subroutines@>
26238 @<Declare miscellaneous procedures that were declared |forward|@>
26239
26240 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
26241 @.INIMP@>
26242 has to be run first; it initializes everything from scratch, without
26243 reading a mem file, and it has the capability of dumping a mem file.
26244 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
26245 @.VIRMP@>
26246 to input a mem file in order to get started. \.{VIRMP} typically has
26247 a bit more memory capacity than \.{INIMP}, because it does not need the
26248 space consumed by the dumping/undumping routines and the numerous calls on
26249 |primitive|, etc.
26250
26251 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
26252 the best implementations therefore allow for production versions of \MP\ that
26253 not only avoid the loading routine for object code, they also have
26254 a mem file pre-loaded. 
26255
26256 @ @<Option variables@>=
26257 int ini_version; /* are we iniMP? */
26258
26259 @ @<Set |ini_version|@>=
26260 mp->ini_version = (opt->ini_version ? true : false);
26261
26262 @ The code below make the final chosen hash size the next larger
26263 multiple of 2 from the requested size, and this array is a list of
26264 suitable prime numbers to go with such values. 
26265
26266 The top limit is chosen such that it is definately lower than
26267 |max_halfword-3*param_size|, because |param_size| cannot be larger
26268 than |max_halfword/sizeof(pointer)|.
26269
26270 @<Declarations@>=
26271 static int mp_prime_choices[] = 
26272   { 12289,        24593,    49157,    98317,
26273     196613,      393241,   786433,  1572869,
26274     3145739,    6291469, 12582917, 25165843,
26275     50331653, 100663319  };
26276
26277 @ @<Find constant sizes@>=
26278 if (mp->ini_version) {
26279   unsigned i = 14;
26280   set_value(mp->mem_top,opt->main_memory,5000);
26281   mp->mem_max = mp->mem_top;
26282   set_value(mp->param_size,opt->param_size,150);
26283   set_value(mp->max_in_open,opt->max_in_open,10);
26284   if (opt->hash_size>0x8000000) 
26285     opt->hash_size=0x8000000;
26286   set_value(mp->hash_size,(2*opt->hash_size-1),16384);
26287   mp->hash_size = mp->hash_size>>i;
26288   while (mp->hash_size>=2) {
26289     mp->hash_size /= 2;
26290     i++;
26291   }
26292   mp->hash_size = mp->hash_size << i;
26293   if (mp->hash_size>0x8000000) 
26294     mp->hash_size=0x8000000;
26295   mp->hash_prime=mp_prime_choices[(i-14)];
26296 } else {
26297   int x;
26298   if (mp->mem_name == NULL) {
26299     mp->mem_name = mp_xstrdup(mp,"plain");
26300   }
26301   if (mp_open_mem_file(mp)) {
26302     @<Undump constants for consistency check@>;
26303     set_value(mp->mem_max,opt->main_memory,mp->mem_top);
26304     goto DONE;
26305   } 
26306 OFF_BASE:
26307   wterm_ln("(Fatal mem file error; I'm stymied)\n");
26308   mp->history = mp_fatal_error_stop;
26309   mp_jump_out(mp);
26310 }
26311 DONE:
26312
26313
26314 @ Here we do whatever is needed to complete \MP's job gracefully on the
26315 local operating system. The code here might come into play after a fatal
26316 error; it must therefore consist entirely of ``safe'' operations that
26317 cannot produce error messages. For example, it would be a mistake to call
26318 |str_room| or |make_string| at this time, because a call on |overflow|
26319 might lead to an infinite loop.
26320 @^system dependencies@>
26321
26322 This program doesn't bother to close the input files that may still be open.
26323
26324 @ @c
26325 void mp_close_files_and_terminate (MP mp) {
26326   integer k; /* all-purpose index */
26327   integer LH; /* the length of the \.{TFM} header, in words */
26328   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
26329   pointer p; /* runs through a list of \.{TFM} dimensions */
26330   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
26331   if ( mp->internal[mp_tracing_stats]>0 )
26332     @<Output statistics about this job@>;
26333   wake_up_terminal; 
26334   @<Do all the finishing work on the \.{TFM} file@>;
26335   @<Explain what output files were written@>;
26336   if ( mp->log_opened  && ! mp->noninteractive ){ 
26337     wlog_cr;
26338     (mp->close_file)(mp,mp->log_file); 
26339     mp->selector=mp->selector-2;
26340     if ( mp->selector==term_only ) {
26341       mp_print_nl(mp, "Transcript written on ");
26342 @.Transcript written...@>
26343       mp_print(mp, mp->log_name); mp_print_char(mp, xord('.'));
26344     }
26345   }
26346   mp_print_ln(mp);
26347   mp->finished = true;
26348 }
26349
26350 @ @<Declarations@>=
26351 static void mp_close_files_and_terminate (MP mp) ;
26352
26353 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26354 if (mp->rd_fname!=NULL) {
26355   for (k=0;k<=(int)mp->read_files-1;k++ ) {
26356     if ( mp->rd_fname[k]!=NULL ) {
26357       (mp->close_file)(mp,mp->rd_file[k]);
26358       xfree(mp->rd_fname[k]);      
26359    }
26360  }
26361 }
26362 if (mp->wr_fname!=NULL) {
26363   for (k=0;k<=(int)mp->write_files-1;k++) {
26364     if ( mp->wr_fname[k]!=NULL ) {
26365      (mp->close_file)(mp,mp->wr_file[k]);
26366       xfree(mp->wr_fname[k]); 
26367     }
26368   }
26369 }
26370
26371 @ @<Dealloc ...@>=
26372 for (k=0;k<(int)mp->max_read_files;k++ ) {
26373   if ( mp->rd_fname[k]!=NULL ) {
26374     (mp->close_file)(mp,mp->rd_file[k]);
26375     xfree(mp->rd_fname[k]); 
26376   }
26377 }
26378 xfree(mp->rd_file);
26379 xfree(mp->rd_fname);
26380 for (k=0;k<(int)mp->max_write_files;k++) {
26381   if ( mp->wr_fname[k]!=NULL ) {
26382     (mp->close_file)(mp,mp->wr_file[k]);
26383     xfree(mp->wr_fname[k]); 
26384   }
26385 }
26386 xfree(mp->wr_file);
26387 xfree(mp->wr_fname);
26388
26389
26390 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
26391
26392 We reclaim all of the variable-size memory at this point, so that
26393 there is no chance of another memory overflow after the memory capacity
26394 has already been exceeded.
26395
26396 @<Do all the finishing work on the \.{TFM} file@>=
26397 if ( mp->internal[mp_fontmaking]>0 ) {
26398   @<Make the dynamic memory into one big available node@>;
26399   @<Massage the \.{TFM} widths@>;
26400   mp_fix_design_size(mp); mp_fix_check_sum(mp);
26401   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26402   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
26403   @<Finish the \.{TFM} file@>;
26404 }
26405
26406 @ @<Make the dynamic memory into one big available node@>=
26407 mp->rover=lo_mem_stat_max+1; mp_link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26408 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26409 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
26410 lmp_link(mp->rover)=mp->rover; rmp_link(mp->rover)=mp->rover;
26411 mp_link(mp->lo_mem_max)=null; info(mp->lo_mem_max)=null
26412
26413 @ The present section goes directly to the log file instead of using
26414 |print| commands, because there's no need for these strings to take
26415 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26416
26417 @<Output statistics...@>=
26418 if ( mp->log_opened ) { 
26419   char s[128];
26420   wlog_ln(" ");
26421   wlog_ln("Here is how much of MetaPost's memory you used:");
26422 @.Here is how much...@>
26423   mp_snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26424           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26425           (int)(mp->max_strings-1-mp->init_str_use));
26426   wlog_ln(s);
26427   mp_snprintf(s,128," %i string characters out of %i",
26428            (int)mp->max_pl_used-mp->init_pool_ptr,
26429            (int)mp->pool_size-mp->init_pool_ptr);
26430   wlog_ln(s);
26431   mp_snprintf(s,128," %i words of memory out of %i",
26432            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26433            (int)mp->mem_end);
26434   wlog_ln(s);
26435   mp_snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26436   wlog_ln(s);
26437   mp_snprintf(s,128," %ii,%in,%ip,%ib stack positions out of %ii,%in,%ip,%ib",
26438            (int)mp->max_in_stack,(int)mp->int_ptr,
26439            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26440            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26441   wlog_ln(s);
26442   mp_snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26443           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26444   wlog_ln(s);
26445 }
26446
26447 @ It is nice to have have some of the stats available from the API.
26448
26449 @<Exported function ...@>=
26450 int mp_memory_usage (MP mp );
26451 int mp_hash_usage (MP mp );
26452 int mp_param_usage (MP mp );
26453 int mp_open_usage (MP mp );
26454
26455 @ @c
26456 int mp_memory_usage (MP mp ) {
26457         return (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2;
26458 }
26459 int mp_hash_usage (MP mp ) {
26460   return (int)mp->st_count;
26461 }
26462 int mp_param_usage (MP mp ) {
26463         return (int)mp->max_param_stack;
26464 }
26465 int mp_open_usage (MP mp ) {
26466         return (int)mp->max_in_stack;
26467 }
26468
26469 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26470 been scanned.
26471
26472 @c
26473 void mp_final_cleanup (MP mp) {
26474   quarterword c; /* 0 for \&{end}, 1 for \&{dump} */
26475   c=mp->cur_mod;
26476   if ( mp->job_name==NULL ) mp_open_log_file(mp);
26477   while ( mp->input_ptr>0 ) {
26478     if ( token_state ) mp_end_token_list(mp);
26479     else  mp_end_file_reading(mp);
26480   }
26481   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26482   while ( mp->open_parens>0 ) { 
26483     mp_print(mp, " )"); decr(mp->open_parens);
26484   };
26485   while ( mp->cond_ptr!=null ) {
26486     mp_print_nl(mp, "(end occurred when ");
26487 @.end occurred...@>
26488     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26489     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26490     if ( mp->if_line!=0 ) {
26491       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26492     }
26493     mp_print(mp, " was incomplete)");
26494     mp->if_line=if_line_field(mp->cond_ptr);
26495     mp->cur_if=name_type(mp->cond_ptr); mp->cond_ptr=mp_link(mp->cond_ptr);
26496   }
26497   if ( mp->history!=mp_spotless )
26498     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26499       if ( mp->selector==term_and_log ) {
26500     mp->selector=term_only;
26501     mp_print_nl(mp, "(see the transcript file for additional information)");
26502 @.see the transcript file...@>
26503     mp->selector=term_and_log;
26504   }
26505   if ( c==1 ) {
26506     if (mp->ini_version) {
26507       mp_store_mem_file(mp); return;
26508     }
26509     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26510 @.dump...only by INIMP@>
26511   }
26512 }
26513
26514 @ @<Declarations@>=
26515 static void mp_final_cleanup (MP mp) ;
26516 static void mp_init_prim (MP mp) ;
26517 static void mp_init_tab (MP mp) ;
26518
26519 @ @c
26520 void mp_init_prim (MP mp) { /* initialize all the primitives */
26521   @<Put each...@>;
26522 }
26523 @#
26524 void mp_init_tab (MP mp) { /* initialize other tables */
26525   integer k; /* all-purpose index */
26526   @<Initialize table entries (done by \.{INIMP} only)@>;
26527 }
26528
26529
26530 @ When we begin the following code, \MP's tables may still contain garbage;
26531 thus we must proceed cautiously to get bootstrapped in.
26532
26533 But when we finish this part of the program, \MP\ is ready to call on the
26534 |main_control| routine to do its work.
26535
26536 @<Get the first line...@>=
26537
26538   @<Initialize the input routines@>;
26539   if (mp->mem_ident==NULL) {
26540     if ( ! mp_load_mem_file(mp) ) {
26541       (mp->close_file)(mp, mp->mem_file); 
26542        mp->history = mp_fatal_error_stop;
26543        return mp;
26544     }
26545     (mp->close_file)(mp, mp->mem_file);
26546   }
26547   @<Initializations following first line@>;
26548 }
26549
26550 @ @<Initializations following first line@>=
26551   mp->buffer[limit]=(ASCII_code)'%';
26552   mp_fix_date_and_time(mp);
26553   if (mp->random_seed==0)
26554     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
26555   mp_init_randoms(mp, mp->random_seed);
26556   @<Initialize the print |selector|...@>;
26557   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26558     mp_start_input(mp); /* \&{input} assumed */
26559
26560 @ @<Run inimpost commands@>=
26561 {
26562   mp_get_strings_started(mp);
26563   mp_init_tab(mp); /* initialize the tables */
26564   mp_init_prim(mp); /* call |primitive| for each primitive */
26565   mp->init_str_use=mp->max_str_ptr=mp->str_ptr;
26566   mp->init_pool_ptr=mp->max_pool_ptr=mp->pool_ptr;
26567   mp_fix_date_and_time(mp);
26568 }
26569
26570 @ Saving the filename template
26571
26572 @<Save the filename template@>=
26573
26574   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26575   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26576   else { 
26577     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26578   }
26579 }
26580
26581 @* \[47] Debugging.
26582
26583
26584 @* \[48] System-dependent changes.
26585 This section should be replaced, if necessary, by any special
26586 modification of the program
26587 that are necessary to make \MP\ work at a particular installation.
26588 It is usually best to design your change file so that all changes to
26589 previous sections preserve the section numbering; then everybody's version
26590 will be consistent with the published program. More extensive changes,
26591 which introduce new sections, can be inserted here; then only the index
26592 itself will get a new section number.
26593 @^system dependencies@>
26594
26595 @* \[49] Index.
26596 Here is where you can find all uses of each identifier in the program,
26597 with underlined entries pointing to where the identifier was defined.
26598 If the identifier is only one letter long, however, you get to see only
26599 the underlined entries. {\sl All references are to section numbers instead of
26600 page numbers.}
26601
26602 This index also lists error messages and other aspects of the program
26603 that you might want to look up some day. For example, the entry
26604 for ``system dependencies'' lists all sections that should receive
26605 special attention from people who are installing \MP\ in a new
26606 operating environment. A list of various things that can't happen appears
26607 under ``this can't happen''.
26608 Approximately 25 sections are listed under ``inner loop''; these account
26609 for more than 60\pct! of \MP's running time, exclusive of input and output.