dvitomp fix from Akira
[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\vbv="026A % synonym for `\|'
39 \def\vb{\relax\ifmmode\vbv\else$\vbv$\fi}
40
41 \def\(#1){} % this is used to make section names sort themselves better
42 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
43 \def\title{MetaPost}
44 \pdfoutput=1
45 \pageno=3
46
47 @* \[1] Introduction.
48
49 This is \MP\ by John Hobby, a graphics-language processor based on D. E. Knuth's \MF.
50
51 Much of the original Pascal version of this program was copied with
52 permission from MF.web Version 1.9. It interprets a language very
53 similar to D.E. Knuth's METAFONT, but with changes designed to make it
54 more suitable for PostScript output.
55
56 The main purpose of the following program is to explain the algorithms of \MP\
57 as clearly as possible. However, the program has been written so that it
58 can be tuned to run efficiently in a wide variety of operating environments
59 by making comparatively few changes. Such flexibility is possible because
60 the documentation that follows is written in the \.{WEB} language, which is
61 at a higher level than C.
62
63 A large piece of software like \MP\ has inherent complexity that cannot
64 be reduced below a certain level of difficulty, although each individual
65 part is fairly simple by itself. The \.{WEB} language is intended to make
66 the algorithms as readable as possible, by reflecting the way the
67 individual program pieces fit together and by providing the
68 cross-references that connect different parts. Detailed comments about
69 what is going on, and about why things were done in certain ways, have
70 been liberally sprinkled throughout the program.  These comments explain
71 features of the implementation, but they rarely attempt to explain the
72 \MP\ language itself, since the reader is supposed to be familiar with
73 {\sl The {\logos METAFONT\/}book} as well as the manual
74 @.WEB@>
75 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
76 {\sl A User's Manual for MetaPost}, Computing Science Technical Report 162,
77 AT\AM T Bell Laboratories.
78
79 @ The present implementation is a preliminary version, but the possibilities
80 for new features are limited by the desire to remain as nearly compatible
81 with \MF\ as possible.
82
83 On the other hand, the \.{WEB} description can be extended without changing
84 the core of the program, and it has been designed so that such
85 extensions are not extremely difficult to make.
86 The |banner| string defined here should be changed whenever \MP\
87 undergoes any modifications, so that it will be clear which version of
88 \MP\ might be the guilty party when a problem arises.
89 @^extensions to \MP@>
90 @^system dependencies@>
91
92 @d default_banner "This is MetaPost, Version 1.091" /* printed when \MP\ starts */
93 @d true 1
94 @d false 0
95
96 @(mpmp.h@>=
97 #define metapost_version "1.091"
98 #define metapost_magic (('M'*256) + 'P')*65536 + 1091
99 #define metapost_old_magic (('M'*256) + 'P')*65536 + 1080
100
101 @ The external library header for \MP\ is |mplib.h|. It contains a
102 few typedefs and the header defintions for the externally used
103 fuctions.
104
105 The most important of the typedefs is the definition of the structure 
106 |MP_options|, that acts as a small, configurable front-end to the fairly 
107 large |MP_instance| structure.
108  
109 @(mplib.h@>=
110 typedef struct MP_instance * MP;
111 @<Exported types@>
112 typedef struct MP_options {
113   @<Option variables@>
114 } MP_options;
115 @<Exported function headers@>
116
117 @ The internal header file is much longer: it not only lists the complete
118 |MP_instance|, but also a lot of functions that have to be available to
119 the \ps\ backend, that is defined in a separate \.{WEB} file. 
120
121 The variables from |MP_options| are included inside the |MP_instance| 
122 wholesale.
123
124 @(mpmp.h@>=
125 #include <setjmp.h>
126 typedef struct psout_data_struct * psout_data;
127 #ifndef HAVE_BOOLEAN
128 typedef int boolean;
129 #endif
130 #ifndef INTEGER_TYPE
131 typedef int integer;
132 #endif
133 @<Declare helpers@>
134 @<Types in the outer block@>
135 @<Constants in the outer block@>
136 #  ifndef LIBAVL_ALLOCATOR
137 #    define LIBAVL_ALLOCATOR
138     struct libavl_allocator {
139         void *(*libavl_malloc) (struct libavl_allocator *, size_t libavl_size);
140         void (*libavl_free) (struct libavl_allocator *, void *libavl_block);
141     };
142 #  endif
143 typedef struct MP_instance {
144   @<Option variables@>
145   @<Global variables@>
146 } MP_instance;
147 @<Internal library declarations@>
148
149 @ @c 
150 #include "config.h"
151 #include <stdio.h>
152 #include <stdlib.h>
153 #include <string.h>
154 #include <stdarg.h>
155 #include <assert.h>
156 #ifdef HAVE_UNISTD_H
157 #include <unistd.h> /* for access() */
158 #endif
159 #include <time.h> /* for struct tm \& co */
160 #include "mplib.h"
161 #include "mplibps.h" /* external header */
162 #include "mpmp.h" /* internal header */
163 #include "mppsout.h" /* internal header */
164 extern font_number mp_read_font_info (MP mp, char *fname); /* tfmin.w */
165 @h
166 @<Declarations@>
167 @<Basic printing procedures@>
168 @<Error handling procedures@>
169
170 @ Here are the functions that set up the \MP\ instance.
171
172 @<Declarations@> =
173 MP_options *mp_options (void);
174 MP mp_initialize (MP_options *opt);
175
176 @ @c
177 MP_options *mp_options (void) {
178   MP_options *opt;
179   size_t l = sizeof(MP_options);
180   opt = malloc(l);
181   if (opt!=NULL) {
182     memset (opt,0,l);
183     opt->ini_version = true;
184   }
185   return opt;
186
187
188 @ @<Internal library declarations@>=
189 @<Declare subroutines for parsing file names@>
190
191 @ The whole instance structure is initialized with zeroes,
192 this greatly reduces the number of statements needed in 
193 the |Allocate or initialize variables| block.
194
195 @d set_callback_option(A) do { mp->A = mp_##A;
196   if (opt->A!=NULL) mp->A = opt->A;
197 } while (0)
198
199 @c
200 static MP mp_do_new (jmp_buf *buf) {
201   MP mp = malloc(sizeof(MP_instance));
202   if (mp==NULL) {
203     xfree(buf);
204         return NULL;
205   }
206   memset(mp,0,sizeof(MP_instance));
207   mp->jump_buf = buf;
208   return mp;
209 }
210
211 @ @c
212 static void mp_free (MP mp) {
213   int k; /* loop variable */
214   @<Dealloc variables@>
215   if (mp->noninteractive) {
216     @<Finish non-interactive use@>;
217   }
218   xfree(mp->jump_buf);
219   xfree(mp);
220 }
221
222 @ @c
223 static void mp_do_initialize ( MP mp) {
224   @<Local variables for initialization@>
225   @<Set initial values of key variables@>
226 }
227
228 @ This procedure gets things started properly.
229 @c
230 MP mp_initialize (MP_options *opt) { 
231   MP mp;
232   jmp_buf *buf = malloc(sizeof(jmp_buf));
233   if (buf == NULL || setjmp(*buf) != 0) 
234     return NULL;
235   mp = mp_do_new(buf);
236   if (mp == NULL)
237     return NULL;
238   mp->userdata=opt->userdata;
239   @<Set |ini_version|@>;
240   mp->noninteractive=opt->noninteractive;
241   set_callback_option(find_file);
242   set_callback_option(open_file);
243   set_callback_option(read_ascii_file);
244   set_callback_option(read_binary_file);
245   set_callback_option(close_file);
246   set_callback_option(eof_file);
247   set_callback_option(flush_file);
248   set_callback_option(write_ascii_file);
249   set_callback_option(write_binary_file);
250   set_callback_option(shipout_backend);
251   if (opt->banner && *(opt->banner)) {
252     mp->banner = xstrdup(opt->banner);
253   } else {
254     mp->banner = xstrdup(default_banner);
255   }
256   if (opt->command_line && *(opt->command_line))
257     mp->command_line = xstrdup(opt->command_line);
258   if (mp->noninteractive) {
259     @<Prepare function pointers for non-interactive use@>;
260   } 
261   /* open the terminal for output */
262   t_open_out; 
263   @<Find constant sizes@>;
264   @<Allocate or initialize variables@>
265   mp_reallocate_memory(mp,mp->mem_max);
266   mp_reallocate_paths(mp,1000);
267   mp_reallocate_fonts(mp,8);
268   mp->history=mp_fatal_error_stop; /* in case we quit during initialization */
269   @<Check the ``constant'' values...@>;
270   if ( mp->bad>0 ) {
271         char ss[256];
272     mp_snprintf(ss,256,"Ouch---my internal constants have been clobbered!\n"
273                    "---case %i",(int)mp->bad);
274     do_fprintf(mp->err_out,(char *)ss);
275 @.Ouch...clobbered@>
276     return mp;
277   }
278   mp_do_initialize(mp); /* erase preloaded mem */
279   if (mp->ini_version) {
280     @<Run inimpost commands@>;
281   }
282   if (!mp->noninteractive) {
283     @<Initialize the output routines@>;
284     @<Get the first line of input and prepare to start@>;
285     @<Initializations after first line is read@>;
286   } else {
287     mp->history=mp_spotless;
288   }
289   return mp;
290 }
291
292 @ @<Initializations after first line is read@>=
293 mp_set_job_id(mp);
294 mp_init_map_file(mp, mp->troff_mode);
295 mp->history=mp_spotless; /* ready to go! */
296 if (mp->troff_mode) {
297   mp->internal[mp_gtroffmode]=unity; 
298   mp->internal[mp_prologues]=unity; 
299 }
300 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
301   mp->cur_sym=mp->start_sym; mp_back_input(mp);
302 }
303
304 @ @<Exported function headers@>=
305 extern MP_options *mp_options (void);
306 extern MP mp_initialize (MP_options *opt) ;
307 extern int mp_status(MP mp);
308 extern void *mp_userdata(MP mp);
309
310 @ @c
311 int mp_status(MP mp) { return mp->history; }
312
313 @ @c
314 void *mp_userdata(MP mp) { return mp->userdata; }
315
316 @ The overall \MP\ program begins with the heading just shown, after which
317 comes a bunch of procedure declarations and function declarations.
318 Finally we will get to the main program, which begins with the
319 comment `|start_here|'. If you want to skip down to the
320 main program now, you can look up `|start_here|' in the index.
321 But the author suggests that the best way to understand this program
322 is to follow pretty much the order of \MP's components as they appear in the
323 \.{WEB} description you are now reading, since the present ordering is
324 intended to combine the advantages of the ``bottom up'' and ``top down''
325 approaches to the problem of understanding a somewhat complicated system.
326
327 @ Some of the code below is intended to be used only when diagnosing the
328 strange behavior that sometimes occurs when \MP\ is being installed or
329 when system wizards are fooling around with \MP\ without quite knowing
330 what they are doing. Such code will not normally be compiled; it is
331 delimited by the preprocessor test `|#ifdef DEBUG .. #endif|'.
332
333 @ This program has two important variations: (1) There is a long and slow
334 version called \.{INIMP}, which does the extra calculations needed to
335 @.INIMP@>
336 initialize \MP's internal tables; and (2)~there is a shorter and faster
337 production version, which cuts the initialization to a bare minimum.
338
339 Which is which is decided at runtime.
340
341 @ The following parameters can be changed at compile time to extend or
342 reduce \MP's capacity. They may have different values in \.{INIMP} and
343 in production versions of \MP.
344 @.INIMP@>
345 @^system dependencies@>
346
347 @<Constants...@>=
348 #define file_name_size 255 /* file names shouldn't be longer than this */
349 #define bistack_size 1500 /* size of stack for bisection algorithms;
350   should probably be left at this value */
351
352 @ Like the preceding parameters, the following quantities can be changed
353 to extend or reduce \MP's capacity. But if they are changed,
354 it is necessary to rerun the initialization program \.{INIMP}
355 @.INIMP@>
356 to generate new tables for the production \MP\ program.
357 One can't simply make helter-skelter changes to the following constants,
358 since certain rather complex initialization
359 numbers are computed from them. 
360
361 @ @<Glob...@>=
362 int max_strings; /* maximum number of strings; must not exceed |max_halfword| */
363 int pool_size; /* maximum number of characters in strings, including all
364   error messages and help texts, and the names of all identifiers */
365 int mem_max; /* greatest index in \MP's internal |mem| array;
366   must be strictly less than |max_halfword|;
367   must be equal to |mem_top| in \.{INIMP}, otherwise |>=mem_top| */
368 int mem_top; /* largest index in the |mem| array dumped by \.{INIMP};
369   must not be greater than |mem_max| */
370 int hash_prime; /* a prime number equal to about 85\pct! of |hash_size| */
371
372 @ @<Option variables@>=
373 int error_line; /* width of context lines on terminal error messages */
374 int half_error_line; /* width of first lines of contexts in terminal
375   error messages; should be between 30 and |error_line-15| */
376 int max_print_line; /* width of longest text lines output; should be at least 60 */
377 unsigned hash_size; /* maximum number of symbolic tokens,
378   must be less than |max_halfword-3*param_size| */
379 int param_size; /* maximum number of simultaneous macro parameters */
380 int max_in_open; /* maximum number of input files and error insertions that
381   can be going on simultaneously */
382 int main_memory; /* only for options, to set up |mem_max| and |mem_top| */
383 void *userdata; /* this allows the calling application to setup local */
384 char *banner; /* the banner that is printed to the screen and log */
385
386 @ @<Dealloc variables@>=
387 xfree(mp->banner);
388
389
390 @d set_value(a,b,c) do { a=c; if (b>c) a=b; } while (0)
391
392 @<Allocate or ...@>=
393 mp->max_strings=500;
394 mp->pool_size=10000;
395 set_value(mp->error_line,opt->error_line,79);
396 set_value(mp->half_error_line,opt->half_error_line,50);
397 if (mp->half_error_line>mp->error_line-15 ) 
398   mp->half_error_line = mp->error_line-15;
399 set_value(mp->max_print_line,opt->max_print_line,100);
400
401 @ In case somebody has inadvertently made bad settings of the ``constants,''
402 \MP\ checks them using a global variable called |bad|.
403
404 This is the second of many sections of \MP\ where global variables are
405 defined.
406
407 @<Glob...@>=
408 integer bad; /* is some ``constant'' wrong? */
409
410 @ Later on we will say `\ignorespaces|if (mem_max>=max_halfword) bad=10;|',
411 or something similar. (We can't do that until |max_halfword| has been defined.)
412
413 In case you are wondering about the non-consequtive values of |bad|: some
414 of the things that used to be WEB constants are now runtime variables
415 with checking at assignment time.
416
417 @<Check the ``constant'' values for consistency@>=
418 mp->bad=0;
419 if ( mp->mem_top<=1100 ) mp->bad=4;
420
421 @ Some |goto| labels are used by the following definitions. The label
422 `|restart|' is occasionally used at the very beginning of a procedure; and
423 the label `|reswitch|' is occasionally used just prior to a |case|
424 statement in which some cases change the conditions and we wish to branch
425 to the newly applicable case.  Loops that are set up with the |loop|
426 construction defined below are commonly exited by going to `|done|' or to
427 `|found|' or to `|not_found|', and they are sometimes repeated by going to
428 `|continue|'.  If two or more parts of a subroutine start differently but
429 end up the same, the shared code may be gathered together at
430 `|common_ending|'.
431
432 @ Here are some macros for common programming idioms.
433
434 @d incr(A)   (A)=(A)+1 /* increase a variable by unity */
435 @d decr(A)   (A)=(A)-1 /* decrease a variable by unity */
436 @d negate(A) (A)=-(A) /* change the sign of a variable */
437 @d double(A) (A)=(A)+(A)
438 @d odd(A)   ((A)%2==1)
439 @d do_nothing   /* empty statement */
440
441 @* \[2] The character set.
442 In order to make \MP\ readily portable to a wide variety of
443 computers, all of its input text is converted to an internal eight-bit
444 code that includes standard ASCII, the ``American Standard Code for
445 Information Interchange.''  This conversion is done immediately when each
446 character is read in. Conversely, characters are converted from ASCII to
447 the user's external representation just before they are output to a
448 text file.
449 @^ASCII code@>
450
451 Such an internal code is relevant to users of \MP\ only with respect to
452 the \&{char} and \&{ASCII} operations, and the comparison of strings.
453
454 @ Characters of text that have been converted to \MP's internal form
455 are said to be of type |ASCII_code|, which is a subrange of the integers.
456
457 @<Types...@>=
458 typedef unsigned char ASCII_code; /* eight-bit numbers */
459
460 @ The present specification of \MP\ has been written under the assumption
461 that the character set contains at least the letters and symbols associated
462 with ASCII codes 040 through 0176; all of these characters are now
463 available on most computer terminals.
464
465 @<Types...@>=
466 typedef unsigned char text_char; /* the data type of characters in text files */
467
468 @ @<Local variables for init...@>=
469 integer i;
470
471 @ The \MP\ processor converts between ASCII code and
472 the user's external character set by means of arrays |xord| and |xchr|
473 that are analogous to Pascal's |ord| and |chr| functions.
474
475 @(mpmp.h@>=
476 #define xchr(A) mp->xchr[(A)]
477 #define xord(A) mp->xord[(A)]
478
479 @ @<Glob...@>=
480 ASCII_code xord[256];  /* specifies conversion of input characters */
481 text_char xchr[256];  /* specifies conversion of output characters */
482
483 @ The core system assumes all 8-bit is acceptable.  If it is not,
484 a change file has to alter the below section.
485 @^system dependencies@>
486
487 Additionally, people with extended character sets can
488 assign codes arbitrarily, giving an |xchr| equivalent to whatever
489 characters the users of \MP\ are allowed to have in their input files.
490 Appropriate changes to \MP's |char_class| table should then be made.
491 (Unlike \TeX, each installation of \MP\ has a fixed assignment of category
492 codes, called the |char_class|.) Such changes make portability of programs
493 more difficult, so they should be introduced cautiously if at all.
494 @^character set dependencies@>
495 @^system dependencies@>
496
497 @<Set initial ...@>=
498 for (i=0;i<=0377;i++) { xchr(i)=(text_char)i; }
499
500 @ The following system-independent code makes the |xord| array contain a
501 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
502 where |i<j<0177|, the value of |xord[xchr[i]]| will turn out to be
503 |j| or more; hence, standard ASCII code numbers will be used instead of
504 codes below 040 in case there is a coincidence.
505
506 @<Set initial ...@>=
507 for (i=0;i<=255;i++) { 
508    xord(xchr(i))=0177;
509 }
510 for (i=0200;i<=0377;i++) { xord(xchr(i))=(ASCII_code)i;}
511 for (i=0;i<=0176;i++) { xord(xchr(i))=(ASCII_code)i;}
512
513 @* \[3] Input and output.
514 The bane of portability is the fact that different operating systems treat
515 input and output quite differently, perhaps because computer scientists
516 have not given sufficient attention to this problem. People have felt somehow
517 that input and output are not part of ``real'' programming. Well, it is true
518 that some kinds of programming are more fun than others. With existing
519 input/output conventions being so diverse and so messy, the only sources of
520 joy in such parts of the code are the rare occasions when one can find a
521 way to make the program a little less bad than it might have been. We have
522 two choices, either to attack I/O now and get it over with, or to postpone
523 I/O until near the end. Neither prospect is very attractive, so let's
524 get it over with.
525
526 The basic operations we need to do are (1)~inputting and outputting of
527 text, to or from a file or the user's terminal; (2)~inputting and
528 outputting of eight-bit bytes, to or from a file; (3)~instructing the
529 operating system to initiate (``open'') or to terminate (``close'') input or
530 output from a specified file; (4)~testing whether the end of an input
531 file has been reached; (5)~display of bits on the user's screen.
532 The bit-display operation will be discussed in a later section; we shall
533 deal here only with more traditional kinds of I/O.
534
535 @ Finding files happens in a slightly roundabout fashion: the \MP\
536 instance object contains a field that holds a function pointer that finds a
537 file, and returns its name, or NULL. For this, it receives three
538 parameters: the non-qualified name |fname|, the intended |fopen|
539 operation type |fmode|, and the type of the file |ftype|.
540
541 The file types that are passed on in |ftype| can be  used to 
542 differentiate file searches if a library like kpathsea is used,
543 the fopen mode is passed along for the same reason.
544
545 @<Types...@>=
546 typedef unsigned char eight_bits ; /* unsigned one-byte quantity */
547
548 @ @<Exported types@>=
549 enum mp_filetype {
550   mp_filetype_terminal = 0, /* the terminal */
551   mp_filetype_error, /* the terminal */
552   mp_filetype_program , /* \MP\ language input */
553   mp_filetype_log,  /* the log file */
554   mp_filetype_postscript, /* the postscript output */
555   mp_filetype_memfile, /* memory dumps */
556   mp_filetype_metrics, /* TeX font metric files */
557   mp_filetype_fontmap, /* PostScript font mapping files */
558   mp_filetype_font, /*  PostScript type1 font programs */
559   mp_filetype_encoding, /*  PostScript font encoding files */
560   mp_filetype_text  /* first text file for readfrom and writeto primitives */
561 };
562 typedef char *(*mp_file_finder)(MP, const char *, const char *, int);
563 typedef void *(*mp_file_opener)(MP, const char *, const char *, int);
564 typedef char *(*mp_file_reader)(MP, void *, size_t *);
565 typedef void (*mp_binfile_reader)(MP, void *, void **, size_t *);
566 typedef void (*mp_file_closer)(MP, void *);
567 typedef int (*mp_file_eoftest)(MP, void *);
568 typedef void (*mp_file_flush)(MP, void *);
569 typedef void (*mp_file_writer)(MP, void *, const char *);
570 typedef void (*mp_binfile_writer)(MP, void *, void *, size_t);
571
572 @ @<Option variables@>=
573 mp_file_finder find_file;
574 mp_file_opener open_file;
575 mp_file_reader read_ascii_file;
576 mp_binfile_reader read_binary_file;
577 mp_file_closer close_file;
578 mp_file_eoftest eof_file;
579 mp_file_flush flush_file;
580 mp_file_writer write_ascii_file;
581 mp_binfile_writer write_binary_file;
582
583 @ The default function for finding files is |mp_find_file|. It is 
584 pretty stupid: it will only find files in the current directory.
585
586 This function may disappear altogether, it is currently only
587 used for the default font map file.
588
589 @c
590 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype)  {
591   (void) mp;
592   if (fmode[0] != 'r' || (! access (fname,R_OK)) || ftype) {  
593      return mp_strdup(fname);
594   }
595   return NULL;
596 }
597
598 @ Because |mp_find_file| is used so early, it has to be in the helpers
599 section.
600
601 @<Declarations@>=
602 static char *mp_find_file (MP mp, const char *fname, const char *fmode, int ftype) ;
603 static void *mp_open_file (MP mp , const char *fname, const char *fmode, int ftype) ;
604 static char *mp_read_ascii_file (MP mp, void *f, size_t *size) ;
605 static void mp_read_binary_file (MP mp, void *f, void **d, size_t *size) ;
606 static void mp_close_file (MP mp, void *f) ;
607 static int mp_eof_file (MP mp, void *f) ;
608 static void mp_flush_file (MP mp, void *f) ;
609 static void mp_write_ascii_file (MP mp, void *f, const char *s) ;
610 static void mp_write_binary_file (MP mp, void *f, void *s, size_t t) ;
611
612 @ The function to open files can now be very short.
613
614 @c
615 void *mp_open_file(MP mp, const char *fname, const char *fmode, int ftype)  {
616   char realmode[3];
617   (void) mp;
618   realmode[0] = *fmode;
619   realmode[1] = 'b';
620   realmode[2] = 0;
621   if (ftype==mp_filetype_terminal) {
622     return (fmode[0] == 'r' ? stdin : stdout);
623   } else if (ftype==mp_filetype_error) {
624     return stderr;
625   } else if (fname != NULL && (fmode[0] != 'r' || (! access (fname,R_OK)))) {
626     return (void *)fopen(fname, realmode);
627   }
628   return NULL;
629 }
630
631 @ This is a legacy interface: (almost) all file names pass through |name_of_file|.
632
633 @<Glob...@>=
634 char name_of_file[file_name_size+1]; /* the name of a system file */
635 int name_length;/* this many characters are actually
636   relevant in |name_of_file| (the rest are blank) */
637
638 @ @<Option variables@>=
639 int print_found_names; /* configuration parameter */
640
641 @ If this parameter is true, the terminal and log will report the found
642 file names for input files instead of the requested ones. 
643 It is off by default because it creates an extra filename lookup.
644
645 @<Allocate or initialize ...@>=
646 mp->print_found_names = (opt->print_found_names>0 ? true : false);
647
648 @ \MP's file-opening procedures return |false| if no file identified by
649 |name_of_file| could be opened.
650
651 The |OPEN_FILE| macro takes care of the |print_found_names| parameter.
652 It is not used for opening a mem file for read, because that file name 
653 is never printed.
654
655 @d OPEN_FILE(A) do {
656   if (mp->print_found_names) {
657     char *s = (mp->find_file)(mp,mp->name_of_file,A,ftype);
658     if (s!=NULL) {
659       *f = (mp->open_file)(mp,mp->name_of_file,A, ftype); 
660       strncpy(mp->name_of_file,s,file_name_size);
661       xfree(s);
662     } else {
663       *f = NULL;
664     }
665   } else {
666     *f = (mp->open_file)(mp,mp->name_of_file,A, ftype); 
667   }
668 } while (0);
669 return (*f ? true : false)
670
671 @c 
672 static boolean mp_a_open_in (MP mp, void **f, int ftype) {
673   /* open a text file for input */
674   OPEN_FILE("r");
675 }
676 @#
677 boolean mp_w_open_in (MP mp, void **f) {
678   /* open a word file for input */
679   *f = (mp->open_file)(mp,mp->name_of_file,"r",mp_filetype_memfile); 
680   return (*f ? true : false);
681 }
682 @#
683 static boolean mp_a_open_out (MP mp, void **f, int ftype) {
684   /* open a text file for output */
685   OPEN_FILE("w");
686 }
687 @#
688 static boolean mp_b_open_out (MP mp, void **f, int ftype) {
689   /* open a binary file for output */
690   OPEN_FILE("w");
691 }
692 @#
693 boolean mp_w_open_out (MP mp, void **f) {
694   /* open a word file for output */
695   int ftype = mp_filetype_memfile;
696   OPEN_FILE("w");
697 }
698
699 @ @<Internal library ...@>=
700 boolean mp_w_open_out (MP mp, void **f);
701
702 @ @c
703 static char *mp_read_ascii_file (MP mp, void *ff, size_t *size) {
704   int c;
705   size_t len = 0, lim = 128;
706   char *s = NULL;
707   FILE *f = (FILE *)ff;
708   *size = 0;
709   (void) mp; /* for -Wunused */
710   if (f==NULL)
711     return NULL;
712   c = fgetc(f);
713   if (c==EOF)
714     return NULL;
715   s = malloc(lim); 
716   if (s==NULL) return NULL;
717   while (c!=EOF && c!='\n' && c!='\r') { 
718     if (len==lim) {
719       s =realloc(s, (lim+(lim>>2)));
720       if (s==NULL) return NULL;
721       lim+=(lim>>2);
722     }
723         s[len++] = c;
724     c =fgetc(f);
725   }
726   if (c=='\r') {
727     c = fgetc(f);
728     if (c!=EOF && c!='\n')
729        ungetc(c,f);
730   }
731   s[len] = 0;
732   *size = len;
733   return s;
734 }
735
736 @ @c
737 void mp_write_ascii_file (MP mp, void *f, const char *s) {
738   (void) mp;
739   if (f!=NULL) {
740     fputs(s,(FILE *)f);
741   }
742 }
743
744 @ @c
745 void mp_read_binary_file (MP mp, void *f, void **data, size_t *size) {
746   size_t len = 0;
747   (void) mp;
748   if (f!=NULL)
749     len = fread(*data,1,*size,(FILE *)f);
750   *size = len;
751 }
752
753 @ @c
754 void mp_write_binary_file (MP mp, void *f, void *s, size_t size) {
755   (void) mp;
756   if (f!=NULL)
757     (void)fwrite(s,size,1,(FILE *)f);
758 }
759
760
761 @ @c
762 void mp_close_file (MP mp, void *f) {
763   (void) mp;
764   if (f!=NULL)
765     fclose((FILE *)f);
766 }
767
768 @ @c
769 int mp_eof_file (MP mp, void *f) {
770   (void) mp;
771   if (f!=NULL)
772     return feof((FILE *)f);
773    else 
774     return 1;
775 }
776
777 @ @c
778 void mp_flush_file (MP mp, void *f) {
779   (void) mp;
780   if (f!=NULL)
781     fflush((FILE *)f);
782 }
783
784 @ Input from text files is read one line at a time, using a routine called
785 |input_ln|. This function is defined in terms of global variables called
786 |buffer|, |first|, and |last| that will be described in detail later; for
787 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
788 values, and that |first| and |last| are indices into this array
789 representing the beginning and ending of a line of text.
790
791 @<Glob...@>=
792 size_t buf_size; /* maximum number of characters simultaneously present in
793                     current lines of open files */
794 ASCII_code *buffer; /* lines of characters being read */
795 size_t first; /* the first unused position in |buffer| */
796 size_t last; /* end of the line just input to |buffer| */
797 size_t max_buf_stack; /* largest index used in |buffer| */
798
799 @ @<Allocate or initialize ...@>=
800 mp->buf_size = 200;
801 mp->buffer = xmalloc((mp->buf_size+1),sizeof(ASCII_code));
802
803 @ @<Dealloc variables@>=
804 xfree(mp->buffer);
805
806 @ @c
807 static void mp_reallocate_buffer(MP mp, size_t l) {
808   ASCII_code *buffer;
809   if (l>max_halfword) {
810     mp_confusion(mp,"buffer size"); /* can't happen (I hope) */
811   }
812   buffer = xmalloc((l+1),sizeof(ASCII_code));
813   memcpy(buffer,mp->buffer,(mp->buf_size+1));
814   xfree(mp->buffer);
815   mp->buffer = buffer ;
816   mp->buf_size = l;
817 }
818
819 @ The |input_ln| function brings the next line of input from the specified
820 field into available positions of the buffer array and returns the value
821 |true|, unless the file has already been entirely read, in which case it
822 returns |false| and sets |last:=first|.  In general, the |ASCII_code|
823 numbers that represent the next line of the file are input into
824 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
825 global variable |last| is set equal to |first| plus the length of the
826 line. Trailing blanks are removed from the line; thus, either |last=first|
827 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
828 @^inner loop@>
829
830 The variable |max_buf_stack|, which is used to keep track of how large
831 the |buf_size| parameter must be to accommodate the present job, is
832 also kept up to date by |input_ln|.
833
834 @c 
835 static boolean mp_input_ln (MP mp, void *f ) {
836   /* inputs the next line or returns |false| */
837   char *s;
838   size_t size = 0; 
839   mp->last=mp->first; /* cf.\ Matthew 19\thinspace:\thinspace30 */
840   s = (mp->read_ascii_file)(mp,f, &size);
841   if (s==NULL)
842         return false;
843   if (size>0) {
844     mp->last = mp->first+size;
845     if ( mp->last>=mp->max_buf_stack ) { 
846       mp->max_buf_stack=mp->last+1;
847       while ( mp->max_buf_stack>=mp->buf_size ) {
848         mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size>>2)));
849       }
850     }
851     memcpy((mp->buffer+mp->first),s,size);
852     /* while ( mp->buffer[mp->last]==' ' ) mp->last--; */
853   } 
854   free(s);
855   return true;
856 }
857
858 @ The user's terminal acts essentially like other files of text, except
859 that it is used both for input and for output. When the terminal is
860 considered an input file, the file variable is called |term_in|, and when it
861 is considered an output file the file variable is |term_out|.
862 @^system dependencies@>
863
864 @<Glob...@>=
865 void * term_in; /* the terminal as an input file */
866 void * term_out; /* the terminal as an output file */
867 void * err_out; /* the terminal as an output file */
868
869 @ Here is how to open the terminal files. In the default configuration,
870 nothing happens except that the command line (if there is one) is copied
871 to the input buffer.  The variable |command_line| will be filled by the 
872 |main| procedure. The copying can not be done earlier in the program 
873 logic because in the |INI| version, the |buffer| is also used for primitive 
874 initialization.
875
876 @d t_open_out  do {/* open the terminal for text output */
877     mp->term_out = (mp->open_file)(mp,"terminal", "w", mp_filetype_terminal);
878     mp->err_out = (mp->open_file)(mp,"error", "w", mp_filetype_error);
879 } while (0)
880 @d t_open_in  do { /* open the terminal for text input */
881     mp->term_in = (mp->open_file)(mp,"terminal", "r", mp_filetype_terminal);
882     if (mp->command_line!=NULL) {
883       mp->last = strlen(mp->command_line);
884       strncpy((char *)mp->buffer,mp->command_line,mp->last);
885       xfree(mp->command_line);
886     } else {
887           mp->last = 0;
888     }
889 } while (0)
890
891 @<Option variables@>=
892 char *command_line;
893
894 @ Sometimes it is necessary to synchronize the input/output mixture that
895 happens on the user's terminal, and three system-dependent
896 procedures are used for this
897 purpose. The first of these, |update_terminal|, is called when we want
898 to make sure that everything we have output to the terminal so far has
899 actually left the computer's internal buffers and been sent.
900 The second, |clear_terminal|, is called when we wish to cancel any
901 input that the user may have typed ahead (since we are about to
902 issue an unexpected error message). The third, |wake_up_terminal|,
903 is supposed to revive the terminal if the user has disabled it by
904 some instruction to the operating system.  The following macros show how
905 these operations can be specified:
906 @^system dependencies@>
907
908 @(mpmp.h@>=
909 #define update_terminal  (mp->flush_file)(mp,mp->term_out) /* empty the terminal output buffer */
910 #define clear_terminal   do_nothing /* clear the terminal input buffer */
911 #define wake_up_terminal (mp->flush_file)(mp,mp->term_out) 
912                     /* cancel the user's cancellation of output */
913
914 @ We need a special routine to read the first line of \MP\ input from
915 the user's terminal. This line is different because it is read before we
916 have opened the transcript file; there is sort of a ``chicken and
917 egg'' problem here. If the user types `\.{input cmr10}' on the first
918 line, or if some macro invoked by that line does such an \.{input},
919 the transcript file will be named `\.{cmr10.log}'; but if no \.{input}
920 commands are performed during the first line of terminal input, the transcript
921 file will acquire its default name `\.{mpout.log}'. (The transcript file
922 will not contain error messages generated by the first line before the
923 first \.{input} command.)
924
925 The first line is even more special. It's nice to let the user start
926 running a \MP\ job by typing a command line like `\.{MP cmr10}'; in
927 such a case, \MP\ will operate as if the first line of input were
928 `\.{cmr10}', i.e., the first line will consist of the remainder of the
929 command line, after the part that invoked \MP.
930
931 @ Different systems have different ways to get started. But regardless of
932 what conventions are adopted, the routine that initializes the terminal
933 should satisfy the following specifications:
934
935 \yskip\textindent{1)}It should open file |term_in| for input from the
936   terminal. (The file |term_out| will already be open for output to the
937   terminal.)
938
939 \textindent{2)}If the user has given a command line, this line should be
940   considered the first line of terminal input. Otherwise the
941   user should be prompted with `\.{**}', and the first line of input
942   should be whatever is typed in response.
943
944 \textindent{3)}The first line of input, which might or might not be a
945   command line, should appear in locations |first| to |last-1| of the
946   |buffer| array.
947
948 \textindent{4)}The global variable |loc| should be set so that the
949   character to be read next by \MP\ is in |buffer[loc]|. This
950   character should not be blank, and we should have |loc<last|.
951
952 \yskip\noindent(It may be necessary to prompt the user several times
953 before a non-blank line comes in. The prompt is `\.{**}' instead of the
954 later `\.*' because the meaning is slightly different: `\.{input}' need
955 not be typed immediately after~`\.{**}'.)
956
957 @d loc mp->cur_input.loc_field /* location of first unread character in |buffer| */
958
959 @c 
960 boolean mp_init_terminal (MP mp) { /* gets the terminal input started */
961   t_open_in; 
962   if (mp->last!=0) {
963     loc = 0; mp->first = 0;
964         return true;
965   }
966   while (1) { 
967     if (!mp->noninteractive) {
968           wake_up_terminal; do_fprintf(mp->term_out,"**"); update_terminal;
969 @.**@>
970     }
971     if ( ! mp_input_ln(mp, mp->term_in ) ) { /* this shouldn't happen */
972       do_fprintf(mp->term_out,"\n! End of file on the terminal... why?");
973 @.End of file on the terminal@>
974       return false;
975     }
976     loc=(halfword)mp->first;
977     while ( (loc<(int)mp->last)&&(mp->buffer[loc]==' ') ) 
978       incr(loc);
979     if ( loc<(int)mp->last ) { 
980       return true; /* return unless the line was all blank */
981     }
982     if (!mp->noninteractive) {
983           do_fprintf(mp->term_out,"Please type the name of your input file.\n");
984     }
985   }
986 }
987
988 @ @<Declarations@>=
989 static boolean mp_init_terminal (MP mp) ;
990
991
992 @* \[4] String handling.
993 Symbolic token names and diagnostic messages are variable-length strings
994 of eight-bit characters. Many strings \MP\ uses are simply literals
995 in the compiled source, like the error messages and the names of the
996 internal parameters. Other strings are used or defined from the \MP\ input 
997 language, and these have to be interned.
998
999 \MP\ uses strings more extensively than \MF\ does, but the necessary
1000 operations can still be handled with a fairly simple data structure.
1001 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1002 of the strings, and the array |str_start| contains indices of the starting
1003 points of each string. Strings are referred to by integer numbers, so that
1004 string number |s| comprises the characters |str_pool[j]| for
1005 |str_start[s]<=j<str_start[ss]| where |ss=next_str[s]|.  The string pool
1006 is allocated sequentially and |str_pool[pool_ptr]| is the next unused
1007 location.  The first string number not currently in use is |str_ptr|
1008 and |next_str[str_ptr]| begins a list of free string numbers.  String
1009 pool entries |str_start[str_ptr]| up to |pool_ptr| are reserved for a
1010 string currently being constructed.
1011
1012 String numbers 0 to 255 are reserved for strings that correspond to single
1013 ASCII characters. This is in accordance with the conventions of \.{WEB},
1014 @.WEB@>
1015 which converts single-character strings into the ASCII code number of the
1016 single character involved, while it converts other strings into integers
1017 and builds a string pool file. Thus, when the string constant \.{"."} appears
1018 in the program below, \.{WEB} converts it into the integer 46, which is the
1019 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1020 into some integer greater than~255. String number 46 will presumably be the
1021 single character `\..'\thinspace; but some ASCII codes have no standard visible
1022 representation, and \MP\ may need to be able to print an arbitrary
1023 ASCII character, so the first 256 strings are used to specify exactly what
1024 should be printed for each of the 256 possibilities.
1025
1026 @<Types...@>=
1027 typedef int pool_pointer; /* for variables that point into |str_pool| */
1028 typedef int str_number; /* for variables that point into |str_start| */
1029
1030 @ @<Glob...@>=
1031 ASCII_code *str_pool; /* the characters */
1032 pool_pointer *str_start; /* the starting pointers */
1033 str_number *next_str; /* for linking strings in order */
1034 pool_pointer pool_ptr; /* first unused position in |str_pool| */
1035 str_number str_ptr; /* number of the current string being created */
1036 pool_pointer init_pool_ptr; /* the starting value of |pool_ptr| */
1037 str_number init_str_use; /* the initial number of strings in use */
1038 pool_pointer max_pool_ptr; /* the maximum so far of |pool_ptr| */
1039 str_number max_str_ptr; /* the maximum so far of |str_ptr| */
1040
1041 @ @<Allocate or initialize ...@>=
1042 mp->str_pool  = xmalloc ((mp->pool_size +1),sizeof(ASCII_code));
1043 mp->str_start = xmalloc ((mp->max_strings+1),sizeof(pool_pointer));
1044 mp->next_str  = xmalloc ((mp->max_strings+1),sizeof(str_number));
1045
1046 @ @<Dealloc variables@>=
1047 xfree(mp->str_pool);
1048 xfree(mp->str_start);
1049 xfree(mp->next_str);
1050
1051 @ Most printing is done from |char *|s, but sometimes not. Here are
1052 functions that convert an internal string into a |char *| for use
1053 by the printing routines, and vice versa.
1054
1055 @d str(A) mp_str(mp,A)
1056 @d rts(A) mp_rts(mp,A)
1057 @d null_str rts("")
1058
1059 @<Internal ...@>=
1060 int mp_xstrcmp (const char *a, const char *b);
1061 char * mp_str (MP mp, str_number s);
1062
1063 @ @<Declarations@>=
1064 static str_number mp_rts (MP mp, const char *s);
1065 static str_number mp_make_string (MP mp);
1066
1067 @ @c 
1068 int mp_xstrcmp (const char *a, const char *b) {
1069         if (a==NULL && b==NULL) 
1070           return 0;
1071     if (a==NULL)
1072       return -1;
1073     if (b==NULL)
1074       return 1;
1075     return strcmp(a,b);
1076 }
1077
1078 @ The attempt to catch interrupted strings that is in |mp_rts|, is not 
1079 very good: it does not handle nesting over more than one level.
1080
1081 @c
1082 char * mp_str (MP mp, str_number ss) {
1083   char *s;
1084   size_t len;
1085   if (ss==mp->str_ptr) {
1086     return NULL;
1087   } else {
1088     len = (size_t)length(ss);
1089     s = xmalloc(len+1,sizeof(char));
1090     strncpy(s,(char *)(mp->str_pool+(mp->str_start[ss])),len);
1091     s[len] = 0;
1092     return (char *)s;
1093   }
1094 }
1095 str_number mp_rts (MP mp, const char *s) {
1096   int r; /* the new string */ 
1097   int old; /* a possible string in progress */
1098   int i=0;
1099   if (strlen(s)==0) {
1100     return 256;
1101   } else if (strlen(s)==1) {
1102     return s[0];
1103   } else {
1104    old=0;
1105    str_room((integer)strlen(s));
1106    if (mp->str_start[mp->str_ptr]<mp->pool_ptr)
1107      old = mp_make_string(mp);
1108    while (*s) {
1109      append_char(*s);
1110      s++;
1111    }
1112    r = mp_make_string(mp);
1113    if (old!=0) {
1114       str_room(length(old));
1115       while (i<length(old)) {
1116         append_char((mp->str_start[old]+i));
1117       } 
1118       mp_flush_string(mp,old);
1119     }
1120     return r;
1121   }
1122 }
1123
1124 @ Except for |strs_used_up|, the following string statistics are only
1125 maintained when code between |stat| $\ldots$ |tats| delimiters is not
1126 commented out:
1127
1128 @<Glob...@>=
1129 integer strs_used_up; /* strings in use or unused but not reclaimed */
1130 integer pool_in_use; /* total number of cells of |str_pool| actually in use */
1131 integer strs_in_use; /* total number of strings actually in use */
1132 integer max_pl_used; /* maximum |pool_in_use| so far */
1133 integer max_strs_used; /* maximum |strs_in_use| so far */
1134
1135 @ Several of the elementary string operations are performed using \.{WEB}
1136 macros instead of functions, because many of the
1137 operations are done quite frequently and we want to avoid the
1138 overhead of procedure calls. For example, here is
1139 a simple macro that computes the length of a string.
1140 @.WEB@>
1141
1142 @d str_stop(A) mp->str_start[mp->next_str[(A)]] /* one cell past the end of string \# */
1143 @d length(A) (str_stop((A))-mp->str_start[(A)]) /* the number of characters in string \# */
1144
1145 @ The length of the current string is called |cur_length|.  If we decide that
1146 the current string is not needed, |flush_cur_string| resets |pool_ptr| so that
1147 |cur_length| becomes zero.
1148
1149 @d cur_length   (mp->pool_ptr - mp->str_start[mp->str_ptr])
1150 @d flush_cur_string   mp->pool_ptr=mp->str_start[mp->str_ptr]
1151
1152 @ Strings are created by appending character codes to |str_pool|.
1153 The |append_char| macro, defined here, does not check to see if the
1154 value of |pool_ptr| has gotten too high; this test is supposed to be
1155 made before |append_char| is used.
1156
1157 To test if there is room to append |l| more characters to |str_pool|,
1158 we shall write |str_room(l)|, which tries to make sure there is enough room
1159 by compacting the string pool if necessary.  If this does not work,
1160 |do_compaction| aborts \MP\ and gives an apologetic error message.
1161
1162 @d append_char(A)   /* put |ASCII_code| \# at the end of |str_pool| */
1163 { mp->str_pool[mp->pool_ptr]=(ASCII_code)(A); incr(mp->pool_ptr);
1164 }
1165 @d str_room(A)   /* make sure that the pool hasn't overflowed */
1166   { if ( mp->pool_ptr+(A) > mp->max_pool_ptr ) {
1167     if ( mp->pool_ptr+(A) > mp->pool_size ) mp_do_compaction(mp, (A));
1168     else mp->max_pool_ptr=mp->pool_ptr+(A); }
1169   }
1170
1171 @ The following routine is similar to |str_room(1)| but it uses the
1172 argument |mp->pool_size| to prevent |do_compaction| from aborting when
1173 string space is exhausted.
1174
1175 @<Declarations@>=
1176 static void mp_unit_str_room (MP mp);
1177
1178 @ @c
1179 void mp_unit_str_room (MP mp) { 
1180   if ( mp->pool_ptr>=mp->pool_size ) mp_do_compaction(mp, mp->pool_size);
1181   if ( mp->pool_ptr>=mp->max_pool_ptr ) mp->max_pool_ptr=mp->pool_ptr+1;
1182 }
1183
1184 @ \MP's string expressions are implemented in a brute-force way: Every
1185 new string or substring that is needed is simply copied into the string pool.
1186 Space is eventually reclaimed by a procedure called |do_compaction| with
1187 the aid of a simple system system of reference counts.
1188 @^reference counts@>
1189
1190 The number of references to string number |s| will be |str_ref[s]|. The
1191 special value |str_ref[s]=max_str_ref=127| is used to denote an unknown
1192 positive number of references; such strings will never be recycled. If
1193 a string is ever referred to more than 126 times, simultaneously, we
1194 put it in this category. Hence a single byte suffices to store each |str_ref|.
1195
1196 @d max_str_ref 127 /* ``infinite'' number of references */
1197 @d add_str_ref(A) { if ( mp->str_ref[(A)]<max_str_ref ) incr(mp->str_ref[(A)]); }
1198
1199 @<Glob...@>=
1200 int *str_ref;
1201
1202 @ @<Allocate or initialize ...@>=
1203 mp->str_ref = xmalloc ((mp->max_strings+1),sizeof(int));
1204
1205 @ @<Dealloc variables@>=
1206 xfree(mp->str_ref);
1207
1208 @ Here's what we do when a string reference disappears:
1209
1210 @d delete_str_ref(A)  { 
1211     if ( mp->str_ref[(A)]<max_str_ref ) {
1212        if ( mp->str_ref[(A)]>1 ) decr(mp->str_ref[(A)]); 
1213        else mp_flush_string(mp, (A));
1214     }
1215   }
1216
1217 @<Declarations@>=
1218 static void mp_flush_string (MP mp,str_number s) ;
1219
1220 @ We can't flush the first set of static strings at all, so there 
1221 is no point in trying
1222
1223 @c
1224 void mp_flush_string (MP mp,str_number s) { 
1225   if (length(s)>1) {
1226     mp->pool_in_use=mp->pool_in_use-length(s);
1227     decr(mp->strs_in_use);
1228     if ( mp->next_str[s]!=mp->str_ptr ) {
1229       mp->str_ref[s]=0;
1230     } else { 
1231       mp->str_ptr=s;
1232       decr(mp->strs_used_up);
1233     }
1234     mp->pool_ptr=mp->str_start[mp->str_ptr];
1235   }
1236 }
1237
1238 @ C literals cannot be simply added, they need to be set so they can't
1239 be flushed.
1240
1241 @d intern(A) mp_intern(mp,(A))
1242
1243 @c
1244 str_number mp_intern (MP mp, const char *s) {
1245   str_number r ;
1246   r = rts(s);
1247   mp->str_ref[r] = max_str_ref;
1248   return r;
1249 }
1250
1251 @ @<Declarations@>=
1252 static str_number mp_intern (MP mp, const char *s);
1253
1254
1255 @ Once a sequence of characters has been appended to |str_pool|, it
1256 officially becomes a string when the function |make_string| is called.
1257 This function returns the identification number of the new string as its
1258 value.
1259
1260 When getting the next unused string number from the linked list, we pretend
1261 that
1262 $$ \hbox{|max_str_ptr+1|, |max_str_ptr+2|, $\ldots$, |mp->max_strings|} $$
1263 are linked sequentially even though the |next_str| entries have not been
1264 initialized yet.  We never allow |str_ptr| to reach |mp->max_strings|;
1265 |do_compaction| is responsible for making sure of this.
1266
1267 @<Declarations@>=
1268 static str_number mp_make_string (MP mp);
1269
1270 @ @c 
1271 str_number mp_make_string (MP mp) { /* current string enters the pool */
1272   str_number s; /* the new string */
1273 RESTART: 
1274   s=mp->str_ptr;
1275   mp->str_ptr=mp->next_str[s];
1276   if ( mp->str_ptr>mp->max_str_ptr ) {
1277     if ( mp->str_ptr==mp->max_strings ) { 
1278       mp->str_ptr=s;
1279       mp_do_compaction(mp, 0);
1280       goto RESTART;
1281     } else {
1282       mp->max_str_ptr=mp->str_ptr;
1283       mp->next_str[mp->str_ptr]=mp->max_str_ptr+1;
1284     }
1285   }
1286   mp->str_ref[s]=1;
1287   mp->str_start[mp->str_ptr]=mp->pool_ptr;
1288   incr(mp->strs_used_up);
1289   incr(mp->strs_in_use);
1290   mp->pool_in_use=mp->pool_in_use+length(s);
1291   if ( mp->pool_in_use>mp->max_pl_used ) 
1292     mp->max_pl_used=mp->pool_in_use;
1293   if ( mp->strs_in_use>mp->max_strs_used ) 
1294     mp->max_strs_used=mp->strs_in_use;
1295   return s;
1296 }
1297
1298 @ The most interesting string operation is string pool compaction.  The idea
1299 is to recover unused space in the |str_pool| array by recopying the strings
1300 to close the gaps created when some strings become unused.  All string
1301 numbers~$k$ where |str_ref[k]=0| are to be linked into the list of free string
1302 numbers after |str_ptr|.  If this fails to free enough pool space we issue an
1303 |overflow| error unless |needed=mp->pool_size|.  Calling |do_compaction|
1304 with |needed=mp->pool_size| supresses all overflow tests.
1305
1306 The compaction process starts with |last_fixed_str| because all lower numbered
1307 strings are permanently allocated with |max_str_ref| in their |str_ref| entries.
1308
1309 @<Glob...@>=
1310 str_number last_fixed_str; /* last permanently allocated string */
1311 str_number fixed_str_use; /* number of permanently allocated strings */
1312
1313 @ @<Internal library ...@>=
1314 void mp_do_compaction (MP mp, pool_pointer needed) ;
1315
1316 @ @c
1317 void mp_do_compaction (MP mp, pool_pointer needed) {
1318   str_number str_use; /* a count of strings in use */
1319   str_number r,s,t; /* strings being manipulated */
1320   pool_pointer p,q; /* destination and source for copying string characters */
1321   @<Advance |last_fixed_str| as far as possible and set |str_use|@>;
1322   r=mp->last_fixed_str;
1323   s=mp->next_str[r];
1324   p=mp->str_start[s];
1325   while ( s!=mp->str_ptr ) { 
1326     while ( mp->str_ref[s]==0 ) {
1327       @<Advance |s| and add the old |s| to the list of free string numbers;
1328         then |break| if |s=str_ptr|@>;
1329     }
1330     r=s; s=mp->next_str[s];
1331     incr(str_use);
1332     @<Move string |r| back so that |str_start[r]=p|; make |p| the location
1333      after the end of the string@>;
1334   }
1335 DONE:   
1336   @<Move the current string back so that it starts at |p|@>;
1337   if ( needed<mp->pool_size ) {
1338     @<Make sure that there is room for another string with |needed| characters@>;
1339   }
1340   @<Account for the compaction and make sure the statistics agree with the
1341      global versions@>;
1342   mp->strs_used_up=str_use;
1343 }
1344
1345 @ @<Advance |last_fixed_str| as far as possible and set |str_use|@>=
1346 t=mp->next_str[mp->last_fixed_str];
1347 while (t!=mp->str_ptr && mp->str_ref[t]==max_str_ref) {
1348   incr(mp->fixed_str_use);
1349   mp->last_fixed_str=t;
1350   t=mp->next_str[t];
1351 }
1352 str_use=mp->fixed_str_use
1353
1354 @ Because of the way |flush_string| has been written, it should never be
1355 necessary to |break| here.  The extra line of code seems worthwhile to
1356 preserve the generality of |do_compaction|.
1357
1358 @<Advance |s| and add the old |s| to the list of free string numbers;...@>=
1359 {
1360 t=s;
1361 s=mp->next_str[s];
1362 mp->next_str[r]=s;
1363 mp->next_str[t]=mp->next_str[mp->str_ptr];
1364 mp->next_str[mp->str_ptr]=t;
1365 if ( s==mp->str_ptr ) goto DONE;
1366 }
1367
1368 @ The string currently starts at |str_start[r]| and ends just before
1369 |str_start[s]|.  We don't change |str_start[s]| because it might be needed
1370 to locate the next string.
1371
1372 @<Move string |r| back so that |str_start[r]=p|; make |p| the location...@>=
1373 q=mp->str_start[r];
1374 mp->str_start[r]=p;
1375 while ( q<mp->str_start[s] ) { 
1376   mp->str_pool[p]=mp->str_pool[q];
1377   incr(p); incr(q);
1378 }
1379
1380 @ Pointers |str_start[str_ptr]| and |pool_ptr| have not been updated.  When
1381 we do this, anything between them should be moved.
1382
1383 @ @<Move the current string back so that it starts at |p|@>=
1384 q=mp->str_start[mp->str_ptr];
1385 mp->str_start[mp->str_ptr]=p;
1386 while ( q<mp->pool_ptr ) { 
1387   mp->str_pool[p]=mp->str_pool[q];
1388   incr(p); incr(q);
1389 }
1390 mp->pool_ptr=p
1391
1392 @ We must remember that |str_ptr| is not allowed to reach |mp->max_strings|.
1393
1394 @<Make sure that there is room for another string with |needed| char...@>=
1395 if ( str_use>=mp->max_strings-1 )
1396   mp_reallocate_strings (mp,str_use);
1397 if ( mp->pool_ptr+needed>mp->max_pool_ptr ) {
1398   mp_reallocate_pool(mp, mp->pool_ptr+needed);
1399   mp->max_pool_ptr=mp->pool_ptr+needed;
1400 }
1401
1402 @ @<Internal library ...@>=
1403 void mp_reallocate_strings (MP mp, str_number str_use) ;
1404 void mp_reallocate_pool(MP mp, pool_pointer needed) ;
1405
1406 @ @c 
1407 void mp_reallocate_strings (MP mp, str_number str_use) { 
1408   while ( str_use>=mp->max_strings-1 ) {
1409     int l = mp->max_strings + (mp->max_strings/4);
1410     XREALLOC (mp->str_ref,   l, int);
1411     XREALLOC (mp->str_start, l, pool_pointer);
1412     XREALLOC (mp->next_str,  l, str_number);
1413     mp->max_strings = l;
1414   }
1415 }
1416 void mp_reallocate_pool(MP mp, pool_pointer needed) {
1417   while ( needed>mp->pool_size ) {
1418     int l = mp->pool_size + (mp->pool_size/4);
1419         XREALLOC (mp->str_pool, l, ASCII_code);
1420     mp->pool_size = l;
1421   }
1422 }
1423
1424 @ @<Account for the compaction and make sure the statistics agree with...@>=
1425 if ( (mp->str_start[mp->str_ptr]!=mp->pool_in_use)||(str_use!=mp->strs_in_use) )
1426   mp_confusion(mp, "string");
1427 @:this can't happen string}{\quad string@>
1428 incr(mp->pact_count);
1429 mp->pact_chars=mp->pact_chars+mp->pool_ptr-str_stop(mp->last_fixed_str);
1430 mp->pact_strs=mp->pact_strs+str_use-mp->fixed_str_use;
1431
1432 @ A few more global variables are needed to keep track of statistics when
1433 |stat| $\ldots$ |tats| blocks are not commented out.
1434
1435 @<Glob...@>=
1436 integer pact_count; /* number of string pool compactions so far */
1437 integer pact_chars; /* total number of characters moved during compactions */
1438 integer pact_strs; /* total number of strings moved during compactions */
1439
1440 @ @<Initialize compaction statistics@>=
1441 mp->pact_count=0;
1442 mp->pact_chars=0;
1443 mp->pact_strs=0;
1444
1445 @ The following subroutine compares string |s| with another string of the
1446 same length that appears in |buffer| starting at position |k|;
1447 the result is |true| if and only if the strings are equal.
1448
1449 @c 
1450 static boolean mp_str_eq_buf (MP mp,str_number s, integer k) {
1451   /* test equality of strings */
1452   pool_pointer j; /* running index */
1453   j=mp->str_start[s];
1454   while ( j<str_stop(s) ) { 
1455     if ( mp->str_pool[j++]!=mp->buffer[k++] ) 
1456       return false;
1457   }
1458   return true;
1459 }
1460
1461 @ Here is a similar routine, but it compares two strings in the string pool,
1462 and it does not assume that they have the same length. If the first string
1463 is lexicographically greater than, less than, or equal to the second,
1464 the result is respectively positive, negative, or zero.
1465
1466 @c 
1467 static integer mp_str_vs_str (MP mp, str_number s, str_number t) {
1468   /* test equality of strings */
1469   pool_pointer j,k; /* running indices */
1470   integer ls,lt; /* lengths */
1471   integer l; /* length remaining to test */
1472   ls=length(s); lt=length(t);
1473   if ( ls<=lt ) l=ls; else l=lt;
1474   j=mp->str_start[s]; k=mp->str_start[t];
1475   while ( l-->0 ) { 
1476     if ( mp->str_pool[j]!=mp->str_pool[k] ) {
1477        return (mp->str_pool[j]-mp->str_pool[k]); 
1478     }
1479     j++; k++;
1480   }
1481   return (ls-lt);
1482 }
1483
1484 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1485 and |str_ptr| are computed by the \.{INIMP} program, based in part
1486 on the information that \.{WEB} has output while processing \MP.
1487 @.INIMP@>
1488 @^string pool@>
1489
1490 @c 
1491 void mp_get_strings_started (MP mp) { 
1492   /* initializes the string pool,
1493     but returns |false| if something goes wrong */
1494   int k; /* small indices or counters */
1495   str_number g; /* a new string */
1496   mp->pool_ptr=0; mp->str_ptr=0; mp->max_pool_ptr=0; mp->max_str_ptr=0;
1497   mp->str_start[0]=0;
1498   mp->next_str[0]=1;
1499   mp->pool_in_use=0; mp->strs_in_use=0;
1500   mp->max_pl_used=0; mp->max_strs_used=0;
1501   @<Initialize compaction statistics@>;
1502   mp->strs_used_up=0;
1503   @<Make the first 256 strings@>;
1504   g=mp_make_string(mp); /* string 256 == "" */
1505   mp->str_ref[g]=max_str_ref;
1506   mp->last_fixed_str=mp->str_ptr-1;
1507   mp->fixed_str_use=mp->str_ptr;
1508   return;
1509 }
1510
1511 @ @<Declarations@>=
1512 static void mp_get_strings_started (MP mp);
1513
1514 @ The first 256 strings will consist of a single character only.
1515
1516 @<Make the first 256...@>=
1517 for (k=0;k<=255;k++) { 
1518   append_char(k);
1519   g=mp_make_string(mp); 
1520   mp->str_ref[g]=max_str_ref;
1521 }
1522
1523 @ The first 128 strings will contain 95 standard ASCII characters, and the
1524 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1525 unless a system-dependent change is made here. Installations that have
1526 an extended character set, where for example |xchr[032]=@t\.{'^^Z'}@>|,
1527 would like string 032 to be printed as the single character 032 instead
1528 of the three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1529 even people with an extended character set will want to represent string
1530 015 by \.{\^\^M}, since 015 is ASCII's ``carriage return'' code; the idea is
1531 to produce visible strings instead of tabs or line-feeds or carriage-returns
1532 or bell-rings or characters that are treated anomalously in text files.
1533
1534 The boolean expression defined here should be |true| unless \MP\ internal
1535 code number~|k| corresponds to a non-troublesome visible symbol in the
1536 local character set.
1537 If character |k| cannot be printed, and |k<0200|, then character |k+0100| or
1538 |k-0100| must be printable; moreover, ASCII codes |[060..071, 0141..0146]|
1539 must be printable.
1540 @^character set dependencies@>
1541 @^system dependencies@>
1542
1543 @<Character |k| cannot be printed@>=
1544   (k<' ')||(k==127)
1545
1546 @* \[5] On-line and off-line printing.
1547 Messages that are sent to a user's terminal and to the transcript-log file
1548 are produced by several `|print|' procedures. These procedures will
1549 direct their output to a variety of places, based on the setting of
1550 the global variable |selector|, which has the following possible
1551 values:
1552
1553 \yskip
1554 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1555   transcript file.
1556
1557 \hang |log_only|, prints only on the transcript file.
1558
1559 \hang |term_only|, prints only on the terminal.
1560
1561 \hang |no_print|, doesn't print at all. This is used only in rare cases
1562   before the transcript file is open.
1563
1564 \hang |pseudo|, puts output into a cyclic buffer that is used
1565   by the |show_context| routine; when we get to that routine we shall discuss
1566   the reasoning behind this curious mode.
1567
1568 \hang |new_string|, appends the output to the current string in the
1569   string pool.
1570
1571 \hang |>=write_file| prints on one of the files used for the \&{write}
1572 @:write_}{\&{write} primitive@>
1573   command.
1574
1575 \yskip
1576 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1577 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1578 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.  These
1579 relations are not used when |selector| could be |pseudo|, or |new_string|.
1580 We need not check for unprintable characters when |selector<pseudo|.
1581
1582 Three additional global variables, |tally|, |term_offset| and |file_offset|
1583 record the number of characters that have been printed
1584 since they were most recently cleared to zero. We use |tally| to record
1585 the length of (possibly very long) stretches of printing; |term_offset|,
1586 and |file_offset|, on the other hand, keep track of how many
1587 characters have appeared so far on the current line that has been output
1588 to the terminal, the transcript file, or the \ps\ output file, respectively.
1589
1590 @d new_string 0 /* printing is deflected to the string pool */
1591 @d pseudo 2 /* special |selector| setting for |show_context| */
1592 @d no_print 3 /* |selector| setting that makes data disappear */
1593 @d term_only 4 /* printing is destined for the terminal only */
1594 @d log_only 5 /* printing is destined for the transcript file only */
1595 @d term_and_log 6 /* normal |selector| setting */
1596 @d write_file 7 /* first write file selector */
1597
1598 @<Glob...@>=
1599 void * log_file; /* transcript of \MP\ session */
1600 void * ps_file; /* the generic font output goes here */
1601 unsigned int selector; /* where to print a message */
1602 unsigned char dig[23]; /* digits in a number, for rounding */
1603 integer tally; /* the number of characters recently printed */
1604 unsigned int term_offset;
1605   /* the number of characters on the current terminal line */
1606 unsigned int file_offset;
1607   /* the number of characters on the current file line */
1608 ASCII_code *trick_buf; /* circular buffer for pseudoprinting */
1609 integer trick_count; /* threshold for pseudoprinting, explained later */
1610 integer first_count; /* another variable for pseudoprinting */
1611
1612 @ @<Allocate or initialize ...@>=
1613 mp->trick_buf = xmalloc((mp->error_line+1),sizeof(ASCII_code));
1614
1615 @ @<Dealloc variables@>=
1616 xfree(mp->trick_buf);
1617
1618 @ @<Initialize the output routines@>=
1619 mp->selector=term_only; mp->tally=0; mp->term_offset=0; mp->file_offset=0; 
1620
1621 @ Macro abbreviations for output to the terminal and to the log file are
1622 defined here for convenience. Some systems need special conventions
1623 for terminal output, and it is possible to adhere to those conventions
1624 by changing |wterm|, |wterm_ln|, and |wterm_cr| here.
1625 @^system dependencies@>
1626
1627 @(mpmp.h@>=
1628 #define do_fprintf(f,b) (mp->write_ascii_file)(mp,f,b)
1629 #define wterm(A)     do_fprintf(mp->term_out,(A))
1630 #define wterm_chr(A) { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wterm((char *)ss);}
1631 #define wterm_cr     do_fprintf(mp->term_out,"\n")
1632 #define wterm_ln(A)  { wterm_cr; do_fprintf(mp->term_out,(A)); }
1633 #define wlog(A)        do_fprintf(mp->log_file,(A))
1634 #define wlog_chr(A)  { unsigned char ss[2]; ss[0]=(A); ss[1]='\0'; wlog((char *)ss);}
1635 #define wlog_cr      do_fprintf(mp->log_file, "\n")
1636 #define wlog_ln(A)   { wlog_cr; do_fprintf(mp->log_file,(A)); }
1637
1638
1639 @ To end a line of text output, we call |print_ln|.  Cases |0..max_write_files|
1640 use an array |wr_file| that will be declared later.
1641
1642 @d mp_print_text(A) mp_print_str(mp,text((A)))
1643
1644 @<Internal library ...@>=
1645 void mp_print (MP mp, const char *s);
1646 void mp_print_ln (MP mp);
1647 void mp_print_visible_char (MP mp, ASCII_code s); 
1648 void mp_print_char (MP mp, ASCII_code k);
1649 void mp_print_str (MP mp, str_number s);
1650 void mp_print_nl (MP mp, const char *s);
1651 void mp_print_two (MP mp,scaled x, scaled y) ;
1652 void mp_print_scaled (MP mp,scaled s);
1653
1654 @ @<Basic print...@>=
1655 void mp_print_ln (MP mp) { /* prints an end-of-line */
1656  switch (mp->selector) {
1657   case term_and_log: 
1658     wterm_cr; wlog_cr;
1659     mp->term_offset=0;  mp->file_offset=0;
1660     break;
1661   case log_only: 
1662     wlog_cr; mp->file_offset=0;
1663     break;
1664   case term_only: 
1665     wterm_cr; mp->term_offset=0;
1666     break;
1667   case no_print:
1668   case pseudo: 
1669   case new_string: 
1670     break;
1671   default: 
1672     do_fprintf(mp->wr_file[(mp->selector-write_file)],"\n");
1673   }
1674 } /* note that |tally| is not affected */
1675
1676 @ The |print_visible_char| procedure sends one character to the desired
1677 destination, using the |xchr| array to map it into an external character
1678 compatible with |input_ln|.  (It assumes that it is always called with
1679 a visible ASCII character.)  All printing comes through |print_ln| or
1680 |print_char|, which ultimately calls |print_visible_char|, hence these
1681 routines are the ones that limit lines to at most |max_print_line| characters.
1682 But we must make an exception for the \ps\ output file since it is not safe
1683 to cut up lines arbitrarily in \ps.
1684
1685 Procedure |unit_str_room| needs to be declared |forward| here because it calls
1686 |do_compaction| and |do_compaction| can call the error routines.  Actually,
1687 |unit_str_room| avoids |overflow| errors but it can call |confusion|.
1688
1689 @<Basic printing...@>=
1690 void mp_print_visible_char (MP mp, ASCII_code s) { /* prints a single character */
1691   switch (mp->selector) {
1692   case term_and_log: 
1693     wterm_chr(xchr(s)); wlog_chr(xchr(s));
1694     incr(mp->term_offset); incr(mp->file_offset);
1695     if ( mp->term_offset==(unsigned)mp->max_print_line ) { 
1696        wterm_cr; mp->term_offset=0;
1697     };
1698     if ( mp->file_offset==(unsigned)mp->max_print_line ) { 
1699        wlog_cr; mp->file_offset=0;
1700     };
1701     break;
1702   case log_only: 
1703     wlog_chr(xchr(s)); incr(mp->file_offset);
1704     if ( mp->file_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1705     break;
1706   case term_only: 
1707     wterm_chr(xchr(s)); incr(mp->term_offset);
1708     if ( mp->term_offset==(unsigned)mp->max_print_line ) mp_print_ln(mp);
1709     break;
1710   case no_print: 
1711     break;
1712   case pseudo: 
1713     if ( mp->tally<mp->trick_count ) 
1714       mp->trick_buf[mp->tally % mp->error_line]=s;
1715     break;
1716   case new_string: 
1717     if ( mp->pool_ptr>=mp->max_pool_ptr ) { 
1718       mp_unit_str_room(mp);
1719       if ( mp->pool_ptr>=mp->pool_size ) 
1720         goto DONE; /* drop characters if string space is full */
1721     };
1722     append_char(s);
1723     break;
1724   default:
1725     { text_char ss[2]; ss[0] = xchr(s); ss[1]=0;
1726       do_fprintf(mp->wr_file[(mp->selector-write_file)],(char *)ss);
1727     }
1728   }
1729 DONE:
1730   incr(mp->tally);
1731 }
1732
1733 @ The |print_char| procedure sends one character to the desired destination.
1734 File names and string expressions might contain |ASCII_code| values that
1735 can't be printed using |print_visible_char|.  These characters will be
1736 printed in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}'.
1737 (This procedure assumes that it is safe to bypass all checks for unprintable
1738 characters when |selector| is in the range |0..max_write_files-1|.
1739 The user might want to write unprintable characters.
1740
1741 @<Basic printing...@>=
1742 void mp_print_char (MP mp, ASCII_code k) { /* prints a single character */
1743   if ( mp->selector<pseudo || mp->selector>=write_file) {
1744     mp_print_visible_char(mp, k);
1745   } else if ( @<Character |k| cannot be printed@> ) { 
1746     mp_print(mp, "^^"); 
1747     if ( k<0100 ) { 
1748       mp_print_visible_char(mp, k+0100); 
1749     } else if ( k<0200 ) { 
1750       mp_print_visible_char(mp, k-0100); 
1751     } else {
1752       int l; /* small index or counter */
1753       l = (k / 16);
1754       mp_print_visible_char(mp, xord(l<10 ? l+'0' : l-10+'a'));
1755       l = (k % 16);
1756       mp_print_visible_char(mp, xord(l<10 ? l+'0' : l-10+'a'));
1757     }
1758   } else {
1759     mp_print_visible_char(mp, k);
1760   }
1761 }
1762
1763 @ An entire string is output by calling |print|. Note that if we are outputting
1764 the single standard ASCII character \.c, we could call |print("c")|, since
1765 |"c"=99| is the number of a single-character string, as explained above. But
1766 |print_char("c")| is quicker, so \MP\ goes directly to the |print_char|
1767 routine when it knows that this is safe. (The present implementation
1768 assumes that it is always safe to print a visible ASCII character.)
1769 @^system dependencies@>
1770
1771 @<Basic print...@>=
1772 static void mp_do_print (MP mp, const char *ss, size_t len) { /* prints string |s| */
1773   size_t j = 0;
1774   while ( j<len ){ 
1775     mp_print_char(mp, xord((int)ss[j])); j++;
1776   }
1777 }
1778
1779
1780 @<Basic print...@>=
1781 void mp_print (MP mp, const char *ss) {
1782   if (ss==NULL) return;
1783   mp_do_print(mp, ss,strlen(ss));
1784 }
1785 void mp_print_str (MP mp, str_number s) {
1786   pool_pointer j; /* current character code position */
1787   if ( (s<0)||(s>mp->max_str_ptr) ) {
1788      mp_do_print(mp,"???",3); /* this can't happen */
1789 @.???@>
1790   }
1791   j=mp->str_start[s];
1792   mp_do_print(mp, (char *)(mp->str_pool+j), (size_t)(str_stop(s)-j));
1793 }
1794
1795
1796 @ Here is the very first thing that \MP\ prints: a headline that identifies
1797 the version number and base name. The |term_offset| variable is temporarily
1798 incorrect, but the discrepancy is not serious since we assume that the banner
1799 and mem identifier together will occupy at most |max_print_line|
1800 character positions.
1801
1802 @<Initialize the output...@>=
1803 wterm (mp->banner);
1804 if (mp->mem_ident!=NULL) 
1805   mp_print(mp,mp->mem_ident); 
1806 mp_print_ln(mp);
1807 update_terminal;
1808
1809 @ The procedure |print_nl| is like |print|, but it makes sure that the
1810 string appears at the beginning of a new line.
1811
1812 @<Basic print...@>=
1813 void mp_print_nl (MP mp, const char *s) { /* prints string |s| at beginning of line */
1814   switch(mp->selector) {
1815   case term_and_log: 
1816     if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_ln(mp);
1817     break;
1818   case log_only: 
1819     if ( mp->file_offset>0 ) mp_print_ln(mp);
1820     break;
1821   case term_only: 
1822     if ( mp->term_offset>0 ) mp_print_ln(mp);
1823     break;
1824   case no_print:
1825   case pseudo:
1826   case new_string: 
1827         break;
1828   } /* there are no other cases */
1829   mp_print(mp, s);
1830 }
1831
1832 @ The following procedure, which prints out the decimal representation of a
1833 given integer |n|, assumes that all integers fit nicely into a |int|.
1834 @^system dependencies@>
1835
1836 @<Basic print...@>=
1837 void mp_print_int (MP mp,integer n) { /* prints an integer in decimal form */
1838   char s[12];
1839   mp_snprintf(s,12,"%d", (int)n);
1840   mp_print(mp,s);
1841 }
1842
1843 @ @<Internal library ...@>=
1844 void mp_print_int (MP mp,integer n);
1845
1846 @ \MP\ also makes use of a trivial procedure to print two digits. The
1847 following subroutine is usually called with a parameter in the range |0<=n<=99|.
1848
1849 @c 
1850 static void mp_print_dd (MP mp,integer n) { /* prints two least significant digits */
1851   n=abs(n) % 100; 
1852   mp_print_char(mp, xord('0'+(n / 10)));
1853   mp_print_char(mp, xord('0'+(n % 10)));
1854 }
1855
1856
1857 @ @<Declarations@>=
1858 static void mp_print_dd (MP mp,integer n);
1859
1860 @ Here is a procedure that asks the user to type a line of input,
1861 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1862 The input is placed into locations |first| through |last-1| of the
1863 |buffer| array, and echoed on the transcript file if appropriate.
1864
1865 This procedure is never called when |interaction<mp_scroll_mode|.
1866
1867 @d prompt_input(A) do { 
1868     if (!mp->noninteractive) {
1869       wake_up_terminal; mp_print(mp, (A)); 
1870     }
1871     mp_term_input(mp);
1872   } while (0) /* prints a string and gets a line of input */
1873
1874 @c 
1875 void mp_term_input (MP mp) { /* gets a line from the terminal */
1876   size_t k; /* index into |buffer| */
1877   if (mp->noninteractive) {
1878     if (!mp_input_ln(mp, mp->term_in ))
1879           longjmp(*(mp->jump_buf),1);  /* chunk finished */
1880     mp->buffer[mp->last]=xord('%'); 
1881   } else {
1882     update_terminal; /* Now the user sees the prompt for sure */
1883     if (!mp_input_ln(mp, mp->term_in )) {
1884           mp_fatal_error(mp, "End of file on the terminal!");
1885 @.End of file on the terminal@>
1886     }
1887     mp->term_offset=0; /* the user's line ended with \<\rm return> */
1888     decr(mp->selector); /* prepare to echo the input */
1889     if ( mp->last!=mp->first ) {
1890       for (k=mp->first;k<=mp->last-1;k++) {
1891         mp_print_char(mp, mp->buffer[k]);
1892       }
1893     }
1894     mp_print_ln(mp); 
1895     mp->buffer[mp->last]=xord('%'); 
1896     incr(mp->selector); /* restore previous status */
1897   }
1898 }
1899
1900 @* \[6] Reporting errors.
1901 When something anomalous is detected, \MP\ typically does something like this:
1902 $$\vbox{\halign{#\hfil\cr
1903 |print_err("Something anomalous has been detected");|\cr
1904 |help3("This is the first line of my offer to help.")|\cr
1905 |("This is the second line. I'm trying to")|\cr
1906 |("explain the best way for you to proceed.");|\cr
1907 |error;|\cr}}$$
1908 A two-line help message would be given using |help2|, etc.; these informal
1909 helps should use simple vocabulary that complements the words used in the
1910 official error message that was printed. (Outside the U.S.A., the help
1911 messages should preferably be translated into the local vernacular. Each
1912 line of help is at most 60 characters long, in the present implementation,
1913 so that |max_print_line| will not be exceeded.)
1914
1915 The |print_err| procedure supplies a `\.!' before the official message,
1916 and makes sure that the terminal is awake if a stop is going to occur.
1917 The |error| procedure supplies a `\..' after the official message, then it
1918 shows the location of the error; and if |interaction=error_stop_mode|,
1919 it also enters into a dialog with the user, during which time the help
1920 message may be printed.
1921 @^system dependencies@>
1922
1923 @ The global variable |interaction| has four settings, representing increasing
1924 amounts of user interaction:
1925
1926 @<Exported types@>=
1927 enum mp_interaction_mode { 
1928  mp_unspecified_mode=0, /* extra value for command-line switch */
1929  mp_batch_mode, /* omits all stops and omits terminal output */
1930  mp_nonstop_mode, /* omits all stops */
1931  mp_scroll_mode, /* omits error stops */
1932  mp_error_stop_mode /* stops at every opportunity to interact */
1933 };
1934
1935 @ @<Option variables@>=
1936 int interaction; /* current level of interaction */
1937 int noninteractive; /* do we have a terminal? */
1938
1939 @ Set it here so it can be overwritten by the commandline
1940
1941 @<Allocate or initialize ...@>=
1942 mp->interaction=opt->interaction;
1943 if (mp->interaction==mp_unspecified_mode || mp->interaction>mp_error_stop_mode) 
1944   mp->interaction=mp_error_stop_mode;
1945 if (mp->interaction<mp_unspecified_mode) 
1946   mp->interaction=mp_batch_mode;
1947
1948
1949
1950 @d print_err(A) mp_print_err(mp,(A))
1951
1952 @<Internal ...@>=
1953 void mp_print_err(MP mp, const char * A);
1954
1955 @ @c
1956 void mp_print_err(MP mp, const char * A) { 
1957   if ( mp->interaction==mp_error_stop_mode ) 
1958     wake_up_terminal;
1959   mp_print_nl(mp, "! "); 
1960   mp_print(mp, A);
1961 @.!\relax@>
1962 }
1963
1964
1965 @ \MP\ is careful not to call |error| when the print |selector| setting
1966 might be unusual. The only possible values of |selector| at the time of
1967 error messages are
1968
1969 \yskip\hang|no_print| (when |interaction=mp_batch_mode|
1970   and |log_file| not yet open);
1971
1972 \hang|term_only| (when |interaction>mp_batch_mode| and |log_file| not yet open);
1973
1974 \hang|log_only| (when |interaction=mp_batch_mode| and |log_file| is open);
1975
1976 \hang|term_and_log| (when |interaction>mp_batch_mode| and |log_file| is open).
1977
1978 @<Initialize the print |selector| based on |interaction|@>=
1979 if ( mp->interaction==mp_batch_mode ) mp->selector=no_print; else mp->selector=term_only
1980
1981 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1982 routine is active when |error| is called; this ensures that |get_next|
1983 will never be called recursively.
1984 @^recursion@>
1985
1986 The global variable |history| records the worst level of error that
1987 has been detected. It has four possible values: |spotless|, |warning_issued|,
1988 |error_message_issued|, and |fatal_error_stop|.
1989
1990 Another global variable, |error_count|, is increased by one when an
1991 |error| occurs without an interactive dialog, and it is reset to zero at
1992 the end of every statement.  If |error_count| reaches 100, \MP\ decides
1993 that there is no point in continuing further.
1994
1995 @<Exported types@>=
1996 enum mp_history_state {
1997   mp_spotless=0, /* |history| value when nothing has been amiss yet */
1998   mp_warning_issued, /* |history| value when |begin_diagnostic| has been called */
1999   mp_error_message_issued, /* |history| value when |error| has been called */
2000   mp_fatal_error_stop, /* |history| value when termination was premature */
2001   mp_system_error_stop /* |history| value when termination was due to disaster */
2002 };
2003
2004 @ @<Glob...@>=
2005 boolean deletions_allowed; /* is it safe for |error| to call |get_next|? */
2006 int history; /* has the source input been clean so far? */
2007 int error_count; /* the number of scrolled errors since the last statement ended */
2008
2009 @ The value of |history| is initially |fatal_error_stop|, but it will
2010 be changed to |spotless| if \MP\ survives the initialization process.
2011
2012 @<Allocate or ...@>=
2013 mp->deletions_allowed=true; /* |history| is initialized elsewhere */
2014
2015 @ Since errors can be detected almost anywhere in \MP, we want to declare the
2016 error procedures near the beginning of the program. But the error procedures
2017 in turn use some other procedures, which need to be declared |forward|
2018 before we get to |error| itself.
2019
2020 It is possible for |error| to be called recursively if some error arises
2021 when |get_next| is being used to delete a token, and/or if some fatal error
2022 occurs while \MP\ is trying to fix a non-fatal one. But such recursion
2023 @^recursion@>
2024 is never more than two levels deep.
2025
2026 @<Declarations@>=
2027 static void mp_get_next (MP mp);
2028 static void mp_term_input (MP mp);
2029 static void mp_show_context (MP mp);
2030 static void mp_begin_file_reading (MP mp);
2031 static void mp_open_log_file (MP mp);
2032 static void mp_clear_for_error_prompt (MP mp);
2033
2034 @ @<Internal ...@>=
2035 void mp_normalize_selector (MP mp);
2036
2037 @ Individual lines of help are recorded in the array |help_line|, which
2038 contains entries in positions |0..(help_ptr-1)|. They should be printed
2039 in reverse order, i.e., with |help_line[0]| appearing last.
2040
2041 @d hlp1(A) mp->help_line[0]=A; }
2042 @d hlp2(A,B) mp->help_line[1]=A; hlp1(B)
2043 @d hlp3(A,B,C) mp->help_line[2]=A; hlp2(B,C)
2044 @d hlp4(A,B,C,D) mp->help_line[3]=A; hlp3(B,C,D)
2045 @d hlp5(A,B,C,D,E) mp->help_line[4]=A; hlp4(B,C,D,E)
2046 @d hlp6(A,B,C,D,E,F) mp->help_line[5]=A; hlp5(B,C,D,E,F)
2047 @d help0 mp->help_ptr=0 /* sometimes there might be no help */
2048 @d help1  { mp->help_ptr=1; hlp1 /* use this with one help line */
2049 @d help2  { mp->help_ptr=2; hlp2 /* use this with two help lines */
2050 @d help3  { mp->help_ptr=3; hlp3 /* use this with three help lines */
2051 @d help4  { mp->help_ptr=4; hlp4 /* use this with four help lines */
2052 @d help5  { mp->help_ptr=5; hlp5 /* use this with five help lines */
2053 @d help6  { mp->help_ptr=6; hlp6 /* use this with six help lines */
2054
2055 @<Glob...@>=
2056 const char * help_line[6]; /* helps for the next |error| */
2057 unsigned int help_ptr; /* the number of help lines present */
2058 boolean use_err_help; /* should the |err_help| string be shown? */
2059 str_number err_help; /* a string set up by \&{errhelp} */
2060 str_number filename_template; /* a string set up by \&{filenametemplate} */
2061
2062 @ @<Allocate or ...@>=
2063 mp->use_err_help=false;
2064
2065 @ The |jump_out| procedure just cuts across all active procedure levels and
2066 goes to |end_of_MP|. This is the only nonlocal |goto| statement in the
2067 whole program. It is used when there is no recovery from a particular error.
2068
2069 The program uses a |jump_buf| to handle this, this is initialized at three
2070 spots: the start of |mp_new|, the start of |mp_initialize|, and the start 
2071 of |mp_run|. Those are the only library enty points.
2072
2073 @^system dependencies@>
2074
2075 @<Glob...@>=
2076 jmp_buf *jump_buf;
2077
2078 @ If the array of internals is still |NULL| when |jump_out| is called, a
2079 crash occured during initialization, and it is not safe to run the normal
2080 cleanup routine.
2081
2082 @<Error hand...@>=
2083 static void mp_jump_out (MP mp) { 
2084   if (mp->internal!=NULL && mp->history < mp_system_error_stop) 
2085     mp_close_files_and_terminate(mp);
2086   longjmp(*(mp->jump_buf),1);
2087 }
2088
2089 @ Here now is the general |error| routine.
2090
2091 @<Error hand...@>=
2092 void mp_error (MP mp) { /* completes the job of error reporting */
2093   ASCII_code c; /* what the user types */
2094   integer s1,s2,s3; /* used to save global variables when deleting tokens */
2095   pool_pointer j; /* character position being printed */
2096   if ( mp->history<mp_error_message_issued ) 
2097         mp->history=mp_error_message_issued;
2098   mp_print_char(mp, xord('.')); mp_show_context(mp);
2099   if ((!mp->noninteractive) && (mp->interaction==mp_error_stop_mode )) {
2100     @<Get user's advice and |return|@>;
2101   }
2102   incr(mp->error_count);
2103   if ( mp->error_count==100 ) { 
2104     mp_print_nl(mp,"(That makes 100 errors; please try again.)");
2105 @.That makes 100 errors...@>
2106     mp->history=mp_fatal_error_stop; mp_jump_out(mp);
2107   }
2108   @<Put help message on the transcript file@>;
2109 }
2110 void mp_warn (MP mp, const char *msg) {
2111   unsigned saved_selector = mp->selector;
2112   mp_normalize_selector(mp);
2113   mp_print_nl(mp,"Warning: ");
2114   mp_print(mp,msg);
2115   mp_print_ln(mp);
2116   mp->selector = saved_selector;
2117 }
2118
2119 @ @<Exported function ...@>=
2120 extern void mp_error (MP mp);
2121 extern void mp_warn (MP mp, const char *msg);
2122
2123
2124 @ @<Get user's advice...@>=
2125 while (true) { 
2126 CONTINUE:
2127   mp_clear_for_error_prompt(mp); prompt_input("? ");
2128 @.?\relax@>
2129   if ( mp->last==mp->first ) return;
2130   c=mp->buffer[mp->first];
2131   if ( c>='a' ) c=c+'A'-'a'; /* convert to uppercase */
2132   @<Interpret code |c| and |return| if done@>;
2133 }
2134
2135 @ It is desirable to provide an `\.E' option here that gives the user
2136 an easy way to return from \MP\ to the system editor, with the offending
2137 line ready to be edited. But such an extension requires some system
2138 wizardry, so the present implementation simply types out the name of the
2139 file that should be
2140 edited and the relevant line number.
2141 @^system dependencies@>
2142
2143 @<Exported types@>=
2144 typedef void (*mp_editor_cmd)(MP, char *, int);
2145
2146 @ @<Option variables@>=
2147 mp_editor_cmd run_editor;
2148
2149 @ @<Allocate or initialize ...@>=
2150 set_callback_option(run_editor);
2151
2152 @ @<Declarations@>=
2153 static void mp_run_editor (MP mp, char *fname, int fline);
2154
2155 @ @c 
2156 void mp_run_editor (MP mp, char *fname, int fline) {
2157     char *s = xmalloc(256,1);
2158     mp_snprintf(s, 256,"You want to edit file %s at line %d\n", fname, fline);
2159     wterm_ln(s);
2160 @.You want to edit file x@>
2161 }
2162
2163
2164 There is a secret `\.D' option available when the debugging routines haven't
2165 been commented~out.
2166 @^debugging@>
2167
2168 @<Interpret code |c| and |return| if done@>=
2169 switch (c) {
2170 case '0': case '1': case '2': case '3': case '4':
2171 case '5': case '6': case '7': case '8': case '9': 
2172   if ( mp->deletions_allowed ) {
2173     @<Delete |c-"0"| tokens and |continue|@>;
2174   }
2175   break;
2176 case 'E': 
2177   if ( mp->file_ptr>0 ){ 
2178     mp->interaction=mp_scroll_mode; 
2179     mp_close_files_and_terminate(mp);
2180     (mp->run_editor)(mp, 
2181                      str(mp->input_stack[mp->file_ptr].name_field), 
2182                      mp_true_line(mp));
2183     mp_jump_out(mp);
2184   }
2185   break;
2186 case 'H': 
2187   @<Print the help information and |continue|@>;
2188   /* |break;| */
2189 case 'I':
2190   @<Introduce new material from the terminal and |return|@>;
2191   /* |break;| */
2192 case 'Q': case 'R': case 'S':
2193   @<Change the interaction level and |return|@>;
2194   /* |break;| */
2195 case 'X':
2196   mp->interaction=mp_scroll_mode; mp_jump_out(mp);
2197   break;
2198 default:
2199   break;
2200 }
2201 @<Print the menu of available options@>
2202
2203 @ @<Print the menu...@>=
2204
2205   mp_print(mp, "Type <return> to proceed, S to scroll future error messages,");
2206 @.Type <return> to proceed...@>
2207   mp_print_nl(mp, "R to run without stopping, Q to run quietly,");
2208   mp_print_nl(mp, "I to insert something, ");
2209   if ( mp->file_ptr>0 ) 
2210     mp_print(mp, "E to edit your file,");
2211   if ( mp->deletions_allowed )
2212     mp_print_nl(mp, "1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2213   mp_print_nl(mp, "H for help, X to quit.");
2214 }
2215
2216 @ Here the author of \MP\ apologizes for making use of the numerical
2217 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2218 |mp_batch_mode|, |mp_nonstop_mode|, |mp_scroll_mode|.
2219 @^Knuth, Donald Ervin@>
2220
2221 @<Change the interaction...@>=
2222
2223   mp->error_count=0; mp->interaction=mp_batch_mode+c-'Q';
2224   mp_print(mp, "OK, entering ");
2225   switch (c) {
2226   case 'Q': mp_print(mp, "batchmode"); decr(mp->selector); break;
2227   case 'R': mp_print(mp, "nonstopmode"); break;
2228   case 'S': mp_print(mp, "scrollmode"); break;
2229   } /* there are no other cases */
2230   mp_print(mp, "..."); mp_print_ln(mp); update_terminal; return;
2231 }
2232
2233 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2234 contain the material inserted by the user; otherwise another prompt will
2235 be given. In order to understand this part of the program fully, you need
2236 to be familiar with \MP's input stacks.
2237
2238 @<Introduce new material...@>=
2239
2240   mp_begin_file_reading(mp); /* enter a new syntactic level for terminal input */
2241   if ( mp->last>mp->first+1 ) { 
2242     loc=(halfword)(mp->first+1); mp->buffer[mp->first]=xord(' ');
2243   } else { 
2244    prompt_input("insert>"); loc=(halfword)mp->first;
2245 @.insert>@>
2246   };
2247   mp->first=mp->last+1; mp->cur_input.limit_field=(halfword)mp->last; return;
2248 }
2249
2250 @ We allow deletion of up to 99 tokens at a time.
2251
2252 @<Delete |c-"0"| tokens...@>=
2253
2254   s1=mp->cur_cmd; s2=mp->cur_mod; s3=mp->cur_sym; mp->OK_to_interrupt=false;
2255   if ( (mp->last>mp->first+1) && (mp->buffer[mp->first+1]>='0')&&(mp->buffer[mp->first+1]<='9') )
2256     c=xord(c*10+mp->buffer[mp->first+1]-'0'*11);
2257   else 
2258     c=c-'0';
2259   while ( c>0 ) { 
2260     mp_get_next(mp); /* one-level recursive call of |error| is possible */
2261     @<Decrease the string reference count, if the current token is a string@>;
2262     decr(c);
2263   };
2264   mp->cur_cmd=s1; mp->cur_mod=s2; mp->cur_sym=s3; mp->OK_to_interrupt=true;
2265   help2("I have just deleted some text, as you asked.",
2266        "You can now delete more, or insert, or whatever.");
2267   mp_show_context(mp); 
2268   goto CONTINUE;
2269 }
2270
2271 @ @<Print the help info...@>=
2272
2273   if ( mp->use_err_help ) { 
2274     @<Print the string |err_help|, possibly on several lines@>;
2275     mp->use_err_help=false;
2276   } else { 
2277     if ( mp->help_ptr==0 ) {
2278       help2("Sorry, I don't know how to help in this situation.",
2279             "Maybe you should try asking a human?");
2280      }
2281     do { 
2282       decr(mp->help_ptr); mp_print(mp, mp->help_line[mp->help_ptr]); mp_print_ln(mp);
2283     } while (mp->help_ptr!=0);
2284   };
2285   help4("Sorry, I already gave what help I could...",
2286        "Maybe you should try asking a human?",
2287        "An error might have occurred before I noticed any problems.",
2288        "``If all else fails, read the instructions.''");
2289   goto CONTINUE;
2290 }
2291
2292 @ @<Print the string |err_help|, possibly on several lines@>=
2293 j=mp->str_start[mp->err_help];
2294 while ( j<str_stop(mp->err_help) ) { 
2295   if ( mp->str_pool[j]!='%' ) mp_print_str(mp, mp->str_pool[j]);
2296   else if ( j+1==str_stop(mp->err_help) ) mp_print_ln(mp);
2297   else if ( mp->str_pool[j+1]!='%' ) mp_print_ln(mp);
2298   else  { j++; mp_print_char(mp, xord('%')); };
2299   j++;
2300 }
2301
2302 @ @<Put help message on the transcript file@>=
2303 if ( mp->interaction>mp_batch_mode ) decr(mp->selector); /* avoid terminal output */
2304 if ( mp->use_err_help ) { 
2305   mp_print_nl(mp, "");
2306   @<Print the string |err_help|, possibly on several lines@>;
2307 } else { 
2308   while ( mp->help_ptr>0 ){ 
2309     decr(mp->help_ptr); mp_print_nl(mp, mp->help_line[mp->help_ptr]);
2310   };
2311 }
2312 mp_print_ln(mp);
2313 if ( mp->interaction>mp_batch_mode ) incr(mp->selector); /* re-enable terminal output */
2314 mp_print_ln(mp)
2315
2316 @ In anomalous cases, the print selector might be in an unknown state;
2317 the following subroutine is called to fix things just enough to keep
2318 running a bit longer.
2319
2320 @c 
2321 void mp_normalize_selector (MP mp) { 
2322   if ( mp->log_opened ) mp->selector=term_and_log;
2323   else mp->selector=term_only;
2324   if ( mp->job_name==NULL) mp_open_log_file(mp);
2325   if ( mp->interaction==mp_batch_mode ) decr(mp->selector);
2326 }
2327
2328 @ The following procedure prints \MP's last words before dying.
2329
2330 @d succumb { if ( mp->interaction==mp_error_stop_mode )
2331     mp->interaction=mp_scroll_mode; /* no more interaction */
2332   if ( mp->log_opened ) mp_error(mp);
2333   mp->history=mp_fatal_error_stop; mp_jump_out(mp); /* irrecoverable error */
2334   }
2335
2336 @<Error hand...@>=
2337 void mp_fatal_error (MP mp, const char *s) { /* prints |s|, and that's it */
2338   mp_normalize_selector(mp);
2339   print_err("Emergency stop"); help1(s); succumb;
2340 @.Emergency stop@>
2341 }
2342
2343 @ @<Exported function ...@>=
2344 extern void mp_fatal_error (MP mp, const char *s);
2345
2346
2347 @ Here is the most dreaded error message.
2348
2349 @<Error hand...@>=
2350 void mp_overflow (MP mp, const char *s, integer n) { /* stop due to finiteness */
2351   char msg[256];
2352   mp_normalize_selector(mp);
2353   mp_snprintf(msg, 256, "MetaPost capacity exceeded, sorry [%s=%d]",s,(int)n);
2354 @.MetaPost capacity exceeded ...@>
2355   print_err(msg);
2356   help2("If you really absolutely need more capacity,",
2357         "you can ask a wizard to enlarge me.");
2358   succumb;
2359 }
2360
2361 @ @<Internal library declarations@>=
2362 void mp_overflow (MP mp, const char *s, integer n);
2363
2364 @ The program might sometime run completely amok, at which point there is
2365 no choice but to stop. If no previous error has been detected, that's bad
2366 news; a message is printed that is really intended for the \MP\
2367 maintenance person instead of the user (unless the user has been
2368 particularly diabolical).  The index entries for `this can't happen' may
2369 help to pinpoint the problem.
2370 @^dry rot@>
2371
2372 @<Internal library ...@>=
2373 void mp_confusion (MP mp, const char *s);
2374
2375 @ Consistency check violated; |s| tells where.
2376 @<Error hand...@>=
2377 void mp_confusion (MP mp, const char *s) {
2378   char msg[256];
2379   mp_normalize_selector(mp);
2380   if ( mp->history<mp_error_message_issued ) { 
2381     mp_snprintf(msg, 256, "This can't happen (%s)",s);
2382 @.This can't happen@>
2383     print_err(msg);
2384     help1("I'm broken. Please show this to someone who can fix can fix");
2385   } else { 
2386     print_err("I can\'t go on meeting you like this");
2387 @.I can't go on...@>
2388     help2("One of your faux pas seems to have wounded me deeply...",
2389           "in fact, I'm barely conscious. Please fix it and try again.");
2390   }
2391   succumb;
2392 }
2393
2394 @ Users occasionally want to interrupt \MP\ while it's running.
2395 If the runtime system allows this, one can implement
2396 a routine that sets the global variable |interrupt| to some nonzero value
2397 when such an interrupt is signaled. Otherwise there is probably at least
2398 a way to make |interrupt| nonzero using the C debugger.
2399 @^system dependencies@>
2400 @^debugging@>
2401
2402 @d check_interrupt { if ( mp->interrupt!=0 )
2403    mp_pause_for_instructions(mp); }
2404
2405 @<Global...@>=
2406 integer interrupt; /* should \MP\ pause for instructions? */
2407 boolean OK_to_interrupt; /* should interrupts be observed? */
2408 integer run_state; /* are we processing input ?*/
2409 boolean finished; /* set true by |close_files_and_terminate| */
2410
2411 @ @<Allocate or ...@>=
2412 mp->OK_to_interrupt=true;
2413 mp->finished=false;
2414
2415 @ When an interrupt has been detected, the program goes into its
2416 highest interaction level and lets the user have the full flexibility of
2417 the |error| routine.  \MP\ checks for interrupts only at times when it is
2418 safe to do this.
2419
2420 @c 
2421 static void mp_pause_for_instructions (MP mp) { 
2422   if ( mp->OK_to_interrupt ) { 
2423     mp->interaction=mp_error_stop_mode;
2424     if ( (mp->selector==log_only)||(mp->selector==no_print) )
2425       incr(mp->selector);
2426     print_err("Interruption");
2427 @.Interruption@>
2428     help3("You rang?",
2429          "Try to insert some instructions for me (e.g.,`I show x'),",
2430          "unless you just want to quit by typing `X'.");
2431     mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
2432     mp->interrupt=0;
2433   }
2434 }
2435
2436 @ Many of \MP's error messages state that a missing token has been
2437 inserted behind the scenes. We can save string space and program space
2438 by putting this common code into a subroutine.
2439
2440 @c 
2441 static void mp_missing_err (MP mp, const char *s) { 
2442   char msg[256];
2443   mp_snprintf(msg, 256, "Missing `%s' has been inserted", s);
2444 @.Missing...inserted@>
2445   print_err(msg);
2446 }
2447
2448 @* \[7] Arithmetic with scaled numbers.
2449 The principal computations performed by \MP\ are done entirely in terms of
2450 integers less than $2^{31}$ in magnitude; thus, the arithmetic specified in this
2451 program can be carried out in exactly the same way on a wide variety of
2452 computers, including some small ones.
2453 @^small computers@>
2454
2455 But C does not rigidly define the |/| operation in the case of negative
2456 dividends; for example, the result of |(-2*n-1) / 2| is |-(n+1)| on some
2457 computers and |-n| on others (is this true ?).  There are two principal
2458 types of arithmetic: ``translation-preserving,'' in which the identity
2459 |(a+q*b)/b=(a/b)+q| is valid; and ``negation-preserving,'' in which
2460 |(-a)/b=-(a/b)|. This leads to two \MP s, which can produce
2461 different results, although the differences should be negligible when the
2462 language is being used properly.  The \TeX\ processor has been defined
2463 carefully so that both varieties of arithmetic will produce identical
2464 output, but it would be too inefficient to constrain \MP\ in a similar way.
2465
2466 @d el_gordo   0x7fffffff /* $2^{31}-1$, the largest value that \MP\ likes */
2467
2468
2469 @ One of \MP's most common operations is the calculation of
2470 $\lfloor{a+b\over2}\rfloor$,
2471 the midpoint of two given integers |a| and~|b|. The most decent way to do
2472 this is to write `|(a+b)/2|'; but on many machines it is more efficient 
2473 to calculate `|(a+b)>>1|'.
2474
2475 Therefore the midpoint operation will always be denoted by `|half(a+b)|'
2476 in this program. If \MP\ is being implemented with languages that permit
2477 binary shifting, the |half| macro should be changed to make this operation
2478 as efficient as possible.  Since some systems have shift operators that can
2479 only be trusted to work on positive numbers, there is also a macro |halfp|
2480 that is used only when the quantity being halved is known to be positive
2481 or zero.
2482
2483 @d half(A) ((A) / 2)
2484 @d halfp(A) (integer)((unsigned)(A) >> 1)
2485
2486 @ A single computation might use several subroutine calls, and it is
2487 desirable to avoid producing multiple error messages in case of arithmetic
2488 overflow. So the routines below set the global variable |arith_error| to |true|
2489 instead of reporting errors directly to the user.
2490 @^overflow in arithmetic@>
2491
2492 @<Glob...@>=
2493 boolean arith_error; /* has arithmetic overflow occurred recently? */
2494
2495 @ @<Allocate or ...@>=
2496 mp->arith_error=false;
2497
2498 @ At crucial points the program will say |check_arith|, to test if
2499 an arithmetic error has been detected.
2500
2501 @d check_arith { if ( mp->arith_error ) mp_clear_arith(mp); }
2502
2503 @c 
2504 static void mp_clear_arith (MP mp) { 
2505   print_err("Arithmetic overflow");
2506 @.Arithmetic overflow@>
2507   help4("Uh, oh. A little while ago one of the quantities that I was",
2508        "computing got too large, so I'm afraid your answers will be",
2509        "somewhat askew. You'll probably have to adopt different",
2510        "tactics next time. But I shall try to carry on anyway.");
2511   mp_error(mp); 
2512   mp->arith_error=false;
2513 }
2514
2515 @ Addition is not always checked to make sure that it doesn't overflow,
2516 but in places where overflow isn't too unlikely the |slow_add| routine
2517 is used.
2518
2519 @c static integer mp_slow_add (MP mp,integer x, integer y) { 
2520   if ( x>=0 )  {
2521     if ( y<=el_gordo-x ) { 
2522       return x+y;
2523     } else  { 
2524       mp->arith_error=true; 
2525           return el_gordo;
2526     }
2527   } else  if ( -y<=el_gordo+x ) {
2528     return x+y;
2529   } else { 
2530     mp->arith_error=true; 
2531         return -el_gordo;
2532   }
2533 }
2534
2535 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2536 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2537 positions from the right end of a binary computer word.
2538
2539 @d quarter_unit   040000 /* $2^{14}$, represents 0.250000 */
2540 @d half_unit   0100000 /* $2^{15}$, represents 0.50000 */
2541 @d three_quarter_unit   0140000 /* $3\cdot2^{14}$, represents 0.75000 */
2542 @d unity   0200000 /* $2^{16}$, represents 1.00000 */
2543 @d two   0400000 /* $2^{17}$, represents 2.00000 */
2544 @d three   0600000 /* $2^{17}+2^{16}$, represents 3.00000 */
2545
2546 @<Types...@>=
2547 typedef integer scaled; /* this type is used for scaled integers */
2548
2549 @ The following function is used to create a scaled integer from a given decimal
2550 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2551 given in |dig[i]|, and the calculation produces a correctly rounded result.
2552
2553 @c 
2554 static scaled mp_round_decimals (MP mp,quarterword k) {
2555   /* converts a decimal fraction */
2556  unsigned a = 0; /* the accumulator */
2557  while ( k-->0 ) { 
2558     a=(a+mp->dig[k]*two) / 10;
2559   }
2560   return (scaled)halfp(a+1);
2561 }
2562
2563 @ Conversely, here is a procedure analogous to |print_int|. If the output
2564 of this procedure is subsequently read by \MP\ and converted by the
2565 |round_decimals| routine above, it turns out that the original value will
2566 be reproduced exactly. A decimal point is printed only if the value is
2567 not an integer. If there is more than one way to print the result with
2568 the optimum number of digits following the decimal point, the closest
2569 possible value is given.
2570
2571 The invariant relation in the \&{repeat} loop is that a sequence of
2572 decimal digits yet to be printed will yield the original number if and only if
2573 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2574 We can stop if and only if $f=0$ satisfies this condition; the loop will
2575 terminate before $s$ can possibly become zero.
2576
2577 @<Basic printing...@>=
2578 void mp_print_scaled (MP mp,scaled s) { /* prints scaled real, rounded to five  digits */
2579   scaled delta; /* amount of allowable inaccuracy */
2580   if ( s<0 ) { 
2581         mp_print_char(mp, xord('-')); 
2582     negate(s); /* print the sign, if negative */
2583   }
2584   mp_print_int(mp, s / unity); /* print the integer part */
2585   s=10*(s % unity)+5;
2586   if ( s!=5 ) { 
2587     delta=10; 
2588     mp_print_char(mp, xord('.'));
2589     do {  
2590       if ( delta>unity )
2591         s=s+0100000-(delta / 2); /* round the final digit */
2592       mp_print_char(mp, xord('0'+(s / unity))); 
2593       s=10*(s % unity); 
2594       delta=delta*10;
2595     } while (s>delta);
2596   }
2597 }
2598
2599 @ We often want to print two scaled quantities in parentheses,
2600 separated by a comma.
2601
2602 @<Basic printing...@>=
2603 void mp_print_two (MP mp,scaled x, scaled y) { /* prints `|(x,y)|' */
2604   mp_print_char(mp, xord('(')); 
2605   mp_print_scaled(mp, x); 
2606   mp_print_char(mp, xord(',')); 
2607   mp_print_scaled(mp, y);
2608   mp_print_char(mp, xord(')'));
2609 }
2610
2611 @ The |scaled| quantities in \MP\ programs are generally supposed to be
2612 less than $2^{12}$ in absolute value, so \MP\ does much of its internal
2613 arithmetic with 28~significant bits of precision. A |fraction| denotes
2614 a scaled integer whose binary point is assumed to be 28 bit positions
2615 from the right.
2616
2617 @d fraction_half 01000000000 /* $2^{27}$, represents 0.50000000 */
2618 @d fraction_one 02000000000 /* $2^{28}$, represents 1.00000000 */
2619 @d fraction_two 04000000000 /* $2^{29}$, represents 2.00000000 */
2620 @d fraction_three 06000000000 /* $3\cdot2^{28}$, represents 3.00000000 */
2621 @d fraction_four 010000000000 /* $2^{30}$, represents 4.00000000 */
2622
2623 @<Types...@>=
2624 typedef integer fraction; /* this type is used for scaled fractions */
2625
2626 @ In fact, the two sorts of scaling discussed above aren't quite
2627 sufficient; \MP\ has yet another, used internally to keep track of angles
2628 in units of $2^{-20}$ degrees.
2629
2630 @d forty_five_deg 0264000000 /* $45\cdot2^{20}$, represents $45^\circ$ */
2631 @d ninety_deg 0550000000 /* $90\cdot2^{20}$, represents $90^\circ$ */
2632 @d one_eighty_deg 01320000000 /* $180\cdot2^{20}$, represents $180^\circ$ */
2633 @d three_sixty_deg 02640000000 /* $360\cdot2^{20}$, represents $360^\circ$ */
2634
2635 @<Types...@>=
2636 typedef integer angle; /* this type is used for scaled angles */
2637
2638 @ The |make_fraction| routine produces the |fraction| equivalent of
2639 |p/q|, given integers |p| and~|q|; it computes the integer
2640 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2641 positive. If |p| and |q| are both of the same scaled type |t|,
2642 the ``type relation'' |make_fraction(t,t)=fraction| is valid;
2643 and it's also possible to use the subroutine ``backwards,'' using
2644 the relation |make_fraction(t,fraction)=t| between scaled types.
2645
2646 If the result would have magnitude $2^{31}$ or more, |make_fraction|
2647 sets |arith_error:=true|. Most of \MP's internal computations have
2648 been designed to avoid this sort of error.
2649
2650 If this subroutine were programmed in assembly language on a typical
2651 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2652 double-precision product can often be input to a fixed-point division
2653 instruction. But when we are restricted to int-eger arithmetic it
2654 is necessary either to resort to multiple-precision maneuvering
2655 or to use a simple but slow iteration. The multiple-precision technique
2656 would be about three times faster than the code adopted here, but it
2657 would be comparatively long and tricky, involving about sixteen
2658 additional multiplications and divisions.
2659
2660 This operation is part of \MP's ``inner loop''; indeed, it will
2661 consume nearly 10\pct! of the running time (exclusive of input and output)
2662 if the code below is left unchanged. A machine-dependent recoding
2663 will therefore make \MP\ run faster. The present implementation
2664 is highly portable, but slow; it avoids multiplication and division
2665 except in the initial stage. System wizards should be careful to
2666 replace it with a routine that is guaranteed to produce identical
2667 results in all cases.
2668 @^system dependencies@>
2669
2670 As noted below, a few more routines should also be replaced by machine-dependent
2671 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2672 such changes aren't advisable; simplicity and robustness are
2673 preferable to trickery, unless the cost is too high.
2674 @^inner loop@>
2675
2676 @<Internal library declarations@>=
2677 integer mp_take_scaled (MP mp,integer q, scaled f) ;
2678
2679 @ @<Declarations@>=
2680 static fraction mp_make_fraction (MP mp,integer p, integer q);
2681
2682 @ If FIXPT is not defined, we need these preprocessor values
2683
2684 @d TWEXP31  2147483648.0
2685 @d TWEXP28  268435456.0
2686 @d TWEXP16 65536.0
2687 @d TWEXP_16 (1.0/65536.0)
2688 @d TWEXP_28 (1.0/268435456.0)
2689
2690
2691 @c 
2692 fraction mp_make_fraction (MP mp,integer p, integer q) {
2693   fraction i;
2694   if ( q==0 ) mp_confusion(mp, "/");
2695 @:this can't happen /}{\quad \./@>
2696 #ifdef FIXPT
2697 {
2698   integer f; /* the fraction bits, with a leading 1 bit */
2699   integer n; /* the integer part of $\vert p/q\vert$ */
2700   boolean negative = false; /* should the result be negated? */
2701   if ( p<0 ) {
2702     negate(p); negative=true;
2703   }
2704   if ( q<0 ) { 
2705     negate(q); negative = ! negative;
2706   }
2707   n=p / q; p=p % q;
2708   if ( n>=8 ){ 
2709     mp->arith_error=true;
2710     i= ( negative ? -el_gordo : el_gordo);
2711   } else { 
2712     n=(n-1)*fraction_one;
2713     @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2714     i = (negative ? (-(f+n)) : (f+n));
2715   }
2716 }
2717 #else /* FIXPT */
2718   {
2719     register double d;
2720         d = TWEXP28 * (double)p /(double)q;
2721         if ((p^q) >= 0) {
2722                 d += 0.5;
2723                 if (d>=TWEXP31) {mp->arith_error=true; return el_gordo;}
2724                 i = (integer) d;
2725                 if (d==(double)i && ( ((q>0 ? -q : q)&077777)
2726                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2727         } else {
2728                 d -= 0.5;
2729                 if (d<= -TWEXP31) {mp->arith_error=true; return -el_gordo;}
2730                 i = (integer) d;
2731                 if (d==(double)i && ( ((q>0 ? q : -q)&077777)
2732                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2733         }
2734   }
2735 #endif /* FIXPT */
2736   return i;
2737 }
2738
2739 @ The |repeat| loop here preserves the following invariant relations
2740 between |f|, |p|, and~|q|:
2741 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2742 $p_0$ is the original value of~$p$.
2743
2744 Notice that the computation specifies
2745 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2746 Let us hope that optimizing compilers do not miss this point; a
2747 special variable |be_careful| is used to emphasize the necessary
2748 order of computation. Optimizing compilers should keep |be_careful|
2749 in a register, not store it in memory.
2750 @^inner loop@>
2751
2752 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2753 {
2754   integer be_careful; /* disables certain compiler optimizations */
2755   f=1;
2756   do {  
2757     be_careful=p-q; p=be_careful+p;
2758     if ( p>=0 ) { 
2759       f=f+f+1;
2760     } else  { 
2761       f+=f; p=p+q;
2762     }
2763   } while (f<fraction_one);
2764   be_careful=p-q;
2765   if ( be_careful+p>=0 ) incr(f);
2766 }
2767
2768 @ The dual of |make_fraction| is |take_fraction|, which multiplies a
2769 given integer~|q| by a fraction~|f|. When the operands are positive, it
2770 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
2771 of |q| and~|f|.
2772
2773 This routine is even more ``inner loopy'' than |make_fraction|;
2774 the present implementation consumes almost 20\pct! of \MP's computation
2775 time during typical jobs, so a machine-language substitute is advisable.
2776 @^inner loop@> @^system dependencies@>
2777
2778 @<Internal library declarations@>=
2779 integer mp_take_fraction (MP mp,integer q, fraction f) ;
2780
2781 @ @c 
2782 #ifdef FIXPT
2783 integer mp_take_fraction (MP mp,integer q, fraction f) {
2784   integer p; /* the fraction so far */
2785   boolean negative; /* should the result be negated? */
2786   integer n; /* additional multiple of $q$ */
2787   integer be_careful; /* disables certain compiler optimizations */
2788   @<Reduce to the case that |f>=0| and |q>=0|@>;
2789   if ( f<fraction_one ) { 
2790     n=0;
2791   } else { 
2792     n=f / fraction_one; f=f % fraction_one;
2793     if ( q<=el_gordo / n ) { 
2794       n=n*q ; 
2795     } else { 
2796       mp->arith_error=true; n=el_gordo;
2797     }
2798   }
2799   f=f+fraction_one;
2800   @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2801   be_careful=n-el_gordo;
2802   if ( be_careful+p>0 ){ 
2803     mp->arith_error=true; n=el_gordo-p;
2804   }
2805   if ( negative ) 
2806         return (-(n+p));
2807   else 
2808     return (n+p);
2809 #else /* FIXPT */
2810 integer mp_take_fraction (MP mp,integer p, fraction q) {
2811     register double d;
2812         register integer i;
2813         d = (double)p * (double)q * TWEXP_28;
2814         if ((p^q) >= 0) {
2815                 d += 0.5;
2816                 if (d>=TWEXP31) {
2817                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2818                                 mp->arith_error = true;
2819                         return el_gordo;
2820                 }
2821                 i = (integer) d;
2822                 if (d==(double)i && (((p&077777)*(q&077777))&040000)!=0) --i;
2823         } else {
2824                 d -= 0.5;
2825                 if (d<= -TWEXP31) {
2826                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2827                                 mp->arith_error = true;
2828                         return -el_gordo;
2829                 }
2830                 i = (integer) d;
2831                 if (d==(double)i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2832         }
2833         return i;
2834 #endif /* FIXPT */
2835 }
2836
2837 @ @<Reduce to the case that |f>=0| and |q>=0|@>=
2838 if ( f>=0 ) {
2839   negative=false;
2840 } else { 
2841   negate( f); negative=true;
2842 }
2843 if ( q<0 ) { 
2844   negate(q); negative=! negative;
2845 }
2846
2847 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2848 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2849 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2850 @^inner loop@>
2851
2852 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2853 p=fraction_half; /* that's $2^{27}$; the invariants hold now with $k=28$ */
2854 if ( q<fraction_four ) {
2855   do {  
2856     if ( odd(f) ) p=halfp(p+q); else p=halfp(p);
2857     f=halfp(f);
2858   } while (f!=1);
2859 } else  {
2860   do {  
2861     if ( odd(f) ) p=p+halfp(q-p); else p=halfp(p);
2862     f=halfp(f);
2863   } while (f!=1);
2864 }
2865
2866
2867 @ When we want to multiply something by a |scaled| quantity, we use a scheme
2868 analogous to |take_fraction| but with a different scaling.
2869 Given positive operands, |take_scaled|
2870 computes the quantity $p=\lfloor qf/2^{16}+{1\over2}\rfloor$.
2871
2872 Once again it is a good idea to use a machine-language replacement if
2873 possible; otherwise |take_scaled| will use more than 2\pct! of the running time
2874 when the Computer Modern fonts are being generated.
2875 @^inner loop@>
2876
2877 @c 
2878 #ifdef FIXPT
2879 integer mp_take_scaled (MP mp,integer q, scaled f) {
2880   integer p; /* the fraction so far */
2881   boolean negative; /* should the result be negated? */
2882   integer n; /* additional multiple of $q$ */
2883   integer be_careful; /* disables certain compiler optimizations */
2884   @<Reduce to the case that |f>=0| and |q>=0|@>;
2885   if ( f<unity ) { 
2886     n=0;
2887   } else  { 
2888     n=f / unity; f=f % unity;
2889     if ( q<=el_gordo / n ) {
2890       n=n*q;
2891     } else  { 
2892       mp->arith_error=true; n=el_gordo;
2893     }
2894   }
2895   f=f+unity;
2896   @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>;
2897   be_careful=n-el_gordo;
2898   if ( be_careful+p>0 ) { 
2899     mp->arith_error=true; n=el_gordo-p;
2900   }
2901   return ( negative ?(-(n+p)) :(n+p));
2902 #else /* FIXPT */
2903 integer mp_take_scaled (MP mp,integer p, scaled q) {
2904     register double d;
2905         register integer i;
2906         d = (double)p * (double)q * TWEXP_16;
2907         if ((p^q) >= 0) {
2908                 d += 0.5;
2909                 if (d>=TWEXP31) {
2910                         if (d!=TWEXP31 || (((p&077777)*(q&077777))&040000)==0)
2911                                 mp->arith_error = true;
2912                         return el_gordo;
2913                 }
2914                 i = (integer) d;
2915                 if (d==(double)i && (((p&077777)*(q&077777))&040000)!=0) --i;
2916         } else {
2917                 d -= 0.5;
2918                 if (d<= -TWEXP31) {
2919                         if (d!= -TWEXP31 || ((-(p&077777)*(q&077777))&040000)==0)
2920                                 mp->arith_error = true;
2921                         return -el_gordo;
2922                 }
2923                 i = (integer) d;
2924                 if (d==(double)i && ((-(p&077777)*(q&077777))&040000)!=0) ++i;
2925         }
2926         return i;
2927 #endif /* FIXPT */
2928 }
2929
2930 @ @<Compute $p=\lfloor qf/2^{16}+{1\over2}\rfloor-q$@>=
2931 p=half_unit; /* that's $2^{15}$; the invariants hold now with $k=16$ */
2932 @^inner loop@>
2933 if ( q<fraction_four ) {
2934   do {  
2935     p = (odd(f) ? halfp(p+q) : halfp(p));
2936     f=halfp(f);
2937   } while (f!=1);
2938 } else {
2939   do {  
2940     p = (odd(f) ? p+halfp(q-p) : halfp(p));
2941     f=halfp(f);
2942   } while (f!=1);
2943 }
2944
2945 @ For completeness, there's also |make_scaled|, which computes a
2946 quotient as a |scaled| number instead of as a |fraction|.
2947 In other words, the result is $\lfloor2^{16}p/q+{1\over2}\rfloor$, if the
2948 operands are positive. \ (This procedure is not used especially often,
2949 so it is not part of \MP's inner loop.)
2950
2951 @<Internal library ...@>=
2952 scaled mp_make_scaled (MP mp,integer p, integer q) ;
2953
2954 @ @c 
2955 scaled mp_make_scaled (MP mp,integer p, integer q) {
2956   register integer i;
2957   if ( q==0 ) mp_confusion(mp, "/");
2958 @:this can't happen /}{\quad \./@>
2959   {
2960 #ifdef FIXPT 
2961     integer f; /* the fraction bits, with a leading 1 bit */
2962     integer n; /* the integer part of $\vert p/q\vert$ */
2963     boolean negative; /* should the result be negated? */
2964     integer be_careful; /* disables certain compiler optimizations */
2965     if ( p>=0 ) negative=false;
2966     else  { negate(p); negative=true; };
2967     if ( q<0 ) { 
2968       negate(q); negative=! negative;
2969     }
2970     n=p / q; p=p % q;
2971     if ( n>=0100000 ) { 
2972       mp->arith_error=true;
2973       return (negative ? (-el_gordo) : el_gordo);
2974     } else  { 
2975       n=(n-1)*unity;
2976       @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>;
2977       i = (negative ? (-(f+n)) :(f+n));
2978     }
2979 #else /* FIXPT */
2980     register double d;
2981         d = TWEXP16 * (double)p /(double)q;
2982         if ((p^q) >= 0) {
2983                 d += 0.5;
2984                 if (d>=TWEXP31) {mp->arith_error=true; return el_gordo;}
2985                 i = (integer) d;
2986                 if (d==(double)i && ( ((q>0 ? -q : q)&077777)
2987                                 * (((i&037777)<<1)-1) & 04000)!=0) --i;
2988         } else {
2989                 d -= 0.5;
2990                 if (d<= -TWEXP31) {mp->arith_error=true; return -el_gordo;}
2991                 i = (integer) d;
2992                 if (d==(double)i && ( ((q>0 ? q : -q)&077777)
2993                                 * (((i&037777)<<1)+1) & 04000)!=0) ++i;
2994         }
2995 #endif /* FIXPT */
2996   }
2997   return i;
2998 }
2999
3000 @ @<Compute $f=\lfloor 2^{16}(1+p/q)+{1\over2}\rfloor$@>=
3001 f=1;
3002 do {  
3003   be_careful=p-q; p=be_careful+p;
3004   if ( p>=0 ) f=f+f+1;
3005   else  { f+=f; p=p+q; };
3006 } while (f<unity);
3007 be_careful=p-q;
3008 if ( be_careful+p>=0 ) incr(f)
3009
3010 @ Here is a typical example of how the routines above can be used.
3011 It computes the function
3012 $${1\over3\tau}f(\theta,\phi)=
3013 {\tau^{-1}\bigl(2+\sqrt2\,(\sin\theta-{1\over16}\sin\phi)
3014  (\sin\phi-{1\over16}\sin\theta)(\cos\theta-\cos\phi)\bigr)\over
3015 3\,\bigl(1+{1\over2}(\sqrt5-1)\cos\theta+{1\over2}(3-\sqrt5\,)\cos\phi\bigr)},$$
3016 where $\tau$ is a |scaled| ``tension'' parameter. This is \MP's magic
3017 fudge factor for placing the first control point of a curve that starts
3018 at an angle $\theta$ and ends at an angle $\phi$ from the straight path.
3019 (Actually, if the stated quantity exceeds 4, \MP\ reduces it to~4.)
3020
3021 The trigonometric quantity to be multiplied by $\sqrt2$ is less than $\sqrt2$.
3022 (It's a sum of eight terms whose absolute values can be bounded using
3023 relations such as $\sin\theta\cos\theta\L{1\over2}$.) Thus the numerator
3024 is positive; and since the tension $\tau$ is constrained to be at least
3025 $3\over4$, the numerator is less than $16\over3$. The denominator is
3026 nonnegative and at most~6.  Hence the fixed-point calculations below
3027 are guaranteed to stay within the bounds of a 32-bit computer word.
3028
3029 The angles $\theta$ and $\phi$ are given implicitly in terms of |fraction|
3030 arguments |st|, |ct|, |sf|, and |cf|, representing $\sin\theta$, $\cos\theta$,
3031 $\sin\phi$, and $\cos\phi$, respectively.
3032
3033 @c 
3034 static fraction mp_velocity (MP mp,fraction st, fraction ct, fraction sf,
3035                       fraction cf, scaled t) {
3036   integer acc,num,denom; /* registers for intermediate calculations */
3037   acc=mp_take_fraction(mp, st-(sf / 16), sf-(st / 16));
3038   acc=mp_take_fraction(mp, acc,ct-cf);
3039   num=fraction_two+mp_take_fraction(mp, acc,379625062);
3040                    /* $2^{28}\sqrt2\approx379625062.497$ */
3041   denom=fraction_three+mp_take_fraction(mp, ct,497706707)+mp_take_fraction(mp, cf,307599661);
3042                       /* $3\cdot2^{27}\cdot(\sqrt5-1)\approx497706706.78$ and
3043                          $3\cdot2^{27}\cdot(3-\sqrt5\,)\approx307599661.22$ */
3044   if ( t!=unity ) num=mp_make_scaled(mp, num,t);
3045   /* |make_scaled(fraction,scaled)=fraction| */
3046   if ( num / 4>=denom ) 
3047     return fraction_four;
3048   else 
3049     return mp_make_fraction(mp, num, denom);
3050 }
3051
3052 @ The following somewhat different subroutine tests rigorously if $ab$ is
3053 greater than, equal to, or less than~$cd$,
3054 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
3055 The result is $+1$, 0, or~$-1$ in the three respective cases.
3056
3057 @d mp_ab_vs_cd(M,A,B,C,D) mp_do_ab_vs_cd(A,B,C,D)
3058
3059 @c 
3060 static integer mp_do_ab_vs_cd (integer a,integer b, integer c, integer d) {
3061   integer q,r; /* temporary registers */
3062   @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
3063   while (1) { 
3064     q = a / d; r = c / b;
3065     if ( q!=r )
3066       return ( q>r ? 1 : -1);
3067     q = a % d; r = c % b;
3068     if ( r==0 )
3069       return (q ? 1 : 0);
3070     if ( q==0 ) return -1;
3071     a=b; b=q; c=d; d=r;
3072   } /* now |a>d>0| and |c>b>0| */
3073 }
3074
3075 @ @<Reduce to the case that |a...@>=
3076 if ( a<0 ) { negate(a); negate(b);  };
3077 if ( c<0 ) { negate(c); negate(d);  };
3078 if ( d<=0 ) { 
3079   if ( b>=0 ) {
3080     if ( (a==0||b==0)&&(c==0||d==0) ) return 0;
3081     else return 1;
3082   }
3083   if ( d==0 )
3084     return ( a==0 ? 0 : -1);
3085   q=a; a=c; c=q; q=-b; b=-d; d=q;
3086 } else if ( b<=0 ) { 
3087   if ( b<0 ) if ( a>0 ) return -1;
3088   return (c==0 ? 0 : -1);
3089 }
3090
3091 @ We conclude this set of elementary routines with some simple rounding
3092 and truncation operations.
3093
3094 @<Internal library declarations@>=
3095 #define mp_floor_scaled(M,i) ((i)&(-65536))
3096 #define mp_round_unscaled(M,i) (((i/32768)+1)/2)
3097 #define mp_round_fraction(M,i) (((i/2048)+1)/2)
3098
3099
3100 @* \[8] Algebraic and transcendental functions.
3101 \MP\ computes all of the necessary special functions from scratch, without
3102 relying on |real| arithmetic or system subroutines for sines, cosines, etc.
3103
3104 @ To get the square root of a |scaled| number |x|, we want to calculate
3105 $s=\lfloor 2^8\!\sqrt x +{1\over2}\rfloor$. If $x>0$, this is the unique
3106 integer such that $2^{16}x-s\L s^2<2^{16}x+s$. The following subroutine
3107 determines $s$ by an iterative method that maintains the invariant
3108 relations $x=2^{46-2k}x_0\bmod 2^{30}$, $0<y=\lfloor 2^{16-2k}x_0\rfloor
3109 -s^2+s\L q=2s$, where $x_0$ is the initial value of $x$. The value of~$y$
3110 might, however, be zero at the start of the first iteration.
3111
3112 @<Declarations@>=
3113 static scaled mp_square_rt (MP mp,scaled x) ;
3114
3115 @ @c 
3116 scaled mp_square_rt (MP mp,scaled x) {
3117   quarterword k; /* iteration control counter */
3118   integer y; /* register for intermediate calculations */
3119   unsigned q; /* register for intermediate calculations */
3120   if ( x<=0 ) { 
3121     @<Handle square root of zero or negative argument@>;
3122   } else { 
3123     k=23; q=2;
3124     while ( x<fraction_two ) { /* i.e., |while x<@t$2^{29}$@>|\unskip */
3125       decr(k); x=x+x+x+x;
3126     }
3127     if ( x<fraction_four ) y=0;
3128     else  { x=x-fraction_four; y=1; };
3129     do {  
3130       @<Decrease |k| by 1, maintaining the invariant
3131       relations between |x|, |y|, and~|q|@>;
3132     } while (k!=0);
3133     return (scaled)(halfp(q));
3134   }
3135 }
3136
3137 @ @<Handle square root of zero...@>=
3138
3139   if ( x<0 ) { 
3140     print_err("Square root of ");
3141 @.Square root...replaced by 0@>
3142     mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3143     help2("Since I don't take square roots of negative numbers,",
3144           "I'm zeroing this one. Proceed, with fingers crossed.");
3145     mp_error(mp);
3146   };
3147   return 0;
3148 }
3149
3150 @ @<Decrease |k| by 1, maintaining...@>=
3151 x+=x; y+=y;
3152 if ( x>=fraction_four ) { /* note that |fraction_four=@t$2^{30}$@>| */
3153   x=x-fraction_four; y++;
3154 };
3155 x+=x; y=y+y-q; q+=q;
3156 if ( x>=fraction_four ) { x=x-fraction_four; y++; };
3157 if ( y>(int)q ){ y=y-q; q=q+2; }
3158 else if ( y<=0 )  { q=q-2; y=y+q;  };
3159 decr(k)
3160
3161 @ Pythagorean addition $\psqrt{a^2+b^2}$ is implemented by an elegant
3162 iterative scheme due to Cleve Moler and Donald Morrison [{\sl IBM Journal
3163 @^Moler, Cleve Barry@>
3164 @^Morrison, Donald Ross@>
3165 of Research and Development\/ \bf27} (1983), 577--581]. It modifies |a| and~|b|
3166 in such a way that their Pythagorean sum remains invariant, while the
3167 smaller argument decreases.
3168
3169 @<Internal library ...@>=
3170 integer mp_pyth_add (MP mp,integer a, integer b);
3171
3172
3173 @ @c 
3174 integer mp_pyth_add (MP mp,integer a, integer b) {
3175   fraction r; /* register used to transform |a| and |b| */
3176   boolean big; /* is the result dangerously near $2^{31}$? */
3177   a=abs(a); b=abs(b);
3178   if ( a<b ) { r=b; b=a; a=r; }; /* now |0<=b<=a| */
3179   if ( b>0 ) {
3180     if ( a<fraction_two ) {
3181       big=false;
3182     } else { 
3183       a=a / 4; b=b / 4; big=true;
3184     }; /* we reduced the precision to avoid arithmetic overflow */
3185     @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>;
3186     if ( big ) {
3187       if ( a<fraction_two ) {
3188         a=a+a+a+a;
3189       } else  { 
3190         mp->arith_error=true; a=el_gordo;
3191       };
3192     }
3193   }
3194   return a;
3195 }
3196
3197 @ The key idea here is to reflect the vector $(a,b)$ about the
3198 line through $(a,b/2)$.
3199
3200 @<Replace |a| by an approximation to $\psqrt{a^2+b^2}$@>=
3201 while (1) {  
3202   r=mp_make_fraction(mp, b,a);
3203   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3204   if ( r==0 ) break;
3205   r=mp_make_fraction(mp, r,fraction_four+r);
3206   a=a+mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3207 }
3208
3209
3210 @ Here is a similar algorithm for $\psqrt{a^2-b^2}$.
3211 It converges slowly when $b$ is near $a$, but otherwise it works fine.
3212
3213 @c 
3214 static integer mp_pyth_sub (MP mp,integer a, integer b) {
3215   fraction r; /* register used to transform |a| and |b| */
3216   boolean big; /* is the input dangerously near $2^{31}$? */
3217   a=abs(a); b=abs(b);
3218   if ( a<=b ) {
3219     @<Handle erroneous |pyth_sub| and set |a:=0|@>;
3220   } else { 
3221     if ( a<fraction_four ) {
3222       big=false;
3223     } else  { 
3224       a=(integer)halfp(a); b=(integer)halfp(b); big=true;
3225     }
3226     @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>;
3227     if ( big ) double(a);
3228   }
3229   return a;
3230 }
3231
3232 @ @<Replace |a| by an approximation to $\psqrt{a^2-b^2}$@>=
3233 while (1) { 
3234   r=mp_make_fraction(mp, b,a);
3235   r=mp_take_fraction(mp, r,r); /* now $r\approx b^2/a^2$ */
3236   if ( r==0 ) break;
3237   r=mp_make_fraction(mp, r,fraction_four-r);
3238   a=a-mp_take_fraction(mp, a+a,r); b=mp_take_fraction(mp, b,r);
3239 }
3240
3241 @ @<Handle erroneous |pyth_sub| and set |a:=0|@>=
3242
3243   if ( a<b ){ 
3244     print_err("Pythagorean subtraction "); mp_print_scaled(mp, a);
3245     mp_print(mp, "+-+"); mp_print_scaled(mp, b); 
3246     mp_print(mp, " has been replaced by 0");
3247 @.Pythagorean...@>
3248     help2("Since I don't take square roots of negative numbers,",
3249           "I'm zeroing this one. Proceed, with fingers crossed.");
3250     mp_error(mp);
3251   }
3252   a=0;
3253 }
3254
3255 @ The subroutines for logarithm and exponential involve two tables.
3256 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
3257 a bit more calculation, which the author claims to have done correctly:
3258 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
3259 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
3260 nearest integer.
3261
3262 @d two_to_the(A) (1<<(unsigned)(A))
3263
3264 @<Declarations@>=
3265 static const integer spec_log[29] = { 0, /* special logarithms */
3266 93032640, 38612034, 17922280, 8662214, 4261238, 2113709,
3267 1052693, 525315, 262400, 131136, 65552, 32772, 16385,
3268 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 1 };
3269
3270 @ @<Local variables for initialization@>=
3271 integer k; /* all-purpose loop index */
3272
3273
3274 @ Here is the routine that calculates $2^8$ times the natural logarithm
3275 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
3276 when |x| is a given positive integer.
3277
3278 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
3279 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
3280 and the logarithm of $2^{30}x$ remains to be added to an accumulator
3281 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
3282 during the calculation, and sixteen auxiliary bits to extend |y| are
3283 kept in~|z| during the initial argument reduction. (We add
3284 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
3285 not become negative; also, the actual amount subtracted from~|y| is~96,
3286 not~100, because we want to add~4 for rounding before the final division by~8.)
3287
3288 @c 
3289 static scaled mp_m_log (MP mp,scaled x) {
3290   integer y,z; /* auxiliary registers */
3291   integer k; /* iteration counter */
3292   if ( x<=0 ) {
3293      @<Handle non-positive logarithm@>;
3294   } else  { 
3295     y=1302456956+4-100; /* $14\times2^{27}\ln2\approx1302456956.421063$ */
3296     z=27595+6553600; /* and $2^{16}\times .421063\approx 27595$ */
3297     while ( x<fraction_four ) {
3298        double(x); y-=93032639; z-=48782;
3299     } /* $2^{27}\ln2\approx 93032639.74436163$ and $2^{16}\times.74436163\approx 48782$ */
3300     y=y+(z / unity); k=2;
3301     while ( x>fraction_four+4 ) {
3302       @<Increase |k| until |x| can be multiplied by a
3303         factor of $2^{-k}$, and adjust $y$ accordingly@>;
3304     }
3305     return (y / 8);
3306   }
3307 }
3308
3309 @ @<Increase |k| until |x| can...@>=
3310
3311   z=((x-1) / two_to_the(k))+1; /* $z=\lceil x/2^k\rceil$ */
3312   while ( x<fraction_four+z ) { z=halfp(z+1); k++; };
3313   y+=spec_log[k]; x-=z;
3314 }
3315
3316 @ @<Handle non-positive logarithm@>=
3317
3318   print_err("Logarithm of ");
3319 @.Logarithm...replaced by 0@>
3320   mp_print_scaled(mp, x); mp_print(mp, " has been replaced by 0");
3321   help2("Since I don't take logs of non-positive numbers,",
3322         "I'm zeroing this one. Proceed, with fingers crossed.");
3323   mp_error(mp); 
3324   return 0;
3325 }
3326
3327 @ Conversely, the exponential routine calculates $\exp(x/2^8)$,
3328 when |x| is |scaled|. The result is an integer approximation to
3329 $2^{16}\exp(x/2^{24})$, when |x| is regarded as an integer.
3330
3331 @c 
3332 static scaled mp_m_exp (MP mp,scaled x) {
3333   quarterword k; /* loop control index */
3334   integer y,z; /* auxiliary registers */
3335   if ( x>174436200 ) {
3336     /* $2^{24}\ln((2^{31}-1)/2^{16})\approx 174436199.51$ */
3337     mp->arith_error=true; 
3338     return el_gordo;
3339   } else if ( x<-197694359 ) {
3340         /* $2^{24}\ln(2^{-1}/2^{16})\approx-197694359.45$ */
3341     return 0;
3342   } else { 
3343     if ( x<=0 ) { 
3344        z=-8*x; y=04000000; /* $y=2^{20}$ */
3345     } else { 
3346       if ( x<=127919879 ) { 
3347         z=1023359037-8*x;
3348         /* $2^{27}\ln((2^{31}-1)/2^{20})\approx 1023359037.125$ */
3349       } else {
3350        z=8*(174436200-x); /* |z| is always nonnegative */
3351       }
3352       y=el_gordo;
3353     };
3354     @<Multiply |y| by $\exp(-z/2^{27})$@>;
3355     if ( x<=127919879 ) 
3356        return ((y+8) / 16);
3357      else 
3358        return y;
3359   }
3360 }
3361
3362 @ The idea here is that subtracting |spec_log[k]| from |z| corresponds
3363 to multiplying |y| by $1-2^{-k}$.
3364
3365 A subtle point (which had to be checked) was that if $x=127919879$, the
3366 value of~|y| will decrease so that |y+8| doesn't overflow. In fact,
3367 $z$ will be 5 in this case, and |y| will decrease by~64 when |k=25|
3368 and by~16 when |k=27|.
3369
3370 @<Multiply |y| by...@>=
3371 k=1;
3372 while ( z>0 ) { 
3373   while ( z>=spec_log[k] ) { 
3374     z-=spec_log[k];
3375     y=y-1-((y-two_to_the(k-1)) / two_to_the(k));
3376   }
3377   k++;
3378 }
3379
3380 @ The trigonometric subroutines use an auxiliary table such that
3381 |spec_atan[k]| contains an approximation to the |angle| whose tangent
3382 is~$1/2^k$. $\arctan2^{-k}$ times $2^{20}\cdot180/\pi$ 
3383
3384 @<Declarations@>=
3385 static const angle spec_atan[27] = { 0, 27855475, 14718068, 7471121, 3750058, 
3386 1876857, 938658, 469357, 234682, 117342, 58671, 29335, 14668, 7334, 3667, 
3387 1833, 917, 458, 229, 115, 57, 29, 14, 7, 4, 2, 1 };
3388
3389 @ Given integers |x| and |y|, not both zero, the |n_arg| function
3390 returns the |angle| whose tangent points in the direction $(x,y)$.
3391 This subroutine first determines the correct octant, then solves the
3392 problem for |0<=y<=x|, then converts the result appropriately to
3393 return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
3394 (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
3395 |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
3396
3397 The octants are represented in a ``Gray code,'' since that turns out
3398 to be computationally simplest.
3399
3400 @d negate_x 1
3401 @d negate_y 2
3402 @d switch_x_and_y 4
3403 @d first_octant 1
3404 @d second_octant (first_octant+switch_x_and_y)
3405 @d third_octant (first_octant+switch_x_and_y+negate_x)
3406 @d fourth_octant (first_octant+negate_x)
3407 @d fifth_octant (first_octant+negate_x+negate_y)
3408 @d sixth_octant (first_octant+switch_x_and_y+negate_x+negate_y)
3409 @d seventh_octant (first_octant+switch_x_and_y+negate_y)
3410 @d eighth_octant (first_octant+negate_y)
3411
3412 @c 
3413 static angle mp_n_arg (MP mp,integer x, integer y) {
3414   angle z; /* auxiliary register */
3415   integer t; /* temporary storage */
3416   quarterword k; /* loop counter */
3417   int octant; /* octant code */
3418   if ( x>=0 ) {
3419     octant=first_octant;
3420   } else { 
3421     negate(x); octant=first_octant+negate_x;
3422   }
3423   if ( y<0 ) { 
3424     negate(y); octant=octant+negate_y;
3425   }
3426   if ( x<y ) { 
3427     t=y; y=x; x=t; octant=octant+switch_x_and_y;
3428   }
3429   if ( x==0 ) { 
3430     @<Handle undefined arg@>; 
3431   } else { 
3432     @<Set variable |z| to the arg of $(x,y)$@>;
3433     @<Return an appropriate answer based on |z| and |octant|@>;
3434   }
3435 }
3436
3437 @ @<Handle undefined arg@>=
3438
3439   print_err("angle(0,0) is taken as zero");
3440 @.angle(0,0)...zero@>
3441   help2("The `angle' between two identical points is undefined.",
3442         "I'm zeroing this one. Proceed, with fingers crossed.");
3443   mp_error(mp); 
3444   return 0;
3445 }
3446
3447 @ @<Return an appropriate answer...@>=
3448 switch (octant) {
3449 case first_octant: return z;
3450 case second_octant: return (ninety_deg-z);
3451 case third_octant: return (ninety_deg+z);
3452 case fourth_octant: return (one_eighty_deg-z);
3453 case fifth_octant: return (z-one_eighty_deg);
3454 case sixth_octant: return (-z-ninety_deg);
3455 case seventh_octant: return (z-ninety_deg);
3456 case eighth_octant: return (-z);
3457 }; /* there are no other cases */
3458 return 0
3459
3460 @ At this point we have |x>=y>=0|, and |x>0|. The numbers are scaled up
3461 or down until $2^{28}\L x<2^{29}$, so that accurate fixed-point calculations
3462 will be made.
3463
3464 @<Set variable |z| to the arg...@>=
3465 while ( x>=fraction_two ) { 
3466   x=halfp(x); y=halfp(y);
3467 }
3468 z=0;
3469 if ( y>0 ) { 
3470  while ( x<fraction_one ) { 
3471     x+=x; y+=y; 
3472  };
3473  @<Increase |z| to the arg of $(x,y)$@>;
3474 }
3475
3476 @ During the calculations of this section, variables |x| and~|y|
3477 represent actual coordinates $(x,2^{-k}y)$. We will maintain the
3478 condition |x>=y|, so that the tangent will be at most $2^{-k}$.
3479 If $x<2y$, the tangent is greater than $2^{-k-1}$. The transformation
3480 $(a,b)\mapsto(a+b\tan\phi,b-a\tan\phi)$ replaces $(a,b)$ by
3481 coordinates whose angle has decreased by~$\phi$; in the special case
3482 $a=x$, $b=2^{-k}y$, and $\tan\phi=2^{-k-1}$, this operation reduces
3483 to the particularly simple iteration shown here. [Cf.~John E. Meggitt,
3484 @^Meggitt, John E.@>
3485 {\sl IBM Journal of Research and Development\/ \bf6} (1962), 210--226.]
3486
3487 The initial value of |x| will be multiplied by at most
3488 $(1+{1\over2})(1+{1\over8})(1+{1\over32})\cdots\approx 1.7584$; hence
3489 there is no chance of integer overflow.
3490
3491 @<Increase |z|...@>=
3492 k=0;
3493 do {  
3494   y+=y; k++;
3495   if ( y>x ){ 
3496     z=z+spec_atan[k]; t=x; x=x+(y / two_to_the(k+k)); y=y-t;
3497   };
3498 } while (k!=15);
3499 do {  
3500   y+=y; k++;
3501   if ( y>x ) { z=z+spec_atan[k]; y=y-x; };
3502 } while (k!=26)
3503
3504 @ Conversely, the |n_sin_cos| routine takes an |angle| and produces the sine
3505 and cosine of that angle. The results of this routine are
3506 stored in global integer variables |n_sin| and |n_cos|.
3507
3508 @<Glob...@>=
3509 fraction n_sin;fraction n_cos; /* results computed by |n_sin_cos| */
3510
3511 @ Given an integer |z| that is $2^{20}$ times an angle $\theta$ in degrees,
3512 the purpose of |n_sin_cos(z)| is to set
3513 |x=@t$r\cos\theta$@>| and |y=@t$r\sin\theta$@>| (approximately),
3514 for some rather large number~|r|. The maximum of |x| and |y|
3515 will be between $2^{28}$ and $2^{30}$, so that there will be hardly
3516 any loss of accuracy. Then |x| and~|y| are divided by~|r|.
3517
3518 @c 
3519 static void mp_n_sin_cos (MP mp,angle z) { /* computes a multiple of the sine
3520                                        and cosine */ 
3521   quarterword k; /* loop control variable */
3522   int q; /* specifies the quadrant */
3523   fraction r; /* magnitude of |(x,y)| */
3524   integer x,y,t; /* temporary registers */
3525   while ( z<0 ) z=z+three_sixty_deg;
3526   z=z % three_sixty_deg; /* now |0<=z<three_sixty_deg| */
3527   q=z / forty_five_deg; z=z % forty_five_deg;
3528   x=fraction_one; y=x;
3529   if ( ! odd(q) ) z=forty_five_deg-z;
3530   @<Subtract angle |z| from |(x,y)|@>;
3531   @<Convert |(x,y)| to the octant determined by~|q|@>;
3532   r=mp_pyth_add(mp, x,y); 
3533   mp->n_cos=mp_make_fraction(mp, x,r); 
3534   mp->n_sin=mp_make_fraction(mp, y,r);
3535 }
3536
3537 @ In this case the octants are numbered sequentially.
3538
3539 @<Convert |(x,...@>=
3540 switch (q) {
3541 case 0: break;
3542 case 1: t=x; x=y; y=t; break;
3543 case 2: t=x; x=-y; y=t; break;
3544 case 3: negate(x); break;
3545 case 4: negate(x); negate(y); break;
3546 case 5: t=x; x=-y; y=-t; break;
3547 case 6: t=x; x=y; y=-t; break;
3548 case 7: negate(y); break;
3549 } /* there are no other cases */
3550
3551 @ The main iteration of |n_sin_cos| is similar to that of |n_arg| but
3552 applied in reverse. The values of |spec_atan[k]| decrease slowly enough
3553 that this loop is guaranteed to terminate before the (nonexistent) value
3554 |spec_atan[27]| would be required.
3555
3556 @<Subtract angle |z|...@>=
3557 k=1;
3558 while ( z>0 ){ 
3559   if ( z>=spec_atan[k] ) { 
3560     z=z-spec_atan[k]; t=x;
3561     x=t+y / two_to_the(k);
3562     y=y-t / two_to_the(k);
3563   }
3564   k++;
3565 }
3566 if ( y<0 ) y=0 /* this precaution may never be needed */
3567
3568 @ And now let's complete our collection of numeric utility routines
3569 by considering random number generation.
3570 \MP\ generates pseudo-random numbers with the additive scheme recommended
3571 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
3572 results are random fractions between 0 and |fraction_one-1|, inclusive.
3573
3574 There's an auxiliary array |randoms| that contains 55 pseudo-random
3575 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
3576 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
3577 The global variable |j_random| tells which element has most recently
3578 been consumed.
3579 The global variable |random_seed| was introduced in version 0.9,
3580 for the sole reason of stressing the fact that the initial value of the
3581 random seed is system-dependant. The initialization code below will initialize
3582 this variable to |(internal[mp_time] div unity)+internal[mp_day]|, but this 
3583 is not good enough on modern fast machines that are capable of running
3584 multiple MetaPost processes within the same second.
3585 @^system dependencies@>
3586
3587 @<Glob...@>=
3588 fraction randoms[55]; /* the last 55 random values generated */
3589 int j_random; /* the number of unused |randoms| */
3590
3591 @ @<Option variables@>=
3592 int random_seed; /* the default random seed */
3593
3594 @ @<Allocate or initialize ...@>=
3595 mp->random_seed = (scaled)opt->random_seed;
3596
3597 @ To consume a random fraction, the program below will say `|next_random|'
3598 and then it will fetch |randoms[j_random]|.
3599
3600 @d next_random { if ( mp->j_random==0 ) mp_new_randoms(mp);
3601   else decr(mp->j_random); }
3602
3603 @c 
3604 static void mp_new_randoms (MP mp) {
3605   int k; /* index into |randoms| */
3606   fraction x; /* accumulator */
3607   for (k=0;k<=23;k++) { 
3608    x=mp->randoms[k]-mp->randoms[k+31];
3609     if ( x<0 ) x=x+fraction_one;
3610     mp->randoms[k]=x;
3611   }
3612   for (k=24;k<= 54;k++){ 
3613     x=mp->randoms[k]-mp->randoms[k-24];
3614     if ( x<0 ) x=x+fraction_one;
3615     mp->randoms[k]=x;
3616   }
3617   mp->j_random=54;
3618 }
3619
3620 @ @<Declarations@>=
3621 static void mp_init_randoms (MP mp,scaled seed);
3622
3623 @ To initialize the |randoms| table, we call the following routine.
3624
3625 @c 
3626 void mp_init_randoms (MP mp,scaled seed) {
3627   fraction j,jj,k; /* more or less random integers */
3628   int i; /* index into |randoms| */
3629   j=abs(seed);
3630   while ( j>=fraction_one ) j=halfp(j);
3631   k=1;
3632   for (i=0;i<=54;i++ ){ 
3633     jj=k; k=j-k; j=jj;
3634     if ( k<0 ) k=k+fraction_one;
3635     mp->randoms[(i*21)% 55]=j;
3636   }
3637   mp_new_randoms(mp); 
3638   mp_new_randoms(mp); 
3639   mp_new_randoms(mp); /* ``warm up'' the array */
3640 }
3641
3642 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
3643 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
3644
3645 Note that the call of |take_fraction| will produce the values 0 and~|x|
3646 with about half the probability that it will produce any other particular
3647 values between 0 and~|x|, because it rounds its answers.
3648
3649 @c 
3650 static scaled mp_unif_rand (MP mp,scaled x) {
3651   scaled y; /* trial value */
3652   next_random; y=mp_take_fraction(mp, abs(x),mp->randoms[mp->j_random]);
3653   if ( y==abs(x) ) return 0;
3654   else if ( x>0 ) return y;
3655   else return (-y);
3656 }
3657
3658 @ Finally, a normal deviate with mean zero and unit standard deviation
3659 can readily be obtained with the ratio method (Algorithm 3.4.1R in
3660 {\sl The Art of Computer Programming\/}).
3661
3662 @c 
3663 static scaled mp_norm_rand (MP mp) {
3664   integer x,u,l; /* what the book would call $2^{16}X$, $2^{28}U$, and $-2^{24}\ln U$ */
3665   do { 
3666     do {  
3667       next_random;
3668       x=mp_take_fraction(mp, 112429,mp->randoms[mp->j_random]-fraction_half);
3669       /* $2^{16}\sqrt{8/e}\approx 112428.82793$ */
3670       next_random; u=mp->randoms[mp->j_random];
3671     } while (abs(x)>=u);
3672     x=mp_make_fraction(mp, x,u);
3673     l=139548960-mp_m_log(mp, u); /* $2^{24}\cdot12\ln2\approx139548959.6165$ */
3674   } while (mp_ab_vs_cd(mp, 1024,l,x,x)<0);
3675   return x;
3676 }
3677
3678 @* \[9] Packed data.
3679 In order to make efficient use of storage space, \MP\ bases its major data
3680 structures on a |memory_word|, which contains either a (signed) integer,
3681 possibly scaled, or a small number of fields that are one half or one
3682 quarter of the size used for storing integers.
3683
3684 If |x| is a variable of type |memory_word|, it contains up to four
3685 fields that can be referred to as follows:
3686 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
3687 |x|&.|int|&(an |integer|)\cr
3688 |x|&.|sc|\qquad&(a |scaled| integer)\cr
3689 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
3690 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
3691   field)\cr
3692 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
3693   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
3694 This is somewhat cumbersome to write, and not very readable either, but
3695 macros will be used to make the notation shorter and more transparent.
3696 The code below gives a formal definition of |memory_word| and
3697 its subsidiary types, using packed variant records. \MP\ makes no
3698 assumptions about the relative positions of the fields within a word.
3699
3700 @d max_quarterword 0x3FFF /* largest allowable value in a |quarterword| */
3701 @d max_halfword 0xFFFFFFF /* largest allowable value in a |halfword| */
3702
3703 @ Here are the inequalities that the quarterword and halfword values
3704 must satisfy (or rather, the inequalities that they mustn't satisfy):
3705
3706 @<Check the ``constant''...@>=
3707 if (mp->ini_version) {
3708   if ( mp->mem_max!=mp->mem_top ) mp->bad=8;
3709 } else {
3710   if ( mp->mem_max<mp->mem_top ) mp->bad=8;
3711 }
3712 if ( mp->mem_max>=max_halfword ) mp->bad=12;
3713 if ( mp->max_strings>max_halfword ) mp->bad=13;
3714
3715 @ The macros |qi| and |qo| are used for input to and output 
3716 from quarterwords. These are legacy macros.
3717 @^system dependencies@>
3718
3719 @d qo(A) (A) /* to read eight bits from a quarterword */
3720 @d qi(A) (quarterword)(A) /* to store eight bits in a quarterword */
3721
3722 @ The reader should study the following definitions closely:
3723 @^system dependencies@>
3724
3725 @d sc cint /* |scaled| data is equivalent to |integer| */
3726
3727 @<Types...@>=
3728 typedef short quarterword; /* 1/4 of a word */
3729 typedef int halfword; /* 1/2 of a word */
3730 typedef union {
3731   struct {
3732     halfword RH, LH;
3733   } v;
3734   struct { /* Make B0,B1 overlap the most significant bytes of LH.  */
3735     halfword junk;
3736     quarterword B0, B1;
3737   } u;
3738 } two_halves;
3739 typedef struct {
3740   struct {
3741     quarterword B2, B3, B0, B1;
3742   } u;
3743 } four_quarters;
3744 typedef union {
3745   two_halves hh;
3746   integer cint;
3747   four_quarters qqqq;
3748 } memory_word;
3749 #define b0 u.B0
3750 #define b1 u.B1
3751 #define b2 u.B2
3752 #define b3 u.B3
3753 #define rh v.RH
3754 #define lh v.LH
3755
3756 @ When debugging, we may want to print a |memory_word| without knowing
3757 what type it is; so we print it in all modes.
3758 @^debugging@>
3759
3760 @c 
3761 void mp_print_word (MP mp,memory_word w) {
3762   /* prints |w| in all ways */
3763   mp_print_int(mp, w.cint); mp_print_char(mp, xord(' '));
3764   mp_print_scaled(mp, w.sc); mp_print_char(mp, xord(' ')); 
3765   mp_print_scaled(mp, w.sc / 010000); mp_print_ln(mp);
3766   mp_print_int(mp, w.hh.lh); mp_print_char(mp, xord('=')); 
3767   mp_print_int(mp, w.hh.b0); mp_print_char(mp, xord(':'));
3768   mp_print_int(mp, w.hh.b1); mp_print_char(mp, xord(';')); 
3769   mp_print_int(mp, w.hh.rh); mp_print_char(mp, xord(' '));
3770   mp_print_int(mp, w.qqqq.b0); mp_print_char(mp, xord(':')); 
3771   mp_print_int(mp, w.qqqq.b1); mp_print_char(mp, xord(':'));
3772   mp_print_int(mp, w.qqqq.b2); mp_print_char(mp, xord(':')); 
3773   mp_print_int(mp, w.qqqq.b3);
3774 }
3775
3776
3777 @* \[10] Dynamic memory allocation.
3778
3779 The \MP\ system does nearly all of its own memory allocation, so that it
3780 can readily be transported into environments that do not have automatic
3781 facilities for strings, garbage collection, etc., and so that it can be in
3782 control of what error messages the user receives. The dynamic storage
3783 requirements of \MP\ are handled by providing a large array |mem| in
3784 which consecutive blocks of words are used as nodes by the \MP\ routines.
3785
3786 Pointer variables are indices into this array, or into another array
3787 called |eqtb| that will be explained later. A pointer variable might
3788 also be a special flag that lies outside the bounds of |mem|, so we
3789 allow pointers to assume any |halfword| value. The minimum memory
3790 index represents a null pointer.
3791
3792 @d null 0 /* the null pointer */
3793 @d mp_void (null+1) /* a null pointer different from |null| */
3794
3795
3796 @<Types...@>=
3797 typedef halfword pointer; /* a flag or a location in |mem| or |eqtb| */
3798
3799 @ The |mem| array is divided into two regions that are allocated separately,
3800 but the dividing line between these two regions is not fixed; they grow
3801 together until finding their ``natural'' size in a particular job.
3802 Locations less than or equal to |lo_mem_max| are used for storing
3803 variable-length records consisting of two or more words each. This region
3804 is maintained using an algorithm similar to the one described in exercise
3805 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3806 appears in the allocated nodes; the program is responsible for knowing the
3807 relevant size when a node is freed. Locations greater than or equal to
3808 |hi_mem_min| are used for storing one-word records; a conventional
3809 \.{AVAIL} stack is used for allocation in this region.
3810
3811 Locations of |mem| between |0| and |mem_top| may be dumped as part
3812 of preloaded mem files, by the \.{INIMP} preprocessor.
3813 @.INIMP@>
3814 Production versions of \MP\ may extend the memory at the top end in order to
3815 provide more space; these locations, between |mem_top| and |mem_max|,
3816 are always used for single-word nodes.
3817
3818 The key pointers that govern |mem| allocation have a prescribed order:
3819 $$\hbox{|null=0<lo_mem_max<hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3820
3821 @<Glob...@>=
3822 memory_word *mem; /* the big dynamic storage area */
3823 pointer lo_mem_max; /* the largest location of variable-size memory in use */
3824 pointer hi_mem_min; /* the smallest location of one-word memory in use */
3825
3826
3827
3828 @d xfree(A) do { mp_xfree(A); A=NULL; } while (0)
3829 @d xrealloc(P,A,B) mp_xrealloc(mp,P,(size_t)A,B)
3830 @d xmalloc(A,B)  mp_xmalloc(mp,(size_t)A,B)
3831 @d xstrdup(A)  mp_xstrdup(mp,A)
3832 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
3833
3834 @<Declare helpers@>=
3835 extern char *mp_strdup(const char *p) ;
3836 extern void mp_xfree ( @= /*@@only@@*/ /*@@out@@*/ /*@@null@@*/ @> void *x);
3837 extern @= /*@@only@@*/ @> void *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) ;
3838 extern @= /*@@only@@*/ @> void *mp_xmalloc (MP mp, size_t nmem, size_t size) ;
3839 extern @= /*@@only@@*/ @> char *mp_xstrdup(MP mp, const char *s);
3840 extern void mp_do_snprintf(char *str, int size, const char *fmt, ...);
3841
3842 @ The |max_size_test| guards against overflow, on the assumption that
3843 |size_t| is at least 31bits wide.
3844
3845 @d max_size_test 0x7FFFFFFF
3846
3847 @c
3848 char *mp_strdup(const char *p) {
3849   char *r;
3850   size_t l;
3851   if (p==NULL) return NULL;
3852   l = strlen(p);
3853   r = malloc (l*sizeof(char)+1);
3854   if (r==NULL)
3855     return NULL;
3856   return memcpy (r,p,(l+1));
3857 }
3858 void mp_xfree (void *x) {
3859   if (x!=NULL) free(x);
3860 }
3861 void  *mp_xrealloc (MP mp, void *p, size_t nmem, size_t size) {
3862   void *w ; 
3863   if ((max_size_test/size)<nmem) {
3864     do_fprintf(mp->err_out,"Memory size overflow!\n");
3865     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3866   }
3867   w = realloc (p,(nmem*size));
3868   if (w==NULL) {
3869     do_fprintf(mp->err_out,"Out of memory!\n");
3870     mp->history =mp_system_error_stop;    mp_jump_out(mp);
3871   }
3872   return w;
3873 }
3874 void  *mp_xmalloc (MP mp, size_t nmem, size_t size) {
3875   void *w;
3876   if ((max_size_test/size)<nmem) {
3877     do_fprintf(mp->err_out,"Memory size overflow!\n");
3878     mp->history =mp_fatal_error_stop;    mp_jump_out(mp);
3879   }
3880   w = malloc (nmem*size);
3881   if (w==NULL) {
3882     do_fprintf(mp->err_out,"Out of memory!\n");
3883     mp->history =mp_system_error_stop;    mp_jump_out(mp);
3884   }
3885   return w;
3886 }
3887 char *mp_xstrdup(MP mp, const char *s) {
3888   char *w; 
3889   if (s==NULL)
3890     return NULL;
3891   w = mp_strdup(s);
3892   if (w==NULL) {
3893     do_fprintf(mp->err_out,"Out of memory!\n");
3894     mp->history =mp_system_error_stop;    mp_jump_out(mp);
3895   }
3896   return w;
3897 }
3898
3899 @ @<Internal library declarations@>=
3900 #ifdef HAVE_SNPRINTF
3901 #define mp_snprintf (void)snprintf
3902 #else
3903 #define mp_snprintf mp_do_snprintf
3904 #endif
3905
3906 @ This internal version is rather stupid, but good enough for its purpose.
3907
3908 @c
3909 static char *mp_itoa (int i) {
3910   char res[32] ;
3911   unsigned idx = 30;
3912   unsigned v = (unsigned)abs(i);
3913   memset(res,0,32*sizeof(char));
3914   while (v>=10) {
3915     char d = (char)(v % 10);
3916     v = v / 10;
3917     res[idx--] = (char)d + '0';
3918   }
3919   res[idx--] = (char)v + '0';
3920   if (i<0) {
3921       res[idx--] = '-';
3922   }
3923   return mp_strdup((res+idx+1));
3924 }
3925 static char *mp_utoa (unsigned v) {
3926   char res[32] ;
3927   unsigned idx = 30;
3928   memset(res,0,32*sizeof(char));
3929   while (v>=10) {
3930     char d = (char)(v % 10);
3931     v = v / 10;
3932     res[idx--] = d + '0';
3933   }
3934   res[idx--] = (char)v + '0';
3935   return mp_strdup((res+idx+1));
3936 }
3937 void mp_do_snprintf (char *str, int size, const char *format, ...) {
3938   const char *fmt;
3939   char *res;
3940   va_list ap;
3941   va_start(ap, format);
3942   res = str;
3943   for (fmt=format;*fmt!='\0';fmt++) {
3944      if (*fmt=='%') {
3945        fmt++;
3946        switch(*fmt) {
3947        case 's':
3948          {
3949            char *s = va_arg(ap, char *);
3950            while (*s) {
3951              *res = *s++;
3952              if (size-->0) res++;
3953            }
3954          }
3955          break;
3956        case 'i':
3957        case 'd':
3958          {
3959            char *s = mp_itoa(va_arg(ap, int));
3960            if (s != NULL) {
3961              while (*s) {
3962                *res = *s++;
3963                if (size-->0) res++;
3964              }
3965            }
3966          }
3967          break;
3968        case 'u':
3969          {
3970            char *s = mp_utoa(va_arg(ap, unsigned));
3971            if (s != NULL) {
3972              while (*s) {
3973                *res = *s++;
3974                if (size-->0) res++;
3975              }
3976            }
3977          }
3978          break;
3979        case '%':
3980          *res = '%';
3981          if (size-->0) res++;
3982          break;
3983        default:
3984          *res = '%';
3985          if (size-->0) res++;
3986          *res = *fmt;
3987          if (size-->0) res++;
3988          break;
3989        }
3990      } else {
3991        *res = *fmt;
3992        if (size-->0) res++;
3993      }
3994   }
3995   *res = '\0';
3996   va_end(ap);
3997 }
3998
3999
4000 @<Allocate or initialize ...@>=
4001 mp->mem = xmalloc ((mp->mem_max+1),sizeof (memory_word));
4002 memset(mp->mem,0,(mp->mem_max+1)*sizeof (memory_word));
4003
4004 @ @<Dealloc variables@>=
4005 xfree(mp->mem);
4006
4007 @ Users who wish to study the memory requirements of particular applications can
4008 can use optional special features that keep track of current and
4009 maximum memory usage. When code between the delimiters |stat| $\ldots$
4010 |tats| is not ``commented out,'' \MP\ will run a bit slower but it will
4011 report these statistics when |mp_tracing_stats| is positive.
4012
4013 @<Glob...@>=
4014 integer var_used; integer dyn_used; /* how much memory is in use */
4015
4016 @ Let's consider the one-word memory region first, since it's the
4017 simplest. The pointer variable |mem_end| holds the highest-numbered location
4018 of |mem| that has ever been used. The free locations of |mem| that
4019 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
4020 |two_halves|, and we write |info(p)| and |mp_link(p)| for the |lh|
4021 and |rh| fields of |mem[p]| when it is of this type. The single-word
4022 free locations form a linked list
4023 $$|avail|,\;\hbox{|mp_link(avail)|},\;\hbox{|mp_link(mp_link(avail))|},\;\ldots$$
4024 terminated by |null|.
4025
4026 @(mpmp.h@>=
4027 #define mp_link(A)   mp->mem[(A)].hh.rh /* the |link| field of a memory word */
4028 #define mp_info(A)   mp->mem[(A)].hh.lh /* the |info| field of a memory word */
4029
4030 @ @<Glob...@>=
4031 pointer avail; /* head of the list of available one-word nodes */
4032 pointer mem_end; /* the last one-word node used in |mem| */
4033
4034 @ If one-word memory is exhausted, it might mean that the user has forgotten
4035 a token like `\&{enddef}' or `\&{endfor}'. We will define some procedures
4036 later that try to help pinpoint the trouble.
4037
4038 @ The function |get_avail| returns a pointer to a new one-word node whose
4039 |link| field is null. However, \MP\ will halt if there is no more room left.
4040 @^inner loop@>
4041
4042 @c 
4043 static pointer mp_get_avail (MP mp) { /* single-word node allocation */
4044   pointer p; /* the new node being got */
4045   p=mp->avail; /* get top location in the |avail| stack */
4046   if ( p!=null ) {
4047     mp->avail=mp_link(mp->avail); /* and pop it off */
4048   } else if ( mp->mem_end<mp->mem_max ) { /* or go into virgin territory */
4049     incr(mp->mem_end); p=mp->mem_end;
4050   } else { 
4051     decr(mp->hi_mem_min); p=mp->hi_mem_min;
4052     if ( mp->hi_mem_min<=mp->lo_mem_max ) { 
4053       mp_runaway(mp); /* if memory is exhausted, display possible runaway text */
4054       mp_overflow(mp, "main memory size",mp->mem_max);
4055       /* quit; all one-word nodes are busy */
4056 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4057     }
4058   }
4059   mp_link(p)=null; /* provide an oft-desired initialization of the new node */
4060   incr(mp->dyn_used);/* maintain statistics */
4061   return p;
4062 }
4063
4064 @ Conversely, a one-word node is recycled by calling |free_avail|.
4065
4066 @d free_avail(A)  /* single-word node liberation */
4067   { mp_link((A))=mp->avail; mp->avail=(A); decr(mp->dyn_used);  }
4068
4069 @ There's also a |fast_get_avail| routine, which saves the procedure-call
4070 overhead at the expense of extra programming. This macro is used in
4071 the places that would otherwise account for the most calls of |get_avail|.
4072 @^inner loop@>
4073
4074 @d fast_get_avail(A) { 
4075   (A)=mp->avail; /* avoid |get_avail| if possible, to save time */
4076   if ( (A)==null ) { (A)=mp_get_avail(mp); } 
4077   else { mp->avail=mp_link((A)); mp_link((A))=null;  incr(mp->dyn_used); }
4078   }
4079
4080 @ The available-space list that keeps track of the variable-size portion
4081 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
4082 pointed to by the roving pointer |rover|.
4083
4084 Each empty node has size 2 or more; the first word contains the special
4085 value |max_halfword| in its |link| field and the size in its |info| field;
4086 the second word contains the two pointers for double linking.
4087
4088 Each nonempty node also has size 2 or more. Its first word is of type
4089 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
4090 Otherwise there is complete flexibility with respect to the contents
4091 of its other fields and its other words.
4092
4093 (We require |mem_max<max_halfword| because terrible things can happen
4094 when |max_halfword| appears in the |link| field of a nonempty node.)
4095
4096 @d empty_flag   max_halfword /* the |link| of an empty variable-size node */
4097 @d is_empty(A)   (mp_link((A))==empty_flag) /* tests for empty node */
4098
4099 @(mpmp.h@>=
4100 #define node_size   mp_info /* the size field in empty variable-size nodes */
4101 #define lmp_link(A)   mp_info((A)+1) /* left link in doubly-linked list of empty nodes */
4102 #define rmp_link(A)   mp_link((A)+1) /* right link in doubly-linked list of empty nodes */
4103
4104 @ @<Glob...@>=
4105 pointer rover; /* points to some node in the list of empties */
4106
4107 @ A call to |get_node| with argument |s| returns a pointer to a new node
4108 of size~|s|, which must be 2~or more. The |link| field of the first word
4109 of this new node is set to null. An overflow stop occurs if no suitable
4110 space exists.
4111
4112 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
4113 areas and returns the value |max_halfword|.
4114
4115 @<Internal library declarations@>=
4116 pointer mp_get_node (MP mp,integer s) ;
4117
4118 @ @c 
4119 pointer mp_get_node (MP mp,integer s) { /* variable-size node allocation */
4120   pointer p; /* the node currently under inspection */
4121   pointer q;  /* the node physically after node |p| */
4122   integer r; /* the newly allocated node, or a candidate for this honor */
4123   integer t,tt; /* temporary registers */
4124 @^inner loop@>
4125  RESTART: 
4126   p=mp->rover; /* start at some free node in the ring */
4127   do {  
4128     @<Try to allocate within node |p| and its physical successors,
4129      and |goto found| if allocation was possible@>;
4130     if (rmp_link(p)==null || (rmp_link(p)==p && p!=mp->rover)) {
4131       print_err("Free list garbled");
4132       help3("I found an entry in the list of free nodes that links",
4133        "badly. I will try to ignore the broken link, but something",
4134        "is seriously amiss. It is wise to warn the maintainers.")
4135           mp_error(mp);
4136       rmp_link(p)=mp->rover;
4137     }
4138         p=rmp_link(p); /* move to the next node in the ring */
4139   } while (p!=mp->rover); /* repeat until the whole list has been traversed */
4140   if ( s==010000000000 ) { 
4141     return max_halfword;
4142   };
4143   if ( mp->lo_mem_max+2<mp->hi_mem_min ) {
4144     if ( mp->lo_mem_max+2<=max_halfword ) {
4145       @<Grow more variable-size memory and |goto restart|@>;
4146     }
4147   }
4148   mp_overflow(mp, "main memory size",mp->mem_max);
4149   /* sorry, nothing satisfactory is left */
4150 @:MetaPost capacity exceeded main memory size}{\quad main memory size@>
4151 FOUND: 
4152   mp_link(r)=null; /* this node is now nonempty */
4153   mp->var_used+=s; /* maintain usage statistics */
4154   return r;
4155 }
4156
4157 @ The lower part of |mem| grows by 1000 words at a time, unless
4158 we are very close to going under. When it grows, we simply link
4159 a new node into the available-space list. This method of controlled
4160 growth helps to keep the |mem| usage consecutive when \MP\ is
4161 implemented on ``virtual memory'' systems.
4162 @^virtual memory@>
4163
4164 @<Grow more variable-size memory and |goto restart|@>=
4165
4166   if ( mp->hi_mem_min-mp->lo_mem_max>=1998 ) {
4167     t=mp->lo_mem_max+1000;
4168   } else {
4169     t=mp->lo_mem_max+1+(mp->hi_mem_min-mp->lo_mem_max) / 2; 
4170     /* |lo_mem_max+2<=t<hi_mem_min| */
4171   }
4172   if ( t>max_halfword ) t=max_halfword;
4173   p=lmp_link(mp->rover); q=mp->lo_mem_max; rmp_link(p)=q; lmp_link(mp->rover)=q;
4174   rmp_link(q)=mp->rover; lmp_link(q)=p; mp_link(q)=empty_flag; 
4175   node_size(q)=t-mp->lo_mem_max;
4176   mp->lo_mem_max=t; mp_link(mp->lo_mem_max)=null; mp_info(mp->lo_mem_max)=null;
4177   mp->rover=q; 
4178   goto RESTART;
4179 }
4180
4181 @ @<Try to allocate...@>=
4182 q=p+node_size(p); /* find the physical successor */
4183 while ( is_empty(q) ) { /* merge node |p| with node |q| */
4184   t=rmp_link(q); tt=lmp_link(q);
4185 @^inner loop@>
4186   if ( q==mp->rover ) mp->rover=t;
4187   lmp_link(t)=tt; rmp_link(tt)=t;
4188   q=q+node_size(q);
4189 }
4190 r=q-s;
4191 if ( r>p+1 ) {
4192   @<Allocate from the top of node |p| and |goto found|@>;
4193 }
4194 if ( r==p ) { 
4195   if ( rmp_link(p)!=p ) {
4196     @<Allocate entire node |p| and |goto found|@>;
4197   }
4198 }
4199 node_size(p)=q-p /* reset the size in case it grew */
4200
4201 @ @<Allocate from the top...@>=
4202
4203   node_size(p)=r-p; /* store the remaining size */
4204   mp->rover=p; /* start searching here next time */
4205   goto FOUND;
4206 }
4207
4208 @ Here we delete node |p| from the ring, and let |rover| rove around.
4209
4210 @<Allocate entire...@>=
4211
4212   mp->rover=rmp_link(p); t=lmp_link(p);
4213   lmp_link(mp->rover)=t; rmp_link(t)=mp->rover;
4214   goto FOUND;
4215 }
4216
4217 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
4218 the operation |free_node(p,s)| will make its words available, by inserting
4219 |p| as a new empty node just before where |rover| now points.
4220
4221 @<Internal library declarations@>=
4222 void mp_free_node (MP mp, pointer p, halfword s) ;
4223
4224 @ @c 
4225 void mp_free_node (MP mp, pointer p, halfword s) { /* variable-size node
4226   liberation */
4227   pointer q; /* |lmp_link(rover)| */
4228   node_size(p)=s; mp_link(p)=empty_flag;
4229 @^inner loop@>
4230   q=lmp_link(mp->rover); lmp_link(p)=q; rmp_link(p)=mp->rover; /* set both links */
4231   lmp_link(mp->rover)=p; rmp_link(q)=p; /* insert |p| into the ring */
4232   mp->var_used-=s; /* maintain statistics */
4233 }
4234
4235 @* \[11] Memory layout.
4236 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4237 more efficient than dynamic allocation when we can get away with it. For
4238 example, locations |0| to |1| are always used to store a
4239 two-word dummy token whose second word is zero.
4240 The following macro definitions accomplish the static allocation by giving
4241 symbolic names to the fixed positions. Static variable-size nodes appear
4242 in locations |0| through |lo_mem_stat_max|, and static single-word nodes
4243 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive.
4244
4245 @d sentinel mp->mem_top /* end of sorted lists */
4246 @d temp_head (mp->mem_top-1) /* head of a temporary list of some kind */
4247 @d hold_head (mp->mem_top-2) /* head of a temporary list of another kind */
4248
4249 @(mpmp.h@>=
4250 #define spec_head (mp->mem_top-3) /* head of a list of unprocessed \&{special} items */
4251 #define null_dash (2) /* the first two words are reserved for a null value */
4252 #define dep_head (null_dash+3) /* we will define |dash_node_size=3| */
4253 #define zero_val (dep_head+2) /* two words for a permanently zero value */
4254 #define temp_val (zero_val+2) /* two words for a temporary value node */
4255 #define end_attr temp_val /* we use |end_attr+2| only */
4256 #define inf_val (end_attr+2) /* and |inf_val+1| only */
4257 #define bad_vardef (inf_val+2) /* two words for \&{vardef} error recovery */
4258 #define lo_mem_stat_max (bad_vardef+1)  /* largest statically
4259   allocated word in the variable-size |mem| */
4260 #define hi_mem_stat_min (mp->mem_top-3) /* smallest statically allocated word in
4261   the one-word |mem| */
4262
4263 @ The following code gets the dynamic part of |mem| off to a good start,
4264 when \MP\ is initializing itself the slow way.
4265
4266 @<Initialize table entries (done by \.{INIMP} only)@>=
4267 mp->rover=lo_mem_stat_max+1; /* initialize the dynamic memory */
4268 mp_link(mp->rover)=empty_flag;
4269 node_size(mp->rover)=1000; /* which is a 1000-word available node */
4270 lmp_link(mp->rover)=mp->rover; rmp_link(mp->rover)=mp->rover;
4271 mp->lo_mem_max=mp->rover+1000; 
4272 mp_link(mp->lo_mem_max)=null; mp_info(mp->lo_mem_max)=null;
4273 for (k=hi_mem_stat_min;k<=(int)mp->mem_top;k++) {
4274   mp->mem[k]=mp->mem[mp->lo_mem_max]; /* clear list heads */
4275 }
4276 mp->avail=null; mp->mem_end=mp->mem_top;
4277 mp->hi_mem_min=hi_mem_stat_min; /* initialize the one-word memory */
4278 mp->var_used=lo_mem_stat_max+1; 
4279 mp->dyn_used=mp->mem_top+1-(hi_mem_stat_min);  /* initialize statistics */
4280
4281 @ The procedure |flush_list(p)| frees an entire linked list of one-word
4282 nodes that starts at a given position, until coming to |sentinel| or a
4283 pointer that is not in the one-word region. Another procedure,
4284 |flush_node_list|, frees an entire linked list of one-word and two-word
4285 nodes, until coming to a |null| pointer.
4286 @^inner loop@>
4287
4288 @c 
4289 static void mp_flush_list (MP mp,pointer p) { /* makes list of single-word nodes  available */
4290   pointer q,r; /* list traversers */
4291   if ( p>=mp->hi_mem_min ) if ( p!=sentinel ) { 
4292     r=p;
4293     do {  
4294       q=r; r=mp_link(r); 
4295       decr(mp->dyn_used);
4296       if ( r<mp->hi_mem_min ) break;
4297     } while (r!=sentinel);
4298   /* now |q| is the last node on the list */
4299     mp_link(q)=mp->avail; mp->avail=p;
4300   }
4301 }
4302 @#
4303 static void mp_flush_node_list (MP mp,pointer p) {
4304   pointer q; /* the node being recycled */
4305   while ( p!=null ){ 
4306     q=p; p=mp_link(p);
4307     if ( q<mp->hi_mem_min ) 
4308       mp_free_node(mp, q,2);
4309     else 
4310       free_avail(q);
4311   }
4312 }
4313
4314 @ If \MP\ is extended improperly, the |mem| array might get screwed up.
4315 For example, some pointers might be wrong, or some ``dead'' nodes might not
4316 have been freed when the last reference to them disappeared. Procedures
4317 |check_mem| and |search_mem| are available to help diagnose such
4318 problems. These procedures make use of two arrays called |free| and
4319 |was_free| that are present only if \MP's debugging routines have
4320 been included. (You may want to decrease the size of |mem| while you
4321 @^debugging@>
4322 are debugging.)
4323
4324 Because |boolean|s are typedef-d as ints, it is better to use
4325 unsigned chars here.
4326
4327 @<Glob...@>=
4328 unsigned char *free; /* free cells */
4329 unsigned char *was_free; /* previously free cells */
4330 pointer was_mem_end; pointer was_lo_max; pointer was_hi_min;
4331   /* previous |mem_end|, |lo_mem_max|,and |hi_mem_min| */
4332 boolean panicking; /* do we want to check memory constantly? */
4333
4334 @ @<Allocate or initialize ...@>=
4335 mp->free = xmalloc ((mp->mem_max+1),sizeof (unsigned char));
4336 mp->was_free = xmalloc ((mp->mem_max+1), sizeof (unsigned char));
4337
4338 @ @<Dealloc variables@>=
4339 xfree(mp->free);
4340 xfree(mp->was_free);
4341
4342 @ @<Allocate or ...@>=
4343 mp->was_hi_min=mp->mem_max;
4344 mp->panicking=false;
4345
4346 @ @<Declarations@>=
4347 static void mp_reallocate_memory(MP mp, int l) ;
4348
4349 @ @c
4350 static void mp_reallocate_memory(MP mp, int l) {
4351    XREALLOC(mp->free,     l, unsigned char);
4352    XREALLOC(mp->was_free, l, unsigned char);
4353    if (mp->mem) {
4354          int newarea = l-mp->mem_max;
4355      XREALLOC(mp->mem,      l, memory_word);
4356      memset (mp->mem+(mp->mem_max+1),0,sizeof(memory_word)*(newarea));
4357    } else {
4358      XREALLOC(mp->mem,      l, memory_word);
4359      memset(mp->mem,0,sizeof(memory_word)*(l+1));
4360    }
4361    mp->mem_max = l;
4362    if (mp->ini_version) 
4363      mp->mem_top = l;
4364 }
4365
4366
4367
4368 @ Procedure |check_mem| makes sure that the available space lists of
4369 |mem| are well formed, and it optionally prints out all locations
4370 that are reserved now but were free the last time this procedure was called.
4371
4372 @c 
4373 void mp_check_mem (MP mp,boolean print_locs ) {
4374   pointer p,q,r; /* current locations of interest in |mem| */
4375   boolean clobbered; /* is something amiss? */
4376   for (p=0;p<=mp->lo_mem_max;p++) {
4377     mp->free[p]=false; /* you can probably do this faster */
4378   }
4379   for (p=mp->hi_mem_min;p<= mp->mem_end;p++) {
4380     mp->free[p]=false; /* ditto */
4381   }
4382   @<Check single-word |avail| list@>;
4383   @<Check variable-size |avail| list@>;
4384   @<Check flags of unavailable nodes@>;
4385   @<Check the list of linear dependencies@>;
4386   if ( print_locs ) {
4387     @<Print newly busy locations@>;
4388   }
4389   memcpy(mp->was_free,mp->free, sizeof(char)*(mp->mem_end+1));
4390   mp->was_mem_end=mp->mem_end; 
4391   mp->was_lo_max=mp->lo_mem_max; 
4392   mp->was_hi_min=mp->hi_mem_min;
4393 }
4394
4395 @ @<Check single-word...@>=
4396 p=mp->avail; q=null; clobbered=false;
4397 while ( p!=null ) { 
4398   if ( (p>mp->mem_end)||(p<mp->hi_mem_min) ) clobbered=true;
4399   else if ( mp->free[p] ) clobbered=true;
4400   if ( clobbered ) { 
4401     mp_print_nl(mp, "AVAIL list clobbered at ");
4402 @.AVAIL list clobbered...@>
4403     mp_print_int(mp, q); break;
4404   }
4405   mp->free[p]=true; q=p; p=mp_link(q);
4406 }
4407
4408 @ @<Check variable-size...@>=
4409 p=mp->rover; q=null; clobbered=false;
4410 do {  
4411   if ( (p>=mp->lo_mem_max)||(p<0) ) clobbered=true;
4412   else if ( (rmp_link(p)>=mp->lo_mem_max)||(rmp_link(p)<0) ) clobbered=true;
4413   else if (  !(is_empty(p))||(node_size(p)<2)||
4414    (p+node_size(p)>mp->lo_mem_max)|| (lmp_link(rmp_link(p))!=p) ) clobbered=true;
4415   if ( clobbered ) { 
4416     mp_print_nl(mp, "Double-AVAIL list clobbered at ");
4417 @.Double-AVAIL list clobbered...@>
4418     mp_print_int(mp, q); break;
4419   }
4420   for (q=p;q<=p+node_size(p)-1;q++) { /* mark all locations free */
4421     if ( mp->free[q] ) { 
4422       mp_print_nl(mp, "Doubly free location at ");
4423 @.Doubly free location...@>
4424       mp_print_int(mp, q); break;
4425     }
4426     mp->free[q]=true;
4427   }
4428   q=p; p=rmp_link(p);
4429 } while (p!=mp->rover)
4430
4431
4432 @ @<Check flags...@>=
4433 p=0;
4434 while ( p<=mp->lo_mem_max ) { /* node |p| should not be empty */
4435   if ( is_empty(p) ) {
4436     mp_print_nl(mp, "Bad flag at "); mp_print_int(mp, p);
4437 @.Bad flag...@>
4438   }
4439   while ( (p<=mp->lo_mem_max) && ! mp->free[p] ) p++;
4440   while ( (p<=mp->lo_mem_max) && mp->free[p] ) p++;
4441 }
4442
4443 @ @<Print newly busy...@>=
4444
4445   @<Do intialization required before printing new busy locations@>;
4446   mp_print_nl(mp, "New busy locs:");
4447 @.New busy locs@>
4448   for (p=0;p<= mp->lo_mem_max;p++ ) {
4449     if ( ! mp->free[p] && ((p>mp->was_lo_max) || mp->was_free[p]) ) {
4450       @<Indicate that |p| is a new busy location@>;
4451     }
4452   }
4453   for (p=mp->hi_mem_min;p<=mp->mem_end;p++ ) {
4454     if ( ! mp->free[p] &&
4455         ((p<mp->was_hi_min) || (p>mp->was_mem_end) || mp->was_free[p]) ) {
4456       @<Indicate that |p| is a new busy location@>;
4457     }
4458   }
4459   @<Finish printing new busy locations@>;
4460 }
4461
4462 @ There might be many new busy locations so we are careful to print contiguous
4463 blocks compactly.  During this operation |q| is the last new busy location and
4464 |r| is the start of the block containing |q|.
4465
4466 @<Indicate that |p| is a new busy location@>=
4467
4468   if ( p>q+1 ) { 
4469     if ( q>r ) { 
4470       mp_print(mp, ".."); mp_print_int(mp, q);
4471     }
4472     mp_print_char(mp, xord(' ')); mp_print_int(mp, p);
4473     r=p;
4474   }
4475   q=p;
4476 }
4477
4478 @ @<Do intialization required before printing new busy locations@>=
4479 q=mp->mem_max; r=mp->mem_max
4480
4481 @ @<Finish printing new busy locations@>=
4482 if ( q>r ) { 
4483   mp_print(mp, ".."); mp_print_int(mp, q);
4484 }
4485
4486 @ The |search_mem| procedure attempts to answer the question ``Who points
4487 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4488 that might not be of type |two_halves|. Strictly speaking, this is
4489 undefined, and it can lead to ``false drops'' (words that seem to
4490 point to |p| purely by coincidence). But for debugging purposes, we want
4491 to rule out the places that do {\sl not\/} point to |p|, so a few false
4492 drops are tolerable.
4493
4494 @c
4495 void mp_search_mem (MP mp, pointer p) { /* look for pointers to |p| */
4496   integer q; /* current position being searched */
4497   for (q=0;q<=mp->lo_mem_max;q++) { 
4498     if ( mp_link(q)==p ){ 
4499       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4500     }
4501     if ( mp_info(q)==p ) { 
4502       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4503     }
4504   }
4505   for (q=mp->hi_mem_min;q<=mp->mem_end;q++) {
4506     if ( mp_link(q)==p ) {
4507       mp_print_nl(mp, "LINK("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4508     }
4509     if ( mp_info(q)==p ) {
4510       mp_print_nl(mp, "INFO("); mp_print_int(mp, q); mp_print_char(mp, xord(')'));
4511     }
4512   }
4513   @<Search |eqtb| for equivalents equal to |p|@>;
4514 }
4515
4516 @ Just before \.{INIMP} writes out the memory, it sorts the doubly linked
4517 available space list. The list is probably very short at such times, so a
4518 simple insertion sort is used. The smallest available location will be
4519 pointed to by |rover|, the next-smallest by |rmp_link(rover)|, etc.
4520
4521 @<Internal library ...@>=
4522 void mp_sort_avail (MP mp);
4523
4524 @ @c 
4525 void mp_sort_avail (MP mp) { /* sorts the available variable-size nodes
4526   by location */
4527   pointer p,q,r; /* indices into |mem| */
4528   pointer old_rover; /* initial |rover| setting */
4529   p=mp_get_node(mp, 010000000000); /* merge adjacent free areas */
4530   p=rmp_link(mp->rover); rmp_link(mp->rover)=max_halfword; old_rover=mp->rover;
4531   while ( p!=old_rover ) {
4532     @<Sort |p| into the list starting at |rover|
4533      and advance |p| to |rmp_link(p)|@>;
4534   }
4535   p=mp->rover;
4536   while ( rmp_link(p)!=max_halfword ) { 
4537     lmp_link(rmp_link(p))=p; p=rmp_link(p);
4538   };
4539   rmp_link(p)=mp->rover; lmp_link(mp->rover)=p;
4540 }
4541
4542 @ The following |while| loop is guaranteed to
4543 terminate, since the list that starts at
4544 |rover| ends with |max_halfword| during the sorting procedure.
4545
4546 @<Sort |p|...@>=
4547 if ( p<mp->rover ) { 
4548   q=p; p=rmp_link(q); rmp_link(q)=mp->rover; mp->rover=q;
4549 } else  { 
4550   q=mp->rover;
4551   while ( rmp_link(q)<p ) q=rmp_link(q);
4552   r=rmp_link(p); rmp_link(p)=rmp_link(q); rmp_link(q)=p; p=r;
4553 }
4554
4555
4556 @* \[12] The command codes.
4557 Before we can go much further, we need to define symbolic names for the internal
4558 code numbers that represent the various commands obeyed by \MP. These codes
4559 are somewhat arbitrary, but not completely so. For example,
4560 some codes have been made adjacent so that |case| statements in the
4561 program need not consider cases that are widely spaced, or so that |case|
4562 statements can be replaced by |if| statements. A command can begin an
4563 expression if and only if its code lies between |min_primary_command| and
4564 |max_primary_command|, inclusive. The first token of a statement that doesn't
4565 begin with an expression has a command code between |min_command| and
4566 |max_statement_command|, inclusive. Anything less than |min_command| is
4567 eliminated during macro expansions, and anything no more than |max_pre_command|
4568 is eliminated when expanding \TeX\ material.  Ranges such as
4569 |min_secondary_command..max_secondary_command| are used when parsing
4570 expressions, but the relative ordering within such a range is generally not
4571 critical.
4572
4573 The ordering of the highest-numbered commands
4574 (|comma<semicolon<end_group<stop|) is crucial for the parsing and
4575 error-recovery methods of this program as is the ordering |if_test<fi_or_else|
4576 for the smallest two commands.  The ordering is also important in the ranges
4577 |numeric_token..plus_or_minus| and |left_brace..ampersand|.
4578
4579 At any rate, here is the list, for future reference.
4580
4581 @d start_tex 1 /* begin \TeX\ material (\&{btex}, \&{verbatimtex}) */
4582 @d etex_marker 2 /* end \TeX\ material (\&{etex}) */
4583 @d mpx_break 3 /* stop reading an \.{MPX} file (\&{mpxbreak}) */
4584 @d max_pre_command mpx_break
4585 @d if_test 4 /* conditional text (\&{if}) */
4586 @d fi_or_else 5 /* delimiters for conditionals (\&{elseif}, \&{else}, \&{fi}) */
4587 @d input 6 /* input a source file (\&{input}, \&{endinput}) */
4588 @d iteration 7 /* iterate (\&{for}, \&{forsuffixes}, \&{forever}, \&{endfor}) */
4589 @d repeat_loop 8 /* special command substituted for \&{endfor} */
4590 @d exit_test 9 /* premature exit from a loop (\&{exitif}) */
4591 @d relax 10 /* do nothing (\.{\char`\\}) */
4592 @d scan_tokens 11 /* put a string into the input buffer */
4593 @d expand_after 12 /* look ahead one token */
4594 @d defined_macro 13 /* a macro defined by the user */
4595 @d min_command (defined_macro+1)
4596 @d save_command 14 /* save a list of tokens (\&{save}) */
4597 @d interim_command 15 /* save an internal quantity (\&{interim}) */
4598 @d let_command 16 /* redefine a symbolic token (\&{let}) */
4599 @d new_internal 17 /* define a new internal quantity (\&{newinternal}) */
4600 @d macro_def 18 /* define a macro (\&{def}, \&{vardef}, etc.) */
4601 @d ship_out_command 19 /* output a character (\&{shipout}) */
4602 @d add_to_command 20 /* add to edges (\&{addto}) */
4603 @d bounds_command 21  /* add bounding path to edges (\&{setbounds}, \&{clip}) */
4604 @d tfm_command 22 /* command for font metric info (\&{ligtable}, etc.) */
4605 @d protection_command 23 /* set protection flag (\&{outer}, \&{inner}) */
4606 @d show_command 24 /* diagnostic output (\&{show}, \&{showvariable}, etc.) */
4607 @d mode_command 25 /* set interaction level (\&{batchmode}, etc.) */
4608 @d mp_random_seed 26 /* initialize random number generator (\&{randomseed}) */
4609 @d message_command 27 /* communicate to user (\&{message}, \&{errmessage}) */
4610 @d every_job_command 28 /* designate a starting token (\&{everyjob}) */
4611 @d delimiters 29 /* define a pair of delimiters (\&{delimiters}) */
4612 @d special_command 30 /* output special info (\&{special})
4613                        or font map info (\&{fontmapfile}, \&{fontmapline}) */
4614 @d write_command 31 /* write text to a file (\&{write}) */
4615 @d type_name 32 /* declare a type (\&{numeric}, \&{pair}, etc.) */
4616 @d max_statement_command type_name
4617 @d min_primary_command type_name
4618 @d left_delimiter 33 /* the left delimiter of a matching pair */
4619 @d begin_group 34 /* beginning of a group (\&{begingroup}) */
4620 @d nullary 35 /* an operator without arguments (e.g., \&{normaldeviate}) */
4621 @d unary 36 /* an operator with one argument (e.g., \&{sqrt}) */
4622 @d str_op 37 /* convert a suffix to a string (\&{str}) */
4623 @d cycle 38 /* close a cyclic path (\&{cycle}) */
4624 @d primary_binary 39 /* binary operation taking `\&{of}' (e.g., \&{point}) */
4625 @d capsule_token 40 /* a value that has been put into a token list */
4626 @d string_token 41 /* a string constant (e.g., |"hello"|) */
4627 @d internal_quantity 42 /* internal numeric parameter (e.g., \&{pausing}) */
4628 @d min_suffix_token internal_quantity
4629 @d tag_token 43 /* a symbolic token without a primitive meaning */
4630 @d numeric_token 44 /* a numeric constant (e.g., \.{3.14159}) */
4631 @d max_suffix_token numeric_token
4632 @d plus_or_minus 45 /* either `\.+' or `\.-' */
4633 @d max_primary_command plus_or_minus /* should also be |numeric_token+1| */
4634 @d min_tertiary_command plus_or_minus
4635 @d tertiary_secondary_macro 46 /* a macro defined by \&{secondarydef} */
4636 @d tertiary_binary 47 /* an operator at the tertiary level (e.g., `\.{++}') */
4637 @d max_tertiary_command tertiary_binary
4638 @d left_brace 48 /* the operator `\.{\char`\{}' */
4639 @d min_expression_command left_brace
4640 @d path_join 49 /* the operator `\.{..}' */
4641 @d ampersand 50 /* the operator `\.\&' */
4642 @d expression_tertiary_macro 51 /* a macro defined by \&{tertiarydef} */
4643 @d expression_binary 52 /* an operator at the expression level (e.g., `\.<') */
4644 @d equals 53 /* the operator `\.=' */
4645 @d max_expression_command equals
4646 @d and_command 54 /* the operator `\&{and}' */
4647 @d min_secondary_command and_command
4648 @d secondary_primary_macro 55 /* a macro defined by \&{primarydef} */
4649 @d slash 56 /* the operator `\./' */
4650 @d secondary_binary 57 /* an operator at the binary level (e.g., \&{shifted}) */
4651 @d max_secondary_command secondary_binary
4652 @d param_type 58 /* type of parameter (\&{primary}, \&{expr}, \&{suffix}, etc.) */
4653 @d controls 59 /* specify control points explicitly (\&{controls}) */
4654 @d tension 60 /* specify tension between knots (\&{tension}) */
4655 @d at_least 61 /* bounded tension value (\&{atleast}) */
4656 @d curl_command 62 /* specify curl at an end knot (\&{curl}) */
4657 @d macro_special 63 /* special macro operators (\&{quote}, \.{\#\AT!}, etc.) */
4658 @d right_delimiter 64 /* the right delimiter of a matching pair */
4659 @d left_bracket 65 /* the operator `\.[' */
4660 @d right_bracket 66 /* the operator `\.]' */
4661 @d right_brace 67 /* the operator `\.{\char`\}}' */
4662 @d with_option 68 /* option for filling (\&{withpen}, \&{withweight}, etc.) */
4663 @d thing_to_add 69
4664   /* variant of \&{addto} (\&{contour}, \&{doublepath}, \&{also}) */
4665 @d of_token 70 /* the operator `\&{of}' */
4666 @d to_token 71 /* the operator `\&{to}' */
4667 @d step_token 72 /* the operator `\&{step}' */
4668 @d until_token 73 /* the operator `\&{until}' */
4669 @d within_token 74 /* the operator `\&{within}' */
4670 @d lig_kern_token 75
4671   /* the operators `\&{kern}' and `\.{=:}' and `\.{=:\char'174}', etc. */
4672 @d assignment 76 /* the operator `\.{:=}' */
4673 @d skip_to 77 /* the operation `\&{skipto}' */
4674 @d bchar_label 78 /* the operator `\.{\char'174\char'174:}' */
4675 @d double_colon 79 /* the operator `\.{::}' */
4676 @d colon 80 /* the operator `\.:' */
4677 @#
4678 @d comma 81 /* the operator `\.,', must be |colon+1| */
4679 @d end_of_statement (mp->cur_cmd>comma)
4680 @d semicolon 82 /* the operator `\.;', must be |comma+1| */
4681 @d end_group 83 /* end a group (\&{endgroup}), must be |semicolon+1| */
4682 @d stop 84 /* end a job (\&{end}, \&{dump}), must be |end_group+1| */
4683 @d max_command_code stop
4684 @d outer_tag (max_command_code+1) /* protection code added to command code */
4685
4686 @<Types...@>=
4687 typedef int command_code;
4688
4689 @ Variables and capsules in \MP\ have a variety of ``types,''
4690 distinguished by the code numbers defined here. These numbers are also
4691 not completely arbitrary.  Things that get expanded must have types
4692 |>mp_independent|; a type remaining after expansion is numeric if and only if
4693 its code number is at least |numeric_type|; objects containing numeric
4694 parts must have types between |transform_type| and |pair_type|;
4695 all other types must be smaller than |transform_type|; and among the types
4696 that are not unknown or vacuous, the smallest two must be |boolean_type|
4697 and |string_type| in that order.
4698  
4699 @d undefined 0 /* no type has been declared */
4700 @d unknown_tag 1 /* this constant is added to certain type codes below */
4701 @d unknown_types mp_unknown_boolean: case mp_unknown_string:
4702   case mp_unknown_pen: case mp_unknown_picture: case mp_unknown_path
4703
4704 @<Types...@>=
4705 enum mp_variable_type {
4706 mp_vacuous=1, /* no expression was present */
4707 mp_boolean_type, /* \&{boolean} with a known value */
4708 mp_unknown_boolean,
4709 mp_string_type, /* \&{string} with a known value */
4710 mp_unknown_string,
4711 mp_pen_type, /* \&{pen} with a known value */
4712 mp_unknown_pen,
4713 mp_path_type, /* \&{path} with a known value */
4714 mp_unknown_path,
4715 mp_picture_type, /* \&{picture} with a known value */
4716 mp_unknown_picture,
4717 mp_transform_type, /* \&{transform} variable or capsule */
4718 mp_color_type, /* \&{color} variable or capsule */
4719 mp_cmykcolor_type, /* \&{cmykcolor} variable or capsule */
4720 mp_pair_type, /* \&{pair} variable or capsule */
4721 mp_numeric_type, /* variable that has been declared \&{numeric} but not used */
4722 mp_known, /* \&{numeric} with a known value */
4723 mp_dependent, /* a linear combination with |fraction| coefficients */
4724 mp_proto_dependent, /* a linear combination with |scaled| coefficients */
4725 mp_independent, /* \&{numeric} with unknown value */
4726 mp_token_list, /* variable name or suffix argument or text argument */
4727 mp_structured, /* variable with subscripts and attributes */
4728 mp_unsuffixed_macro, /* variable defined with \&{vardef} but no \.{\AT!\#} */
4729 mp_suffixed_macro /* variable defined with \&{vardef} and \.{\AT!\#} */
4730 } ;
4731
4732 @ @<Declarations@>=
4733 static void mp_print_type (MP mp,quarterword t) ;
4734
4735 @ @<Basic printing procedures@>=
4736 void mp_print_type (MP mp,quarterword t) { 
4737   switch (t) {
4738   case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
4739   case mp_boolean_type:mp_print(mp, "boolean"); break;
4740   case mp_unknown_boolean:mp_print(mp, "unknown boolean"); break;
4741   case mp_string_type:mp_print(mp, "string"); break;
4742   case mp_unknown_string:mp_print(mp, "unknown string"); break;
4743   case mp_pen_type:mp_print(mp, "pen"); break;
4744   case mp_unknown_pen:mp_print(mp, "unknown pen"); break;
4745   case mp_path_type:mp_print(mp, "path"); break;
4746   case mp_unknown_path:mp_print(mp, "unknown path"); break;
4747   case mp_picture_type:mp_print(mp, "picture"); break;
4748   case mp_unknown_picture:mp_print(mp, "unknown picture"); break;
4749   case mp_transform_type:mp_print(mp, "transform"); break;
4750   case mp_color_type:mp_print(mp, "color"); break;
4751   case mp_cmykcolor_type:mp_print(mp, "cmykcolor"); break;
4752   case mp_pair_type:mp_print(mp, "pair"); break;
4753   case mp_known:mp_print(mp, "known numeric"); break;
4754   case mp_dependent:mp_print(mp, "dependent"); break;
4755   case mp_proto_dependent:mp_print(mp, "proto-dependent"); break;
4756   case mp_numeric_type:mp_print(mp, "numeric"); break;
4757   case mp_independent:mp_print(mp, "independent"); break;
4758   case mp_token_list:mp_print(mp, "token list"); break;
4759   case mp_structured:mp_print(mp, "mp_structured"); break;
4760   case mp_unsuffixed_macro:mp_print(mp, "unsuffixed macro"); break;
4761   case mp_suffixed_macro:mp_print(mp, "suffixed macro"); break;
4762   default: mp_print(mp, "undefined"); break;
4763   }
4764 }
4765
4766 @ Values inside \MP\ are stored in two-word nodes that have a |name_type|
4767 as well as a |type|. The possibilities for |name_type| are defined
4768 here; they will be explained in more detail later.
4769
4770 @<Types...@>=
4771 enum mp_name_types {
4772  mp_root=0, /* |name_type| at the top level of a variable */
4773  mp_saved_root, /* same, when the variable has been saved */
4774  mp_structured_root, /* |name_type| where a |mp_structured| branch occurs */
4775  mp_subscr, /* |name_type| in a subscript node */
4776  mp_attr, /* |name_type| in an attribute node */
4777  mp_x_part_sector, /* |name_type| in the \&{xpart} of a node */
4778  mp_y_part_sector, /* |name_type| in the \&{ypart} of a node */
4779  mp_xx_part_sector, /* |name_type| in the \&{xxpart} of a node */
4780  mp_xy_part_sector, /* |name_type| in the \&{xypart} of a node */
4781  mp_yx_part_sector, /* |name_type| in the \&{yxpart} of a node */
4782  mp_yy_part_sector, /* |name_type| in the \&{yypart} of a node */
4783  mp_red_part_sector, /* |name_type| in the \&{redpart} of a node */
4784  mp_green_part_sector, /* |name_type| in the \&{greenpart} of a node */
4785  mp_blue_part_sector, /* |name_type| in the \&{bluepart} of a node */
4786  mp_cyan_part_sector, /* |name_type| in the \&{redpart} of a node */
4787  mp_magenta_part_sector, /* |name_type| in the \&{greenpart} of a node */
4788  mp_yellow_part_sector, /* |name_type| in the \&{bluepart} of a node */
4789  mp_black_part_sector, /* |name_type| in the \&{greenpart} of a node */
4790  mp_grey_part_sector, /* |name_type| in the \&{bluepart} of a node */
4791  mp_capsule, /* |name_type| in stashed-away subexpressions */
4792  mp_token  /* |name_type| in a numeric token or string token */
4793 };
4794
4795 @ Primitive operations that produce values have a secondary identification
4796 code in addition to their command code; it's something like genera and species.
4797 For example, `\.*' has the command code |primary_binary|, and its
4798 secondary identification is |times|. The secondary codes start at 30 so that
4799 they don't overlap with the type codes; some type codes (e.g., |mp_string_type|)
4800 are used as operators as well as type identifications.  The relative values
4801 are not critical, except for |true_code..false_code|, |or_op..and_op|,
4802 and |filled_op..bounded_op|.  The restrictions are that
4803 |and_op-false_code=or_op-true_code|, that the ordering of
4804 |x_part...blue_part| must match that of |x_part_sector..mp_blue_part_sector|,
4805 and the ordering of |filled_op..bounded_op| must match that of the code
4806 values they test for.
4807
4808 @d true_code 30 /* operation code for \.{true} */
4809 @d false_code 31 /* operation code for \.{false} */
4810 @d null_picture_code 32 /* operation code for \.{nullpicture} */
4811 @d null_pen_code 33 /* operation code for \.{nullpen} */
4812 @d job_name_op 34 /* operation code for \.{jobname} */
4813 @d read_string_op 35 /* operation code for \.{readstring} */
4814 @d pen_circle 36 /* operation code for \.{pencircle} */
4815 @d normal_deviate 37 /* operation code for \.{normaldeviate} */
4816 @d read_from_op 38 /* operation code for \.{readfrom} */
4817 @d close_from_op 39 /* operation code for \.{closefrom} */
4818 @d odd_op 40 /* operation code for \.{odd} */
4819 @d known_op 41 /* operation code for \.{known} */
4820 @d unknown_op 42 /* operation code for \.{unknown} */
4821 @d not_op 43 /* operation code for \.{not} */
4822 @d decimal 44 /* operation code for \.{decimal} */
4823 @d reverse 45 /* operation code for \.{reverse} */
4824 @d make_path_op 46 /* operation code for \.{makepath} */
4825 @d make_pen_op 47 /* operation code for \.{makepen} */
4826 @d oct_op 48 /* operation code for \.{oct} */
4827 @d hex_op 49 /* operation code for \.{hex} */
4828 @d ASCII_op 50 /* operation code for \.{ASCII} */
4829 @d char_op 51 /* operation code for \.{char} */
4830 @d length_op 52 /* operation code for \.{length} */
4831 @d turning_op 53 /* operation code for \.{turningnumber} */
4832 @d color_model_part 54 /* operation code for \.{colormodel} */
4833 @d x_part 55 /* operation code for \.{xpart} */
4834 @d y_part 56 /* operation code for \.{ypart} */
4835 @d xx_part 57 /* operation code for \.{xxpart} */
4836 @d xy_part 58 /* operation code for \.{xypart} */
4837 @d yx_part 59 /* operation code for \.{yxpart} */
4838 @d yy_part 60 /* operation code for \.{yypart} */
4839 @d red_part 61 /* operation code for \.{redpart} */
4840 @d green_part 62 /* operation code for \.{greenpart} */
4841 @d blue_part 63 /* operation code for \.{bluepart} */
4842 @d cyan_part 64 /* operation code for \.{cyanpart} */
4843 @d magenta_part 65 /* operation code for \.{magentapart} */
4844 @d yellow_part 66 /* operation code for \.{yellowpart} */
4845 @d black_part 67 /* operation code for \.{blackpart} */
4846 @d grey_part 68 /* operation code for \.{greypart} */
4847 @d font_part 69 /* operation code for \.{fontpart} */
4848 @d text_part 70 /* operation code for \.{textpart} */
4849 @d path_part 71 /* operation code for \.{pathpart} */
4850 @d pen_part 72 /* operation code for \.{penpart} */
4851 @d dash_part 73 /* operation code for \.{dashpart} */
4852 @d sqrt_op 74 /* operation code for \.{sqrt} */
4853 @d mp_m_exp_op 75 /* operation code for \.{mexp} */
4854 @d mp_m_log_op 76 /* operation code for \.{mlog} */
4855 @d sin_d_op 77 /* operation code for \.{sind} */
4856 @d cos_d_op 78 /* operation code for \.{cosd} */
4857 @d floor_op 79 /* operation code for \.{floor} */
4858 @d uniform_deviate 80 /* operation code for \.{uniformdeviate} */
4859 @d char_exists_op 81 /* operation code for \.{charexists} */
4860 @d font_size 82 /* operation code for \.{fontsize} */
4861 @d ll_corner_op 83 /* operation code for \.{llcorner} */
4862 @d lr_corner_op 84 /* operation code for \.{lrcorner} */
4863 @d ul_corner_op 85 /* operation code for \.{ulcorner} */
4864 @d ur_corner_op 86 /* operation code for \.{urcorner} */
4865 @d arc_length 87 /* operation code for \.{arclength} */
4866 @d angle_op 88 /* operation code for \.{angle} */
4867 @d cycle_op 89 /* operation code for \.{cycle} */
4868 @d filled_op 90 /* operation code for \.{filled} */
4869 @d stroked_op 91 /* operation code for \.{stroked} */
4870 @d textual_op 92 /* operation code for \.{textual} */
4871 @d clipped_op 93 /* operation code for \.{clipped} */
4872 @d bounded_op 94 /* operation code for \.{bounded} */
4873 @d plus 95 /* operation code for \.+ */
4874 @d minus 96 /* operation code for \.- */
4875 @d times 97 /* operation code for \.* */
4876 @d over 98 /* operation code for \./ */
4877 @d pythag_add 99 /* operation code for \.{++} */
4878 @d pythag_sub 100 /* operation code for \.{+-+} */
4879 @d or_op 101 /* operation code for \.{or} */
4880 @d and_op 102 /* operation code for \.{and} */
4881 @d less_than 103 /* operation code for \.< */
4882 @d less_or_equal 104 /* operation code for \.{<=} */
4883 @d greater_than 105 /* operation code for \.> */
4884 @d greater_or_equal 106 /* operation code for \.{>=} */
4885 @d equal_to 107 /* operation code for \.= */
4886 @d unequal_to 108 /* operation code for \.{<>} */
4887 @d concatenate 109 /* operation code for \.\& */
4888 @d rotated_by 110 /* operation code for \.{rotated} */
4889 @d slanted_by 111 /* operation code for \.{slanted} */
4890 @d scaled_by 112 /* operation code for \.{scaled} */
4891 @d shifted_by 113 /* operation code for \.{shifted} */
4892 @d transformed_by 114 /* operation code for \.{transformed} */
4893 @d x_scaled 115 /* operation code for \.{xscaled} */
4894 @d y_scaled 116 /* operation code for \.{yscaled} */
4895 @d z_scaled 117 /* operation code for \.{zscaled} */
4896 @d in_font 118 /* operation code for \.{infont} */
4897 @d intersect 119 /* operation code for \.{intersectiontimes} */
4898 @d double_dot 120 /* operation code for improper \.{..} */
4899 @d substring_of 121 /* operation code for \.{substring} */
4900 @d min_of substring_of
4901 @d subpath_of 122 /* operation code for \.{subpath} */
4902 @d direction_time_of 123 /* operation code for \.{directiontime} */
4903 @d point_of 124 /* operation code for \.{point} */
4904 @d precontrol_of 125 /* operation code for \.{precontrol} */
4905 @d postcontrol_of 126 /* operation code for \.{postcontrol} */
4906 @d pen_offset_of 127 /* operation code for \.{penoffset} */
4907 @d arc_time_of 128 /* operation code for \.{arctime} */
4908 @d mp_version 129 /* operation code for \.{mpversion} */
4909 @d envelope_of 130 /* operation code for \.{envelope} */
4910
4911 @c static void mp_print_op (MP mp,quarterword c) { 
4912   if (c<=mp_numeric_type ) {
4913     mp_print_type(mp, c);
4914   } else {
4915     switch (c) {
4916     case true_code:mp_print(mp, "true"); break;
4917     case false_code:mp_print(mp, "false"); break;
4918     case null_picture_code:mp_print(mp, "nullpicture"); break;
4919     case null_pen_code:mp_print(mp, "nullpen"); break;
4920     case job_name_op:mp_print(mp, "jobname"); break;
4921     case read_string_op:mp_print(mp, "readstring"); break;
4922     case pen_circle:mp_print(mp, "pencircle"); break;
4923     case normal_deviate:mp_print(mp, "normaldeviate"); break;
4924     case read_from_op:mp_print(mp, "readfrom"); break;
4925     case close_from_op:mp_print(mp, "closefrom"); break;
4926     case odd_op:mp_print(mp, "odd"); break;
4927     case known_op:mp_print(mp, "known"); break;
4928     case unknown_op:mp_print(mp, "unknown"); break;
4929     case not_op:mp_print(mp, "not"); break;
4930     case decimal:mp_print(mp, "decimal"); break;
4931     case reverse:mp_print(mp, "reverse"); break;
4932     case make_path_op:mp_print(mp, "makepath"); break;
4933     case make_pen_op:mp_print(mp, "makepen"); break;
4934     case oct_op:mp_print(mp, "oct"); break;
4935     case hex_op:mp_print(mp, "hex"); break;
4936     case ASCII_op:mp_print(mp, "ASCII"); break;
4937     case char_op:mp_print(mp, "char"); break;
4938     case length_op:mp_print(mp, "length"); break;
4939     case turning_op:mp_print(mp, "turningnumber"); break;
4940     case x_part:mp_print(mp, "xpart"); break;
4941     case y_part:mp_print(mp, "ypart"); break;
4942     case xx_part:mp_print(mp, "xxpart"); break;
4943     case xy_part:mp_print(mp, "xypart"); break;
4944     case yx_part:mp_print(mp, "yxpart"); break;
4945     case yy_part:mp_print(mp, "yypart"); break;
4946     case red_part:mp_print(mp, "redpart"); break;
4947     case green_part:mp_print(mp, "greenpart"); break;
4948     case blue_part:mp_print(mp, "bluepart"); break;
4949     case cyan_part:mp_print(mp, "cyanpart"); break;
4950     case magenta_part:mp_print(mp, "magentapart"); break;
4951     case yellow_part:mp_print(mp, "yellowpart"); break;
4952     case black_part:mp_print(mp, "blackpart"); break;
4953     case grey_part:mp_print(mp, "greypart"); break;
4954     case color_model_part:mp_print(mp, "colormodel"); break;
4955     case font_part:mp_print(mp, "fontpart"); break;
4956     case text_part:mp_print(mp, "textpart"); break;
4957     case path_part:mp_print(mp, "pathpart"); break;
4958     case pen_part:mp_print(mp, "penpart"); break;
4959     case dash_part:mp_print(mp, "dashpart"); break;
4960     case sqrt_op:mp_print(mp, "sqrt"); break;
4961     case mp_m_exp_op:mp_print(mp, "mexp"); break;
4962     case mp_m_log_op:mp_print(mp, "mlog"); break;
4963     case sin_d_op:mp_print(mp, "sind"); break;
4964     case cos_d_op:mp_print(mp, "cosd"); break;
4965     case floor_op:mp_print(mp, "floor"); break;
4966     case uniform_deviate:mp_print(mp, "uniformdeviate"); break;
4967     case char_exists_op:mp_print(mp, "charexists"); break;
4968     case font_size:mp_print(mp, "fontsize"); break;
4969     case ll_corner_op:mp_print(mp, "llcorner"); break;
4970     case lr_corner_op:mp_print(mp, "lrcorner"); break;
4971     case ul_corner_op:mp_print(mp, "ulcorner"); break;
4972     case ur_corner_op:mp_print(mp, "urcorner"); break;
4973     case arc_length:mp_print(mp, "arclength"); break;
4974     case angle_op:mp_print(mp, "angle"); break;
4975     case cycle_op:mp_print(mp, "cycle"); break;
4976     case filled_op:mp_print(mp, "filled"); break;
4977     case stroked_op:mp_print(mp, "stroked"); break;
4978     case textual_op:mp_print(mp, "textual"); break;
4979     case clipped_op:mp_print(mp, "clipped"); break;
4980     case bounded_op:mp_print(mp, "bounded"); break;
4981     case plus:mp_print_char(mp, xord('+')); break;
4982     case minus:mp_print_char(mp, xord('-')); break;
4983     case times:mp_print_char(mp, xord('*')); break;
4984     case over:mp_print_char(mp, xord('/')); break;
4985     case pythag_add:mp_print(mp, "++"); break;
4986     case pythag_sub:mp_print(mp, "+-+"); break;
4987     case or_op:mp_print(mp, "or"); break;
4988     case and_op:mp_print(mp, "and"); break;
4989     case less_than:mp_print_char(mp, xord('<')); break;
4990     case less_or_equal:mp_print(mp, "<="); break;
4991     case greater_than:mp_print_char(mp, xord('>')); break;
4992     case greater_or_equal:mp_print(mp, ">="); break;
4993     case equal_to:mp_print_char(mp, xord('=')); break;
4994     case unequal_to:mp_print(mp, "<>"); break;
4995     case concatenate:mp_print(mp, "&"); break;
4996     case rotated_by:mp_print(mp, "rotated"); break;
4997     case slanted_by:mp_print(mp, "slanted"); break;
4998     case scaled_by:mp_print(mp, "scaled"); break;
4999     case shifted_by:mp_print(mp, "shifted"); break;
5000     case transformed_by:mp_print(mp, "transformed"); break;
5001     case x_scaled:mp_print(mp, "xscaled"); break;
5002     case y_scaled:mp_print(mp, "yscaled"); break;
5003     case z_scaled:mp_print(mp, "zscaled"); break;
5004     case in_font:mp_print(mp, "infont"); break;
5005     case intersect:mp_print(mp, "intersectiontimes"); break;
5006     case substring_of:mp_print(mp, "substring"); break;
5007     case subpath_of:mp_print(mp, "subpath"); break;
5008     case direction_time_of:mp_print(mp, "directiontime"); break;
5009     case point_of:mp_print(mp, "point"); break;
5010     case precontrol_of:mp_print(mp, "precontrol"); break;
5011     case postcontrol_of:mp_print(mp, "postcontrol"); break;
5012     case pen_offset_of:mp_print(mp, "penoffset"); break;
5013     case arc_time_of:mp_print(mp, "arctime"); break;
5014     case mp_version:mp_print(mp, "mpversion"); break;
5015     case envelope_of:mp_print(mp, "envelope"); break;
5016     default: mp_print(mp, ".."); break;
5017     }
5018   }
5019 }
5020
5021 @ \MP\ also has a bunch of internal parameters that a user might want to
5022 fuss with. Every such parameter has an identifying code number, defined here.
5023
5024 @<Types...@>=
5025 enum mp_given_internal {
5026   mp_tracing_titles=1, /* show titles online when they appear */
5027   mp_tracing_equations, /* show each variable when it becomes known */
5028   mp_tracing_capsules, /* show capsules too */
5029   mp_tracing_choices, /* show the control points chosen for paths */
5030   mp_tracing_specs, /* show path subdivision prior to filling with polygonal a pen */
5031   mp_tracing_commands, /* show commands and operations before they are performed */
5032   mp_tracing_restores, /* show when a variable or internal is restored */
5033   mp_tracing_macros, /* show macros before they are expanded */
5034   mp_tracing_output, /* show digitized edges as they are output */
5035   mp_tracing_stats, /* show memory usage at end of job */
5036   mp_tracing_lost_chars, /* show characters that aren't \&{infont} */
5037   mp_tracing_online, /* show long diagnostics on terminal and in the log file */
5038   mp_year, /* the current year (e.g., 1984) */
5039   mp_month, /* the current month (e.g., 3 $\equiv$ March) */
5040   mp_day, /* the current day of the month */
5041   mp_time, /* the number of minutes past midnight when this job started */
5042   mp_char_code, /* the number of the next character to be output */
5043   mp_char_ext, /* the extension code of the next character to be output */
5044   mp_char_wd, /* the width of the next character to be output */
5045   mp_char_ht, /* the height of the next character to be output */
5046   mp_char_dp, /* the depth of the next character to be output */
5047   mp_char_ic, /* the italic correction of the next character to be output */
5048   mp_design_size, /* the unit of measure used for |mp_char_wd..mp_char_ic|, in points */
5049   mp_pausing, /* positive to display lines on the terminal before they are read */
5050   mp_showstopping, /* positive to stop after each \&{show} command */
5051   mp_fontmaking, /* positive if font metric output is to be produced */
5052   mp_linejoin, /* as in \ps: 0 for mitered, 1 for round, 2 for beveled */
5053   mp_linecap, /* as in \ps: 0 for butt, 1 for round, 2 for square */
5054   mp_miterlimit, /* controls miter length as in \ps */
5055   mp_warning_check, /* controls error message when variable value is large */
5056   mp_boundary_char, /* the right boundary character for ligatures */
5057   mp_prologues, /* positive to output conforming PostScript using built-in fonts */
5058   mp_true_corners, /* positive to make \&{llcorner} etc. ignore \&{setbounds} */
5059   mp_default_color_model, /* the default color model for unspecified items */
5060   mp_restore_clip_color,
5061   mp_procset, /* wether or not create PostScript command shortcuts */
5062   mp_gtroffmode  /* whether the user specified |-troff| on the command line */
5063 };
5064
5065 @
5066
5067 @d max_given_internal mp_gtroffmode
5068
5069 @<Glob...@>=
5070 scaled *internal;  /* the values of internal quantities */
5071 char **int_name;  /* their names */
5072 int int_ptr;  /* the maximum internal quantity defined so far */
5073 int max_internal; /* current maximum number of internal quantities */
5074
5075 @ @<Option variables@>=
5076 int troff_mode; 
5077
5078 @ @<Allocate or initialize ...@>=
5079 mp->max_internal=2*max_given_internal;
5080 mp->internal = xmalloc ((mp->max_internal+1), sizeof(scaled));
5081 memset(mp->internal,0,(mp->max_internal+1)* sizeof(scaled));
5082 mp->int_name = xmalloc ((mp->max_internal+1), sizeof(char *));
5083 memset(mp->int_name,0,(mp->max_internal+1) * sizeof(char *));
5084 mp->troff_mode=(opt->troff_mode>0 ? true : false);
5085
5086 @ @<Exported function ...@>=
5087 int mp_troff_mode(MP mp);
5088
5089 @ @c
5090 int mp_troff_mode(MP mp) { return mp->troff_mode; }
5091
5092 @ @<Set initial ...@>=
5093 mp->int_ptr=max_given_internal;
5094
5095 @ The symbolic names for internal quantities are put into \MP's hash table
5096 by using a routine called |primitive|, which will be defined later. Let us
5097 enter them now, so that we don't have to list all those names again
5098 anywhere else.
5099
5100 @<Put each of \MP's primitives into the hash table@>=
5101 mp_primitive(mp, "tracingtitles",internal_quantity,mp_tracing_titles);
5102 @:tracingtitles_}{\&{tracingtitles} primitive@>
5103 mp_primitive(mp, "tracingequations",internal_quantity,mp_tracing_equations);
5104 @:mp_tracing_equations_}{\&{tracingequations} primitive@>
5105 mp_primitive(mp, "tracingcapsules",internal_quantity,mp_tracing_capsules);
5106 @:mp_tracing_capsules_}{\&{tracingcapsules} primitive@>
5107 mp_primitive(mp, "tracingchoices",internal_quantity,mp_tracing_choices);
5108 @:mp_tracing_choices_}{\&{tracingchoices} primitive@>
5109 mp_primitive(mp, "tracingspecs",internal_quantity,mp_tracing_specs);
5110 @:mp_tracing_specs_}{\&{tracingspecs} primitive@>
5111 mp_primitive(mp, "tracingcommands",internal_quantity,mp_tracing_commands);
5112 @:mp_tracing_commands_}{\&{tracingcommands} primitive@>
5113 mp_primitive(mp, "tracingrestores",internal_quantity,mp_tracing_restores);
5114 @:mp_tracing_restores_}{\&{tracingrestores} primitive@>
5115 mp_primitive(mp, "tracingmacros",internal_quantity,mp_tracing_macros);
5116 @:mp_tracing_macros_}{\&{tracingmacros} primitive@>
5117 mp_primitive(mp, "tracingoutput",internal_quantity,mp_tracing_output);
5118 @:mp_tracing_output_}{\&{tracingoutput} primitive@>
5119 mp_primitive(mp, "tracingstats",internal_quantity,mp_tracing_stats);
5120 @:mp_tracing_stats_}{\&{tracingstats} primitive@>
5121 mp_primitive(mp, "tracinglostchars",internal_quantity,mp_tracing_lost_chars);
5122 @:mp_tracing_lost_chars_}{\&{tracinglostchars} primitive@>
5123 mp_primitive(mp, "tracingonline",internal_quantity,mp_tracing_online);
5124 @:mp_tracing_online_}{\&{tracingonline} primitive@>
5125 mp_primitive(mp, "year",internal_quantity,mp_year);
5126 @:mp_year_}{\&{year} primitive@>
5127 mp_primitive(mp, "month",internal_quantity,mp_month);
5128 @:mp_month_}{\&{month} primitive@>
5129 mp_primitive(mp, "day",internal_quantity,mp_day);
5130 @:mp_day_}{\&{day} primitive@>
5131 mp_primitive(mp, "time",internal_quantity,mp_time);
5132 @:time_}{\&{time} primitive@>
5133 mp_primitive(mp, "charcode",internal_quantity,mp_char_code);
5134 @:mp_char_code_}{\&{charcode} primitive@>
5135 mp_primitive(mp, "charext",internal_quantity,mp_char_ext);
5136 @:mp_char_ext_}{\&{charext} primitive@>
5137 mp_primitive(mp, "charwd",internal_quantity,mp_char_wd);
5138 @:mp_char_wd_}{\&{charwd} primitive@>
5139 mp_primitive(mp, "charht",internal_quantity,mp_char_ht);
5140 @:mp_char_ht_}{\&{charht} primitive@>
5141 mp_primitive(mp, "chardp",internal_quantity,mp_char_dp);
5142 @:mp_char_dp_}{\&{chardp} primitive@>
5143 mp_primitive(mp, "charic",internal_quantity,mp_char_ic);
5144 @:mp_char_ic_}{\&{charic} primitive@>
5145 mp_primitive(mp, "designsize",internal_quantity,mp_design_size);
5146 @:mp_design_size_}{\&{designsize} primitive@>
5147 mp_primitive(mp, "pausing",internal_quantity,mp_pausing);
5148 @:mp_pausing_}{\&{pausing} primitive@>
5149 mp_primitive(mp, "showstopping",internal_quantity,mp_showstopping);
5150 @:mp_showstopping_}{\&{showstopping} primitive@>
5151 mp_primitive(mp, "fontmaking",internal_quantity,mp_fontmaking);
5152 @:mp_fontmaking_}{\&{fontmaking} primitive@>
5153 mp_primitive(mp, "linejoin",internal_quantity,mp_linejoin);
5154 @:mp_linejoin_}{\&{linejoin} primitive@>
5155 mp_primitive(mp, "linecap",internal_quantity,mp_linecap);
5156 @:mp_linecap_}{\&{linecap} primitive@>
5157 mp_primitive(mp, "miterlimit",internal_quantity,mp_miterlimit);
5158 @:mp_miterlimit_}{\&{miterlimit} primitive@>
5159 mp_primitive(mp, "warningcheck",internal_quantity,mp_warning_check);
5160 @:mp_warning_check_}{\&{warningcheck} primitive@>
5161 mp_primitive(mp, "boundarychar",internal_quantity,mp_boundary_char);
5162 @:mp_boundary_char_}{\&{boundarychar} primitive@>
5163 mp_primitive(mp, "prologues",internal_quantity,mp_prologues);
5164 @:mp_prologues_}{\&{prologues} primitive@>
5165 mp_primitive(mp, "truecorners",internal_quantity,mp_true_corners);
5166 @:mp_true_corners_}{\&{truecorners} primitive@>
5167 mp_primitive(mp, "mpprocset",internal_quantity,mp_procset);
5168 @:mp_procset_}{\&{mpprocset} primitive@>
5169 mp_primitive(mp, "troffmode",internal_quantity,mp_gtroffmode);
5170 @:troffmode_}{\&{troffmode} primitive@>
5171 mp_primitive(mp, "defaultcolormodel",internal_quantity,mp_default_color_model);
5172 @:mp_default_color_model_}{\&{defaultcolormodel} primitive@>
5173 mp_primitive(mp, "restoreclipcolor",internal_quantity,mp_restore_clip_color);
5174 @:mp_restore_clip_color_}{\&{restoreclipcolor} primitive@>
5175
5176 @ Colors can be specified in four color models. In the special
5177 case of |no_model|, MetaPost does not output any color operator to
5178 the postscript output.
5179
5180 Note: these values are passed directly on to |with_option|. This only
5181 works because the other possible values passed to |with_option| are
5182 8 and 10 respectively (from |with_pen| and |with_picture|).
5183
5184 There is a first state, that is only used for |gs_colormodel|. It flags
5185 the fact that there has not been any kind of color specification by
5186 the user so far in the game.
5187
5188 @(mplib.h@>=
5189 enum mp_color_model {
5190   mp_no_model=1,
5191   mp_grey_model=3,
5192   mp_rgb_model=5,
5193   mp_cmyk_model=7,
5194   mp_uninitialized_model=9
5195 };
5196
5197
5198 @ @<Initialize table entries (done by \.{INIMP} only)@>=
5199 mp->internal[mp_default_color_model]=(mp_rgb_model*unity);
5200 mp->internal[mp_restore_clip_color]=unity;
5201
5202 @ Well, we do have to list the names one more time, for use in symbolic
5203 printouts.
5204
5205 @<Initialize table...@>=
5206 mp->int_name[mp_tracing_titles]=xstrdup("tracingtitles");
5207 mp->int_name[mp_tracing_equations]=xstrdup("tracingequations");
5208 mp->int_name[mp_tracing_capsules]=xstrdup("tracingcapsules");
5209 mp->int_name[mp_tracing_choices]=xstrdup("tracingchoices");
5210 mp->int_name[mp_tracing_specs]=xstrdup("tracingspecs");
5211 mp->int_name[mp_tracing_commands]=xstrdup("tracingcommands");
5212 mp->int_name[mp_tracing_restores]=xstrdup("tracingrestores");
5213 mp->int_name[mp_tracing_macros]=xstrdup("tracingmacros");
5214 mp->int_name[mp_tracing_output]=xstrdup("tracingoutput");
5215 mp->int_name[mp_tracing_stats]=xstrdup("tracingstats");
5216 mp->int_name[mp_tracing_lost_chars]=xstrdup("tracinglostchars");
5217 mp->int_name[mp_tracing_online]=xstrdup("tracingonline");
5218 mp->int_name[mp_year]=xstrdup("year");
5219 mp->int_name[mp_month]=xstrdup("month");
5220 mp->int_name[mp_day]=xstrdup("day");
5221 mp->int_name[mp_time]=xstrdup("time");
5222 mp->int_name[mp_char_code]=xstrdup("charcode");
5223 mp->int_name[mp_char_ext]=xstrdup("charext");
5224 mp->int_name[mp_char_wd]=xstrdup("charwd");
5225 mp->int_name[mp_char_ht]=xstrdup("charht");
5226 mp->int_name[mp_char_dp]=xstrdup("chardp");
5227 mp->int_name[mp_char_ic]=xstrdup("charic");
5228 mp->int_name[mp_design_size]=xstrdup("designsize");
5229 mp->int_name[mp_pausing]=xstrdup("pausing");
5230 mp->int_name[mp_showstopping]=xstrdup("showstopping");
5231 mp->int_name[mp_fontmaking]=xstrdup("fontmaking");
5232 mp->int_name[mp_linejoin]=xstrdup("linejoin");
5233 mp->int_name[mp_linecap]=xstrdup("linecap");
5234 mp->int_name[mp_miterlimit]=xstrdup("miterlimit");
5235 mp->int_name[mp_warning_check]=xstrdup("warningcheck");
5236 mp->int_name[mp_boundary_char]=xstrdup("boundarychar");
5237 mp->int_name[mp_prologues]=xstrdup("prologues");
5238 mp->int_name[mp_true_corners]=xstrdup("truecorners");
5239 mp->int_name[mp_default_color_model]=xstrdup("defaultcolormodel");
5240 mp->int_name[mp_procset]=xstrdup("mpprocset");
5241 mp->int_name[mp_gtroffmode]=xstrdup("troffmode");
5242 mp->int_name[mp_restore_clip_color]=xstrdup("restoreclipcolor");
5243
5244 @ The following procedure, which is called just before \MP\ initializes its
5245 input and output, establishes the initial values of the date and time.
5246 @^system dependencies@>
5247
5248 Note that the values are |scaled| integers. Hence \MP\ can no longer
5249 be used after the year 32767.
5250
5251 @c 
5252 static void mp_fix_date_and_time (MP mp) { 
5253   time_t aclock = time ((time_t *) 0);
5254   struct tm *tmptr = localtime (&aclock);
5255   mp->internal[mp_time]=
5256       (tmptr->tm_hour*60+tmptr->tm_min)*unity; /* minutes since midnight */
5257   mp->internal[mp_day]=(tmptr->tm_mday)*unity; /* fourth day of the month */
5258   mp->internal[mp_month]=(tmptr->tm_mon+1)*unity; /* seventh month of the year */
5259   mp->internal[mp_year]=(tmptr->tm_year+1900)*unity; /* Anno Domini */
5260 }
5261
5262 @ @<Declarations@>=
5263 static void mp_fix_date_and_time (MP mp) ;
5264
5265 @ \MP\ is occasionally supposed to print diagnostic information that
5266 goes only into the transcript file, unless |mp_tracing_online| is positive.
5267 Now that we have defined |mp_tracing_online| we can define
5268 two routines that adjust the destination of print commands:
5269
5270 @<Declarations@>=
5271 static void mp_begin_diagnostic (MP mp) ;
5272 static void mp_end_diagnostic (MP mp,boolean blank_line);
5273 static void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) ;
5274
5275 @ @<Basic printing...@>=
5276 void mp_begin_diagnostic (MP mp) { /* prepare to do some tracing */
5277   mp->old_setting=mp->selector;
5278   if ((mp->internal[mp_tracing_online]<=0)&&(mp->selector==term_and_log)){ 
5279     decr(mp->selector);
5280     if ( mp->history==mp_spotless ) mp->history=mp_warning_issued;
5281   }
5282 }
5283 @#
5284 void mp_end_diagnostic (MP mp,boolean blank_line) {
5285   /* restore proper conditions after tracing */
5286   mp_print_nl(mp, "");
5287   if ( blank_line ) mp_print_ln(mp);
5288   mp->selector=mp->old_setting;
5289 }
5290
5291
5292
5293 @<Glob...@>=
5294 unsigned int old_setting;
5295
5296 @ We will occasionally use |begin_diagnostic| in connection with line-number
5297 printing, as follows. (The parameter |s| is typically |"Path"| or
5298 |"Cycle spec"|, etc.)
5299
5300 @<Basic printing...@>=
5301 void mp_print_diagnostic (MP mp, const char *s, const char *t, boolean nuline) { 
5302   mp_begin_diagnostic(mp);
5303   if ( nuline ) mp_print_nl(mp, s); else mp_print(mp, s);
5304   mp_print(mp, " at line "); 
5305   mp_print_int(mp, mp_true_line(mp));
5306   mp_print(mp, t); mp_print_char(mp, xord(':'));
5307 }
5308
5309 @ The 256 |ASCII_code| characters are grouped into classes by means of
5310 the |char_class| table. Individual class numbers have no semantic
5311 or syntactic significance, except in a few instances defined here.
5312 There's also |max_class|, which can be used as a basis for additional
5313 class numbers in nonstandard extensions of \MP.
5314
5315 @d digit_class 0 /* the class number of \.{0123456789} */
5316 @d period_class 1 /* the class number of `\..' */
5317 @d space_class 2 /* the class number of spaces and nonstandard characters */
5318 @d percent_class 3 /* the class number of `\.\%' */
5319 @d string_class 4 /* the class number of `\."' */
5320 @d right_paren_class 8 /* the class number of `\.)' */
5321 @d isolated_classes 5: case 6: case 7: case 8 /* characters that make length-one tokens only */
5322 @d letter_class 9 /* letters and the underline character */
5323 @d left_bracket_class 17 /* `\.[' */
5324 @d right_bracket_class 18 /* `\.]' */
5325 @d invalid_class 20 /* bad character in the input */
5326 @d max_class 20 /* the largest class number */
5327
5328 @<Glob...@>=
5329 int char_class[256]; /* the class numbers */
5330
5331 @ If changes are made to accommodate non-ASCII character sets, they should
5332 follow the guidelines in Appendix~C of {\sl The {\logos METAFONT\/}book}.
5333 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
5334 @^system dependencies@>
5335
5336 @<Set initial ...@>=
5337 for (k='0';k<='9';k++) 
5338   mp->char_class[k]=digit_class;
5339 mp->char_class['.']=period_class;
5340 mp->char_class[' ']=space_class;
5341 mp->char_class['%']=percent_class;
5342 mp->char_class['"']=string_class;
5343 mp->char_class[',']=5;
5344 mp->char_class[';']=6;
5345 mp->char_class['(']=7;
5346 mp->char_class[')']=right_paren_class;
5347 for (k='A';k<= 'Z';k++ )
5348   mp->char_class[k]=letter_class;
5349 for (k='a';k<='z';k++) 
5350   mp->char_class[k]=letter_class;
5351 mp->char_class['_']=letter_class;
5352 mp->char_class['<']=10;
5353 mp->char_class['=']=10;
5354 mp->char_class['>']=10;
5355 mp->char_class[':']=10;
5356 mp->char_class['|']=10;
5357 mp->char_class['`']=11;
5358 mp->char_class['\'']=11;
5359 mp->char_class['+']=12;
5360 mp->char_class['-']=12;
5361 mp->char_class['/']=13;
5362 mp->char_class['*']=13;
5363 mp->char_class['\\']=13;
5364 mp->char_class['!']=14;
5365 mp->char_class['?']=14;
5366 mp->char_class['#']=15;
5367 mp->char_class['&']=15;
5368 mp->char_class['@@']=15;
5369 mp->char_class['$']=15;
5370 mp->char_class['^']=16;
5371 mp->char_class['~']=16;
5372 mp->char_class['[']=left_bracket_class;
5373 mp->char_class[']']=right_bracket_class;
5374 mp->char_class['{']=19;
5375 mp->char_class['}']=19;
5376 for (k=0;k<' ';k++)
5377   mp->char_class[k]=invalid_class;
5378 mp->char_class['\t']=space_class;
5379 mp->char_class['\f']=space_class;
5380 for (k=127;k<=255;k++)
5381   mp->char_class[k]=invalid_class;
5382
5383 @* \[13] The hash table.
5384 Symbolic tokens are stored and retrieved by means of a fairly standard hash
5385 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5386 in {\sl The Art of Computer Programming\/}). Once a symbolic token enters the
5387 table, it is never removed.
5388
5389 The actual sequence of characters forming a symbolic token is
5390 stored in the |str_pool| array together with all the other strings. An
5391 auxiliary array |hash| consists of items with two halfword fields per
5392 word. The first of these, called |mp_next(p)|, points to the next identifier
5393 belonging to the same coalesced list as the identifier corresponding to~|p|;
5394 and the other, called |text(p)|, points to the |str_start| entry for
5395 |p|'s identifier. If position~|p| of the hash table is empty, we have
5396 |text(p)=0|; if position |p| is either empty or the end of a coalesced
5397 hash list, we have |mp_next(p)=0|.
5398
5399 An auxiliary pointer variable called |hash_used| is maintained in such a
5400 way that all locations |p>=hash_used| are nonempty. The global variable
5401 |st_count| tells how many symbolic tokens have been defined, if statistics
5402 are being kept.
5403
5404 The first 256 locations of |hash| are reserved for symbols of length one.
5405
5406 There's a parallel array called |eqtb| that contains the current equivalent
5407 values of each symbolic token. The entries of this array consist of
5408 two halfwords called |eq_type| (a command code) and |equiv| (a secondary
5409 piece of information that qualifies the |eq_type|).
5410
5411 @d eq_type(A)   mp->eqtb[(A)].lh /* the current ``meaning'' of a symbolic token */
5412 @d equiv(A)   mp->eqtb[(A)].rh /* parametric part of a token's meaning */
5413 @d hash_is_full   (mp->hash_used==hash_base) /* are all positions occupied? */
5414
5415 @(mpmp.h@>=
5416 #define mp_next(A)   mp->hash[(A)].lh /* link for coalesced lists */
5417 #define text(A)   mp->hash[(A)].rh /* string number for symbolic token name */
5418 #define hash_base 257 /* hashing actually starts here */
5419
5420 @ @<Glob...@>=
5421 pointer hash_used; /* allocation pointer for |hash| */
5422 integer st_count; /* total number of known identifiers */
5423
5424 @ Certain entries in the hash table are ``frozen'' and not redefinable,
5425 since they are used in error recovery.
5426
5427 @(mpmp.h@>=
5428 #define hash_top (integer)(hash_base+mp->hash_size) /* the first location of the frozen area */
5429 #define frozen_inaccessible hash_top /* |hash| location to protect the frozen area */
5430 #define frozen_repeat_loop (hash_top+1) /* |hash| location of a loop-repeat token */
5431 #define frozen_right_delimiter (hash_top+2) /* |hash| location of a permanent `\.)' */
5432 #define frozen_left_bracket (hash_top+3) /* |hash| location of a permanent `\.[' */
5433 #define frozen_slash (hash_top+4) /* |hash| location of a permanent `\./' */
5434 #define frozen_colon (hash_top+5) /* |hash| location of a permanent `\.:' */
5435 #define frozen_semicolon (hash_top+6) /* |hash| location of a permanent `\.;' */
5436 #define frozen_end_for (hash_top+7) /* |hash| location of a permanent \&{endfor} */
5437 #define frozen_end_def (hash_top+8) /* |hash| location of a permanent \&{enddef} */
5438 #define frozen_fi (hash_top+9) /* |hash| location of a permanent \&{fi} */
5439 #define frozen_end_group (hash_top+10) /* |hash| location of a permanent `\.{endgroup}' */
5440 #define frozen_etex (hash_top+11) /* |hash| location of a permanent \&{etex} */
5441 #define frozen_mpx_break (hash_top+12) /* |hash| location of a permanent \&{mpxbreak} */
5442 #define frozen_bad_vardef (hash_top+13) /* |hash| location of `\.{a bad variable}' */
5443 #define frozen_undefined (hash_top+14) /* |hash| location that never gets defined */
5444 #define hash_end (integer)(hash_top+14) /* the actual size of the |hash| and |eqtb| arrays */
5445
5446
5447 @ @<Glob...@>=
5448 two_halves *hash; /* the hash table */
5449 two_halves *eqtb; /* the equivalents */
5450
5451 @ @<Allocate or initialize ...@>=
5452 mp->hash = xmalloc((hash_end+1),sizeof(two_halves));
5453 mp->eqtb = xmalloc((hash_end+1),sizeof(two_halves));
5454
5455 @ @<Dealloc variables@>=
5456 xfree(mp->hash);
5457 xfree(mp->eqtb);
5458
5459 @ @<Set init...@>=
5460 mp_next(1)=0; text(1)=0; eq_type(1)=tag_token; equiv(1)=null;
5461 for (k=2;k<=hash_end;k++)  { 
5462   mp->hash[k]=mp->hash[1]; mp->eqtb[k]=mp->eqtb[1];
5463 }
5464
5465 @ @<Initialize table entries...@>=
5466 mp->hash_used=frozen_inaccessible; /* nothing is used */
5467 mp->st_count=0;
5468 text(frozen_bad_vardef)=intern("a bad variable");
5469 text(frozen_etex)=intern("etex");
5470 text(frozen_mpx_break)=intern("mpxbreak");
5471 text(frozen_fi)=intern("fi");
5472 text(frozen_end_group)=intern("endgroup");
5473 text(frozen_end_def)=intern("enddef");
5474 text(frozen_end_for)=intern("endfor");
5475 text(frozen_semicolon)=intern(";");
5476 text(frozen_colon)=intern(":");
5477 text(frozen_slash)=intern("/");
5478 text(frozen_left_bracket)=intern("[");
5479 text(frozen_right_delimiter)=intern(")");
5480 text(frozen_inaccessible)=intern(" INACCESSIBLE");
5481 eq_type(frozen_right_delimiter)=right_delimiter;
5482
5483 @ @<Check the ``constant'' values...@>=
5484 if ( hash_end+mp->max_internal>max_halfword ) mp->bad=17;
5485
5486 @ Here is the subroutine that searches the hash table for an identifier
5487 that matches a given string of length~|l| appearing in |buffer[j..
5488 (j+l-1)]|. If the identifier is not found, it is inserted; hence it
5489 will always be found, and the corresponding hash table address
5490 will be returned.
5491
5492 @c 
5493 static pointer mp_id_lookup (MP mp,integer j, integer l) { /* search the hash table */
5494   integer h; /* hash code */
5495   pointer p; /* index in |hash| array */
5496   pointer k; /* index in |buffer| array */
5497   if (l==1) {
5498     @<Treat special case of length 1 and |break|@>;
5499   }
5500   @<Compute the hash code |h|@>;
5501   p=h+hash_base; /* we start searching here; note that |0<=h<hash_prime| */
5502   while (true)  { 
5503         if (text(p)>0 && length(text(p))==l && mp_str_eq_buf(mp, text(p),j)) 
5504       break;
5505     if ( mp_next(p)==0 ) {
5506       @<Insert a new symbolic token after |p|, then
5507         make |p| point to it and |break|@>;
5508     }
5509     p=mp_next(p);
5510   }
5511   return p;
5512 }
5513
5514 @ @<Treat special case of length 1...@>=
5515  p=mp->buffer[j]+1; text(p)=p-1; return p;
5516
5517
5518 @ @<Insert a new symbolic...@>=
5519 {
5520 if ( text(p)>0 ) { 
5521   do {  
5522     if ( hash_is_full )
5523       mp_overflow(mp, "hash size",(integer)mp->hash_size);
5524 @:MetaPost capacity exceeded hash size}{\quad hash size@>
5525     decr(mp->hash_used);
5526   } while (text(mp->hash_used)!=0); /* search for an empty location in |hash| */
5527   mp_next(p)=mp->hash_used; 
5528   p=mp->hash_used;
5529 }
5530 str_room(l);
5531 for (k=j;k<=j+l-1;k++) {
5532   append_char(mp->buffer[k]);
5533 }
5534 text(p)=mp_make_string(mp); 
5535 mp->str_ref[text(p)]=max_str_ref;
5536 incr(mp->st_count);
5537 break;
5538 }
5539
5540
5541 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5542 should be a prime number.  The theory of hashing tells us to expect fewer
5543 than two table probes, on the average, when the search is successful.
5544 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5545 @^Vitter, Jeffrey Scott@>
5546
5547 @<Compute the hash code |h|@>=
5548 h=mp->buffer[j];
5549 for (k=j+1;k<=j+l-1;k++){ 
5550   h=h+h+mp->buffer[k];
5551   while ( h>=mp->hash_prime ) h=h-mp->hash_prime;
5552 }
5553
5554 @ @<Search |eqtb| for equivalents equal to |p|@>=
5555 for (q=1;q<=hash_end;q++) { 
5556   if ( equiv(q)==p ) { 
5557     mp_print_nl(mp, "EQUIV("); 
5558     mp_print_int(mp, q); 
5559     mp_print_char(mp, xord(')'));
5560   }
5561 }
5562
5563 @ We need to put \MP's ``primitive'' symbolic tokens into the hash
5564 table, together with their command code (which will be the |eq_type|)
5565 and an operand (which will be the |equiv|). The |primitive| procedure
5566 does this, in a way that no \MP\ user can. The global value |cur_sym|
5567 contains the new |eqtb| pointer after |primitive| has acted.
5568
5569 @c 
5570 static void mp_primitive (MP mp, const char *ss, halfword c, halfword o) {
5571   pool_pointer k; /* index into |str_pool| */
5572   quarterword j; /* index into |buffer| */
5573   quarterword l; /* length of the string */
5574   str_number s;
5575   s = intern(ss);
5576   k=mp->str_start[s]; l=str_stop(s)-k;
5577   /* we will move |s| into the (empty) |buffer| */
5578   for (j=0;j<=l-1;j++) {
5579     mp->buffer[j]=mp->str_pool[k+j];
5580   }
5581   mp->cur_sym=mp_id_lookup(mp, 0,l);
5582   if ( s>=256 ) { /* we don't want to have the string twice */
5583     mp_flush_string(mp, text(mp->cur_sym)); text(mp->cur_sym)=s;
5584   };
5585   eq_type(mp->cur_sym)=c; 
5586   equiv(mp->cur_sym)=o;
5587 }
5588
5589
5590 @ Many of \MP's primitives need no |equiv|, since they are identifiable
5591 by their |eq_type| alone. These primitives are loaded into the hash table
5592 as follows:
5593
5594 @<Put each of \MP's primitives into the hash table@>=
5595 mp_primitive(mp, "..",path_join,0);
5596 @:.._}{\.{..} primitive@>
5597 mp_primitive(mp, "[",left_bracket,0); mp->eqtb[frozen_left_bracket]=mp->eqtb[mp->cur_sym];
5598 @:[ }{\.{[} primitive@>
5599 mp_primitive(mp, "]",right_bracket,0);
5600 @:] }{\.{]} primitive@>
5601 mp_primitive(mp, "}",right_brace,0);
5602 @:]]}{\.{\char`\}} primitive@>
5603 mp_primitive(mp, "{",left_brace,0);
5604 @:][}{\.{\char`\{} primitive@>
5605 mp_primitive(mp, ":",colon,0); mp->eqtb[frozen_colon]=mp->eqtb[mp->cur_sym];
5606 @:: }{\.{:} primitive@>
5607 mp_primitive(mp, "::",double_colon,0);
5608 @::: }{\.{::} primitive@>
5609 mp_primitive(mp, "||:",bchar_label,0);
5610 @:::: }{\.{\char'174\char'174:} primitive@>
5611 mp_primitive(mp, ":=",assignment,0);
5612 @::=_}{\.{:=} primitive@>
5613 mp_primitive(mp, ",",comma,0);
5614 @:, }{\., primitive@>
5615 mp_primitive(mp, ";",semicolon,0); mp->eqtb[frozen_semicolon]=mp->eqtb[mp->cur_sym];
5616 @:; }{\.; primitive@>
5617 mp_primitive(mp, "\\",relax,0);
5618 @:]]\\}{\.{\char`\\} primitive@>
5619 @#
5620 mp_primitive(mp, "addto",add_to_command,0);
5621 @:add_to_}{\&{addto} primitive@>
5622 mp_primitive(mp, "atleast",at_least,0);
5623 @:at_least_}{\&{atleast} primitive@>
5624 mp_primitive(mp, "begingroup",begin_group,0); mp->bg_loc=mp->cur_sym;
5625 @:begin_group_}{\&{begingroup} primitive@>
5626 mp_primitive(mp, "controls",controls,0);
5627 @:controls_}{\&{controls} primitive@>
5628 mp_primitive(mp, "curl",curl_command,0);
5629 @:curl_}{\&{curl} primitive@>
5630 mp_primitive(mp, "delimiters",delimiters,0);
5631 @:delimiters_}{\&{delimiters} primitive@>
5632 mp_primitive(mp, "endgroup",end_group,0);
5633  mp->eqtb[frozen_end_group]=mp->eqtb[mp->cur_sym]; mp->eg_loc=mp->cur_sym;
5634 @:endgroup_}{\&{endgroup} primitive@>
5635 mp_primitive(mp, "everyjob",every_job_command,0);
5636 @:every_job_}{\&{everyjob} primitive@>
5637 mp_primitive(mp, "exitif",exit_test,0);
5638 @:exit_if_}{\&{exitif} primitive@>
5639 mp_primitive(mp, "expandafter",expand_after,0);
5640 @:expand_after_}{\&{expandafter} primitive@>
5641 mp_primitive(mp, "interim",interim_command,0);
5642 @:interim_}{\&{interim} primitive@>
5643 mp_primitive(mp, "let",let_command,0);
5644 @:let_}{\&{let} primitive@>
5645 mp_primitive(mp, "newinternal",new_internal,0);
5646 @:new_internal_}{\&{newinternal} primitive@>
5647 mp_primitive(mp, "of",of_token,0);
5648 @:of_}{\&{of} primitive@>
5649 mp_primitive(mp, "randomseed",mp_random_seed,0);
5650 @:mp_random_seed_}{\&{randomseed} primitive@>
5651 mp_primitive(mp, "save",save_command,0);
5652 @:save_}{\&{save} primitive@>
5653 mp_primitive(mp, "scantokens",scan_tokens,0);
5654 @:scan_tokens_}{\&{scantokens} primitive@>
5655 mp_primitive(mp, "shipout",ship_out_command,0);
5656 @:ship_out_}{\&{shipout} primitive@>
5657 mp_primitive(mp, "skipto",skip_to,0);
5658 @:skip_to_}{\&{skipto} primitive@>
5659 mp_primitive(mp, "special",special_command,0);
5660 @:special}{\&{special} primitive@>
5661 mp_primitive(mp, "fontmapfile",special_command,1);
5662 @:fontmapfile}{\&{fontmapfile} primitive@>
5663 mp_primitive(mp, "fontmapline",special_command,2);
5664 @:fontmapline}{\&{fontmapline} primitive@>
5665 mp_primitive(mp, "step",step_token,0);
5666 @:step_}{\&{step} primitive@>
5667 mp_primitive(mp, "str",str_op,0);
5668 @:str_}{\&{str} primitive@>
5669 mp_primitive(mp, "tension",tension,0);
5670 @:tension_}{\&{tension} primitive@>
5671 mp_primitive(mp, "to",to_token,0);
5672 @:to_}{\&{to} primitive@>
5673 mp_primitive(mp, "until",until_token,0);
5674 @:until_}{\&{until} primitive@>
5675 mp_primitive(mp, "within",within_token,0);
5676 @:within_}{\&{within} primitive@>
5677 mp_primitive(mp, "write",write_command,0);
5678 @:write_}{\&{write} primitive@>
5679
5680 @ Each primitive has a corresponding inverse, so that it is possible to
5681 display the cryptic numeric contents of |eqtb| in symbolic form.
5682 Every call of |primitive| in this program is therefore accompanied by some
5683 straightforward code that forms part of the |print_cmd_mod| routine
5684 explained below.
5685
5686 @<Cases of |print_cmd_mod| for symbolic printing of primitives@>=
5687 case add_to_command:mp_print(mp, "addto"); break;
5688 case assignment:mp_print(mp, ":="); break;
5689 case at_least:mp_print(mp, "atleast"); break;
5690 case bchar_label:mp_print(mp, "||:"); break;
5691 case begin_group:mp_print(mp, "begingroup"); break;
5692 case colon:mp_print(mp, ":"); break;
5693 case comma:mp_print(mp, ","); break;
5694 case controls:mp_print(mp, "controls"); break;
5695 case curl_command:mp_print(mp, "curl"); break;
5696 case delimiters:mp_print(mp, "delimiters"); break;
5697 case double_colon:mp_print(mp, "::"); break;
5698 case end_group:mp_print(mp, "endgroup"); break;
5699 case every_job_command:mp_print(mp, "everyjob"); break;
5700 case exit_test:mp_print(mp, "exitif"); break;
5701 case expand_after:mp_print(mp, "expandafter"); break;
5702 case interim_command:mp_print(mp, "interim"); break;
5703 case left_brace:mp_print(mp, "{"); break;
5704 case left_bracket:mp_print(mp, "["); break;
5705 case let_command:mp_print(mp, "let"); break;
5706 case new_internal:mp_print(mp, "newinternal"); break;
5707 case of_token:mp_print(mp, "of"); break;
5708 case path_join:mp_print(mp, ".."); break;
5709 case mp_random_seed:mp_print(mp, "randomseed"); break;
5710 case relax:mp_print_char(mp, xord('\\')); break;
5711 case right_brace:mp_print_char(mp, xord('}')); break;
5712 case right_bracket:mp_print_char(mp, xord(']')); break;
5713 case save_command:mp_print(mp, "save"); break;
5714 case scan_tokens:mp_print(mp, "scantokens"); break;
5715 case semicolon:mp_print_char(mp, xord(';')); break;
5716 case ship_out_command:mp_print(mp, "shipout"); break;
5717 case skip_to:mp_print(mp, "skipto"); break;
5718 case special_command: if ( m==2 ) mp_print(mp, "fontmapline"); else
5719                  if ( m==1 ) mp_print(mp, "fontmapfile"); else
5720                  mp_print(mp, "special"); break;
5721 case step_token:mp_print(mp, "step"); break;
5722 case str_op:mp_print(mp, "str"); break;
5723 case tension:mp_print(mp, "tension"); break;
5724 case to_token:mp_print(mp, "to"); break;
5725 case until_token:mp_print(mp, "until"); break;
5726 case within_token:mp_print(mp, "within"); break;
5727 case write_command:mp_print(mp, "write"); break;
5728
5729 @ We will deal with the other primitives later, at some point in the program
5730 where their |eq_type| and |equiv| values are more meaningful.  For example,
5731 the primitives for macro definitions will be loaded when we consider the
5732 routines that define macros.
5733 It is easy to find where each particular
5734 primitive was treated by looking in the index at the end; for example, the
5735 section where |"def"| entered |eqtb| is listed under `\&{def} primitive'.
5736
5737 @* \[14] Token lists.
5738 A \MP\ token is either symbolic or numeric or a string, or it denotes
5739 a macro parameter or capsule; so there are five corresponding ways to encode it
5740 @^token@>
5741 internally: (1)~A symbolic token whose hash code is~|p|
5742 is represented by the number |p|, in the |info| field of a single-word
5743 node in~|mem|. (2)~A numeric token whose |scaled| value is~|v| is
5744 represented in a two-word node of~|mem|; the |type| field is |known|,
5745 the |name_type| field is |token|, and the |value| field holds~|v|.
5746 The fact that this token appears in a two-word node rather than a
5747 one-word node is, of course, clear from the node address.
5748 (3)~A string token is also represented in a two-word node; the |type|
5749 field is |mp_string_type|, the |name_type| field is |token|, and the
5750 |value| field holds the corresponding |str_number|.  (4)~Capsules have
5751 |name_type=capsule|, and their |type| and |value| fields represent
5752 arbitrary values (in ways to be explained later).  (5)~Macro parameters
5753 are like symbolic tokens in that they appear in |info| fields of
5754 one-word nodes. The $k$th parameter is represented by |expr_base+k| if it
5755 is of type \&{expr}, or by |suffix_base+k| if it is of type \&{suffix}, or
5756 by |text_base+k| if it is of type \&{text}.  (Here |0<=k<param_size|.)
5757 Actual values of these parameters are kept in a separate stack, as we will
5758 see later.  The constants |expr_base|, |suffix_base|, and |text_base| are,
5759 of course, chosen so that there will be no confusion between symbolic
5760 tokens and parameters of various types.
5761
5762 Note that
5763 the `\\{type}' field of a node has nothing to do with ``type'' in a
5764 printer's sense. It's curious that the same word is used in such different ways.
5765
5766 @d mp_type(A)     mp->mem[(A)].hh.b0 /* identifies what kind of value this is */
5767 @d mp_name_type(A)   mp->mem[(A)].hh.b1 /* a clue to the name of this value */
5768 @d token_node_size 2 /* the number of words in a large token node */
5769 @d value_loc(A) ((A)+1) /* the word that contains the |value| field */
5770 @d value(A) mp->mem[value_loc((A))].cint /* the value stored in a large token node */
5771 @d expr_base (hash_end+1) /* code for the zeroth \&{expr} parameter */
5772 @d suffix_base (expr_base+mp->param_size) /* code for the zeroth \&{suffix} parameter */
5773 @d text_base (suffix_base+mp->param_size) /* code for the zeroth \&{text} parameter */
5774
5775 @<Check the ``constant''...@>=
5776 if ( text_base+mp->param_size>max_halfword ) mp->bad=18;
5777
5778 @ We have set aside a two word node beginning at |null| so that we can have
5779 |value(null)=0|.  We will make use of this coincidence later.
5780
5781 @<Initialize table entries...@>=
5782 mp_link(null)=null; value(null)=0;
5783
5784 @ A numeric token is created by the following trivial routine.
5785
5786 @c 
5787 static pointer mp_new_num_tok (MP mp,scaled v) {
5788   pointer p; /* the new node */
5789   p=mp_get_node(mp, token_node_size); value(p)=v;
5790   mp_type(p)=mp_known; mp_name_type(p)=mp_token; 
5791   return p;
5792 }
5793
5794 @ A token list is a singly linked list of nodes in |mem|, where
5795 each node contains a token and a link.  Here's a subroutine that gets rid
5796 of a token list when it is no longer needed.
5797
5798 @c static void mp_flush_token_list (MP mp,pointer p) {
5799   pointer q; /* the node being recycled */
5800   while ( p!=null ) { 
5801     q=p; p=mp_link(p);
5802     if ( q>=mp->hi_mem_min ) {
5803      free_avail(q);
5804     } else { 
5805       switch (mp_type(q)) {
5806       case mp_vacuous: case mp_boolean_type: case mp_known:
5807         break;
5808       case mp_string_type:
5809         delete_str_ref(value(q));
5810         break;
5811       case unknown_types: case mp_pen_type: case mp_path_type: 
5812       case mp_picture_type: case mp_pair_type: case mp_color_type:
5813       case mp_cmykcolor_type: case mp_transform_type: case mp_dependent:
5814       case mp_proto_dependent: case mp_independent:
5815         mp_recycle_value(mp,q);
5816         break;
5817       default: mp_confusion(mp, "token");
5818 @:this can't happen token}{\quad token@>
5819       }
5820       mp_free_node(mp, q,token_node_size);
5821     }
5822   }
5823 }
5824
5825 @ The procedure |show_token_list|, which prints a symbolic form of
5826 the token list that starts at a given node |p|, illustrates these
5827 conventions. The token list being displayed should not begin with a reference
5828 count. However, the procedure is intended to be fairly robust, so that if the
5829 memory links are awry or if |p| is not really a pointer to a token list,
5830 almost nothing catastrophic can happen.
5831
5832 An additional parameter |q| is also given; this parameter is either null
5833 or it points to a node in the token list where a certain magic computation
5834 takes place that will be explained later. (Basically, |q| is non-null when
5835 we are printing the two-line context information at the time of an error
5836 message; |q| marks the place corresponding to where the second line
5837 should begin.)
5838
5839 The generation will stop, and `\.{\char`\ ETC.}' will be printed, if the length
5840 of printing exceeds a given limit~|l|; the length of printing upon entry is
5841 assumed to be a given amount called |null_tally|. (Note that
5842 |show_token_list| sometimes uses itself recursively to print
5843 variable names within a capsule.)
5844 @^recursion@>
5845
5846 Unusual entries are printed in the form of all-caps tokens
5847 preceded by a space, e.g., `\.{\char`\ BAD}'.
5848
5849 @<Declarations@>=
5850 static void mp_show_token_list (MP mp, integer p, integer q, integer l,
5851                          integer null_tally) ;
5852
5853 @ @c
5854 void mp_show_token_list (MP mp, integer p, integer q, integer l,
5855                          integer null_tally) {
5856   quarterword class,c; /* the |char_class| of previous and new tokens */
5857   integer r,v; /* temporary registers */
5858   class=percent_class;
5859   mp->tally=null_tally;
5860   while ( (p!=null) && (mp->tally<l) ) { 
5861     if ( p==q ) 
5862       @<Do magic computation@>;
5863     @<Display token |p| and set |c| to its class;
5864       but |return| if there are problems@>;
5865     class=c; p=mp_link(p);
5866   }
5867   if ( p!=null ) 
5868      mp_print(mp, " ETC.");
5869 @.ETC@>
5870   return;
5871 }
5872
5873 @ @<Display token |p| and set |c| to its class...@>=
5874 c=letter_class; /* the default */
5875 if ( (p<0)||(p>mp->mem_end) ) { 
5876   mp_print(mp, " CLOBBERED"); return;
5877 @.CLOBBERED@>
5878 }
5879 if ( p<mp->hi_mem_min ) { 
5880   @<Display two-word token@>;
5881 } else { 
5882   r=mp_info(p);
5883   if ( r>=expr_base ) {
5884      @<Display a parameter token@>;
5885   } else {
5886     if ( r<1 ) {
5887       if ( r==0 ) { 
5888         @<Display a collective subscript@>
5889       } else {
5890         mp_print(mp, " IMPOSSIBLE");
5891 @.IMPOSSIBLE@>
5892       }
5893     } else { 
5894       r=text(r);
5895       if ( (r<0)||(r>mp->max_str_ptr) ) {
5896         mp_print(mp, " NONEXISTENT");
5897 @.NONEXISTENT@>
5898       } else {
5899        @<Print string |r| as a symbolic token
5900         and set |c| to its class@>;
5901       }
5902     }
5903   }
5904 }
5905
5906 @ @<Display two-word token@>=
5907 if ( mp_name_type(p)==mp_token ) {
5908   if ( mp_type(p)==mp_known ) {
5909     @<Display a numeric token@>;
5910   } else if ( mp_type(p)!=mp_string_type ) {
5911     mp_print(mp, " BAD");
5912 @.BAD@>
5913   } else { 
5914     mp_print_char(mp, xord('"')); mp_print_str(mp, value(p)); mp_print_char(mp, xord('"'));
5915     c=string_class;
5916   }
5917 } else if ((mp_name_type(p)!=mp_capsule)||(mp_type(p)<mp_vacuous)||(mp_type(p)>mp_independent) ) {
5918   mp_print(mp, " BAD");
5919 } else { 
5920   mp_print_capsule(mp,p); c=right_paren_class;
5921 }
5922
5923 @ @<Display a numeric token@>=
5924 if ( class==digit_class ) 
5925   mp_print_char(mp, xord(' '));
5926 v=value(p);
5927 if ( v<0 ){ 
5928   if ( class==left_bracket_class ) 
5929     mp_print_char(mp, xord(' '));
5930   mp_print_char(mp, xord('[')); mp_print_scaled(mp, v); mp_print_char(mp, xord(']'));
5931   c=right_bracket_class;
5932 } else { 
5933   mp_print_scaled(mp, v); c=digit_class;
5934 }
5935
5936
5937 @ Strictly speaking, a genuine token will never have |mp_info(p)=0|.
5938 But we will see later (in the |print_variable_name| routine) that
5939 it is convenient to let |mp_info(p)=0| stand for `\.{[]}'.
5940
5941 @<Display a collective subscript@>=
5942 {
5943 if ( class==left_bracket_class ) 
5944   mp_print_char(mp, xord(' '));
5945 mp_print(mp, "[]"); c=right_bracket_class;
5946 }
5947
5948 @ @<Display a parameter token@>=
5949 {
5950 if ( r<suffix_base ) { 
5951   mp_print(mp, "(EXPR"); r=r-(expr_base);
5952 @.EXPR@>
5953 } else if ( r<text_base ) { 
5954   mp_print(mp, "(SUFFIX"); r=r-(suffix_base);
5955 @.SUFFIX@>
5956 } else { 
5957   mp_print(mp, "(TEXT"); r=r-(text_base);
5958 @.TEXT@>
5959 }
5960 mp_print_int(mp, r); mp_print_char(mp, xord(')')); c=right_paren_class;
5961 }
5962
5963
5964 @ @<Print string |r| as a symbolic token...@>=
5965
5966 c=mp->char_class[mp->str_pool[mp->str_start[r]]];
5967 if ( c==class ) {
5968   switch (c) {
5969   case letter_class:mp_print_char(mp, xord('.')); break;
5970   case isolated_classes: break;
5971   default: mp_print_char(mp, xord(' ')); break;
5972   }
5973 }
5974 mp_print_str(mp, r);
5975 }
5976
5977 @ @<Declarations@>=
5978 static void mp_print_capsule (MP mp, pointer p);
5979
5980 @ @<Declare miscellaneous procedures that were declared |forward|@>=
5981 void mp_print_capsule (MP mp, pointer p) { 
5982   mp_print_char(mp, xord('(')); mp_print_exp(mp,p,0); mp_print_char(mp, xord(')'));
5983 }
5984
5985 @ Macro definitions are kept in \MP's memory in the form of token lists
5986 that have a few extra one-word nodes at the beginning.
5987
5988 The first node contains a reference count that is used to tell when the
5989 list is no longer needed. To emphasize the fact that a reference count is
5990 present, we shall refer to the |info| field of this special node as the
5991 |ref_count| field.
5992 @^reference counts@>
5993
5994 The next node or nodes after the reference count serve to describe the
5995 formal parameters. They consist of zero or more parameter tokens followed
5996 by a code for the type of macro.
5997
5998 @d ref_count mp_info
5999   /* reference count preceding a macro definition or picture header */
6000 @d add_mac_ref(A) incr(ref_count((A))) /* make a new reference to a macro list */
6001 @d general_macro 0 /* preface to a macro defined with a parameter list */
6002 @d primary_macro 1 /* preface to a macro with a \&{primary} parameter */
6003 @d secondary_macro 2 /* preface to a macro with a \&{secondary} parameter */
6004 @d tertiary_macro 3 /* preface to a macro with a \&{tertiary} parameter */
6005 @d expr_macro 4 /* preface to a macro with an undelimited \&{expr} parameter */
6006 @d of_macro 5 /* preface to a macro with
6007   undelimited `\&{expr} |x| \&{of}~|y|' parameters */
6008 @d suffix_macro 6 /* preface to a macro with an undelimited \&{suffix} parameter */
6009 @d text_macro 7 /* preface to a macro with an undelimited \&{text} parameter */
6010
6011 @c 
6012 static void mp_delete_mac_ref (MP mp,pointer p) {
6013   /* |p| points to the reference count of a macro list that is
6014     losing one reference */
6015   if ( ref_count(p)==null ) mp_flush_token_list(mp, p);
6016   else decr(ref_count(p));
6017 }
6018
6019 @ The following subroutine displays a macro, given a pointer to its
6020 reference count.
6021
6022 @c 
6023 static void mp_show_macro (MP mp, pointer p, integer q, integer l) {
6024   pointer r; /* temporary storage */
6025   p=mp_link(p); /* bypass the reference count */
6026   while ( mp_info(p)>text_macro ){ 
6027     r=mp_link(p); mp_link(p)=null;
6028     mp_show_token_list(mp, p,null,l,0); mp_link(p)=r; p=r;
6029     if ( l>0 ) l=l-mp->tally; else return;
6030   } /* control printing of `\.{ETC.}' */
6031 @.ETC@>
6032   mp->tally=0;
6033   switch(mp_info(p)) {
6034   case general_macro:mp_print(mp, "->"); break;
6035 @.->@>
6036   case primary_macro: case secondary_macro: case tertiary_macro:
6037     mp_print_char(mp, xord('<'));
6038     mp_print_cmd_mod(mp, param_type,mp_info(p)); 
6039     mp_print(mp, ">->");
6040     break;
6041   case expr_macro:mp_print(mp, "<expr>->"); break;
6042   case of_macro:mp_print(mp, "<expr>of<primary>->"); break;
6043   case suffix_macro:mp_print(mp, "<suffix>->"); break;
6044   case text_macro:mp_print(mp, "<text>->"); break;
6045   } /* there are no other cases */
6046   mp_show_token_list(mp, mp_link(p),q,l-mp->tally,0);
6047 }
6048
6049 @* \[15] Data structures for variables.
6050 The variables of \MP\ programs can be simple, like `\.x', or they can
6051 combine the structural properties of arrays and records, like `\.{x20a.b}'.
6052 A \MP\ user assigns a type to a variable like \.{x20a.b} by saying, for
6053 example, `\.{boolean} \.{x[]a.b}'. It's time for us to study how such
6054 things are represented inside of the computer.
6055
6056 Each variable value occupies two consecutive words, either in a two-word
6057 node called a value node, or as a two-word subfield of a larger node.  One
6058 of those two words is called the |value| field; it is an integer,
6059 containing either a |scaled| numeric value or the representation of some
6060 other type of quantity. (It might also be subdivided into halfwords, in
6061 which case it is referred to by other names instead of |value|.) The other
6062 word is broken into subfields called |type|, |name_type|, and |link|.  The
6063 |type| field is a quarterword that specifies the variable's type, and
6064 |name_type| is a quarterword from which \MP\ can reconstruct the
6065 variable's name (sometimes by using the |link| field as well).  Thus, only
6066 1.25 words are actually devoted to the value itself; the other
6067 three-quarters of a word are overhead, but they aren't wasted because they
6068 allow \MP\ to deal with sparse arrays and to provide meaningful diagnostics.
6069
6070 In this section we shall be concerned only with the structural aspects of
6071 variables, not their values. Later parts of the program will change the
6072 |type| and |value| fields, but we shall treat those fields as black boxes
6073 whose contents should not be touched.
6074
6075 However, if the |type| field is |mp_structured|, there is no |value| field,
6076 and the second word is broken into two pointer fields called |attr_head|
6077 and |subscr_head|. Those fields point to additional nodes that
6078 contain structural information, as we shall see.
6079
6080 @d subscr_head_loc(A)   (A)+1 /* where |value|, |subscr_head| and |attr_head| are */
6081 @d attr_head(A)   mp_info(subscr_head_loc((A))) /* pointer to attribute info */
6082 @d subscr_head(A)   mp_link(subscr_head_loc((A))) /* pointer to subscript info */
6083 @d value_node_size 2 /* the number of words in a value node */
6084
6085 @ An attribute node is three words long. Two of these words contain |type|
6086 and |value| fields as described above, and the third word contains
6087 additional information:  There is an |attr_loc| field, which contains the
6088 hash address of the token that names this attribute; and there's also a
6089 |parent| field, which points to the value node of |mp_structured| type at the
6090 next higher level (i.e., at the level to which this attribute is
6091 subsidiary).  The |name_type| in an attribute node is `|attr|'.  The
6092 |link| field points to the next attribute with the same parent; these are
6093 arranged in increasing order, so that |attr_loc(mp_link(p))>attr_loc(p)|. The
6094 final attribute node links to the constant |end_attr|, whose |attr_loc|
6095 field is greater than any legal hash address. The |attr_head| in the
6096 parent points to a node whose |name_type| is |mp_structured_root|; this
6097 node represents the null attribute, i.e., the variable that is relevant
6098 when no attributes are attached to the parent. The |attr_head| node
6099 has the fields of either
6100 a value node, a subscript node, or an attribute node, depending on what
6101 the parent would be if it were not structured; but the subscript and
6102 attribute fields are ignored, so it effectively contains only the data of
6103 a value node. The |link| field in this special node points to an attribute
6104 node whose |attr_loc| field is zero; the latter node represents a collective
6105 subscript `\.{[]}' attached to the parent, and its |link| field points to
6106 the first non-special attribute node (or to |end_attr| if there are none).
6107
6108 A subscript node likewise occupies three words, with |type| and |value| fields
6109 plus extra information; its |name_type| is |subscr|. In this case the
6110 third word is called the |subscript| field, which is a |scaled| integer.
6111 The |link| field points to the subscript node with the next larger
6112 subscript, if any; otherwise the |link| points to the attribute node
6113 for collective subscripts at this level. We have seen that the latter node
6114 contains an upward pointer, so that the parent can be deduced.
6115
6116 The |name_type| in a parent-less value node is |root|, and the |link|
6117 is the hash address of the token that names this value.
6118
6119 In other words, variables have a hierarchical structure that includes
6120 enough threads running around so that the program is able to move easily
6121 between siblings, parents, and children. An example should be helpful:
6122 (The reader is advised to draw a picture while reading the following
6123 description, since that will help to firm up the ideas.)
6124 Suppose that `\.x' and `\.{x.a}' and `\.{x[]b}' and `\.{x5}'
6125 and `\.{x20b}' have been mentioned in a user's program, where
6126 \.{x[]b} has been declared to be of \&{boolean} type. Let |h(x)|, |h(a)|,
6127 and |h(b)| be the hash addresses of \.x, \.a, and~\.b. Then
6128 |eq_type(h(x))=name| and |equiv(h(x))=p|, where |p|~is a two-word value
6129 node with |mp_name_type(p)=root| and |mp_link(p)=h(x)|. We have |type(p)=mp_structured|,
6130 |attr_head(p)=q|, and |subscr_head(p)=r|, where |q| points to a value
6131 node and |r| to a subscript node. (Are you still following this? Use
6132 a pencil to draw a diagram.) The lone variable `\.x' is represented by
6133 |type(q)| and |value(q)|; furthermore
6134 |mp_name_type(q)=mp_structured_root| and |mp_link(q)=q1|, where |q1| points
6135 to an attribute node representing `\.{x[]}'. Thus |mp_name_type(q1)=attr|,
6136 |attr_loc(q1)=collective_subscript=0|, |parent(q1)=p|,
6137 |type(q1)=mp_structured|, |attr_head(q1)=qq|, and |subscr_head(q1)=qq1|;
6138 |qq| is a  three-word ``attribute-as-value'' node with |type(qq)=numeric_type|
6139 (assuming that \.{x5} is numeric, because |qq| represents `\.{x[]}' 
6140 with no further attributes), |mp_name_type(qq)=structured_root|, 
6141 |attr_loc(qq)=0|, |parent(qq)=p|, and
6142 |mp_link(qq)=qq1|. (Now pay attention to the next part.) Node |qq1| is
6143 an attribute node representing `\.{x[][]}', which has never yet
6144 occurred; its |type| field is |undefined|, and its |value| field is
6145 undefined. We have |mp_name_type(qq1)=attr|, |attr_loc(qq1)=collective_subscript|,
6146 |parent(qq1)=q1|, and |mp_link(qq1)=qq2|. Since |qq2| represents
6147 `\.{x[]b}', |type(qq2)=mp_unknown_boolean|; also |attr_loc(qq2)=h(b)|,
6148 |parent(qq2)=q1|, |mp_name_type(qq2)=attr|, |mp_link(qq2)=end_attr|.
6149 (Maybe colored lines will help untangle your picture.)
6150  Node |r| is a subscript node with |type| and |value|
6151 representing `\.{x5}'; |mp_name_type(r)=subscr|, |subscript(r)=5.0|,
6152 and |mp_link(r)=r1| is another subscript node. To complete the picture,
6153 see if you can guess what |mp_link(r1)| is; give up? It's~|q1|.
6154 Furthermore |subscript(r1)=20.0|, |mp_name_type(r1)=subscr|,
6155 |type(r1)=mp_structured|, |attr_head(r1)=qqq|, |subscr_head(r1)=qqq1|,
6156 and we finish things off with three more nodes
6157 |qqq|, |qqq1|, and |qqq2| hung onto~|r1|. (Perhaps you should start again
6158 with a larger sheet of paper.) The value of variable \.{x20b}
6159 appears in node~|qqq2|, as you can well imagine.
6160
6161 If the example in the previous paragraph doesn't make things crystal
6162 clear, a glance at some of the simpler subroutines below will reveal how
6163 things work out in practice.
6164
6165 The only really unusual thing about these conventions is the use of
6166 collective subscript attributes. The idea is to avoid repeating a lot of
6167 type information when many elements of an array are identical macros
6168 (for which distinct values need not be stored) or when they don't have
6169 all of the possible attributes. Branches of the structure below collective
6170 subscript attributes do not carry actual values except for macro identifiers;
6171 branches of the structure below subscript nodes do not carry significant
6172 information in their collective subscript attributes.
6173
6174 @d attr_loc_loc(A) ((A)+2) /* where the |attr_loc| and |parent| fields are */
6175 @d attr_loc(A) mp_info(attr_loc_loc((A))) /* hash address of this attribute */
6176 @d parent(A) mp_link(attr_loc_loc((A))) /* pointer to |mp_structured| variable */
6177 @d subscript_loc(A) ((A)+2) /* where the |subscript| field lives */
6178 @d subscript(A) mp->mem[subscript_loc((A))].sc /* subscript of this variable */
6179 @d attr_node_size 3 /* the number of words in an attribute node */
6180 @d subscr_node_size 3 /* the number of words in a subscript node */
6181 @d collective_subscript 0 /* code for the attribute `\.{[]}' */
6182
6183 @<Initialize table...@>=
6184 attr_loc(end_attr)=hash_end+1; parent(end_attr)=null;
6185
6186 @ Variables of type \&{pair} will have values that point to four-word
6187 nodes containing two numeric values. The first of these values has
6188 |name_type=mp_x_part_sector| and the second has |name_type=mp_y_part_sector|;
6189 the |link| in the first points back to the node whose |value| points
6190 to this four-word node.
6191
6192 Variables of type \&{transform} are similar, but in this case their
6193 |value| points to a 12-word node containing six values, identified by
6194 |x_part_sector|, |y_part_sector|, |mp_xx_part_sector|, |mp_xy_part_sector|,
6195 |mp_yx_part_sector|, and |mp_yy_part_sector|.
6196 Finally, variables of type \&{color} have 3~values in 6~words
6197 identified by |mp_red_part_sector|, |mp_green_part_sector|, and |mp_blue_part_sector|.
6198
6199 When an entire structured variable is saved, the |root| indication
6200 is temporarily replaced by |saved_root|.
6201
6202 Some variables have no name; they just are used for temporary storage
6203 while expressions are being evaluated. We call them {\sl capsules}.
6204
6205 @d x_part_loc(A) (A) /* where the \&{xpart} is found in a pair or transform node */
6206 @d y_part_loc(A) ((A)+2) /* where the \&{ypart} is found in a pair or transform node */
6207 @d xx_part_loc(A) ((A)+4) /* where the \&{xxpart} is found in a transform node */
6208 @d xy_part_loc(A) ((A)+6) /* where the \&{xypart} is found in a transform node */
6209 @d yx_part_loc(A) ((A)+8) /* where the \&{yxpart} is found in a transform node */
6210 @d yy_part_loc(A) ((A)+10) /* where the \&{yypart} is found in a transform node */
6211 @d red_part_loc(A) (A) /* where the \&{redpart} is found in a color node */
6212 @d green_part_loc(A) ((A)+2) /* where the \&{greenpart} is found in a color node */
6213 @d blue_part_loc(A) ((A)+4) /* where the \&{bluepart} is found in a color node */
6214 @d cyan_part_loc(A) (A) /* where the \&{cyanpart} is found in a color node */
6215 @d magenta_part_loc(A) ((A)+2) /* where the \&{magentapart} is found in a color node */
6216 @d yellow_part_loc(A) ((A)+4) /* where the \&{yellowpart} is found in a color node */
6217 @d black_part_loc(A) ((A)+6) /* where the \&{blackpart} is found in a color node */
6218 @d grey_part_loc(A) (A) /* where the \&{greypart} is found in a color node */
6219 @#
6220 @d pair_node_size 4 /* the number of words in a pair node */
6221 @d transform_node_size 12 /* the number of words in a transform node */
6222 @d color_node_size 6 /* the number of words in a color node */
6223 @d cmykcolor_node_size 8 /* the number of words in a color node */
6224
6225 @<Glob...@>=
6226 quarterword big_node_size[mp_pair_type+1];
6227 quarterword sector0[mp_pair_type+1];
6228 quarterword sector_offset[mp_black_part_sector+1];
6229
6230 @ The |sector0| array gives for each big node type, |name_type| values
6231 for its first subfield; the |sector_offset| array gives for each
6232 |name_type| value, the offset from the first subfield in words;
6233 and the |big_node_size| array gives the size in words for each type of
6234 big node.
6235
6236 @<Set init...@>=
6237 mp->big_node_size[mp_transform_type]=transform_node_size;
6238 mp->big_node_size[mp_pair_type]=pair_node_size;
6239 mp->big_node_size[mp_color_type]=color_node_size;
6240 mp->big_node_size[mp_cmykcolor_type]=cmykcolor_node_size;
6241 mp->sector0[mp_transform_type]=mp_x_part_sector;
6242 mp->sector0[mp_pair_type]=mp_x_part_sector;
6243 mp->sector0[mp_color_type]=mp_red_part_sector;
6244 mp->sector0[mp_cmykcolor_type]=mp_cyan_part_sector;
6245 for (k=mp_x_part_sector;k<= mp_yy_part_sector;k++ ) {
6246   mp->sector_offset[k]=2*(k-mp_x_part_sector);
6247 }
6248 for (k=mp_red_part_sector;k<= mp_blue_part_sector ; k++) {
6249   mp->sector_offset[k]=2*(k-mp_red_part_sector);
6250 }
6251 for (k=mp_cyan_part_sector;k<= mp_black_part_sector;k++ ) {
6252   mp->sector_offset[k]=2*(k-mp_cyan_part_sector);
6253 }
6254
6255 @ If |type(p)=mp_pair_type| or |mp_transform_type| and if |value(p)=null|, the
6256 procedure call |init_big_node(p)| will allocate a pair or transform node
6257 for~|p|.  The individual parts of such nodes are initially of type
6258 |mp_independent|.
6259
6260 @c 
6261 static void mp_init_big_node (MP mp,pointer p) {
6262   pointer q; /* the new node */
6263   quarterword s; /* its size */
6264   s=mp->big_node_size[mp_type(p)]; q=mp_get_node(mp, s);
6265   do {  
6266     s=s-2; 
6267     @<Make variable |q+s| newly independent@>;
6268     mp_name_type(q+s)=halfp(s)+mp->sector0[mp_type(p)]; 
6269     mp_link(q+s)=null;
6270   } while (s!=0);
6271   mp_link(q)=p; value(p)=q;
6272 }
6273
6274 @ The |id_transform| function creates a capsule for the
6275 identity transformation.
6276
6277 @c 
6278 static pointer mp_id_transform (MP mp) {
6279   pointer p,q,r; /* list manipulation registers */
6280   p=mp_get_node(mp, value_node_size); mp_type(p)=mp_transform_type;
6281   mp_name_type(p)=mp_capsule; value(p)=null; mp_init_big_node(mp, p); q=value(p);
6282   r=q+transform_node_size;
6283   do {  
6284     r=r-2;
6285     mp_type(r)=mp_known; value(r)=0;
6286   } while (r!=q);
6287   value(xx_part_loc(q))=unity; 
6288   value(yy_part_loc(q))=unity;
6289   return p;
6290 }
6291
6292 @ Tokens are of type |tag_token| when they first appear, but they point
6293 to |null| until they are first used as the root of a variable.
6294 The following subroutine establishes the root node on such grand occasions.
6295
6296 @c 
6297 static void mp_new_root (MP mp,pointer x) {
6298   pointer p; /* the new node */
6299   p=mp_get_node(mp, value_node_size); mp_type(p)=undefined; mp_name_type(p)=mp_root;
6300   mp_link(p)=x; equiv(x)=p;
6301 }
6302
6303 @ These conventions for variable representation are illustrated by the
6304 |print_variable_name| routine, which displays the full name of a
6305 variable given only a pointer to its two-word value packet.
6306
6307 @<Declarations@>=
6308 static void mp_print_variable_name (MP mp, pointer p);
6309
6310 @ @c 
6311 void mp_print_variable_name (MP mp, pointer p) {
6312   pointer q; /* a token list that will name the variable's suffix */
6313   pointer r; /* temporary for token list creation */
6314   while ( mp_name_type(p)>=mp_x_part_sector ) {
6315     @<Preface the output with a part specifier; |return| in the
6316       case of a capsule@>;
6317   }
6318   q=null;
6319   while ( mp_name_type(p)>mp_saved_root ) {
6320     @<Ascend one level, pushing a token onto list |q|
6321      and replacing |p| by its parent@>;
6322   }
6323   r=mp_get_avail(mp); mp_info(r)=mp_link(p); mp_link(r)=q;
6324   if ( mp_name_type(p)==mp_saved_root ) mp_print(mp, "(SAVED)");
6325 @.SAVED@>
6326   mp_show_token_list(mp, r,null,el_gordo,mp->tally); 
6327   mp_flush_token_list(mp, r);
6328 }
6329
6330 @ @<Ascend one level, pushing a token onto list |q|...@>=
6331
6332   if ( mp_name_type(p)==mp_subscr ) { 
6333     r=mp_new_num_tok(mp, subscript(p));
6334     do {  
6335       p=mp_link(p);
6336     } while (mp_name_type(p)!=mp_attr);
6337   } else if ( mp_name_type(p)==mp_structured_root ) {
6338     p=mp_link(p); goto FOUND;
6339   } else { 
6340     if ( mp_name_type(p)!=mp_attr ) mp_confusion(mp, "var");
6341 @:this can't happen var}{\quad var@>
6342     r=mp_get_avail(mp); mp_info(r)=attr_loc(p);
6343   }
6344   mp_link(r)=q; q=r;
6345 FOUND:  
6346   p=parent(p);
6347 }
6348
6349 @ @<Preface the output with a part specifier...@>=
6350 { switch (mp_name_type(p)) {
6351   case mp_x_part_sector: mp_print_char(mp, xord('x')); break;
6352   case mp_y_part_sector: mp_print_char(mp, xord('y')); break;
6353   case mp_xx_part_sector: mp_print(mp, "xx"); break;
6354   case mp_xy_part_sector: mp_print(mp, "xy"); break;
6355   case mp_yx_part_sector: mp_print(mp, "yx"); break;
6356   case mp_yy_part_sector: mp_print(mp, "yy"); break;
6357   case mp_red_part_sector: mp_print(mp, "red"); break;
6358   case mp_green_part_sector: mp_print(mp, "green"); break;
6359   case mp_blue_part_sector: mp_print(mp, "blue"); break;
6360   case mp_cyan_part_sector: mp_print(mp, "cyan"); break;
6361   case mp_magenta_part_sector: mp_print(mp, "magenta"); break;
6362   case mp_yellow_part_sector: mp_print(mp, "yellow"); break;
6363   case mp_black_part_sector: mp_print(mp, "black"); break;
6364   case mp_grey_part_sector: mp_print(mp, "grey"); break;
6365   case mp_capsule: 
6366     mp_print(mp, "%CAPSULE"); mp_print_int(mp, p-null); return;
6367     break;
6368 @.CAPSULE@>
6369   } /* there are no other cases */
6370   mp_print(mp, "part "); 
6371   p=mp_link(p-mp->sector_offset[mp_name_type(p)]);
6372 }
6373
6374 @ The |interesting| function returns |true| if a given variable is not
6375 in a capsule, or if the user wants to trace capsules.
6376
6377 @c 
6378 static boolean mp_interesting (MP mp,pointer p) {
6379   quarterword t; /* a |name_type| */
6380   if ( mp->internal[mp_tracing_capsules]>0 ) {
6381     return true;
6382   } else { 
6383     t=mp_name_type(p);
6384     if ( t>=mp_x_part_sector ) if ( t!=mp_capsule )
6385       t=mp_name_type(mp_link(p-mp->sector_offset[t]));
6386     return (t!=mp_capsule);
6387   }
6388 }
6389
6390 @ Now here is a subroutine that converts an unstructured type into an
6391 equivalent structured type, by inserting a |mp_structured| node that is
6392 capable of growing. This operation is done only when |mp_name_type(p)=root|,
6393 |subscr|, or |attr|.
6394
6395 The procedure returns a pointer to the new node that has taken node~|p|'s
6396 place in the structure. Node~|p| itself does not move, nor are its
6397 |value| or |type| fields changed in any way.
6398
6399 @c 
6400 static pointer mp_new_structure (MP mp,pointer p) {
6401   pointer q,r=0; /* list manipulation registers */
6402   switch (mp_name_type(p)) {
6403   case mp_root: 
6404     q=mp_link(p); r=mp_get_node(mp, value_node_size); equiv(q)=r;
6405     break;
6406   case mp_subscr: 
6407     @<Link a new subscript node |r| in place of node |p|@>;
6408     break;
6409   case mp_attr: 
6410     @<Link a new attribute node |r| in place of node |p|@>;
6411     break;
6412   default: 
6413     mp_confusion(mp, "struct");
6414 @:this can't happen struct}{\quad struct@>
6415     break;
6416   }
6417   mp_link(r)=mp_link(p); mp_type(r)=mp_structured; mp_name_type(r)=mp_name_type(p);
6418   attr_head(r)=p; mp_name_type(p)=mp_structured_root;
6419   q=mp_get_node(mp, attr_node_size); mp_link(p)=q; subscr_head(r)=q;
6420   parent(q)=r; mp_type(q)=undefined; mp_name_type(q)=mp_attr; mp_link(q)=end_attr;
6421   attr_loc(q)=collective_subscript; 
6422   return r;
6423 }
6424
6425 @ @<Link a new subscript node |r| in place of node |p|@>=
6426
6427   q=p;
6428   do {  
6429     q=mp_link(q);
6430   } while (mp_name_type(q)!=mp_attr);
6431   q=parent(q); r=subscr_head_loc(q); /* |mp_link(r)=subscr_head(q)| */
6432   do {  
6433     q=r; r=mp_link(r);
6434   } while (r!=p);
6435   r=mp_get_node(mp, subscr_node_size);
6436   mp_link(q)=r; subscript(r)=subscript(p);
6437 }
6438
6439 @ If the attribute is |collective_subscript|, there are two pointers to
6440 node~|p|, so we must change both of them.
6441
6442 @<Link a new attribute node |r| in place of node |p|@>=
6443
6444   q=parent(p); r=attr_head(q);
6445   do {  
6446     q=r; r=mp_link(r);
6447   } while (r!=p);
6448   r=mp_get_node(mp, attr_node_size); mp_link(q)=r;
6449   mp->mem[attr_loc_loc(r)]=mp->mem[attr_loc_loc(p)]; /* copy |attr_loc| and |parent| */
6450   if ( attr_loc(p)==collective_subscript ) { 
6451     q=subscr_head_loc(parent(p));
6452     while ( mp_link(q)!=p ) q=mp_link(q);
6453     mp_link(q)=r;
6454   }
6455 }
6456
6457 @ The |find_variable| routine is given a pointer~|t| to a nonempty token
6458 list of suffixes; it returns a pointer to the corresponding two-word
6459 value. For example, if |t| points to token \.x followed by a numeric
6460 token containing the value~7, |find_variable| finds where the value of
6461 \.{x7} is stored in memory. This may seem a simple task, and it
6462 usually is, except when \.{x7} has never been referenced before.
6463 Indeed, \.x may never have even been subscripted before; complexities
6464 arise with respect to updating the collective subscript information.
6465
6466 If a macro type is detected anywhere along path~|t|, or if the first
6467 item on |t| isn't a |tag_token|, the value |null| is returned.
6468 Otherwise |p| will be a non-null pointer to a node such that
6469 |undefined<type(p)<mp_structured|.
6470
6471 @d abort_find { return null; }
6472
6473 @c 
6474 static pointer mp_find_variable (MP mp,pointer t) {
6475   pointer p,q,r,s; /* nodes in the ``value'' line */
6476   pointer pp,qq,rr,ss; /* nodes in the ``collective'' line */
6477   integer n; /* subscript or attribute */
6478   memory_word save_word; /* temporary storage for a word of |mem| */
6479 @^inner loop@>
6480   p=mp_info(t); t=mp_link(t);
6481   if ( (eq_type(p) % outer_tag) != tag_token ) abort_find;
6482   if ( equiv(p)==null ) mp_new_root(mp, p);
6483   p=equiv(p); pp=p;
6484   while ( t!=null ) { 
6485     @<Make sure that both nodes |p| and |pp| are of |mp_structured| type@>;
6486     if ( t<mp->hi_mem_min ) {
6487       @<Descend one level for the subscript |value(t)|@>
6488     } else {
6489       @<Descend one level for the attribute |mp_info(t)|@>;
6490     }
6491     t=mp_link(t);
6492   }
6493   if ( mp_type(pp)>=mp_structured ) {
6494     if ( mp_type(pp)==mp_structured ) pp=attr_head(pp); else abort_find;
6495   }
6496   if ( mp_type(p)==mp_structured ) p=attr_head(p);
6497   if ( mp_type(p)==undefined ) { 
6498     if ( mp_type(pp)==undefined ) { mp_type(pp)=mp_numeric_type; value(pp)=null; };
6499     mp_type(p)=mp_type(pp); value(p)=null;
6500   };
6501   return p;
6502 }
6503
6504 @ Although |pp| and |p| begin together, they diverge when a subscript occurs;
6505 |pp|~stays in the collective line while |p|~goes through actual subscript
6506 values.
6507
6508 @<Make sure that both nodes |p| and |pp|...@>=
6509 if ( mp_type(pp)!=mp_structured ) { 
6510   if ( mp_type(pp)>mp_structured ) abort_find;
6511   ss=mp_new_structure(mp, pp);
6512   if ( p==pp ) p=ss;
6513   pp=ss;
6514 }; /* now |type(pp)=mp_structured| */
6515 if ( mp_type(p)!=mp_structured ) /* it cannot be |>mp_structured| */
6516   p=mp_new_structure(mp, p) /* now |type(p)=mp_structured| */
6517
6518 @ We want this part of the program to be reasonably fast, in case there are
6519 @^inner loop@>
6520 lots of subscripts at the same level of the data structure. Therefore
6521 we store an ``infinite'' value in the word that appears at the end of the
6522 subscript list, even though that word isn't part of a subscript node.
6523
6524 @<Descend one level for the subscript |value(t)|@>=
6525
6526   n=value(t);
6527   pp=mp_link(attr_head(pp)); /* now |attr_loc(pp)=collective_subscript| */
6528   q=mp_link(attr_head(p)); save_word=mp->mem[subscript_loc(q)];
6529   subscript(q)=el_gordo; s=subscr_head_loc(p); /* |mp_link(s)=subscr_head(p)| */
6530   do {  
6531     r=s; s=mp_link(s);
6532   } while (n>subscript(s));
6533   if ( n==subscript(s) ) {
6534     p=s;
6535   } else { 
6536     p=mp_get_node(mp, subscr_node_size); mp_link(r)=p; mp_link(p)=s;
6537     subscript(p)=n; mp_name_type(p)=mp_subscr; mp_type(p)=undefined;
6538   }
6539   mp->mem[subscript_loc(q)]=save_word;
6540 }
6541
6542 @ @<Descend one level for the attribute |mp_info(t)|@>=
6543
6544   n=mp_info(t);
6545   ss=attr_head(pp);
6546   do {  
6547     rr=ss; ss=mp_link(ss);
6548   } while (n>attr_loc(ss));
6549   if ( n<attr_loc(ss) ) { 
6550     qq=mp_get_node(mp, attr_node_size); mp_link(rr)=qq; mp_link(qq)=ss;
6551     attr_loc(qq)=n; mp_name_type(qq)=mp_attr; mp_type(qq)=undefined;
6552     parent(qq)=pp; ss=qq;
6553   }
6554   if ( p==pp ) { 
6555     p=ss; pp=ss;
6556   } else { 
6557     pp=ss; s=attr_head(p);
6558     do {  
6559       r=s; s=mp_link(s);
6560     } while (n>attr_loc(s));
6561     if ( n==attr_loc(s) ) {
6562       p=s;
6563     } else { 
6564       q=mp_get_node(mp, attr_node_size); mp_link(r)=q; mp_link(q)=s;
6565       attr_loc(q)=n; mp_name_type(q)=mp_attr; mp_type(q)=undefined;
6566       parent(q)=p; p=q;
6567     }
6568   }
6569 }
6570
6571 @ Variables lose their former values when they appear in a type declaration,
6572 or when they are defined to be macros or \&{let} equal to something else.
6573 A subroutine will be defined later that recycles the storage associated
6574 with any particular |type| or |value|; our goal now is to study a higher
6575 level process called |flush_variable|, which selectively frees parts of a
6576 variable structure.
6577
6578 This routine has some complexity because of examples such as
6579 `\hbox{\tt numeric x[]a[]b}'
6580 which recycles all variables of the form \.{x[i]a[j]b} (and no others), while
6581 `\hbox{\tt vardef x[]a[]=...}'
6582 discards all variables of the form \.{x[i]a[j]} followed by an arbitrary
6583 suffix, except for the collective node \.{x[]a[]} itself. The obvious way
6584 to handle such examples is to use recursion; so that's what we~do.
6585 @^recursion@>
6586
6587 Parameter |p| points to the root information of the variable;
6588 parameter |t| points to a list of one-word nodes that represent
6589 suffixes, with |info=collective_subscript| for subscripts.
6590
6591 @<Declarations@>=
6592 static void mp_flush_cur_exp (MP mp,scaled v) ;
6593
6594 @ @c 
6595 static void mp_flush_variable (MP mp,pointer p, pointer t, boolean discard_suffixes) {
6596   pointer q,r; /* list manipulation */
6597   halfword n; /* attribute to match */
6598   while ( t!=null ) { 
6599     if ( mp_type(p)!=mp_structured ) return;
6600     n=mp_info(t); t=mp_link(t);
6601     if ( n==collective_subscript ) { 
6602       r=subscr_head_loc(p); q=mp_link(r); /* |q=subscr_head(p)| */
6603       while ( mp_name_type(q)==mp_subscr ){ 
6604         mp_flush_variable(mp, q,t,discard_suffixes);
6605         if ( t==null ) {
6606           if ( mp_type(q)==mp_structured ) r=q;
6607           else  { mp_link(r)=mp_link(q); mp_free_node(mp, q,subscr_node_size);   }
6608         } else {
6609           r=q;
6610         }
6611         q=mp_link(r);
6612       }
6613     }
6614     p=attr_head(p);
6615     do {  
6616       r=p; p=mp_link(p);
6617     } while (attr_loc(p)<n);
6618     if ( attr_loc(p)!=n ) return;
6619   }
6620   if ( discard_suffixes ) {
6621     mp_flush_below_variable(mp, p);
6622   } else { 
6623     if ( mp_type(p)==mp_structured ) p=attr_head(p);
6624     mp_recycle_value(mp, p);
6625   }
6626 }
6627
6628 @ The next procedure is simpler; it wipes out everything but |p| itself,
6629 which becomes undefined.
6630
6631 @<Declarations@>=
6632 static void mp_flush_below_variable (MP mp, pointer p);
6633
6634 @ @c
6635 void mp_flush_below_variable (MP mp,pointer p) {
6636    pointer q,r; /* list manipulation registers */
6637   if ( mp_type(p)!=mp_structured ) {
6638     mp_recycle_value(mp, p); /* this sets |type(p)=undefined| */
6639   } else { 
6640     q=subscr_head(p);
6641     while ( mp_name_type(q)==mp_subscr ) { 
6642       mp_flush_below_variable(mp, q); r=q; q=mp_link(q);
6643       mp_free_node(mp, r,subscr_node_size);
6644     }
6645     r=attr_head(p); q=mp_link(r); mp_recycle_value(mp, r);
6646     if ( mp_name_type(p)<=mp_saved_root ) mp_free_node(mp, r,value_node_size);
6647     else mp_free_node(mp, r,subscr_node_size);
6648     /* we assume that |subscr_node_size=attr_node_size| */
6649     do {  
6650       mp_flush_below_variable(mp, q); r=q; q=mp_link(q); mp_free_node(mp, r,attr_node_size);
6651     } while (q!=end_attr);
6652     mp_type(p)=undefined;
6653   }
6654 }
6655
6656 @ Just before assigning a new value to a variable, we will recycle the
6657 old value and make the old value undefined. The |und_type| routine
6658 determines what type of undefined value should be given, based on
6659 the current type before recycling.
6660
6661 @c 
6662 static quarterword mp_und_type (MP mp,pointer p) { 
6663   switch (mp_type(p)) {
6664   case undefined: case mp_vacuous:
6665     return undefined;
6666   case mp_boolean_type: case mp_unknown_boolean:
6667     return mp_unknown_boolean;
6668   case mp_string_type: case mp_unknown_string:
6669     return mp_unknown_string;
6670   case mp_pen_type: case mp_unknown_pen:
6671     return mp_unknown_pen;
6672   case mp_path_type: case mp_unknown_path:
6673     return mp_unknown_path;
6674   case mp_picture_type: case mp_unknown_picture:
6675     return mp_unknown_picture;
6676   case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
6677   case mp_pair_type: case mp_numeric_type: 
6678     return mp_type(p);
6679   case mp_known: case mp_dependent: case mp_proto_dependent: case mp_independent:
6680     return mp_numeric_type;
6681   } /* there are no other cases */
6682   return 0;
6683 }
6684
6685 @ The |clear_symbol| routine is used when we want to redefine the equivalent
6686 of a symbolic token. It must remove any variable structure or macro
6687 definition that is currently attached to that symbol. If the |saving|
6688 parameter is true, a subsidiary structure is saved instead of destroyed.
6689
6690 @c 
6691 static void mp_clear_symbol (MP mp,pointer p, boolean saving) {
6692   pointer q; /* |equiv(p)| */
6693   q=equiv(p);
6694   switch (eq_type(p) % outer_tag)  {
6695   case defined_macro:
6696   case secondary_primary_macro:
6697   case tertiary_secondary_macro:
6698   case expression_tertiary_macro: 
6699     if ( ! saving ) mp_delete_mac_ref(mp, q);
6700     break;
6701   case tag_token:
6702     if ( q!=null ) {
6703       if ( saving ) {
6704         mp_name_type(q)=mp_saved_root;
6705       } else { 
6706         mp_flush_below_variable(mp, q); 
6707             mp_free_node(mp,q,value_node_size); 
6708       }
6709     }
6710     break;
6711   default:
6712     break;
6713   }
6714   mp->eqtb[p]=mp->eqtb[frozen_undefined];
6715 }
6716
6717 @* \[16] Saving and restoring equivalents.
6718 The nested structure given by \&{begingroup} and \&{endgroup}
6719 allows |eqtb| entries to be saved and restored, so that temporary changes
6720 can be made without difficulty.  When the user requests a current value to
6721 be saved, \MP\ puts that value into its ``save stack.'' An appearance of
6722 \&{endgroup} ultimately causes the old values to be removed from the save
6723 stack and put back in their former places.
6724
6725 The save stack is a linked list containing three kinds of entries,
6726 distinguished by their |info| fields. If |p| points to a saved item,
6727 then
6728
6729 \smallskip\hang
6730 |mp_info(p)=0| stands for a group boundary; each \&{begingroup} contributes
6731 such an item to the save stack and each \&{endgroup} cuts back the stack
6732 until the most recent such entry has been removed.
6733
6734 \smallskip\hang
6735 |mp_info(p)=q|, where |1<=q<=hash_end|, means that |mem[p+1]| holds the former
6736 contents of |eqtb[q]|. Such save stack entries are generated by \&{save}
6737 commands.
6738
6739 \smallskip\hang
6740 |mp_info(p)=hash_end+q|, where |q>0|, means that |value(p)| is a |scaled|
6741 integer to be restored to internal parameter number~|q|. Such entries
6742 are generated by \&{interim} commands.
6743
6744 \smallskip\noindent
6745 The global variable |save_ptr| points to the top item on the save stack.
6746
6747 @d save_node_size 2 /* number of words per non-boundary save-stack node */
6748 @d saved_equiv(A) mp->mem[(A)+1].hh /* where an |eqtb| entry gets saved */
6749 @d save_boundary_item(A) { (A)=mp_get_avail(mp); mp_info((A))=0;
6750   mp_link((A))=mp->save_ptr; mp->save_ptr=(A);
6751   }
6752
6753 @<Glob...@>=
6754 pointer save_ptr; /* the most recently saved item */
6755
6756 @ @<Set init...@>=mp->save_ptr=null;
6757
6758 @ The |save_variable| routine is given a hash address |q|; it salts this
6759 address in the save stack, together with its current equivalent,
6760 then makes token~|q| behave as though it were brand new.
6761
6762 Nothing is stacked when |save_ptr=null|, however; there's no way to remove
6763 things from the stack when the program is not inside a group, so there's
6764 no point in wasting the space.
6765
6766 @c 
6767 static void mp_save_variable (MP mp,pointer q) {
6768   pointer p; /* temporary register */
6769   if ( mp->save_ptr!=null ){ 
6770     p=mp_get_node(mp, save_node_size); mp_info(p)=q; mp_link(p)=mp->save_ptr;
6771     saved_equiv(p)=mp->eqtb[q]; mp->save_ptr=p;
6772   }
6773   mp_clear_symbol(mp, q,(mp->save_ptr!=null));
6774 }
6775
6776 @ Similarly, |save_internal| is given the location |q| of an internal
6777 quantity like |mp_tracing_pens|. It creates a save stack entry of the
6778 third kind.
6779
6780 @c 
6781 static void mp_save_internal (MP mp,halfword q) {
6782   pointer p; /* new item for the save stack */
6783   if ( mp->save_ptr!=null ){ 
6784      p=mp_get_node(mp, save_node_size); mp_info(p)=hash_end+q;
6785     mp_link(p)=mp->save_ptr; value(p)=mp->internal[q]; mp->save_ptr=p;
6786   }
6787 }
6788
6789 @ At the end of a group, the |unsave| routine restores all of the saved
6790 equivalents in reverse order. This routine will be called only when there
6791 is at least one boundary item on the save stack.
6792
6793 @c 
6794 static void mp_unsave (MP mp) {
6795   pointer q; /* index to saved item */
6796   pointer p; /* temporary register */
6797   while ( mp_info(mp->save_ptr)!=0 ) {
6798     q=mp_info(mp->save_ptr);
6799     if ( q>hash_end ) {
6800       if ( mp->internal[mp_tracing_restores]>0 ) {
6801         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6802         mp_print(mp, mp->int_name[q-(hash_end)]); mp_print_char(mp, xord('='));
6803         mp_print_scaled(mp, value(mp->save_ptr)); mp_print_char(mp, xord('}'));
6804         mp_end_diagnostic(mp, false);
6805       }
6806       mp->internal[q-(hash_end)]=value(mp->save_ptr);
6807     } else { 
6808       if ( mp->internal[mp_tracing_restores]>0 ) {
6809         mp_begin_diagnostic(mp); mp_print_nl(mp, "{restoring ");
6810         mp_print_text(q); mp_print_char(mp, xord('}'));
6811         mp_end_diagnostic(mp, false);
6812       }
6813       mp_clear_symbol(mp, q,false);
6814       mp->eqtb[q]=saved_equiv(mp->save_ptr);
6815       if ( eq_type(q) % outer_tag==tag_token ) {
6816         p=equiv(q);
6817         if ( p!=null ) mp_name_type(p)=mp_root;
6818       }
6819     }
6820     p=mp_link(mp->save_ptr); 
6821     mp_free_node(mp, mp->save_ptr,save_node_size); mp->save_ptr=p;
6822   }
6823   p=mp_link(mp->save_ptr); free_avail(mp->save_ptr); mp->save_ptr=p;
6824 }
6825
6826 @* \[17] Data structures for paths.
6827 When a \MP\ user specifies a path, \MP\ will create a list of knots
6828 and control points for the associated cubic spline curves. If the
6829 knots are $z_0$, $z_1$, \dots, $z_n$, there are control points
6830 $z_k^+$ and $z_{k+1}^-$ such that the cubic splines between knots
6831 $z_k$ and $z_{k+1}$ are defined by B\'ezier's formula
6832 @:Bezier}{B\'ezier, Pierre Etienne@>
6833 $$\eqalign{z(t)&=B(z_k,z_k^+,z_{k+1}^-,z_{k+1};t)\cr
6834 &=(1-t)^3z_k+3(1-t)^2tz_k^++3(1-t)t^2z_{k+1}^-+t^3z_{k+1}\cr}$$
6835 for |0<=t<=1|.
6836
6837 There is a 8-word node for each knot $z_k$, containing one word of
6838 control information and six words for the |x| and |y| coordinates of
6839 $z_k^-$ and $z_k$ and~$z_k^+$. The control information appears in the
6840 |mp_left_type| and |mp_right_type| fields, which each occupy a quarter of
6841 the first word in the node; they specify properties of the curve as it
6842 enters and leaves the knot. There's also a halfword |link| field,
6843 which points to the following knot, and a final supplementary word (of
6844 which only a quarter is used).
6845
6846 If the path is a closed contour, knots 0 and |n| are identical;
6847 i.e., the |link| in knot |n-1| points to knot~0. But if the path
6848 is not closed, the |mp_left_type| of knot~0 and the |mp_right_type| of knot~|n|
6849 are equal to |endpoint|. In the latter case the |link| in knot~|n| points
6850 to knot~0, and the control points $z_0^-$ and $z_n^+$ are not used.
6851
6852 @d mp_left_type(A)   mp->mem[(A)].hh.b0 /* characterizes the path entering this knot */
6853 @d mp_right_type(A)   mp->mem[(A)].hh.b1 /* characterizes the path leaving this knot */
6854 @d mp_x_coord(A)   mp->mem[(A)+1].sc /* the |x| coordinate of this knot */ 
6855 @d mp_y_coord(A)   mp->mem[(A)+2].sc /* the |y| coordinate of this knot */
6856 @d mp_left_x(A)   mp->mem[(A)+3].sc /* the |x| coordinate of previous control point */
6857 @d mp_left_y(A)   mp->mem[(A)+4].sc /* the |y| coordinate of previous control point */
6858 @d mp_right_x(A)   mp->mem[(A)+5].sc /* the |x| coordinate of next control point */
6859 @d mp_right_y(A)   mp->mem[(A)+6].sc /* the |y| coordinate of next control point */
6860 @d x_loc(A)   ((A)+1) /* where the |x| coordinate is stored in a knot */
6861 @d y_loc(A)   ((A)+2) /* where the |y| coordinate is stored in a knot */
6862 @d knot_coord(A)   mp->mem[(A)].sc /* |x| or |y| coordinate given |x_loc| or |y_loc| */
6863 @d left_coord(A)   mp->mem[(A)+2].sc
6864   /* coordinate of previous control point given |x_loc| or |y_loc| */
6865 @d right_coord(A)   mp->mem[(A)+4].sc
6866   /* coordinate of next control point given |x_loc| or |y_loc| */
6867 @d knot_node_size 8 /* number of words in a knot node */
6868
6869 @(mplib.h@>=
6870 enum mp_knot_type {
6871  mp_endpoint=0, /* |mp_left_type| at path beginning and |mp_right_type| at path end */
6872  mp_explicit, /* |mp_left_type| or |mp_right_type| when control points are known */
6873  mp_given, /* |mp_left_type| or |mp_right_type| when a direction is given */
6874  mp_curl, /* |mp_left_type| or |mp_right_type| when a curl is desired */
6875  mp_open, /* |mp_left_type| or |mp_right_type| when \MP\ should choose the direction */
6876  mp_end_cycle
6877 };
6878
6879 @ Before the B\'ezier control points have been calculated, the memory
6880 space they will ultimately occupy is taken up by information that can be
6881 used to compute them. There are four cases:
6882
6883 \yskip
6884 \textindent{$\bullet$} If |mp_right_type=mp_open|, the curve should leave
6885 the knot in the same direction it entered; \MP\ will figure out a
6886 suitable direction.
6887
6888 \yskip
6889 \textindent{$\bullet$} If |mp_right_type=mp_curl|, the curve should leave the
6890 knot in a direction depending on the angle at which it enters the next
6891 knot and on the curl parameter stored in |right_curl|.
6892
6893 \yskip
6894 \textindent{$\bullet$} If |mp_right_type=mp_given|, the curve should leave the
6895 knot in a nonzero direction stored as an |angle| in |right_given|.
6896
6897 \yskip
6898 \textindent{$\bullet$} If |mp_right_type=mp_explicit|, the B\'ezier control
6899 point for leaving this knot has already been computed; it is in the
6900 |mp_right_x| and |mp_right_y| fields.
6901
6902 \yskip\noindent
6903 The rules for |mp_left_type| are similar, but they refer to the curve entering
6904 the knot, and to \\{left} fields instead of \\{right} fields.
6905
6906 Non-|explicit| control points will be chosen based on ``tension'' parameters
6907 in the |left_tension| and |right_tension| fields. The
6908 `\&{atleast}' option is represented by negative tension values.
6909 @:at_least_}{\&{atleast} primitive@>
6910
6911 For example, the \MP\ path specification
6912 $$\.{z0..z1..tension atleast 1..\{curl 2\}z2..z3\{-1,-2\}..tension
6913   3 and 4..p},$$
6914 where \.p is the path `\.{z4..controls z45 and z54..z5}', will be represented
6915 by the six knots
6916 \def\lodash{\hbox to 1.1em{\thinspace\hrulefill\thinspace}}
6917 $$\vbox{\halign{#\hfil&&\qquad#\hfil\cr
6918 |mp_left_type|&\\{left} info&|mp_x_coord,mp_y_coord|&|mp_right_type|&\\{right} info\cr
6919 \noalign{\yskip}
6920 |endpoint|&\lodash$,\,$\lodash&$x_0,y_0$&|curl|&$1.0,1.0$\cr
6921 |open|&\lodash$,1.0$&$x_1,y_1$&|open|&\lodash$,-1.0$\cr
6922 |curl|&$2.0,-1.0$&$x_2,y_2$&|curl|&$2.0,1.0$\cr
6923 |given|&$d,1.0$&$x_3,y_3$&|given|&$d,3.0$\cr
6924 |open|&\lodash$,4.0$&$x_4,y_4$&|explicit|&$x_{45},y_{45}$\cr
6925 |explicit|&$x_{54},y_{54}$&$x_5,y_5$&|endpoint|&\lodash$,\,$\lodash\cr}}$$
6926 Here |d| is the |angle| obtained by calling |n_arg(-unity,-two)|.
6927 Of course, this example is more complicated than anything a normal user
6928 would ever write.
6929
6930 These types must satisfy certain restrictions because of the form of \MP's
6931 path syntax:
6932 (i)~|open| type never appears in the same node together with |endpoint|,
6933 |given|, or |curl|.
6934 (ii)~The |mp_right_type| of a node is |explicit| if and only if the
6935 |mp_left_type| of the following node is |explicit|.
6936 (iii)~|endpoint| types occur only at the ends, as mentioned above.
6937
6938 @d left_curl mp_left_x /* curl information when entering this knot */
6939 @d left_given mp_left_x /* given direction when entering this knot */
6940 @d left_tension mp_left_y /* tension information when entering this knot */
6941 @d right_curl mp_right_x /* curl information when leaving this knot */
6942 @d right_given mp_right_x /* given direction when leaving this knot */
6943 @d right_tension mp_right_y /* tension information when leaving this knot */
6944
6945 @ Knots can be user-supplied, or they can be created by program code,
6946 like the |split_cubic| function, or |copy_path|. The distinction is
6947 needed for the cleanup routine that runs after |split_cubic|, because
6948 it should only delete knots it has previously inserted, and never
6949 anything that was user-supplied. In order to be able to differentiate
6950 one knot from another, we will set |originator(p):=mp_metapost_user| when
6951 it appeared in the actual metapost program, and
6952 |originator(p):=mp_program_code| in all other cases.
6953
6954 @d mp_originator(A)   mp->mem[(A)+7].hh.b0 /* the creator of this knot */
6955
6956 @<Exported types@>=
6957 enum mp_knot_originator {
6958   mp_program_code=0, /* not created by a user */
6959   mp_metapost_user /* created by a user */
6960 };
6961
6962 @ Here is a routine that prints a given knot list
6963 in symbolic form. It illustrates the conventions discussed above,
6964 and checks for anomalies that might arise while \MP\ is being debugged.
6965
6966 @<Declarations@>=
6967 static void mp_pr_path (MP mp,pointer h);
6968
6969 @ @c
6970 void mp_pr_path (MP mp,pointer h) {
6971   pointer p,q; /* for list traversal */
6972   p=h;
6973   do {  
6974     q=mp_link(p);
6975     if ( (p==null)||(q==null) ) { 
6976       mp_print_nl(mp, "???"); return; /* this won't happen */
6977 @.???@>
6978     }
6979     @<Print information for adjacent knots |p| and |q|@>;
6980   DONE1:
6981     p=q;
6982     if ( (p!=h)||(mp_left_type(h)!=mp_endpoint) ) {
6983       @<Print two dots, followed by |given| or |curl| if present@>;
6984     }
6985   } while (p!=h);
6986   if ( mp_left_type(h)!=mp_endpoint ) 
6987     mp_print(mp, "cycle");
6988 }
6989
6990 @ @<Print information for adjacent knots...@>=
6991 mp_print_two(mp, mp_x_coord(p),mp_y_coord(p));
6992 switch (mp_right_type(p)) {
6993 case mp_endpoint: 
6994   if ( mp_left_type(p)==mp_open ) mp_print(mp, "{open?}"); /* can't happen */
6995 @.open?@>
6996   if ( (mp_left_type(q)!=mp_endpoint)||(q!=h) ) q=null; /* force an error */
6997   goto DONE1;
6998   break;
6999 case mp_explicit: 
7000   @<Print control points between |p| and |q|, then |goto done1|@>;
7001   break;
7002 case mp_open: 
7003   @<Print information for a curve that begins |open|@>;
7004   break;
7005 case mp_curl:
7006 case mp_given: 
7007   @<Print information for a curve that begins |curl| or |given|@>;
7008   break;
7009 default:
7010   mp_print(mp, "???"); /* can't happen */
7011 @.???@>
7012   break;
7013 }
7014 if ( mp_left_type(q)<=mp_explicit ) {
7015   mp_print(mp, "..control?"); /* can't happen */
7016 @.control?@>
7017 } else if ( (right_tension(p)!=unity)||(left_tension(q)!=unity) ) {
7018   @<Print tension between |p| and |q|@>;
7019 }
7020
7021 @ Since |n_sin_cos| produces |fraction| results, which we will print as if they
7022 were |scaled|, the magnitude of a |given| direction vector will be~4096.
7023
7024 @<Print two dots...@>=
7025
7026   mp_print_nl(mp, " ..");
7027   if ( mp_left_type(p)==mp_given ) { 
7028     mp_n_sin_cos(mp, left_given(p)); mp_print_char(mp, xord('{'));
7029     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, xord(','));
7030     mp_print_scaled(mp, mp->n_sin); mp_print_char(mp, xord('}'));
7031   } else if ( mp_left_type(p)==mp_curl ){ 
7032     mp_print(mp, "{curl "); 
7033     mp_print_scaled(mp, left_curl(p)); mp_print_char(mp, xord('}'));
7034   }
7035 }
7036
7037 @ @<Print tension between |p| and |q|@>=
7038
7039   mp_print(mp, "..tension ");
7040   if ( right_tension(p)<0 ) mp_print(mp, "atleast");
7041   mp_print_scaled(mp, abs(right_tension(p)));
7042   if ( right_tension(p)!=left_tension(q) ){ 
7043     mp_print(mp, " and ");
7044     if ( left_tension(q)<0 ) mp_print(mp, "atleast");
7045     mp_print_scaled(mp, abs(left_tension(q)));
7046   }
7047 }
7048
7049 @ @<Print control points between |p| and |q|, then |goto done1|@>=
7050
7051   mp_print(mp, "..controls "); 
7052   mp_print_two(mp, mp_right_x(p),mp_right_y(p)); 
7053   mp_print(mp, " and ");
7054   if ( mp_left_type(q)!=mp_explicit ) { 
7055     mp_print(mp, "??"); /* can't happen */
7056 @.??@>
7057   } else {
7058     mp_print_two(mp, mp_left_x(q),mp_left_y(q));
7059   }
7060   goto DONE1;
7061 }
7062
7063 @ @<Print information for a curve that begins |open|@>=
7064 if ( (mp_left_type(p)!=mp_explicit)&&(mp_left_type(p)!=mp_open) ) {
7065   mp_print(mp, "{open?}"); /* can't happen */
7066 @.open?@>
7067 }
7068
7069 @ A curl of 1 is shown explicitly, so that the user sees clearly that
7070 \MP's default curl is present.
7071
7072 @<Print information for a curve that begins |curl|...@>=
7073
7074   if ( mp_left_type(p)==mp_open )  
7075     mp_print(mp, "??"); /* can't happen */
7076 @.??@>
7077   if ( mp_right_type(p)==mp_curl ) { 
7078     mp_print(mp, "{curl "); mp_print_scaled(mp, right_curl(p));
7079   } else { 
7080     mp_n_sin_cos(mp, right_given(p)); mp_print_char(mp, xord('{'));
7081     mp_print_scaled(mp, mp->n_cos); mp_print_char(mp, xord(',')); 
7082     mp_print_scaled(mp, mp->n_sin);
7083   }
7084   mp_print_char(mp, xord('}'));
7085 }
7086
7087 @ It is convenient to have another version of |pr_path| that prints the path
7088 as a diagnostic message.
7089
7090 @<Declarations@>=
7091 static void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) ;
7092
7093 @ @c
7094 void mp_print_path (MP mp,pointer h, const char *s, boolean nuline) { 
7095   mp_print_diagnostic(mp, "Path", s, nuline); mp_print_ln(mp);
7096 @.Path at line...@>
7097   mp_pr_path(mp, h);
7098   mp_end_diagnostic(mp, true);
7099 }
7100
7101 @ If we want to duplicate a knot node, we can say |copy_knot|:
7102
7103 @c 
7104 static pointer mp_copy_knot (MP mp,pointer p) {
7105   pointer q; /* the copy */
7106   int k; /* runs through the words of a knot node */
7107   q=mp_get_node(mp, knot_node_size);
7108   for (k=0;k<knot_node_size;k++) {
7109     mp->mem[q+k]=mp->mem[p+k];
7110   }
7111   mp_originator(q)=mp_originator(p);
7112   return q;
7113 }
7114
7115 @ The |copy_path| routine makes a clone of a given path.
7116
7117 @c 
7118 static pointer mp_copy_path (MP mp, pointer p) {
7119   pointer q,pp,qq; /* for list manipulation */
7120   q=mp_copy_knot(mp, p);
7121   qq=q; pp=mp_link(p);
7122   while ( pp!=p ) { 
7123     mp_link(qq)=mp_copy_knot(mp, pp);
7124     qq=mp_link(qq);
7125     pp=mp_link(pp);
7126   }
7127   mp_link(qq)=q;
7128   return q;
7129 }
7130
7131
7132 @ Just before |ship_out|, knot lists are exported for printing.
7133
7134 The |gr_XXXX| macros are defined in |mppsout.h|.
7135
7136 @c 
7137 static mp_knot *mp_export_knot (MP mp,pointer p) {
7138   mp_knot *q; /* the copy */
7139   if (p==null)
7140      return NULL;
7141   q = xmalloc(1, sizeof (mp_knot));
7142   memset(q,0,sizeof (mp_knot));
7143   gr_left_type(q)  = (unsigned short)mp_left_type(p);
7144   gr_right_type(q) = (unsigned short)mp_right_type(p);
7145   gr_x_coord(q)    = mp_x_coord(p);
7146   gr_y_coord(q)    = mp_y_coord(p);
7147   gr_left_x(q)     = mp_left_x(p);
7148   gr_left_y(q)     = mp_left_y(p);
7149   gr_right_x(q)    = mp_right_x(p);
7150   gr_right_y(q)    = mp_right_y(p);
7151   gr_originator(q) = (unsigned char)mp_originator(p);
7152   return q;
7153 }
7154
7155 @ The |export_knot_list| routine therefore also makes a clone 
7156 of a given path.
7157
7158 @c 
7159 static mp_knot *mp_export_knot_list (MP mp, pointer p) {
7160   mp_knot *q, *qq; /* for list manipulation */
7161   pointer pp; /* for list manipulation */
7162   if (p==null)
7163      return NULL;
7164   q=mp_export_knot(mp, p);
7165   qq=q; pp=mp_link(p);
7166   while ( pp!=p ) { 
7167     gr_next_knot(qq)=mp_export_knot(mp, pp);
7168     qq=gr_next_knot(qq);
7169     pp=mp_link(pp);
7170   }
7171   gr_next_knot(qq)=q;
7172   return q;
7173 }
7174
7175
7176 @ Similarly, there's a way to copy the {\sl reverse\/} of a path. This procedure
7177 returns a pointer to the first node of the copy, if the path is a cycle,
7178 but to the final node of a non-cyclic copy. The global
7179 variable |path_tail| will point to the final node of the original path;
7180 this trick makes it easier to implement `\&{doublepath}'.
7181
7182 All node types are assumed to be |endpoint| or |explicit| only.
7183
7184 @c 
7185 static pointer mp_htap_ypoc (MP mp,pointer p) {
7186   pointer q,pp,qq,rr; /* for list manipulation */
7187   q=mp_get_node(mp, knot_node_size); /* this will correspond to |p| */
7188   qq=q; pp=p;
7189   while (1) { 
7190     mp_right_type(qq)=mp_left_type(pp); mp_left_type(qq)=mp_right_type(pp);
7191     mp_x_coord(qq)=mp_x_coord(pp); mp_y_coord(qq)=mp_y_coord(pp);
7192     mp_right_x(qq)=mp_left_x(pp); mp_right_y(qq)=mp_left_y(pp);
7193     mp_left_x(qq)=mp_right_x(pp); mp_left_y(qq)=mp_right_y(pp);
7194     mp_originator(qq)=mp_originator(pp);
7195     if ( mp_link(pp)==p ) { 
7196       mp_link(q)=qq; mp->path_tail=pp; return q;
7197     }
7198     rr=mp_get_node(mp, knot_node_size); mp_link(rr)=qq; qq=rr; pp=mp_link(pp);
7199   }
7200 }
7201
7202 @ @<Glob...@>=
7203 pointer path_tail; /* the node that links to the beginning of a path */
7204
7205 @ When a cyclic list of knot nodes is no longer needed, it can be recycled by
7206 calling the following subroutine.
7207
7208 @<Declarations@>=
7209 static void mp_toss_knot_list (MP mp,pointer p) ;
7210
7211 @ @c
7212 void mp_toss_knot_list (MP mp,pointer p) {
7213   pointer q; /* the node being freed */
7214   pointer r; /* the next node */
7215   q=p;
7216   do {  
7217     r=mp_link(q); 
7218     mp_free_node(mp, q,knot_node_size); q=r;
7219   } while (q!=p);
7220 }
7221
7222 @* \[18] Choosing control points.
7223 Now we must actually delve into one of \MP's more difficult routines,
7224 the |make_choices| procedure that chooses angles and control points for
7225 the splines of a curve when the user has not specified them explicitly.
7226 The parameter to |make_choices| points to a list of knots and
7227 path information, as described above.
7228
7229 A path decomposes into independent segments at ``breakpoint'' knots,
7230 which are knots whose left and right angles are both prespecified in
7231 some way (i.e., their |mp_left_type| and |mp_right_type| aren't both open).
7232
7233 @c 
7234 static void mp_make_choices (MP mp,pointer knots) {
7235   pointer h; /* the first breakpoint */
7236   pointer p,q; /* consecutive breakpoints being processed */
7237   @<Other local variables for |make_choices|@>;
7238   check_arith; /* make sure that |arith_error=false| */
7239   if ( mp->internal[mp_tracing_choices]>0 )
7240     mp_print_path(mp, knots,", before choices",true);
7241   @<If consecutive knots are equal, join them explicitly@>;
7242   @<Find the first breakpoint, |h|, on the path;
7243     insert an artificial breakpoint if the path is an unbroken cycle@>;
7244   p=h;
7245   do {  
7246     @<Fill in the control points between |p| and the next breakpoint,
7247       then advance |p| to that breakpoint@>;
7248   } while (p!=h);
7249   if ( mp->internal[mp_tracing_choices]>0 )
7250     mp_print_path(mp, knots,", after choices",true);
7251   if ( mp->arith_error ) {
7252     @<Report an unexpected problem during the choice-making@>;
7253   }
7254 }
7255
7256 @ @<Report an unexpected problem during the choice...@>=
7257
7258   print_err("Some number got too big");
7259 @.Some number got too big@>
7260   help2("The path that I just computed is out of range.",
7261         "So it will probably look funny. Proceed, for a laugh.");
7262   mp_put_get_error(mp); mp->arith_error=false;
7263 }
7264
7265 @ Two knots in a row with the same coordinates will always be joined
7266 by an explicit ``curve'' whose control points are identical with the
7267 knots.
7268
7269 @<If consecutive knots are equal, join them explicitly@>=
7270 p=knots;
7271 do {  
7272   q=mp_link(p);
7273   if ( mp_x_coord(p)==mp_x_coord(q) && 
7274        mp_y_coord(p)==mp_y_coord(q) && mp_right_type(p)>mp_explicit ) { 
7275     mp_right_type(p)=mp_explicit;
7276     if ( mp_left_type(p)==mp_open ) { 
7277       mp_left_type(p)=mp_curl; left_curl(p)=unity;
7278     }
7279     mp_left_type(q)=mp_explicit;
7280     if ( mp_right_type(q)==mp_open ) { 
7281       mp_right_type(q)=mp_curl; right_curl(q)=unity;
7282     }
7283     mp_right_x(p)=mp_x_coord(p); mp_left_x(q)=mp_x_coord(p);
7284     mp_right_y(p)=mp_y_coord(p); mp_left_y(q)=mp_y_coord(p);
7285   }
7286   p=q;
7287 } while (p!=knots)
7288
7289 @ If there are no breakpoints, it is necessary to compute the direction
7290 angles around an entire cycle. In this case the |mp_left_type| of the first
7291 node is temporarily changed to |end_cycle|.
7292
7293 @<Find the first breakpoint, |h|, on the path...@>=
7294 h=knots;
7295 while (1) { 
7296   if ( mp_left_type(h)!=mp_open ) break;
7297   if ( mp_right_type(h)!=mp_open ) break;
7298   h=mp_link(h);
7299   if ( h==knots ) { 
7300     mp_left_type(h)=mp_end_cycle; break;
7301   }
7302 }
7303
7304 @ If |mp_right_type(p)<given| and |q=mp_link(p)|, we must have
7305 |mp_right_type(p)=mp_left_type(q)=mp_explicit| or |endpoint|.
7306
7307 @<Fill in the control points between |p| and the next breakpoint...@>=
7308 q=mp_link(p);
7309 if ( mp_right_type(p)>=mp_given ) { 
7310   while ( (mp_left_type(q)==mp_open)&&(mp_right_type(q)==mp_open) ) q=mp_link(q);
7311   @<Fill in the control information between
7312     consecutive breakpoints |p| and |q|@>;
7313 } else if ( mp_right_type(p)==mp_endpoint ) {
7314   @<Give reasonable values for the unused control points between |p| and~|q|@>;
7315 }
7316 p=q
7317
7318 @ This step makes it possible to transform an explicitly computed path without
7319 checking the |mp_left_type| and |mp_right_type| fields.
7320
7321 @<Give reasonable values for the unused control points between |p| and~|q|@>=
7322
7323   mp_right_x(p)=mp_x_coord(p); mp_right_y(p)=mp_y_coord(p);
7324   mp_left_x(q)=mp_x_coord(q); mp_left_y(q)=mp_y_coord(q);
7325 }
7326
7327 @ Before we can go further into the way choices are made, we need to
7328 consider the underlying theory. The basic ideas implemented in |make_choices|
7329 are due to John Hobby, who introduced the notion of ``mock curvature''
7330 @^Hobby, John Douglas@>
7331 at a knot. Angles are chosen so that they preserve mock curvature when
7332 a knot is passed, and this has been found to produce excellent results.
7333
7334 It is convenient to introduce some notations that simplify the necessary
7335 formulas. Let $d_{k,k+1}=\vert z\k-z_k\vert$ be the (nonzero) distance
7336 between knots |k| and |k+1|; and let
7337 $${z\k-z_k\over z_k-z_{k-1}}={d_{k,k+1}\over d_{k-1,k}}e^{i\psi_k}$$
7338 so that a polygonal line from $z_{k-1}$ to $z_k$ to $z\k$ turns left
7339 through an angle of~$\psi_k$. We assume that $\vert\psi_k\vert\L180^\circ$.
7340 The control points for the spline from $z_k$ to $z\k$ will be denoted by
7341 $$\eqalign{z_k^+&=z_k+
7342   \textstyle{1\over3}\rho_k e^{i\theta_k}(z\k-z_k),\cr
7343  z\k^-&=z\k-
7344   \textstyle{1\over3}\sigma\k e^{-i\phi\k}(z\k-z_k),\cr}$$
7345 where $\rho_k$ and $\sigma\k$ are nonnegative ``velocity ratios'' at the
7346 beginning and end of the curve, while $\theta_k$ and $\phi\k$ are the
7347 corresponding ``offset angles.'' These angles satisfy the condition
7348 $$\theta_k+\phi_k+\psi_k=0,\eqno(*)$$
7349 whenever the curve leaves an intermediate knot~|k| in the direction that
7350 it enters.
7351
7352 @ Let $\alpha_k$ and $\beta\k$ be the reciprocals of the ``tension'' of
7353 the curve at its beginning and ending points. This means that
7354 $\rho_k=\alpha_k f(\theta_k,\phi\k)$ and $\sigma\k=\beta\k f(\phi\k,\theta_k)$,
7355 where $f(\theta,\phi)$ is \MP's standard velocity function defined in
7356 the |velocity| subroutine. The cubic spline $B(z_k^{\phantom+},z_k^+,
7357 z\k^-,z\k^{\phantom+};t)$
7358 has curvature
7359 @^curvature@>
7360 $${2\sigma\k\sin(\theta_k+\phi\k)-6\sin\theta_k\over\rho_k^2d_{k,k+1}}
7361 \qquad{\rm and}\qquad
7362 {2\rho_k\sin(\theta_k+\phi\k)-6\sin\phi\k\over\sigma\k^2d_{k,k+1}}$$
7363 at |t=0| and |t=1|, respectively. The mock curvature is the linear
7364 @^mock curvature@>
7365 approximation to this true curvature that arises in the limit for
7366 small $\theta_k$ and~$\phi\k$, if second-order terms are discarded.
7367 The standard velocity function satisfies
7368 $$f(\theta,\phi)=1+O(\theta^2+\theta\phi+\phi^2);$$
7369 hence the mock curvatures are respectively
7370 $${2\beta\k(\theta_k+\phi\k)-6\theta_k\over\alpha_k^2d_{k,k+1}}
7371 \qquad{\rm and}\qquad
7372 {2\alpha_k(\theta_k+\phi\k)-6\phi\k\over\beta\k^2d_{k,k+1}}.\eqno(**)$$
7373
7374 @ The turning angles $\psi_k$ are given, and equation $(*)$ above
7375 determines $\phi_k$ when $\theta_k$ is known, so the task of
7376 angle selection is essentially to choose appropriate values for each
7377 $\theta_k$. When equation~$(*)$ is used to eliminate $\phi$~variables
7378 from $(**)$, we obtain a system of linear equations of the form
7379 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7380 where
7381 $$A_k={\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7382 \qquad B_k={3-\alpha_{k-1}\over\beta_k^2d_{k-1,k}},
7383 \qquad C_k={3-\beta\k\over\alpha_k^2d_{k,k+1}},
7384 \qquad D_k={\beta\k\over\alpha_k^2d_{k,k+1}}.$$
7385 The tensions are always $3\over4$ or more, hence each $\alpha$ and~$\beta$
7386 will be at most $4\over3$. It follows that $B_k\G{5\over4}A_k$ and
7387 $C_k\G{5\over4}D_k$; hence the equations are diagonally dominant;
7388 hence they have a unique solution. Moreover, in most cases the tensions
7389 are equal to~1, so that $B_k=2A_k$ and $C_k=2D_k$. This makes the
7390 solution numerically stable, and there is an exponential damping
7391 effect: The data at knot $k\pm j$ affects the angle at knot~$k$ by
7392 a factor of~$O(2^{-j})$.
7393
7394 @ However, we still must consider the angles at the starting and ending
7395 knots of a non-cyclic path. These angles might be given explicitly, or
7396 they might be specified implicitly in terms of an amount of ``curl.''
7397
7398 Let's assume that angles need to be determined for a non-cyclic path
7399 starting at $z_0$ and ending at~$z_n$. Then equations of the form
7400 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta_{k+1}=R_k$$
7401 have been given for $0<k<n$, and it will be convenient to introduce
7402 equations of the same form for $k=0$ and $k=n$, where
7403 $$A_0=B_0=C_n=D_n=0.$$
7404 If $\theta_0$ is supposed to have a given value $E_0$, we simply
7405 define $C_0=1$, $D_0=0$, and $R_0=E_0$. Otherwise a curl
7406 parameter, $\gamma_0$, has been specified at~$z_0$; this means
7407 that the mock curvature at $z_0$ should be $\gamma_0$ times the
7408 mock curvature at $z_1$; i.e.,
7409 $${2\beta_1(\theta_0+\phi_1)-6\theta_0\over\alpha_0^2d_{01}}
7410 =\gamma_0{2\alpha_0(\theta_0+\phi_1)-6\phi_1\over\beta_1^2d_{01}}.$$
7411 This equation simplifies to
7412 $$(\alpha_0\chi_0+3-\beta_1)\theta_0+
7413  \bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\theta_1=
7414  -\bigl((3-\alpha_0)\chi_0+\beta_1\bigr)\psi_1,$$
7415 where $\chi_0=\alpha_0^2\gamma_0/\beta_1^2$; so we can set $C_0=
7416 \chi_0\alpha_0+3-\beta_1$, $D_0=(3-\alpha_0)\chi_0+\beta_1$, $R_0=-D_0\psi_1$.
7417 It can be shown that $C_0>0$ and $C_0B_1-A_1D_0>0$ when $\gamma_0\G0$,
7418 hence the linear equations remain nonsingular.
7419
7420 Similar considerations apply at the right end, when the final angle $\phi_n$
7421 may or may not need to be determined. It is convenient to let $\psi_n=0$,
7422 hence $\theta_n=-\phi_n$. We either have an explicit equation $\theta_n=E_n$,
7423 or we have
7424 $$\bigl((3-\beta_n)\chi_n+\alpha_{n-1}\bigr)\theta_{n-1}+
7425 (\beta_n\chi_n+3-\alpha_{n-1})\theta_n=0,\qquad
7426   \chi_n={\beta_n^2\gamma_n\over\alpha_{n-1}^2}.$$
7427
7428 When |make_choices| chooses angles, it must compute the coefficients of
7429 these linear equations, then solve the equations. To compute the coefficients,
7430 it is necessary to compute arctangents of the given turning angles~$\psi_k$.
7431 When the equations are solved, the chosen directions $\theta_k$ are put
7432 back into the form of control points by essentially computing sines and
7433 cosines.
7434
7435 @ OK, we are ready to make the hard choices of |make_choices|.
7436 Most of the work is relegated to an auxiliary procedure
7437 called |solve_choices|, which has been introduced to keep
7438 |make_choices| from being extremely long.
7439
7440 @<Fill in the control information between...@>=
7441 @<Calculate the turning angles $\psi_k$ and the distances $d_{k,k+1}$;
7442   set $n$ to the length of the path@>;
7443 @<Remove |open| types at the breakpoints@>;
7444 mp_solve_choices(mp, p,q,n)
7445
7446 @ It's convenient to precompute quantities that will be needed several
7447 times later. The values of |delta_x[k]| and |delta_y[k]| will be the
7448 coordinates of $z\k-z_k$, and the magnitude of this vector will be
7449 |delta[k]=@t$d_{k,k+1}$@>|. The path angle $\psi_k$ between $z_k-z_{k-1}$
7450 and $z\k-z_k$ will be stored in |psi[k]|.
7451
7452 @<Glob...@>=
7453 int path_size; /* maximum number of knots between breakpoints of a path */
7454 scaled *delta_x;
7455 scaled *delta_y;
7456 scaled *delta; /* knot differences */
7457 angle  *psi; /* turning angles */
7458
7459 @ @<Dealloc variables@>=
7460 xfree(mp->delta_x);
7461 xfree(mp->delta_y);
7462 xfree(mp->delta);
7463 xfree(mp->psi);
7464
7465 @ @<Other local variables for |make_choices|@>=
7466   int k,n; /* current and final knot numbers */
7467   pointer s,t; /* registers for list traversal */
7468   scaled delx,dely; /* directions where |open| meets |explicit| */
7469   fraction sine,cosine; /* trig functions of various angles */
7470
7471 @ @<Calculate the turning angles...@>=
7472 {
7473 RESTART:
7474   k=0; s=p; n=mp->path_size;
7475   do {  
7476     t=mp_link(s);
7477     mp->delta_x[k]=mp_x_coord(t)-mp_x_coord(s);
7478     mp->delta_y[k]=mp_y_coord(t)-mp_y_coord(s);
7479     mp->delta[k]=mp_pyth_add(mp, mp->delta_x[k],mp->delta_y[k]);
7480     if ( k>0 ) { 
7481       sine=mp_make_fraction(mp, mp->delta_y[k-1],mp->delta[k-1]);
7482       cosine=mp_make_fraction(mp, mp->delta_x[k-1],mp->delta[k-1]);
7483       mp->psi[k]=mp_n_arg(mp, mp_take_fraction(mp, mp->delta_x[k],cosine)+
7484         mp_take_fraction(mp, mp->delta_y[k],sine),
7485         mp_take_fraction(mp, mp->delta_y[k],cosine)-
7486           mp_take_fraction(mp, mp->delta_x[k],sine));
7487     }
7488     incr(k); s=t;
7489     if ( k==mp->path_size ) {
7490       mp_reallocate_paths(mp, mp->path_size+(mp->path_size/4));
7491       goto RESTART; /* retry, loop size has changed */
7492     }
7493     if ( s==q ) n=k;
7494   } while (!((k>=n)&&(mp_left_type(s)!=mp_end_cycle)));
7495   if ( k==n ) mp->psi[n]=0; else mp->psi[k]=mp->psi[1];
7496 }
7497
7498 @ When we get to this point of the code, |mp_right_type(p)| is either
7499 |given| or |curl| or |open|. If it is |open|, we must have
7500 |mp_left_type(p)=mp_end_cycle| or |mp_left_type(p)=mp_explicit|. In the latter
7501 case, the |open| type is converted to |given|; however, if the
7502 velocity coming into this knot is zero, the |open| type is
7503 converted to a |curl|, since we don't know the incoming direction.
7504
7505 Similarly, |mp_left_type(q)| is either |given| or |curl| or |open| or
7506 |mp_end_cycle|. The |open| possibility is reduced either to |given| or to |curl|.
7507
7508 @<Remove |open| types at the breakpoints@>=
7509 if ( mp_left_type(q)==mp_open ) { 
7510   delx=mp_right_x(q)-mp_x_coord(q); dely=mp_right_y(q)-mp_y_coord(q);
7511   if ( (delx==0)&&(dely==0) ) { 
7512     mp_left_type(q)=mp_curl; left_curl(q)=unity;
7513   } else { 
7514     mp_left_type(q)=mp_given; left_given(q)=mp_n_arg(mp, delx,dely);
7515   }
7516 }
7517 if ( (mp_right_type(p)==mp_open)&&(mp_left_type(p)==mp_explicit) ) { 
7518   delx=mp_x_coord(p)-mp_left_x(p); dely=mp_y_coord(p)-mp_left_y(p);
7519   if ( (delx==0)&&(dely==0) ) { 
7520     mp_right_type(p)=mp_curl; right_curl(p)=unity;
7521   } else { 
7522     mp_right_type(p)=mp_given; right_given(p)=mp_n_arg(mp, delx,dely);
7523   }
7524 }
7525
7526 @ Linear equations need to be solved whenever |n>1|; and also when |n=1|
7527 and exactly one of the breakpoints involves a curl. The simplest case occurs
7528 when |n=1| and there is a curl at both breakpoints; then we simply draw
7529 a straight line.
7530
7531 But before coding up the simple cases, we might as well face the general case,
7532 since we must deal with it sooner or later, and since the general case
7533 is likely to give some insight into the way simple cases can be handled best.
7534
7535 When there is no cycle, the linear equations to be solved form a tridiagonal
7536 system, and we can apply the standard technique of Gaussian elimination
7537 to convert that system to a sequence of equations of the form
7538 $$\theta_0+u_0\theta_1=v_0,\quad
7539 \theta_1+u_1\theta_2=v_1,\quad\ldots,\quad
7540 \theta_{n-1}+u_{n-1}\theta_n=v_{n-1},\quad
7541 \theta_n=v_n.$$
7542 It is possible to do this diagonalization while generating the equations.
7543 Once $\theta_n$ is known, it is easy to determine $\theta_{n-1}$, \dots,
7544 $\theta_1$, $\theta_0$; thus, the equations will be solved.
7545
7546 The procedure is slightly more complex when there is a cycle, but the
7547 basic idea will be nearly the same. In the cyclic case the right-hand
7548 sides will be $v_k+w_k\theta_0$ instead of simply $v_k$, and we will start
7549 the process off with $u_0=v_0=0$, $w_0=1$. The final equation will be not
7550 $\theta_n=v_n$ but $\theta_n+u_n\theta_1=v_n+w_n\theta_0$; an appropriate
7551 ending routine will take account of the fact that $\theta_n=\theta_0$ and
7552 eliminate the $w$'s from the system, after which the solution can be
7553 obtained as before.
7554
7555 When $u_k$, $v_k$, and $w_k$ are being computed, the three pointer
7556 variables |r|, |s|,~|t| will point respectively to knots |k-1|, |k|,
7557 and~|k+1|. The $u$'s and $w$'s are scaled by $2^{28}$, i.e., they are
7558 of type |fraction|; the $\theta$'s and $v$'s are of type |angle|.
7559
7560 @<Glob...@>=
7561 angle *theta; /* values of $\theta_k$ */
7562 fraction *uu; /* values of $u_k$ */
7563 angle *vv; /* values of $v_k$ */
7564 fraction *ww; /* values of $w_k$ */
7565
7566 @ @<Dealloc variables@>=
7567 xfree(mp->theta);
7568 xfree(mp->uu);
7569 xfree(mp->vv);
7570 xfree(mp->ww);
7571
7572 @ @<Declarations@>=
7573 static void mp_reallocate_paths (MP mp, int l);
7574
7575 @ @c
7576 void mp_reallocate_paths (MP mp, int l) {
7577   XREALLOC (mp->delta_x, l, scaled);
7578   XREALLOC (mp->delta_y, l, scaled);
7579   XREALLOC (mp->delta,   l, scaled);
7580   XREALLOC (mp->psi,     l, angle);
7581   XREALLOC (mp->theta,   l, angle);
7582   XREALLOC (mp->uu,      l, fraction);
7583   XREALLOC (mp->vv,      l, angle);
7584   XREALLOC (mp->ww,      l, fraction);
7585   mp->path_size = l;
7586 }
7587
7588 @ Our immediate problem is to get the ball rolling by setting up the
7589 first equation or by realizing that no equations are needed, and to fit
7590 this initialization into a framework suitable for the overall computation.
7591
7592 @<Declarations@>=
7593 static void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) ;
7594
7595 @ @c
7596 void mp_solve_choices (MP mp,pointer p, pointer q, halfword n) {
7597   int k; /* current knot number */
7598   pointer r,s,t; /* registers for list traversal */
7599   @<Other local variables for |solve_choices|@>;
7600   k=0; s=p; r=0;
7601   while (1) { 
7602     t=mp_link(s);
7603     if ( k==0 ) {
7604       @<Get the linear equations started; or |return|
7605         with the control points in place, if linear equations
7606         needn't be solved@>
7607     } else  { 
7608       switch (mp_left_type(s)) {
7609       case mp_end_cycle: case mp_open:
7610         @<Set up equation to match mock curvatures
7611           at $z_k$; then |goto found| with $\theta_n$
7612           adjusted to equal $\theta_0$, if a cycle has ended@>;
7613         break;
7614       case mp_curl:
7615         @<Set up equation for a curl at $\theta_n$
7616           and |goto found|@>;
7617         break;
7618       case mp_given:
7619         @<Calculate the given value of $\theta_n$
7620           and |goto found|@>;
7621         break;
7622       } /* there are no other cases */
7623     }
7624     r=s; s=t; incr(k);
7625   }
7626 FOUND:
7627   @<Finish choosing angles and assigning control points@>;
7628 }
7629
7630 @ On the first time through the loop, we have |k=0| and |r| is not yet
7631 defined. The first linear equation, if any, will have $A_0=B_0=0$.
7632
7633 @<Get the linear equations started...@>=
7634 switch (mp_right_type(s)) {
7635 case mp_given: 
7636   if ( mp_left_type(t)==mp_given ) {
7637     @<Reduce to simple case of two givens  and |return|@>
7638   } else {
7639     @<Set up the equation for a given value of $\theta_0$@>;
7640   }
7641   break;
7642 case mp_curl: 
7643   if ( mp_left_type(t)==mp_curl ) {
7644     @<Reduce to simple case of straight line and |return|@>
7645   } else {
7646     @<Set up the equation for a curl at $\theta_0$@>;
7647   }
7648   break;
7649 case mp_open: 
7650   mp->uu[0]=0; mp->vv[0]=0; mp->ww[0]=fraction_one;
7651   /* this begins a cycle */
7652   break;
7653 } /* there are no other cases */
7654
7655 @ The general equation that specifies equality of mock curvature at $z_k$ is
7656 $$A_k\theta_{k-1}+(B_k+C_k)\theta_k+D_k\theta\k=-B_k\psi_k-D_k\psi\k,$$
7657 as derived above. We want to combine this with the already-derived equation
7658 $\theta_{k-1}+u_{k-1}\theta_k=v_{k-1}+w_{k-1}\theta_0$ in order to obtain
7659 a new equation
7660 $\theta_k+u_k\theta\k=v_k+w_k\theta_0$. This can be done by dividing the
7661 equation
7662 $$(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}
7663     -A_kw_{k-1}\theta_0$$
7664 by $B_k-u_{k-1}A_k+C_k$. The trick is to do this carefully with
7665 fixed-point arithmetic, avoiding the chance of overflow while retaining
7666 suitable precision.
7667
7668 The calculations will be performed in several registers that
7669 provide temporary storage for intermediate quantities.
7670
7671 @<Other local variables for |solve_choices|@>=
7672 fraction aa,bb,cc,ff,acc; /* temporary registers */
7673 scaled dd,ee; /* likewise, but |scaled| */
7674 scaled lt,rt; /* tension values */
7675
7676 @ @<Set up equation to match mock curvatures...@>=
7677 { @<Calculate the values $\\{aa}=A_k/B_k$, $\\{bb}=D_k/C_k$,
7678     $\\{dd}=(3-\alpha_{k-1})d_{k,k+1}$, $\\{ee}=(3-\beta\k)d_{k-1,k}$,
7679     and $\\{cc}=(B_k-u_{k-1}A_k)/B_k$@>;
7680   @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>;
7681   mp->uu[k]=mp_take_fraction(mp, ff,bb);
7682   @<Calculate the values of $v_k$ and $w_k$@>;
7683   if ( mp_left_type(s)==mp_end_cycle ) {
7684     @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>;
7685   }
7686 }
7687
7688 @ Since tension values are never less than 3/4, the values |aa| and
7689 |bb| computed here are never more than 4/5.
7690
7691 @<Calculate the values $\\{aa}=...@>=
7692 if ( abs(right_tension(r))==unity) { 
7693   aa=fraction_half; dd=2*mp->delta[k];
7694 } else { 
7695   aa=mp_make_fraction(mp, unity,3*abs(right_tension(r))-unity);
7696   dd=mp_take_fraction(mp, mp->delta[k],
7697     fraction_three-mp_make_fraction(mp, unity,abs(right_tension(r))));
7698 }
7699 if ( abs(left_tension(t))==unity ){ 
7700   bb=fraction_half; ee=2*mp->delta[k-1];
7701 } else { 
7702   bb=mp_make_fraction(mp, unity,3*abs(left_tension(t))-unity);
7703   ee=mp_take_fraction(mp, mp->delta[k-1],
7704     fraction_three-mp_make_fraction(mp, unity,abs(left_tension(t))));
7705 }
7706 cc=fraction_one-mp_take_fraction(mp, mp->uu[k-1],aa)
7707
7708 @ The ratio to be calculated in this step can be written in the form
7709 $$\beta_k^2\cdot\\{ee}\over\beta_k^2\cdot\\{ee}+\alpha_k^2\cdot
7710   \\{cc}\cdot\\{dd},$$
7711 because of the quantities just calculated. The values of |dd| and |ee|
7712 will not be needed after this step has been performed.
7713
7714 @<Calculate the ratio $\\{ff}=C_k/(C_k+B_k-u_{k-1}A_k)$@>=
7715 dd=mp_take_fraction(mp, dd,cc); lt=abs(left_tension(s)); rt=abs(right_tension(s));
7716 if ( lt!=rt ) { /* $\beta_k^{-1}\ne\alpha_k^{-1}$ */
7717   if ( lt<rt ) { 
7718     ff=mp_make_fraction(mp, lt,rt);
7719     ff=mp_take_fraction(mp, ff,ff); /* $\alpha_k^2/\beta_k^2$ */
7720     dd=mp_take_fraction(mp, dd,ff);
7721   } else { 
7722     ff=mp_make_fraction(mp, rt,lt);
7723     ff=mp_take_fraction(mp, ff,ff); /* $\beta_k^2/\alpha_k^2$ */
7724     ee=mp_take_fraction(mp, ee,ff);
7725   }
7726 }
7727 ff=mp_make_fraction(mp, ee,ee+dd)
7728
7729 @ The value of $u_{k-1}$ will be |<=1| except when $k=1$ and the previous
7730 equation was specified by a curl. In that case we must use a special
7731 method of computation to prevent overflow.
7732
7733 Fortunately, the calculations turn out to be even simpler in this ``hard''
7734 case. The curl equation makes $w_0=0$ and $v_0=-u_0\psi_1$, hence
7735 $-B_1\psi_1-A_1v_0=-(B_1-u_0A_1)\psi_1=-\\{cc}\cdot B_1\psi_1$.
7736
7737 @<Calculate the values of $v_k$ and $w_k$@>=
7738 acc=-mp_take_fraction(mp, mp->psi[k+1],mp->uu[k]);
7739 if ( mp_right_type(r)==mp_curl ) { 
7740   mp->ww[k]=0;
7741   mp->vv[k]=acc-mp_take_fraction(mp, mp->psi[1],fraction_one-ff);
7742 } else { 
7743   ff=mp_make_fraction(mp, fraction_one-ff,cc); /* this is
7744     $B_k/(C_k+B_k-u_{k-1}A_k)<5$ */
7745   acc=acc-mp_take_fraction(mp, mp->psi[k],ff);
7746   ff=mp_take_fraction(mp, ff,aa); /* this is $A_k/(C_k+B_k-u_{k-1}A_k)$ */
7747   mp->vv[k]=acc-mp_take_fraction(mp, mp->vv[k-1],ff);
7748   if ( mp->ww[k-1]==0 ) mp->ww[k]=0;
7749   else mp->ww[k]=-mp_take_fraction(mp, mp->ww[k-1],ff);
7750 }
7751
7752 @ When a complete cycle has been traversed, we have $\theta_k+u_k\theta\k=
7753 v_k+w_k\theta_0$, for |1<=k<=n|. We would like to determine the value of
7754 $\theta_n$ and reduce the system to the form $\theta_k+u_k\theta\k=v_k$
7755 for |0<=k<n|, so that the cyclic case can be finished up just as if there
7756 were no cycle.
7757
7758 The idea in the following code is to observe that
7759 $$\eqalign{\theta_n&=v_n+w_n\theta_0-u_n\theta_1=\cdots\cr
7760 &=v_n+w_n\theta_0-u_n\bigl(v_1+w_1\theta_0-u_1(v_2+\cdots
7761   -u_{n-2}(v_{n-1}+w_{n-1}\theta_0-u_{n-1}\theta_0))\bigr),\cr}$$
7762 so we can solve for $\theta_n=\theta_0$.
7763
7764 @<Adjust $\theta_n$ to equal $\theta_0$ and |goto found|@>=
7765
7766 aa=0; bb=fraction_one; /* we have |k=n| */
7767 do {  decr(k);
7768 if ( k==0 ) k=n;
7769   aa=mp->vv[k]-mp_take_fraction(mp, aa,mp->uu[k]);
7770   bb=mp->ww[k]-mp_take_fraction(mp, bb,mp->uu[k]);
7771 } while (k!=n); /* now $\theta_n=\\{aa}+\\{bb}\cdot\theta_n$ */
7772 aa=mp_make_fraction(mp, aa,fraction_one-bb);
7773 mp->theta[n]=aa; mp->vv[0]=aa;
7774 for (k=1;k<=n-1;k++) {
7775   mp->vv[k]=mp->vv[k]+mp_take_fraction(mp, aa,mp->ww[k]);
7776 }
7777 goto FOUND;
7778 }
7779
7780 @ @d reduce_angle(A) if ( abs((A))>one_eighty_deg ) {
7781   if ( (A)>0 ) (A)=(A)-three_sixty_deg; else (A)=(A)+three_sixty_deg; }
7782
7783 @<Calculate the given value of $\theta_n$...@>=
7784
7785   mp->theta[n]=left_given(s)-mp_n_arg(mp, mp->delta_x[n-1],mp->delta_y[n-1]);
7786   reduce_angle(mp->theta[n]);
7787   goto FOUND;
7788 }
7789
7790 @ @<Set up the equation for a given value of $\theta_0$@>=
7791
7792   mp->vv[0]=right_given(s)-mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7793   reduce_angle(mp->vv[0]);
7794   mp->uu[0]=0; mp->ww[0]=0;
7795 }
7796
7797 @ @<Set up the equation for a curl at $\theta_0$@>=
7798 { cc=right_curl(s); lt=abs(left_tension(t)); rt=abs(right_tension(s));
7799   if ( (rt==unity)&&(lt==unity) )
7800     mp->uu[0]=mp_make_fraction(mp, cc+cc+unity,cc+two);
7801   else 
7802     mp->uu[0]=mp_curl_ratio(mp, cc,rt,lt);
7803   mp->vv[0]=-mp_take_fraction(mp, mp->psi[1],mp->uu[0]); mp->ww[0]=0;
7804 }
7805
7806 @ @<Set up equation for a curl at $\theta_n$...@>=
7807 { cc=left_curl(s); lt=abs(left_tension(s)); rt=abs(right_tension(r));
7808   if ( (rt==unity)&&(lt==unity) )
7809     ff=mp_make_fraction(mp, cc+cc+unity,cc+two);
7810   else 
7811     ff=mp_curl_ratio(mp, cc,lt,rt);
7812   mp->theta[n]=-mp_make_fraction(mp, mp_take_fraction(mp, mp->vv[n-1],ff),
7813     fraction_one-mp_take_fraction(mp, ff,mp->uu[n-1]));
7814   goto FOUND;
7815 }
7816
7817 @ The |curl_ratio| subroutine has three arguments, which our previous notation
7818 encourages us to call $\gamma$, $\alpha^{-1}$, and $\beta^{-1}$. It is
7819 a somewhat tedious program to calculate
7820 $${(3-\alpha)\alpha^2\gamma+\beta^3\over
7821   \alpha^3\gamma+(3-\beta)\beta^2},$$
7822 with the result reduced to 4 if it exceeds 4. (This reduction of curl
7823 is necessary only if the curl and tension are both large.)
7824 The values of $\alpha$ and $\beta$ will be at most~4/3.
7825
7826 @<Declarations@>=
7827 static fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7828                         scaled b_tension) ;
7829
7830 @ @c
7831 fraction mp_curl_ratio (MP mp,scaled gamma, scaled a_tension, 
7832                         scaled b_tension) {
7833   fraction alpha,beta,num,denom,ff; /* registers */
7834   alpha=mp_make_fraction(mp, unity,a_tension);
7835   beta=mp_make_fraction(mp, unity,b_tension);
7836   if ( alpha<=beta ) {
7837     ff=mp_make_fraction(mp, alpha,beta); ff=mp_take_fraction(mp, ff,ff);
7838     gamma=mp_take_fraction(mp, gamma,ff);
7839     beta=beta / 010000; /* convert |fraction| to |scaled| */
7840     denom=mp_take_fraction(mp, gamma,alpha)+three-beta;
7841     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7842   } else { 
7843     ff=mp_make_fraction(mp, beta,alpha); ff=mp_take_fraction(mp, ff,ff);
7844     beta=mp_take_fraction(mp, beta,ff) / 010000; /* convert |fraction| to |scaled| */
7845     denom=mp_take_fraction(mp, gamma,alpha)+(ff / 1365)-beta;
7846       /* $1365\approx 2^{12}/3$ */
7847     num=mp_take_fraction(mp, gamma,fraction_three-alpha)+beta;
7848   }
7849   if ( num>=denom+denom+denom+denom ) return fraction_four;
7850   else return mp_make_fraction(mp, num,denom);
7851 }
7852
7853 @ We're in the home stretch now.
7854
7855 @<Finish choosing angles and assigning control points@>=
7856 for (k=n-1;k>=0;k--) {
7857   mp->theta[k]=mp->vv[k]-mp_take_fraction(mp,mp->theta[k+1],mp->uu[k]);
7858 }
7859 s=p; k=0;
7860 do {  
7861   t=mp_link(s);
7862   mp_n_sin_cos(mp, mp->theta[k]); mp->st=mp->n_sin; mp->ct=mp->n_cos;
7863   mp_n_sin_cos(mp, -mp->psi[k+1]-mp->theta[k+1]); mp->sf=mp->n_sin; mp->cf=mp->n_cos;
7864   mp_set_controls(mp, s,t,k);
7865   incr(k); s=t;
7866 } while (k!=n)
7867
7868 @ The |set_controls| routine actually puts the control points into
7869 a pair of consecutive nodes |p| and~|q|. Global variables are used to
7870 record the values of $\sin\theta$, $\cos\theta$, $\sin\phi$, and
7871 $\cos\phi$ needed in this calculation.
7872
7873 @<Glob...@>=
7874 fraction st;
7875 fraction ct;
7876 fraction sf;
7877 fraction cf; /* sines and cosines */
7878
7879 @ @<Declarations@>=
7880 static void mp_set_controls (MP mp,pointer p, pointer q, integer k);
7881
7882 @ @c
7883 void mp_set_controls (MP mp,pointer p, pointer q, integer k) {
7884   fraction rr,ss; /* velocities, divided by thrice the tension */
7885   scaled lt,rt; /* tensions */
7886   fraction sine; /* $\sin(\theta+\phi)$ */
7887   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7888   rr=mp_velocity(mp, mp->st,mp->ct,mp->sf,mp->cf,rt);
7889   ss=mp_velocity(mp, mp->sf,mp->cf,mp->st,mp->ct,lt);
7890   if ( (right_tension(p)<0)||(left_tension(q)<0) ) {
7891     @<Decrease the velocities,
7892       if necessary, to stay inside the bounding triangle@>;
7893   }
7894   mp_right_x(p)=mp_x_coord(p)+mp_take_fraction(mp, 
7895                           mp_take_fraction(mp, mp->delta_x[k],mp->ct)-
7896                           mp_take_fraction(mp, mp->delta_y[k],mp->st),rr);
7897   mp_right_y(p)=mp_y_coord(p)+mp_take_fraction(mp, 
7898                           mp_take_fraction(mp, mp->delta_y[k],mp->ct)+
7899                           mp_take_fraction(mp, mp->delta_x[k],mp->st),rr);
7900   mp_left_x(q)=mp_x_coord(q)-mp_take_fraction(mp, 
7901                          mp_take_fraction(mp, mp->delta_x[k],mp->cf)+
7902                          mp_take_fraction(mp, mp->delta_y[k],mp->sf),ss);
7903   mp_left_y(q)=mp_y_coord(q)-mp_take_fraction(mp, 
7904                          mp_take_fraction(mp, mp->delta_y[k],mp->cf)-
7905                          mp_take_fraction(mp, mp->delta_x[k],mp->sf),ss);
7906   mp_right_type(p)=mp_explicit; mp_left_type(q)=mp_explicit;
7907 }
7908
7909 @ The boundedness conditions $\\{rr}\L\sin\phi\,/\sin(\theta+\phi)$ and
7910 $\\{ss}\L\sin\theta\,/\sin(\theta+\phi)$ are to be enforced if $\sin\theta$,
7911 $\sin\phi$, and $\sin(\theta+\phi)$ all have the same sign. Otherwise
7912 there is no ``bounding triangle.''
7913
7914 @<Decrease the velocities, if necessary...@>=
7915 if (((mp->st>=0)&&(mp->sf>=0))||((mp->st<=0)&&(mp->sf<=0)) ) {
7916   sine=mp_take_fraction(mp, abs(mp->st),mp->cf)+
7917                             mp_take_fraction(mp, abs(mp->sf),mp->ct);
7918   if ( sine>0 ) {
7919     sine=mp_take_fraction(mp, sine,fraction_one+unity); /* safety factor */
7920     if ( right_tension(p)<0 )
7921      if ( mp_ab_vs_cd(mp, abs(mp->sf),fraction_one,rr,sine)<0 )
7922       rr=mp_make_fraction(mp, abs(mp->sf),sine);
7923     if ( left_tension(q)<0 )
7924      if ( mp_ab_vs_cd(mp, abs(mp->st),fraction_one,ss,sine)<0 )
7925       ss=mp_make_fraction(mp, abs(mp->st),sine);
7926   }
7927 }
7928
7929 @ Only the simple cases remain to be handled.
7930
7931 @<Reduce to simple case of two givens and |return|@>=
7932
7933   aa=mp_n_arg(mp, mp->delta_x[0],mp->delta_y[0]);
7934   mp_n_sin_cos(mp, right_given(p)-aa); mp->ct=mp->n_cos; mp->st=mp->n_sin;
7935   mp_n_sin_cos(mp, left_given(q)-aa); mp->cf=mp->n_cos; mp->sf=-mp->n_sin;
7936   mp_set_controls(mp, p,q,0); return;
7937 }
7938
7939 @ @<Reduce to simple case of straight line and |return|@>=
7940
7941   mp_right_type(p)=mp_explicit; mp_left_type(q)=mp_explicit;
7942   lt=abs(left_tension(q)); rt=abs(right_tension(p));
7943   if ( rt==unity ) {
7944     if ( mp->delta_x[0]>=0 ) mp_right_x(p)=mp_x_coord(p)+((mp->delta_x[0]+1) / 3);
7945     else mp_right_x(p)=mp_x_coord(p)+((mp->delta_x[0]-1) / 3);
7946     if ( mp->delta_y[0]>=0 ) mp_right_y(p)=mp_y_coord(p)+((mp->delta_y[0]+1) / 3);
7947     else mp_right_y(p)=mp_y_coord(p)+((mp->delta_y[0]-1) / 3);
7948   } else { 
7949     ff=mp_make_fraction(mp, unity,3*rt); /* $\alpha/3$ */
7950     mp_right_x(p)=mp_x_coord(p)+mp_take_fraction(mp, mp->delta_x[0],ff);
7951     mp_right_y(p)=mp_y_coord(p)+mp_take_fraction(mp, mp->delta_y[0],ff);
7952   }
7953   if ( lt==unity ) {
7954     if ( mp->delta_x[0]>=0 ) mp_left_x(q)=mp_x_coord(q)-((mp->delta_x[0]+1) / 3);
7955     else mp_left_x(q)=mp_x_coord(q)-((mp->delta_x[0]-1) / 3);
7956     if ( mp->delta_y[0]>=0 ) mp_left_y(q)=mp_y_coord(q)-((mp->delta_y[0]+1) / 3);
7957     else mp_left_y(q)=mp_y_coord(q)-((mp->delta_y[0]-1) / 3);
7958   } else  { 
7959     ff=mp_make_fraction(mp, unity,3*lt); /* $\beta/3$ */
7960     mp_left_x(q)=mp_x_coord(q)-mp_take_fraction(mp, mp->delta_x[0],ff);
7961     mp_left_y(q)=mp_y_coord(q)-mp_take_fraction(mp, mp->delta_y[0],ff);
7962   }
7963   return;
7964 }
7965
7966 @* \[19] Measuring paths.
7967 \MP's \&{llcorner}, \&{lrcorner}, \&{ulcorner}, and \&{urcorner} operators
7968 allow the user to measure the bounding box of anything that can go into a
7969 picture.  It's easy to get rough bounds on the $x$ and $y$ extent of a path
7970 by just finding the bounding box of the knots and the control points. We
7971 need a more accurate version of the bounding box, but we can still use the
7972 easy estimate to save time by focusing on the interesting parts of the path.
7973
7974 @ Computing an accurate bounding box involves a theme that will come up again
7975 and again. Given a Bernshte{\u\i}n polynomial
7976 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
7977 $$B(z_0,z_1,\ldots,z_n;t)=\sum_k{n\choose k}t^k(1-t)^{n-k}z_k,$$
7978 we can conveniently bisect its range as follows:
7979
7980 \smallskip
7981 \textindent{1)} Let $z_k^{(0)}=z_k$, for |0<=k<=n|.
7982
7983 \smallskip
7984 \textindent{2)} Let $z_k^{(j+1)}={1\over2}(z_k^{(j)}+z\k^{(j)})$, for
7985 |0<=k<n-j|, for |0<=j<n|.
7986
7987 \smallskip\noindent
7988 Then
7989 $$B(z_0,z_1,\ldots,z_n;t)=B(z_0^{(0)},z_0^{(1)},\ldots,z_0^{(n)};2t)
7990  =B(z_0^{(n)},z_1^{(n-1)},\ldots,z_n^{(0)};2t-1).$$
7991 This formula gives us the coefficients of polynomials to use over the ranges
7992 $0\L t\L{1\over2}$ and ${1\over2}\L t\L1$.
7993
7994 @ Now here's a subroutine that's handy for all sorts of path computations:
7995 Given a quadratic polynomial $B(a,b,c;t)$, the |crossing_point| function
7996 returns the unique |fraction| value |t| between 0 and~1 at which
7997 $B(a,b,c;t)$ changes from positive to negative, or returns
7998 |t=fraction_one+1| if no such value exists. If |a<0| (so that $B(a,b,c;t)$
7999 is already negative at |t=0|), |crossing_point| returns the value zero.
8000
8001 @d no_crossing {  return (fraction_one+1); }
8002 @d one_crossing { return fraction_one; }
8003 @d zero_crossing { return 0; }
8004 @d mp_crossing_point(M,A,B,C) mp_do_crossing_point(A,B,C)
8005
8006 @c static fraction mp_do_crossing_point (integer a, integer b, integer c) {
8007   integer d; /* recursive counter */
8008   integer x,xx,x0,x1,x2; /* temporary registers for bisection */
8009   if ( a<0 ) zero_crossing;
8010   if ( c>=0 ) { 
8011     if ( b>=0 ) {
8012       if ( c>0 ) { no_crossing; }
8013       else if ( (a==0)&&(b==0) ) { no_crossing;} 
8014       else { one_crossing; } 
8015     }
8016     if ( a==0 ) zero_crossing;
8017   } else if ( a==0 ) {
8018     if ( b<=0 ) zero_crossing;
8019   }
8020   @<Use bisection to find the crossing point, if one exists@>;
8021 }
8022
8023 @ The general bisection method is quite simple when $n=2$, hence
8024 |crossing_point| does not take much time. At each stage in the
8025 recursion we have a subinterval defined by |l| and~|j| such that
8026 $B(a,b,c;2^{-l}(j+t))=B(x_0,x_1,x_2;t)$, and we want to ``zero in'' on
8027 the subinterval where $x_0\G0$ and $\min(x_1,x_2)<0$.
8028
8029 It is convenient for purposes of calculation to combine the values
8030 of |l| and~|j| in a single variable $d=2^l+j$, because the operation
8031 of bisection then corresponds simply to doubling $d$ and possibly
8032 adding~1. Furthermore it proves to be convenient to modify
8033 our previous conventions for bisection slightly, maintaining the
8034 variables $X_0=2^lx_0$, $X_1=2^l(x_0-x_1)$, and $X_2=2^l(x_1-x_2)$.
8035 With these variables the conditions $x_0\ge0$ and $\min(x_1,x_2)<0$ are
8036 equivalent to $\max(X_1,X_1+X_2)>X_0\ge0$.
8037
8038 The following code maintains the invariant relations
8039 $0\L|x0|<\max(|x1|,|x1|+|x2|)$,
8040 $\vert|x1|\vert<2^{30}$, $\vert|x2|\vert<2^{30}$;
8041 it has been constructed in such a way that no arithmetic overflow
8042 will occur if the inputs satisfy
8043 $a<2^{30}$, $\vert a-b\vert<2^{30}$, and $\vert b-c\vert<2^{30}$.
8044
8045 @<Use bisection to find the crossing point...@>=
8046 d=1; x0=a; x1=a-b; x2=b-c;
8047 do {  
8048   x=half(x1+x2);
8049   if ( x1-x0>x0 ) { 
8050     x2=x; x0+=x0; d+=d;  
8051   } else { 
8052     xx=x1+x-x0;
8053     if ( xx>x0 ) { 
8054       x2=x; x0+=x0; d+=d;
8055     }  else { 
8056       x0=x0-xx;
8057       if ( x<=x0 ) { if ( x+x2<=x0 ) no_crossing; }
8058       x1=x; d=d+d+1;
8059     }
8060   }
8061 } while (d<fraction_one);
8062 return (d-fraction_one)
8063
8064 @ Here is a routine that computes the $x$ or $y$ coordinate of the point on
8065 a cubic corresponding to the |fraction| value~|t|.
8066
8067 It is convenient to define a \.{WEB} macro |t_of_the_way| such that
8068 |t_of_the_way(a,b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
8069
8070 @d t_of_the_way(A,B) ((A)-mp_take_fraction(mp,((A)-(B)),t))
8071
8072 @c static scaled mp_eval_cubic (MP mp,pointer p, pointer q, fraction t) {
8073   scaled x1,x2,x3; /* intermediate values */
8074   x1=t_of_the_way(knot_coord(p),right_coord(p));
8075   x2=t_of_the_way(right_coord(p),left_coord(q));
8076   x3=t_of_the_way(left_coord(q),knot_coord(q));
8077   x1=t_of_the_way(x1,x2);
8078   x2=t_of_the_way(x2,x3);
8079   return t_of_the_way(x1,x2);
8080 }
8081
8082 @ The actual bounding box information is stored in global variables.
8083 Since it is convenient to address the $x$ and $y$ information
8084 separately, we define arrays indexed by |x_code..y_code| and use
8085 macros to give them more convenient names.
8086
8087 @<Types...@>=
8088 enum mp_bb_code  {
8089   mp_x_code=0, /* index for |minx| and |maxx| */
8090   mp_y_code /* index for |miny| and |maxy| */
8091 } ;
8092
8093
8094 @d mp_minx mp->bbmin[mp_x_code]
8095 @d mp_maxx mp->bbmax[mp_x_code]
8096 @d mp_miny mp->bbmin[mp_y_code]
8097 @d mp_maxy mp->bbmax[mp_y_code]
8098
8099 @<Glob...@>=
8100 scaled bbmin[mp_y_code+1];
8101 scaled bbmax[mp_y_code+1]; 
8102 /* the result of procedures that compute bounding box information */
8103
8104 @ Now we're ready for the key part of the bounding box computation.
8105 The |bound_cubic| procedure updates |bbmin[c]| and |bbmax[c]| based on
8106 $$B(\hbox{|knot_coord(p)|}, \hbox{|right_coord(p)|},
8107     \hbox{|left_coord(q)|}, \hbox{|knot_coord(q)|};t)
8108 $$
8109 for $0<t\le1$.  In other words, the procedure adjusts the bounds to
8110 accommodate |knot_coord(q)| and any extremes over the range $0<t<1$.
8111 The |c| parameter is |x_code| or |y_code|.
8112
8113 @c static void mp_bound_cubic (MP mp,pointer p, pointer q, quarterword c) {
8114   boolean wavy; /* whether we need to look for extremes */
8115   scaled del1,del2,del3,del,dmax; /* proportional to the control
8116      points of a quadratic derived from a cubic */
8117   fraction t,tt; /* where a quadratic crosses zero */
8118   scaled x; /* a value that |bbmin[c]| and |bbmax[c]| must accommodate */
8119   x=knot_coord(q);
8120   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8121   @<Check the control points against the bounding box and set |wavy:=true|
8122     if any of them lie outside@>;
8123   if ( wavy ) {
8124     del1=right_coord(p)-knot_coord(p);
8125     del2=left_coord(q)-right_coord(p);
8126     del3=knot_coord(q)-left_coord(q);
8127     @<Scale up |del1|, |del2|, and |del3| for greater accuracy;
8128       also set |del| to the first nonzero element of |(del1,del2,del3)|@>;
8129     if ( del<0 ) {
8130       negate(del1); negate(del2); negate(del3);
8131     };
8132     t=mp_crossing_point(mp, del1,del2,del3);
8133     if ( t<fraction_one ) {
8134       @<Test the extremes of the cubic against the bounding box@>;
8135     }
8136   }
8137 }
8138
8139 @ @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>=
8140 if ( x<mp->bbmin[c] ) mp->bbmin[c]=x;
8141 if ( x>mp->bbmax[c] ) mp->bbmax[c]=x
8142
8143 @ @<Check the control points against the bounding box and set...@>=
8144 wavy=true;
8145 if ( mp->bbmin[c]<=right_coord(p) )
8146   if ( right_coord(p)<=mp->bbmax[c] )
8147     if ( mp->bbmin[c]<=left_coord(q) )
8148       if ( left_coord(q)<=mp->bbmax[c] )
8149         wavy=false
8150
8151 @ If |del1=del2=del3=0|, it's impossible to obey the title of this
8152 section. We just set |del=0| in that case.
8153
8154 @<Scale up |del1|, |del2|, and |del3| for greater accuracy...@>=
8155 if ( del1!=0 ) del=del1;
8156 else if ( del2!=0 ) del=del2;
8157 else del=del3;
8158 if ( del!=0 ) {
8159   dmax=abs(del1);
8160   if ( abs(del2)>dmax ) dmax=abs(del2);
8161   if ( abs(del3)>dmax ) dmax=abs(del3);
8162   while ( dmax<fraction_half ) {
8163     dmax+=dmax; del1+=del1; del2+=del2; del3+=del3;
8164   }
8165 }
8166
8167 @ Since |crossing_point| has tried to choose |t| so that
8168 $B(|del1|,|del2|,|del3|;\tau)$ crosses zero at $\tau=|t|$ with negative
8169 slope, the value of |del2| computed below should not be positive.
8170 But rounding error could make it slightly positive in which case we
8171 must cut it to zero to avoid confusion.
8172
8173 @<Test the extremes of the cubic against the bounding box@>=
8174
8175   x=mp_eval_cubic(mp, p,q,t);
8176   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8177   del2=t_of_the_way(del2,del3);
8178     /* now |0,del2,del3| represent the derivative on the remaining interval */
8179   if ( del2>0 ) del2=0;
8180   tt=mp_crossing_point(mp, 0,-del2,-del3);
8181   if ( tt<fraction_one ) {
8182     @<Test the second extreme against the bounding box@>;
8183   }
8184 }
8185
8186 @ @<Test the second extreme against the bounding box@>=
8187 {
8188    x=mp_eval_cubic(mp, p,q,t_of_the_way(tt,fraction_one));
8189   @<Adjust |bbmin[c]| and |bbmax[c]| to accommodate |x|@>;
8190 }
8191
8192 @ Finding the bounding box of a path is basically a matter of applying
8193 |bound_cubic| twice for each pair of adjacent knots.
8194
8195 @c static void mp_path_bbox (MP mp,pointer h) {
8196   pointer p,q; /* a pair of adjacent knots */
8197   mp_minx=mp_x_coord(h); mp_miny=mp_y_coord(h);
8198   mp_maxx=mp_minx; mp_maxy=mp_miny;
8199   p=h;
8200   do {  
8201     if ( mp_right_type(p)==mp_endpoint ) return;
8202     q=mp_link(p);
8203     mp_bound_cubic(mp, x_loc(p),x_loc(q),mp_x_code);
8204     mp_bound_cubic(mp, y_loc(p),y_loc(q),mp_y_code);
8205     p=q;
8206   } while (p!=h);
8207 }
8208
8209 @ Another important way to measure a path is to find its arc length.  This
8210 is best done by using the general bisection algorithm to subdivide the path
8211 until obtaining ``well behaved'' subpaths whose arc lengths can be approximated
8212 by simple means.
8213
8214 Since the arc length is the integral with respect to time of the magnitude of
8215 the velocity, it is natural to use Simpson's rule for the approximation.
8216 @^Simpson's rule@>
8217 If $\dot B(t)$ is the spline velocity, Simpson's rule gives
8218 $$ \vb\dot B(0)\vb + 4\vb\dot B({1\over2})\vb + \vb\dot B(1)\vb \over 6 $$
8219 for the arc length of a path of length~1.  For a cubic spline
8220 $B(z_0,z_1,z_2,z_3;t)$, the time derivative $\dot B(t)$ is
8221 $3B(dz_0,dz_1,dz_2;t)$, where $dz_i=z_{i+1}-z_i$.  Hence the arc length
8222 approximation is
8223 $$ {\vb dz_0\vb \over 2} + 2\vb dz_{02}\vb + {\vb dz_2\vb \over 2}, $$
8224 where
8225 $$ dz_{02}={1\over2}\left({dz_0+dz_1\over 2}+{dz_1+dz_2\over 2}\right)$$
8226 is the result of the bisection algorithm.
8227
8228 @ The remaining problem is how to decide when a subpath is ``well behaved.''
8229 This could be done via the theoretical error bound for Simpson's rule,
8230 @^Simpson's rule@>
8231 but this is impractical because it requires an estimate of the fourth
8232 derivative of the quantity being integrated.  It is much easier to just perform
8233 a bisection step and see how much the arc length estimate changes.  Since the
8234 error for Simpson's rule is proportional to the fourth power of the sample
8235 spacing, the remaining error is typically about $1\over16$ of the amount of
8236 the change.  We say ``typically'' because the error has a pseudo-random behavior
8237 that could cause the two estimates to agree when each contain large errors.
8238
8239 To protect against disasters such as undetected cusps, the bisection process
8240 should always continue until all the $dz_i$ vectors belong to a single
8241 $90^\circ$ sector.  This ensures that no point on the spline can have velocity
8242 less than 70\% of the minimum of $\vb dz_0\vb$, $\vb dz_1\vb$ and $\vb dz_2\vb$.
8243 If such a spline happens to produce an erroneous arc length estimate that
8244 is little changed by bisection, the amount of the error is likely to be fairly
8245 small.  We will try to arrange things so that freak accidents of this type do
8246 not destroy the inverse relationship between the \&{arclength} and
8247 \&{arctime} operations.
8248 @:arclength_}{\&{arclength} primitive@>
8249 @:arctime_}{\&{arctime} primitive@>
8250
8251 @ The \&{arclength} and \&{arctime} operations are both based on a recursive
8252 @^recursion@>
8253 function that finds the arc length of a cubic spline given $dz_0$, $dz_1$,
8254 $dz_2$. This |arc_test| routine also takes an arc length goal |a_goal| and
8255 returns the time when the arc length reaches |a_goal| if there is such a time.
8256 Thus the return value is either an arc length less than |a_goal| or, if the
8257 arc length would be at least |a_goal|, it returns a time value decreased by
8258 |two|.  This allows the caller to use the sign of the result to distinguish
8259 between arc lengths and time values.  On certain types of overflow, it is
8260 possible for |a_goal| and the result of |arc_test| both to be |el_gordo|.
8261 Otherwise, the result is always less than |a_goal|.
8262
8263 Rather than halving the control point coordinates on each recursive call to
8264 |arc_test|, it is better to keep them proportional to velocity on the original
8265 curve and halve the results instead.  This means that recursive calls can
8266 potentially use larger error tolerances in their arc length estimates.  How
8267 much larger depends on to what extent the errors behave as though they are
8268 independent of each other.  To save computing time, we use optimistic assumptions
8269 and increase the tolerance by a factor of about $\sqrt2$ for each recursive
8270 call.
8271
8272 In addition to the tolerance parameter, |arc_test| should also have parameters
8273 for ${1\over3}\vb\dot B(0)\vb$, ${2\over3}\vb\dot B({1\over2})\vb$, and
8274 ${1\over3}\vb\dot B(1)\vb$.  These quantities are relatively expensive to compute
8275 and they are needed in different instances of |arc_test|.
8276
8277 @c 
8278 static scaled mp_arc_test (MP mp, scaled dx0, scaled dy0, scaled dx1, scaled dy1, 
8279                     scaled dx2, scaled dy2, scaled  v0, scaled v02, 
8280                     scaled v2, scaled a_goal, scaled tol) {
8281   boolean simple; /* are the control points confined to a $90^\circ$ sector? */
8282   scaled dx01, dy01, dx12, dy12, dx02, dy02;  /* bisection results */
8283   scaled v002, v022;
8284     /* twice the velocity magnitudes at $t={1\over4}$ and $t={3\over4}$ */
8285   scaled arc; /* best arc length estimate before recursion */
8286   @<Other local variables in |arc_test|@>;
8287   @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,
8288     |dx2|, |dy2|@>;
8289   @<Initialize |v002|, |v022|, and the arc length estimate |arc|; if it overflows
8290     set |arc_test| and |return|@>;
8291   @<Test if the control points are confined to one quadrant or rotating them
8292     $45^\circ$ would put them in one quadrant.  Then set |simple| appropriately@>;
8293   if ( simple && (abs(arc-v02-halfp(v0+v2)) <= tol) ) {
8294     if ( arc < a_goal ) {
8295       return arc;
8296     } else {
8297        @<Estimate when the arc length reaches |a_goal| and set |arc_test| to
8298          that time minus |two|@>;
8299     }
8300   } else {
8301     @<Use one or two recursive calls to compute the |arc_test| function@>;
8302   }
8303 }
8304
8305 @ The |tol| value should by multiplied by $\sqrt 2$ before making recursive
8306 calls, but $1.5$ is an adequate approximation.  It is best to avoid using
8307 |make_fraction| in this inner loop.
8308 @^inner loop@>
8309
8310 @<Use one or two recursive calls to compute the |arc_test| function@>=
8311
8312   @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is as
8313     large as possible@>;
8314   tol = tol + halfp(tol);
8315   a = mp_arc_test(mp, dx0,dy0, dx01,dy01, dx02,dy02, v0, v002, 
8316                   halfp(v02), a_new, tol);
8317   if ( a<0 )  {
8318      return (-halfp(two-a));
8319   } else { 
8320     @<Update |a_new| to reduce |a_new+a_aux| by |a|@>;
8321     b = mp_arc_test(mp, dx02,dy02, dx12,dy12, dx2,dy2,
8322                     halfp(v02), v022, v2, a_new, tol);
8323     if ( b<0 )  
8324       return (-halfp(-b) - half_unit);
8325     else  
8326       return (a + half(b-a));
8327   }
8328 }
8329
8330 @ @<Other local variables in |arc_test|@>=
8331 scaled a,b; /* results of recursive calls */
8332 scaled a_new,a_aux; /* the sum of these gives the |a_goal| */
8333
8334 @ @<Set |a_new| and |a_aux| so their sum is |2*a_goal| and |a_new| is...@>=
8335 a_aux = el_gordo - a_goal;
8336 if ( a_goal > a_aux ) {
8337   a_aux = a_goal - a_aux;
8338   a_new = el_gordo;
8339 } else { 
8340   a_new = a_goal + a_goal;
8341   a_aux = 0;
8342 }
8343
8344 @ There is no need to maintain |a_aux| at this point so we use it as a temporary
8345 to force the additions and subtractions to be done in an order that avoids
8346 overflow.
8347
8348 @<Update |a_new| to reduce |a_new+a_aux| by |a|@>=
8349 if ( a > a_aux ) {
8350   a_aux = a_aux - a;
8351   a_new = a_new + a_aux;
8352 }
8353
8354 @ This code assumes all {\it dx} and {\it dy} variables have magnitude less than
8355 |fraction_four|.  To simplify the rest of the |arc_test| routine, we strengthen
8356 this assumption by requiring the norm of each $({\it dx},{\it dy})$ pair to obey
8357 this bound.  Note that recursive calls will maintain this invariant.
8358
8359 @<Bisect the B\'ezier quadratic given by |dx0|, |dy0|, |dx1|, |dy1|,...@>=
8360 dx01 = half(dx0 + dx1);
8361 dx12 = half(dx1 + dx2);
8362 dx02 = half(dx01 + dx12);
8363 dy01 = half(dy0 + dy1);
8364 dy12 = half(dy1 + dy2);
8365 dy02 = half(dy01 + dy12)
8366
8367 @ We should be careful to keep |arc<el_gordo| so that calling |arc_test| with
8368 |a_goal=el_gordo| is guaranteed to yield the arc length.
8369
8370 @<Initialize |v002|, |v022|, and the arc length estimate |arc|;...@>=
8371 v002 = mp_pyth_add(mp, dx01+half(dx0+dx02), dy01+half(dy0+dy02));
8372 v022 = mp_pyth_add(mp, dx12+half(dx02+dx2), dy12+half(dy02+dy2));
8373 tmp = halfp(v02+2);
8374 arc1 = v002 + half(halfp(v0+tmp) - v002);
8375 arc = v022 + half(halfp(v2+tmp) - v022);
8376 if ( (arc < el_gordo-arc1) )  {
8377   arc = arc+arc1;
8378 } else { 
8379   mp->arith_error = true;
8380   if ( a_goal==el_gordo )  return (el_gordo);
8381   else return (-two);
8382 }
8383
8384 @ @<Other local variables in |arc_test|@>=
8385 scaled tmp, tmp2; /* all purpose temporary registers */
8386 scaled arc1; /* arc length estimate for the first half */
8387
8388 @ @<Test if the control points are confined to one quadrant or rotating...@>=
8389 simple = ((dx0>=0) && (dx1>=0) && (dx2>=0)) ||
8390          ((dx0<=0) && (dx1<=0) && (dx2<=0));
8391 if ( simple )
8392   simple = ((dy0>=0) && (dy1>=0) && (dy2>=0)) ||
8393            ((dy0<=0) && (dy1<=0) && (dy2<=0));
8394 if ( ! simple ) {
8395   simple = ((dx0>=dy0) && (dx1>=dy1) && (dx2>=dy2)) ||
8396            ((dx0<=dy0) && (dx1<=dy1) && (dx2<=dy2));
8397   if ( simple ) 
8398     simple = ((-dx0>=dy0) && (-dx1>=dy1) && (-dx2>=dy2)) ||
8399              ((-dx0<=dy0) && (-dx1<=dy1) && (-dx2<=dy2));
8400 }
8401
8402 @ Since Simpson's rule is based on approximating the integrand by a parabola,
8403 @^Simpson's rule@>
8404 it is appropriate to use the same approximation to decide when the integral
8405 reaches the intermediate value |a_goal|.  At this point
8406 $$\eqalign{
8407     {\vb\dot B(0)\vb\over 3} &= \hbox{|v0|}, \qquad
8408     {\vb\dot B({1\over4})\vb\over 3} = {\hbox{|v002|}\over 2}, \qquad
8409     {\vb\dot B({1\over2})\vb\over 3} = {\hbox{|v02|}\over 2}, \cr
8410     {\vb\dot B({3\over4})\vb\over 3} &= {\hbox{|v022|}\over 2}, \qquad
8411     {\vb\dot B(1)\vb\over 3} = \hbox{|v2|} \cr
8412 }
8413 $$
8414 and
8415 $$ {\vb\dot B(t)\vb\over 3} \approx
8416   \cases{B\left(\hbox{|v0|},
8417       \hbox{|v002|}-{1\over 2}\hbox{|v0|}-{1\over 4}\hbox{|v02|},
8418       {1\over 2}\hbox{|v02|}; 2t \right)&
8419     if $t\le{1\over 2}$\cr
8420   B\left({1\over 2}\hbox{|v02|},
8421       \hbox{|v022|}-{1\over 4}\hbox{|v02|}-{1\over 2}\hbox{|v2|},
8422       \hbox{|v2|}; 2t-1 \right)&
8423     if $t\ge{1\over 2}$.\cr}
8424  \eqno (*)
8425 $$
8426 We can integrate $\vb\dot B(t)\vb$ by using
8427 $$\int 3B(a,b,c;\tau)\,dt =
8428   {B(0,a,a+b,a+b+c;\tau) + {\rm constant} \over {d\tau\over dt}}.
8429 $$
8430
8431 This construction allows us to find the time when the arc length reaches
8432 |a_goal| by solving a cubic equation of the form
8433 $$ B(0,a,a+b,a+b+c;\tau) = x, $$
8434 where $\tau$ is $2t$ or $2t+1$, $x$ is |a_goal| or |a_goal-arc1|, and $a$, $b$,
8435 and $c$ are the Bernshte{\u\i}n coefficients from $(*)$ divided by
8436 @^Bernshte{\u\i}n, Serge{\u\i} Natanovich@>
8437 $d\tau\over dt$.  We shall define a function |solve_rising_cubic| that finds
8438 $\tau$ given $a$, $b$, $c$, and $x$.
8439
8440 @<Estimate when the arc length reaches |a_goal| and set |arc_test| to...@>=
8441
8442   tmp = (v02 + 2) / 4;
8443   if ( a_goal<=arc1 ) {
8444     tmp2 = halfp(v0);
8445     return 
8446       (halfp(mp_solve_rising_cubic(mp, tmp2, arc1-tmp2-tmp, tmp, a_goal))- two);
8447   } else { 
8448     tmp2 = halfp(v2);
8449     return ((half_unit - two) +
8450       halfp(mp_solve_rising_cubic(mp, tmp, arc-arc1-tmp-tmp2, tmp2, a_goal-arc1)));
8451   }
8452 }
8453
8454 @ Here is the |solve_rising_cubic| routine that finds the time~$t$ when
8455 $$ B(0, a, a+b, a+b+c; t) = x. $$
8456 This routine is based on |crossing_point| but is simplified by the
8457 assumptions that $B(a,b,c;t)\ge0$ for $0\le t\le1$ and that |0<=x<=a+b+c|.
8458 If rounding error causes this condition to be violated slightly, we just ignore
8459 it and proceed with binary search.  This finds a time when the function value
8460 reaches |x| and the slope is positive.
8461
8462 @<Declarations@>=
8463 static scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) ;
8464
8465 @ @c
8466 scaled mp_solve_rising_cubic (MP mp,scaled a, scaled b,  scaled c, scaled x) {
8467   scaled ab, bc, ac; /* bisection results */
8468   integer t; /* $2^k+q$ where unscaled answer is in $[q2^{-k},(q+1)2^{-k})$ */
8469   integer xx; /* temporary for updating |x| */
8470   if ( (a<0) || (c<0) ) mp_confusion(mp, "rising?");
8471 @:this can't happen rising?}{\quad rising?@>
8472   if ( x<=0 ) {
8473         return 0;
8474   } else if ( x >= a+b+c ) {
8475     return unity;
8476   } else { 
8477     t = 1;
8478     @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than
8479       |el_gordo div 3|@>;
8480     do {  
8481       t+=t;
8482       @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>;
8483       xx = x - a - ab - ac;
8484       if ( xx < -x ) { x+=x; b=ab; c=ac;  }
8485       else { x = x + xx;  a=ac; b=bc; t = t+1; };
8486     } while (t < unity);
8487     return (t - unity);
8488   }
8489 }
8490
8491 @ @<Subdivide the B\'ezier quadratic defined by |a|, |b|, |c|@>=
8492 ab = half(a+b);
8493 bc = half(b+c);
8494 ac = half(ab+bc)
8495
8496 @ @d one_third_el_gordo 05252525252 /* upper bound on |a|, |b|, and |c| */
8497
8498 @<Rescale if necessary to make sure |a|, |b|, and |c| are all less than...@>=
8499 while ((a>one_third_el_gordo)||(b>one_third_el_gordo)||(c>one_third_el_gordo)) { 
8500   a = halfp(a);
8501   b = half(b);
8502   c = halfp(c);
8503   x = halfp(x);
8504 }
8505
8506 @ It is convenient to have a simpler interface to |arc_test| that requires no
8507 unnecessary arguments and ensures that each $({\it dx},{\it dy})$ pair has
8508 length less than |fraction_four|.
8509
8510 @d arc_tol   16  /* quit when change in arc length estimate reaches this */
8511
8512 @c static scaled mp_do_arc_test (MP mp,scaled dx0, scaled dy0, scaled dx1, 
8513                           scaled dy1, scaled dx2, scaled dy2, scaled a_goal) {
8514   scaled v0,v1,v2; /* length of each $({\it dx},{\it dy})$ pair */
8515   scaled v02; /* twice the norm of the quadratic at $t={1\over2}$ */
8516   v0 = mp_pyth_add(mp, dx0,dy0);
8517   v1 = mp_pyth_add(mp, dx1,dy1);
8518   v2 = mp_pyth_add(mp, dx2,dy2);
8519   if ( (v0>=fraction_four) || (v1>=fraction_four) || (v2>=fraction_four) ) { 
8520     mp->arith_error = true;
8521     if ( a_goal==el_gordo )  return el_gordo;
8522     else return (-two);
8523   } else { 
8524     v02 = mp_pyth_add(mp, dx1+half(dx0+dx2), dy1+half(dy0+dy2));
8525     return (mp_arc_test(mp, dx0,dy0, dx1,dy1, dx2,dy2,
8526                                  v0, v02, v2, a_goal, arc_tol));
8527   }
8528 }
8529
8530 @ Now it is easy to find the arc length of an entire path.
8531
8532 @c static scaled mp_get_arc_length (MP mp,pointer h) {
8533   pointer p,q; /* for traversing the path */
8534   scaled a,a_tot; /* current and total arc lengths */
8535   a_tot = 0;
8536   p = h;
8537   while ( mp_right_type(p)!=mp_endpoint ){ 
8538     q = mp_link(p);
8539     a = mp_do_arc_test(mp, mp_right_x(p)-mp_x_coord(p), mp_right_y(p)-mp_y_coord(p),
8540       mp_left_x(q)-mp_right_x(p), mp_left_y(q)-mp_right_y(p),
8541       mp_x_coord(q)-mp_left_x(q), mp_y_coord(q)-mp_left_y(q), el_gordo);
8542     a_tot = mp_slow_add(mp, a, a_tot);
8543     if ( q==h ) break;  else p=q;
8544   }
8545   check_arith;
8546   return a_tot;
8547 }
8548
8549 @ The inverse operation of finding the time on a path~|h| when the arc length
8550 reaches some value |arc0| can also be accomplished via |do_arc_test|.  Some care
8551 is required to handle very large times or negative times on cyclic paths.  For
8552 non-cyclic paths, |arc0| values that are negative or too large cause
8553 |get_arc_time| to return 0 or the length of path~|h|.
8554
8555 If |arc0| is greater than the arc length of a cyclic path~|h|, the result is a
8556 time value greater than the length of the path.  Since it could be much greater,
8557 we must be prepared to compute the arc length of path~|h| and divide this into
8558 |arc0| to find how many multiples of the length of path~|h| to add.
8559
8560 @c static scaled mp_get_arc_time (MP mp,pointer h, scaled  arc0) {
8561   pointer p,q; /* for traversing the path */
8562   scaled t_tot; /* accumulator for the result */
8563   scaled t; /* the result of |do_arc_test| */
8564   scaled arc; /* portion of |arc0| not used up so far */
8565   integer n; /* number of extra times to go around the cycle */
8566   if ( arc0<0 ) {
8567     @<Deal with a negative |arc0| value and |return|@>;
8568   }
8569   if ( arc0==el_gordo ) decr(arc0);
8570   t_tot = 0;
8571   arc = arc0;
8572   p = h;
8573   while ( (mp_right_type(p)!=mp_endpoint) && (arc>0) ) {
8574     q = mp_link(p);
8575     t = mp_do_arc_test(mp, mp_right_x(p)-mp_x_coord(p), mp_right_y(p)-mp_y_coord(p),
8576       mp_left_x(q)-mp_right_x(p), mp_left_y(q)-mp_right_y(p),
8577       mp_x_coord(q)-mp_left_x(q), mp_y_coord(q)-mp_left_y(q), arc);
8578     @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>;
8579     if ( q==h ) {
8580       @<Update |t_tot| and |arc| to avoid going around the cyclic
8581         path too many times but set |arith_error:=true| and |goto done| on
8582         overflow@>;
8583     }
8584     p = q;
8585   }
8586   check_arith;
8587   return t_tot;
8588 }
8589
8590 @ @<Update |arc| and |t_tot| after |do_arc_test| has just returned |t|@>=
8591 if ( t<0 ) { t_tot = t_tot + t + two;  arc = 0;  }
8592 else { t_tot = t_tot + unity;  arc = arc - t;  }
8593
8594 @ @<Deal with a negative |arc0| value and |return|@>=
8595
8596   if ( mp_left_type(h)==mp_endpoint ) {
8597     t_tot=0;
8598   } else { 
8599     p = mp_htap_ypoc(mp, h);
8600     t_tot = -mp_get_arc_time(mp, p, -arc0);
8601     mp_toss_knot_list(mp, p);
8602   }
8603   check_arith;
8604   return t_tot;
8605 }
8606
8607 @ @<Update |t_tot| and |arc| to avoid going around the cyclic...@>=
8608 if ( arc>0 ) { 
8609   n = arc / (arc0 - arc);
8610   arc = arc - n*(arc0 - arc);
8611   if ( t_tot > (el_gordo / (n+1)) ) { 
8612         return el_gordo;
8613   }
8614   t_tot = (n + 1)*t_tot;
8615 }
8616
8617 @* \[20] Data structures for pens.
8618 A Pen in \MP\ can be either elliptical or polygonal.  Elliptical pens result
8619 in \ps\ \&{stroke} commands, while anything drawn with a polygonal pen is
8620 @:stroke}{\&{stroke} command@>
8621 converted into an area fill as described in the next part of this program.
8622 The mathematics behind this process is based on simple aspects of the theory
8623 of tracings developed by Leo Guibas, Lyle Ramshaw, and Jorge Stolfi
8624 [``A kinematic framework for computational geometry,'' Proc.\ IEEE Symp.\
8625 Foundations of Computer Science {\bf 24} (1983), 100--111].
8626
8627 Polygonal pens are created from paths via \MP's \&{makepen} primitive.
8628 @:makepen_}{\&{makepen} primitive@>
8629 This path representation is almost sufficient for our purposes except that
8630 a pen path should always be a convex polygon with the vertices in
8631 counter-clockwise order.
8632 Since we will need to scan pen polygons both forward and backward, a pen
8633 should be represented as a doubly linked ring of knot nodes.  There is
8634 room for the extra back pointer because we do not need the
8635 |mp_left_type| or |mp_right_type| fields.  In fact, we don't need the |mp_left_x|,
8636 |mp_left_y|, |mp_right_x|, or |mp_right_y| fields either but we leave these alone
8637 so that certain procedures can operate on both pens and paths.  In particular,
8638 pens can be copied using |copy_path| and recycled using |toss_knot_list|.
8639
8640 @d knil mp_info
8641   /* this replaces the |mp_left_type| and |mp_right_type| fields in a pen knot */
8642
8643 @ The |make_pen| procedure turns a path into a pen by initializing
8644 the |knil| pointers and making sure the knots form a convex polygon.
8645 Thus each cubic in the given path becomes a straight line and the control
8646 points are ignored.  If the path is not cyclic, the ends are connected by a
8647 straight line.
8648
8649 @d copy_pen(A) mp_make_pen(mp, mp_copy_path(mp, (A)),false)
8650
8651 @c 
8652 static pointer mp_make_pen (MP mp,pointer h, boolean need_hull) {
8653   pointer p,q; /* two consecutive knots */
8654   q=h;
8655   do {  
8656     p=q; q=mp_link(q);
8657     knil(q)=p;
8658   } while (q!=h);
8659   if ( need_hull ){ 
8660     h=mp_convex_hull(mp, h);
8661     @<Make sure |h| isn't confused with an elliptical pen@>;
8662   }
8663   return h;
8664 }
8665
8666 @ The only information required about an elliptical pen is the overall
8667 transformation that has been applied to the original \&{pencircle}.
8668 @:pencircle_}{\&{pencircle} primitive@>
8669 Since it suffices to keep track of how the three points $(0,0)$, $(1,0)$,
8670 and $(0,1)$ are transformed, an elliptical pen can be stored in a single
8671 knot node and transformed as if it were a path.
8672
8673 @d pen_is_elliptical(A) ((A)==mp_link((A)))
8674
8675 @c 
8676 static pointer mp_get_pen_circle (MP mp,scaled diam) {
8677   pointer h; /* the knot node to return */
8678   h=mp_get_node(mp, knot_node_size);
8679   mp_link(h)=h; knil(h)=h;
8680   mp_originator(h)=mp_program_code;
8681   mp_x_coord(h)=0; mp_y_coord(h)=0;
8682   mp_left_x(h)=diam; mp_left_y(h)=0;
8683   mp_right_x(h)=0; mp_right_y(h)=diam;
8684   return h;
8685 }
8686
8687 @ If the polygon being returned by |make_pen| has only one vertex, it will
8688 be interpreted as an elliptical pen.  This is no problem since a degenerate
8689 polygon can equally well be thought of as a degenerate ellipse.  We need only
8690 initialize the |mp_left_x|, |mp_left_y|, |mp_right_x|, and |mp_right_y| fields.
8691
8692 @<Make sure |h| isn't confused with an elliptical pen@>=
8693 if ( pen_is_elliptical( h) ){ 
8694   mp_left_x(h)=mp_x_coord(h); mp_left_y(h)=mp_y_coord(h);
8695   mp_right_x(h)=mp_x_coord(h); mp_right_y(h)=mp_y_coord(h);
8696 }
8697
8698 @ Printing a polygonal pen is very much like printing a path
8699
8700 @<Declarations@>=
8701 static void mp_pr_pen (MP mp,pointer h) ;
8702
8703 @ @c
8704 void mp_pr_pen (MP mp,pointer h) {
8705   pointer p,q; /* for list traversal */
8706   if ( pen_is_elliptical(h) ) {
8707     @<Print the elliptical pen |h|@>;
8708   } else { 
8709     p=h;
8710     do {  
8711       mp_print_two(mp, mp_x_coord(p),mp_y_coord(p));
8712       mp_print_nl(mp, " .. ");
8713       @<Advance |p| making sure the links are OK and |return| if there is
8714         a problem@>;
8715      } while (p!=h);
8716      mp_print(mp, "cycle");
8717   }
8718 }
8719
8720 @ @<Advance |p| making sure the links are OK and |return| if there is...@>=
8721 q=mp_link(p);
8722 if ( (q==null) || (knil(q)!=p) ) { 
8723   mp_print_nl(mp, "???"); return; /* this won't happen */
8724 @.???@>
8725 }
8726 p=q
8727
8728 @ @<Print the elliptical pen |h|@>=
8729
8730 mp_print(mp, "pencircle transformed (");
8731 mp_print_scaled(mp, mp_x_coord(h));
8732 mp_print_char(mp, xord(','));
8733 mp_print_scaled(mp, mp_y_coord(h));
8734 mp_print_char(mp, xord(','));
8735 mp_print_scaled(mp, mp_left_x(h)-mp_x_coord(h));
8736 mp_print_char(mp, xord(','));
8737 mp_print_scaled(mp, mp_right_x(h)-mp_x_coord(h));
8738 mp_print_char(mp, xord(','));
8739 mp_print_scaled(mp, mp_left_y(h)-mp_y_coord(h));
8740 mp_print_char(mp, xord(','));
8741 mp_print_scaled(mp, mp_right_y(h)-mp_y_coord(h));
8742 mp_print_char(mp, xord(')'));
8743 }
8744
8745 @ Here us another version of |pr_pen| that prints the pen as a diagnostic
8746 message.
8747
8748 @<Declarations@>=
8749 static void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) ;
8750
8751 @ @c
8752 void mp_print_pen (MP mp,pointer h, const char *s, boolean nuline) { 
8753   mp_print_diagnostic(mp, "Pen",s,nuline); mp_print_ln(mp);
8754 @.Pen at line...@>
8755   mp_pr_pen(mp, h);
8756   mp_end_diagnostic(mp, true);
8757 }
8758
8759 @ Making a polygonal pen into a path involves restoring the |mp_left_type| and
8760 |mp_right_type| fields and setting the control points so as to make a polygonal
8761 path.
8762
8763 @c 
8764 static void mp_make_path (MP mp,pointer h) {
8765   pointer p; /* for traversing the knot list */
8766   quarterword k; /* a loop counter */
8767   @<Other local variables in |make_path|@>;
8768   if ( pen_is_elliptical(h) ) {
8769     @<Make the elliptical pen |h| into a path@>;
8770   } else { 
8771     p=h;
8772     do {  
8773       mp_left_type(p)=mp_explicit;
8774       mp_right_type(p)=mp_explicit;
8775       @<copy the coordinates of knot |p| into its control points@>;
8776        p=mp_link(p);
8777     } while (p!=h);
8778   }
8779 }
8780
8781 @ @<copy the coordinates of knot |p| into its control points@>=
8782 mp_left_x(p)=mp_x_coord(p);
8783 mp_left_y(p)=mp_y_coord(p);
8784 mp_right_x(p)=mp_x_coord(p);
8785 mp_right_y(p)=mp_y_coord(p)
8786
8787 @ We need an eight knot path to get a good approximation to an ellipse.
8788
8789 @<Make the elliptical pen |h| into a path@>=
8790
8791   @<Extract the transformation parameters from the elliptical pen~|h|@>;
8792   p=h;
8793   for (k=0;k<=7;k++ ) { 
8794     @<Initialize |p| as the |k|th knot of a circle of unit diameter,
8795       transforming it appropriately@>;
8796     if ( k==7 ) mp_link(p)=h;  else mp_link(p)=mp_get_node(mp, knot_node_size);
8797     p=mp_link(p);
8798   }
8799 }
8800
8801 @ @<Extract the transformation parameters from the elliptical pen~|h|@>=
8802 center_x=mp_x_coord(h);
8803 center_y=mp_y_coord(h);
8804 width_x=mp_left_x(h)-center_x;
8805 width_y=mp_left_y(h)-center_y;
8806 height_x=mp_right_x(h)-center_x;
8807 height_y=mp_right_y(h)-center_y
8808
8809 @ @<Other local variables in |make_path|@>=
8810 scaled center_x,center_y; /* translation parameters for an elliptical pen */
8811 scaled width_x,width_y; /* the effect of a unit change in $x$ */
8812 scaled height_x,height_y; /* the effect of a unit change in $y$ */
8813 scaled dx,dy; /* the vector from knot |p| to its right control point */
8814 integer kk;
8815   /* |k| advanced $270^\circ$ around the ring (cf. $\sin\theta=\cos(\theta+270)$) */
8816
8817 @ The only tricky thing here are the tables |half_cos| and |d_cos| used to
8818 find the point $k/8$ of the way around the circle and the direction vector
8819 to use there.
8820
8821 @<Initialize |p| as the |k|th knot of a circle of unit diameter,...@>=
8822 kk=(k+6)% 8;
8823 mp_x_coord(p)=center_x+mp_take_fraction(mp, mp->half_cos[k],width_x)
8824            +mp_take_fraction(mp, mp->half_cos[kk],height_x);
8825 mp_y_coord(p)=center_y+mp_take_fraction(mp, mp->half_cos[k],width_y)
8826            +mp_take_fraction(mp, mp->half_cos[kk],height_y);
8827 dx=-mp_take_fraction(mp, mp->d_cos[kk],width_x)
8828    +mp_take_fraction(mp, mp->d_cos[k],height_x);
8829 dy=-mp_take_fraction(mp, mp->d_cos[kk],width_y)
8830    +mp_take_fraction(mp, mp->d_cos[k],height_y);
8831 mp_right_x(p)=mp_x_coord(p)+dx;
8832 mp_right_y(p)=mp_y_coord(p)+dy;
8833 mp_left_x(p)=mp_x_coord(p)-dx;
8834 mp_left_y(p)=mp_y_coord(p)-dy;
8835 mp_left_type(p)=mp_explicit;
8836 mp_right_type(p)=mp_explicit;
8837 mp_originator(p)=mp_program_code
8838
8839 @ @<Glob...@>=
8840 fraction half_cos[8]; /* ${1\over2}\cos(45k)$ */
8841 fraction d_cos[8]; /* a magic constant times $\cos(45k)$ */
8842
8843 @ The magic constant for |d_cos| is the distance between $({1\over2},0)$ and
8844 $({1\over4}\sqrt2,{1\over4}\sqrt2)$ times the result of the |velocity|
8845 function for $\theta=\phi=22.5^\circ$.  This comes out to be
8846 $$ d = {\sqrt{2-\sqrt2}\over 3+3\cos22.5^\circ}
8847   \approx 0.132608244919772.
8848 $$
8849
8850 @<Set init...@>=
8851 mp->half_cos[0]=fraction_half;
8852 mp->half_cos[1]=94906266; /* $2^{26}\sqrt2\approx94906265.62$ */
8853 mp->half_cos[2]=0;
8854 mp->d_cos[0]=35596755; /* $2^{28}d\approx35596754.69$ */
8855 mp->d_cos[1]=25170707; /* $2^{27}\sqrt2\,d\approx25170706.63$ */
8856 mp->d_cos[2]=0;
8857 for (k=3;k<= 4;k++ ) { 
8858   mp->half_cos[k]=-mp->half_cos[4-k];
8859   mp->d_cos[k]=-mp->d_cos[4-k];
8860 }
8861 for (k=5;k<= 7;k++ ) { 
8862   mp->half_cos[k]=mp->half_cos[8-k];
8863   mp->d_cos[k]=mp->d_cos[8-k];
8864 }
8865
8866 @ The |convex_hull| function forces a pen polygon to be convex when it is
8867 returned by |make_pen| and after any subsequent transformation where rounding
8868 error might allow the convexity to be lost.
8869 The convex hull algorithm used here is described by F.~P. Preparata and
8870 M.~I. Shamos [{\sl Computational Geometry}, Springer-Verlag, 1985].
8871
8872 @<Declarations@>=
8873 static pointer mp_convex_hull (MP mp,pointer h);
8874
8875 @ @c
8876 pointer mp_convex_hull (MP mp,pointer h) { /* Make a polygonal pen convex */
8877   pointer l,r; /* the leftmost and rightmost knots */
8878   pointer p,q; /* knots being scanned */
8879   pointer s; /* the starting point for an upcoming scan */
8880   scaled dx,dy; /* a temporary pointer */
8881   if ( pen_is_elliptical(h) ) {
8882      return h;
8883   } else { 
8884     @<Set |l| to the leftmost knot in polygon~|h|@>;
8885     @<Set |r| to the rightmost knot in polygon~|h|@>;
8886     if ( l!=r ) { 
8887       s=mp_link(r);
8888       @<Find any knots on the path from |l| to |r| above the |l|-|r| line and
8889         move them past~|r|@>;
8890       @<Find any knots on the path from |s| to |l| below the |l|-|r| line and
8891         move them past~|l|@>;
8892       @<Sort the path from |l| to |r| by increasing $x$@>;
8893       @<Sort the path from |r| to |l| by decreasing $x$@>;
8894     }
8895     if ( l!=mp_link(l) ) {
8896       @<Do a Gramm scan and remove vertices where there is no left turn@>;
8897     }
8898     return l;
8899   }
8900 }
8901
8902 @ All comparisons are done primarily on $x$ and secondarily on $y$.
8903
8904 @<Set |l| to the leftmost knot in polygon~|h|@>=
8905 l=h;
8906 p=mp_link(h);
8907 while ( p!=h ) { 
8908   if ( mp_x_coord(p)<=mp_x_coord(l) )
8909     if ( (mp_x_coord(p)<mp_x_coord(l)) || (mp_y_coord(p)<mp_y_coord(l)) )
8910       l=p;
8911   p=mp_link(p);
8912 }
8913
8914 @ @<Set |r| to the rightmost knot in polygon~|h|@>=
8915 r=h;
8916 p=mp_link(h);
8917 while ( p!=h ) { 
8918   if ( mp_x_coord(p)>=mp_x_coord(r) )
8919     if ( (mp_x_coord(p)>mp_x_coord(r)) || (mp_y_coord(p)>mp_y_coord(r)) )
8920       r=p;
8921   p=mp_link(p);
8922 }
8923
8924 @ @<Find any knots on the path from |l| to |r| above the |l|-|r| line...@>=
8925 dx=mp_x_coord(r)-mp_x_coord(l);
8926 dy=mp_y_coord(r)-mp_y_coord(l);
8927 p=mp_link(l);
8928 while ( p!=r ) { 
8929   q=mp_link(p);
8930   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 )
8931     mp_move_knot(mp, p, r);
8932   p=q;
8933 }
8934
8935 @ The |move_knot| procedure removes |p| from a doubly linked list and inserts
8936 it after |q|.
8937
8938 @ @<Declarations@>=
8939 static void mp_move_knot (MP mp,pointer p, pointer q) ;
8940
8941 @ @c
8942 void mp_move_knot (MP mp,pointer p, pointer q) { 
8943   mp_link(knil(p))=mp_link(p);
8944   knil(mp_link(p))=knil(p);
8945   knil(p)=q;
8946   mp_link(p)=mp_link(q);
8947   mp_link(q)=p;
8948   knil(mp_link(p))=p;
8949 }
8950
8951 @ @<Find any knots on the path from |s| to |l| below the |l|-|r| line...@>=
8952 p=s;
8953 while ( p!=l ) { 
8954   q=mp_link(p);
8955   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 )
8956     mp_move_knot(mp, p,l);
8957   p=q;
8958 }
8959
8960 @ The list is likely to be in order already so we just do linear insertions.
8961 Secondary comparisons on $y$ ensure that the sort is consistent with the
8962 choice of |l| and |r|.
8963
8964 @<Sort the path from |l| to |r| by increasing $x$@>=
8965 p=mp_link(l);
8966 while ( p!=r ) { 
8967   q=knil(p);
8968   while ( mp_x_coord(q)>mp_x_coord(p) ) q=knil(q);
8969   while ( mp_x_coord(q)==mp_x_coord(p) ) {
8970     if ( mp_y_coord(q)>mp_y_coord(p) ) q=knil(q); else break;
8971   }
8972   if ( q==knil(p) ) p=mp_link(p);
8973   else { p=mp_link(p); mp_move_knot(mp, knil(p),q); };
8974 }
8975
8976 @ @<Sort the path from |r| to |l| by decreasing $x$@>=
8977 p=mp_link(r);
8978 while ( p!=l ){ 
8979   q=knil(p);
8980   while ( mp_x_coord(q)<mp_x_coord(p) ) q=knil(q);
8981   while ( mp_x_coord(q)==mp_x_coord(p) ) {
8982     if ( mp_y_coord(q)<mp_y_coord(p) ) q=knil(q); else break;
8983   }
8984   if ( q==knil(p) ) p=mp_link(p);
8985   else { p=mp_link(p); mp_move_knot(mp, knil(p),q); };
8986 }
8987
8988 @ The condition involving |ab_vs_cd| tests if there is not a left turn
8989 at knot |q|.  There usually will be a left turn so we streamline the case
8990 where the |then| clause is not executed.
8991
8992 @<Do a Gramm scan and remove vertices where there...@>=
8993
8994 p=l; q=mp_link(l);
8995 while (1) { 
8996   dx=mp_x_coord(q)-mp_x_coord(p);
8997   dy=mp_y_coord(q)-mp_y_coord(p);
8998   p=q; q=mp_link(q);
8999   if ( p==l ) break;
9000   if ( p!=r )
9001     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 ) {
9002       @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>;
9003     }
9004   }
9005 }
9006
9007 @ @<Remove knot |p| and back up |p| and |q| but don't go past |l|@>=
9008
9009 s=knil(p);
9010 mp_free_node(mp, p,knot_node_size);
9011 mp_link(s)=q; knil(q)=s;
9012 if ( s==l ) p=s;
9013 else { p=knil(s); q=s; };
9014 }
9015
9016 @ The |find_offset| procedure sets global variables |(cur_x,cur_y)| to the
9017 offset associated with the given direction |(x,y)|.  If two different offsets
9018 apply, it chooses one of them.
9019
9020 @c 
9021 static void mp_find_offset (MP mp,scaled x, scaled y, pointer h) {
9022   pointer p,q; /* consecutive knots */
9023   scaled wx,wy,hx,hy;
9024   /* the transformation matrix for an elliptical pen */
9025   fraction xx,yy; /* untransformed offset for an elliptical pen */
9026   fraction d; /* a temporary register */
9027   if ( pen_is_elliptical(h) ) {
9028     @<Find the offset for |(x,y)| on the elliptical pen~|h|@>
9029   } else { 
9030     q=h;
9031     do {  
9032       p=q; q=mp_link(q);
9033     } 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));
9034     do {  
9035       p=q; q=mp_link(q);
9036     } 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));
9037     mp->cur_x=mp_x_coord(p);
9038     mp->cur_y=mp_y_coord(p);
9039   }
9040 }
9041
9042 @ @<Glob...@>=
9043 scaled cur_x;
9044 scaled cur_y; /* all-purpose return value registers */
9045
9046 @ @<Find the offset for |(x,y)| on the elliptical pen~|h|@>=
9047 if ( (x==0) && (y==0) ) {
9048   mp->cur_x=mp_x_coord(h); mp->cur_y=mp_y_coord(h);  
9049 } else { 
9050   @<Find the non-constant part of the transformation for |h|@>;
9051   while ( (abs(x)<fraction_half) && (abs(y)<fraction_half) ){ 
9052     x+=x; y+=y;  
9053   };
9054   @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the
9055     untransformed version of |(x,y)|@>;
9056   mp->cur_x=mp_x_coord(h)+mp_take_fraction(mp, xx,wx)+mp_take_fraction(mp, yy,hx);
9057   mp->cur_y=mp_y_coord(h)+mp_take_fraction(mp, xx,wy)+mp_take_fraction(mp, yy,hy);
9058 }
9059
9060 @ @<Find the non-constant part of the transformation for |h|@>=
9061 wx=mp_left_x(h)-mp_x_coord(h);
9062 wy=mp_left_y(h)-mp_y_coord(h);
9063 hx=mp_right_x(h)-mp_x_coord(h);
9064 hy=mp_right_y(h)-mp_y_coord(h)
9065
9066 @ @<Make |(xx,yy)| the offset on the untransformed \&{pencircle} for the...@>=
9067 yy=-(mp_take_fraction(mp, x,hy)+mp_take_fraction(mp, y,-hx));
9068 xx=mp_take_fraction(mp, x,-wy)+mp_take_fraction(mp, y,wx);
9069 d=mp_pyth_add(mp, xx,yy);
9070 if ( d>0 ) { 
9071   xx=half(mp_make_fraction(mp, xx,d));
9072   yy=half(mp_make_fraction(mp, yy,d));
9073 }
9074
9075 @ Finding the bounding box of a pen is easy except if the pen is elliptical.
9076 But we can handle that case by just calling |find_offset| twice.  The answer
9077 is stored in the global variables |minx|, |maxx|, |miny|, and |maxy|.
9078
9079 @c 
9080 static void mp_pen_bbox (MP mp,pointer h) {
9081   pointer p; /* for scanning the knot list */
9082   if ( pen_is_elliptical(h) ) {
9083     @<Find the bounding box of an elliptical pen@>;
9084   } else { 
9085     mp_minx=mp_x_coord(h); mp_maxx=mp_minx;
9086     mp_miny=mp_y_coord(h); mp_maxy=mp_miny;
9087     p=mp_link(h);
9088     while ( p!=h ) {
9089       if ( mp_x_coord(p)<mp_minx ) mp_minx=mp_x_coord(p);
9090       if ( mp_y_coord(p)<mp_miny ) mp_miny=mp_y_coord(p);
9091       if ( mp_x_coord(p)>mp_maxx ) mp_maxx=mp_x_coord(p);
9092       if ( mp_y_coord(p)>mp_maxy ) mp_maxy=mp_y_coord(p);
9093       p=mp_link(p);
9094     }
9095   }
9096 }
9097
9098 @ @<Find the bounding box of an elliptical pen@>=
9099
9100 mp_find_offset(mp, 0,fraction_one,h);
9101 mp_maxx=mp->cur_x;
9102 mp_minx=2*mp_x_coord(h)-mp->cur_x;
9103 mp_find_offset(mp, -fraction_one,0,h);
9104 mp_maxy=mp->cur_y;
9105 mp_miny=2*mp_y_coord(h)-mp->cur_y;
9106 }
9107
9108 @* \[21] Edge structures.
9109 Now we come to \MP's internal scheme for representing pictures.
9110 The representation is very different from \MF's edge structures
9111 because \MP\ pictures contain \ps\ graphics objects instead of pixel
9112 images.  However, the basic idea is somewhat similar in that shapes
9113 are represented via their boundaries.
9114
9115 The main purpose of edge structures is to keep track of graphical objects
9116 until it is time to translate them into \ps.  Since \MP\ does not need to
9117 know anything about an edge structure other than how to translate it into
9118 \ps\ and how to find its bounding box, edge structures can be just linked
9119 lists of graphical objects.  \MP\ has no easy way to determine whether
9120 two such objects overlap, but it suffices to draw the first one first and
9121 let the second one overwrite it if necessary.
9122
9123 @(mplib.h@>=
9124 enum mp_graphical_object_code {
9125   @<Graphical object codes@>
9126   mp_final_graphic
9127 };
9128
9129 @ Let's consider the types of graphical objects one at a time.
9130 First of all, a filled contour is represented by a eight-word node.  The first
9131 word contains |type| and |link| fields, and the next six words contain a
9132 pointer to a cyclic path and the value to use for \ps' \&{currentrgbcolor}
9133 parameter.  If a pen is used for filling |pen_p|, |ljoin_val| and |miterlim_val|
9134 give the relevant information.
9135
9136 @d mp_path_p(A) mp_link((A)+1)
9137   /* a pointer to the path that needs filling */
9138 @d mp_pen_p(A) mp_info((A)+1)
9139   /* a pointer to the pen to fill or stroke with */
9140 @d mp_color_model(A) mp_type((A)+2) /*  the color model  */
9141 @d obj_red_loc(A) ((A)+3)  /* the first of three locations for the color */
9142 @d obj_cyan_loc obj_red_loc  /* the first of four locations for the color */
9143 @d obj_grey_loc obj_red_loc  /* the location for the color */
9144 @d red_val(A) mp->mem[(A)+3].sc
9145   /* the red component of the color in the range $0\ldots1$ */
9146 @d cyan_val red_val
9147 @d grey_val red_val
9148 @d green_val(A) mp->mem[(A)+4].sc
9149   /* the green component of the color in the range $0\ldots1$ */
9150 @d magenta_val green_val
9151 @d blue_val(A) mp->mem[(A)+5].sc
9152   /* the blue component of the color in the range $0\ldots1$ */
9153 @d yellow_val blue_val
9154 @d black_val(A) mp->mem[(A)+6].sc
9155   /* the blue component of the color in the range $0\ldots1$ */
9156 @d ljoin_val(A) mp_name_type((A))  /* the value of \&{linejoin} */
9157 @:mp_linejoin_}{\&{linejoin} primitive@>
9158 @d miterlim_val(A) mp->mem[(A)+7].sc  /* the value of \&{miterlimit} */
9159 @:mp_miterlimit_}{\&{miterlimit} primitive@>
9160 @d obj_color_part(A) mp->mem[(A)+3-red_part].sc
9161   /* interpret an object pointer that has been offset by |red_part..blue_part| */
9162 @d mp_pre_script(A) mp->mem[(A)+8].hh.lh
9163 @d mp_post_script(A) mp->mem[(A)+8].hh.rh
9164 @d fill_node_size 9
9165
9166 @ @<Graphical object codes@>=
9167 mp_fill_code=1,
9168
9169 @ @c 
9170 static pointer mp_new_fill_node (MP mp,pointer p) {
9171   /* make a fill node for cyclic path |p| and color black */
9172   pointer t; /* the new node */
9173   t=mp_get_node(mp, fill_node_size);
9174   mp_type(t)=mp_fill_code;
9175   mp_path_p(t)=p;
9176   mp_pen_p(t)=null; /* |null| means don't use a pen */
9177   red_val(t)=0;
9178   green_val(t)=0;
9179   blue_val(t)=0;
9180   black_val(t)=0;
9181   mp_color_model(t)=mp_uninitialized_model;
9182   mp_pre_script(t)=null;
9183   mp_post_script(t)=null;
9184   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9185   return t;
9186 }
9187
9188 @ @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>=
9189 if ( mp->internal[mp_linejoin]>unity ) ljoin_val(t)=2;
9190 else if ( mp->internal[mp_linejoin]>0 ) ljoin_val(t)=1;
9191 else ljoin_val(t)=0;
9192 if ( mp->internal[mp_miterlimit]<unity )
9193   miterlim_val(t)=unity;
9194 else
9195   miterlim_val(t)=mp->internal[mp_miterlimit]
9196
9197 @ A stroked path is represented by an eight-word node that is like a filled
9198 contour node except that it contains the current \&{linecap} value, a scale
9199 factor for the dash pattern, and a pointer that is non-null if the stroke
9200 is to be dashed.  The purpose of the scale factor is to allow a picture to
9201 be transformed without touching the picture that |dash_p| points to.
9202
9203 @d mp_dash_p(A) mp_link((A)+9)
9204   /* a pointer to the edge structure that gives the dash pattern */
9205 @d lcap_val(A) mp_type((A)+9)
9206   /* the value of \&{linecap} */
9207 @:mp_linecap_}{\&{linecap} primitive@>
9208 @d dash_scale(A) mp->mem[(A)+10].sc /* dash lengths are scaled by this factor */
9209 @d stroked_node_size 11
9210
9211 @ @<Graphical object codes@>=
9212 mp_stroked_code=2,
9213
9214 @ @c 
9215 static pointer mp_new_stroked_node (MP mp,pointer p) {
9216   /* make a stroked node for path |p| with |mp_pen_p(p)| temporarily |null| */
9217   pointer t; /* the new node */
9218   t=mp_get_node(mp, stroked_node_size);
9219   mp_type(t)=mp_stroked_code;
9220   mp_path_p(t)=p; mp_pen_p(t)=null;
9221   mp_dash_p(t)=null;
9222   dash_scale(t)=unity;
9223   red_val(t)=0;
9224   green_val(t)=0;
9225   blue_val(t)=0;
9226   black_val(t)=0;
9227   mp_color_model(t)=mp_uninitialized_model;
9228   mp_pre_script(t)=null;
9229   mp_post_script(t)=null;
9230   @<Set the |ljoin_val| and |miterlim_val| fields in object |t|@>;
9231   if ( mp->internal[mp_linecap]>unity ) lcap_val(t)=2;
9232   else if ( mp->internal[mp_linecap]>0 ) lcap_val(t)=1;
9233   else lcap_val(t)=0;
9234   return t;
9235 }
9236
9237 @ When a dashed line is computed in a transformed coordinate system, the dash
9238 lengths get scaled like the pen shape and we need to compensate for this.  Since
9239 there is no unique scale factor for an arbitrary transformation, we use the
9240 the square root of the determinant.  The properties of the determinant make it
9241 easier to maintain the |dash_scale|.  The computation is fairly straight-forward
9242 except for the initialization of the scale factor |s|.  The factor of 64 is
9243 needed because |square_rt| scales its result by $2^8$ while we need $2^{14}$
9244 to counteract the effect of |take_fraction|.
9245
9246 @ @c
9247 scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) {
9248   scaled maxabs; /* $max(|a|,|b|,|c|,|d|)$ */
9249   unsigned s; /* amount by which the result of |square_rt| needs to be scaled */
9250   @<Initialize |maxabs|@>;
9251   s=64;
9252   while ( (maxabs<fraction_one) && (s>1) ){ 
9253     a+=a; b+=b; c+=c; d+=d;
9254     maxabs+=maxabs; s=(unsigned)(halfp(s));
9255   }
9256   return (scaled)(s*mp_square_rt(mp, abs(mp_take_fraction(mp, a,d)-mp_take_fraction(mp, b,c))));
9257 }
9258 @#
9259 static scaled mp_get_pen_scale (MP mp,pointer p) { 
9260   return mp_sqrt_det(mp, 
9261     mp_left_x(p)-mp_x_coord(p), mp_right_x(p)-mp_x_coord(p),
9262     mp_left_y(p)-mp_y_coord(p), mp_right_y(p)-mp_y_coord(p));
9263 }
9264
9265 @ @<Declarations@>=
9266 static scaled mp_sqrt_det (MP mp,scaled a, scaled b, scaled c, scaled d) ;
9267
9268
9269 @ @<Initialize |maxabs|@>=
9270 maxabs=abs(a);
9271 if ( abs(b)>maxabs ) maxabs=abs(b);
9272 if ( abs(c)>maxabs ) maxabs=abs(c);
9273 if ( abs(d)>maxabs ) maxabs=abs(d)
9274
9275 @ When a picture contains text, this is represented by a fourteen-word node
9276 where the color information and |type| and |link| fields are augmented by
9277 additional fields that describe the text and  how it is transformed.
9278 The |path_p| and |mp_pen_p| pointers are replaced by a number that identifies
9279 the font and a string number that gives the text to be displayed.
9280 The |width|, |height|, and |depth| fields
9281 give the dimensions of the text at its design size, and the remaining six
9282 words give a transformation to be applied to the text.  The |new_text_node|
9283 function initializes everything to default values so that the text comes out
9284 black with its reference point at the origin.
9285
9286 @d mp_text_p(A) mp_link((A)+1)  /* a string pointer for the text to display */
9287 @d mp_font_n(A) mp_info((A)+1)  /* the font number */
9288 @d width_val(A) mp->mem[(A)+7].sc  /* unscaled width of the text */
9289 @d height_val(A) mp->mem[(A)+9].sc  /* unscaled height of the text */
9290 @d depth_val(A) mp->mem[(A)+10].sc  /* unscaled depth of the text */
9291 @d text_tx_loc(A) ((A)+11)
9292   /* the first of six locations for transformation parameters */
9293 @d tx_val(A) mp->mem[(A)+11].sc  /* $x$ shift amount */
9294 @d ty_val(A) mp->mem[(A)+12].sc  /* $y$ shift amount */
9295 @d txx_val(A) mp->mem[(A)+13].sc  /* |txx| transformation parameter */
9296 @d txy_val(A) mp->mem[(A)+14].sc  /* |txy| transformation parameter */
9297 @d tyx_val(A) mp->mem[(A)+15].sc  /* |tyx| transformation parameter */
9298 @d tyy_val(A) mp->mem[(A)+16].sc  /* |tyy| transformation parameter */
9299 @d text_trans_part(A) mp->mem[(A)+11-x_part].sc
9300     /* interpret a text node pointer that has been offset by |x_part..yy_part| */
9301 @d text_node_size 17
9302
9303 @ @<Graphical object codes@>=
9304 mp_text_code=3,
9305
9306 @ @c
9307 static pointer mp_new_text_node (MP mp,char *f,str_number s) {
9308   /* make a text node for font |f| and text string |s| */
9309   pointer t; /* the new node */
9310   t=mp_get_node(mp, text_node_size);
9311   mp_type(t)=mp_text_code;
9312   mp_text_p(t)=s;
9313   mp_font_n(t)=(halfword)mp_find_font(mp, f); /* this identifies the font */
9314   red_val(t)=0;
9315   green_val(t)=0;
9316   blue_val(t)=0;
9317   black_val(t)=0;
9318   mp_color_model(t)=mp_uninitialized_model;
9319   mp_pre_script(t)=null;
9320   mp_post_script(t)=null;
9321   tx_val(t)=0; ty_val(t)=0;
9322   txx_val(t)=unity; txy_val(t)=0;
9323   tyx_val(t)=0; tyy_val(t)=unity;
9324   mp_set_text_box(mp, t); /* this finds the bounding box */
9325   return t;
9326 }
9327
9328 @ The last two types of graphical objects that can occur in an edge structure
9329 are clipping paths and \&{setbounds} paths.  These are slightly more difficult
9330 @:set_bounds_}{\&{setbounds} primitive@>
9331 to implement because we must keep track of exactly what is being clipped or
9332 bounded when pictures get merged together.  For this reason, each clipping or
9333 \&{setbounds} operation is represented by a pair of nodes:  first comes a
9334 two-word node whose |path_p| gives the relevant path, then there is the list
9335 of objects to clip or bound followed by a two-word node whose second word is
9336 unused.
9337
9338 Using at least two words for each graphical object node allows them all to be
9339 allocated and deallocated similarly with a global array |gr_object_size| to
9340 give the size in words for each object type.
9341
9342 @d start_clip_size 2
9343 @d start_bounds_size 2
9344 @d stop_clip_size 2 /* the second word is not used here */
9345 @d stop_bounds_size 2 /* the second word is not used here */
9346 @#
9347 @d stop_type(A) ((A)+2)
9348   /* matching |type| for |start_clip_code| or |start_bounds_code| */
9349 @d has_color(A) (mp_type((A))<mp_start_clip_code)
9350   /* does a graphical object have color fields? */
9351 @d has_pen(A) (mp_type((A))<mp_text_code)
9352   /* does a graphical object have a |mp_pen_p| field? */
9353 @d is_start_or_stop(A) (mp_type((A))>=mp_start_clip_code)
9354 @d is_stop(A) (mp_type((A))>=mp_stop_clip_code)
9355
9356 @ @<Graphical object codes@>=
9357 mp_start_clip_code=4, /* |type| of a node that starts clipping */
9358 mp_start_bounds_code=5, /* |type| of a node that gives a \&{setbounds} path */
9359 mp_stop_clip_code=6, /* |type| of a node that stops clipping */
9360 mp_stop_bounds_code=7, /* |type| of a node that stops \&{setbounds} */
9361
9362 @ @c 
9363 static pointer mp_new_bounds_node (MP mp,pointer p, quarterword  c) {
9364   /* make a node of type |c| where |p| is the clipping or \&{setbounds} path */
9365   pointer t; /* the new node */
9366   t=mp_get_node(mp, mp->gr_object_size[c]);
9367   mp_type(t)=c;
9368   mp_path_p(t)=p;
9369   return t;
9370 }
9371
9372 @ We need an array to keep track of the sizes of graphical objects.
9373
9374 @<Glob...@>=
9375 quarterword gr_object_size[mp_stop_bounds_code+1];
9376
9377 @ @<Set init...@>=
9378 mp->gr_object_size[mp_fill_code]=fill_node_size;
9379 mp->gr_object_size[mp_stroked_code]=stroked_node_size;
9380 mp->gr_object_size[mp_text_code]=text_node_size;
9381 mp->gr_object_size[mp_start_clip_code]=start_clip_size;
9382 mp->gr_object_size[mp_stop_clip_code]=stop_clip_size;
9383 mp->gr_object_size[mp_start_bounds_code]=start_bounds_size;
9384 mp->gr_object_size[mp_stop_bounds_code]=stop_bounds_size;
9385
9386 @ All the essential information in an edge structure is encoded as a linked list
9387 of graphical objects as we have just seen, but it is helpful to add some
9388 redundant information.  A single edge structure might be used as a dash pattern
9389 many times, and it would be nice to avoid scanning the same structure
9390 repeatedly.  Thus, an edge structure known to be a suitable dash pattern
9391 has a header that gives a list of dashes in a sorted order designed for rapid
9392 translation into \ps.
9393
9394 Each dash is represented by a three-word node containing the initial and final
9395 $x$~coordinates as well as the usual |link| field.  The |link| fields points to
9396 the dash node with the next higher $x$-coordinates and the final link points
9397 to a special location called |null_dash|.  (There should be no overlap between
9398 dashes).  Since the $y$~coordinate of the dash pattern is needed to determine
9399 the period of repetition, this needs to be stored in the edge header along
9400 with a pointer to the list of dash nodes.
9401
9402 @d start_x(A) mp->mem[(A)+1].sc  /* the starting $x$~coordinate in a dash node */
9403 @d stop_x(A) mp->mem[(A)+2].sc  /* the ending $x$~coordinate in a dash node */
9404 @d dash_node_size 3
9405 @d dash_list mp_link
9406   /* in an edge header this points to the first dash node */
9407 @d dash_y(A) mp->mem[(A)+1].sc  /* $y$ value for the dash list in an edge header */
9408
9409 @ It is also convenient for an edge header to contain the bounding
9410 box information needed by the \&{llcorner} and \&{urcorner} operators
9411 so that this does not have to be recomputed unnecessarily.  This is done by
9412 adding fields for the $x$~and $y$ extremes as well as a pointer that indicates
9413 how far the bounding box computation has gotten.  Thus if the user asks for
9414 the bounding box and then adds some more text to the picture before asking
9415 for more bounding box information, the second computation need only look at
9416 the additional text.
9417
9418 When the bounding box has not been computed, the |bblast| pointer points
9419 to a dummy link at the head of the graphical object list while the |minx_val|
9420 and |miny_val| fields contain |el_gordo| and the |maxx_val| and |maxy_val|
9421 fields contain |-el_gordo|.
9422
9423 Since the bounding box of pictures containing objects of type
9424 |mp_start_bounds_code| depends on the value of \&{truecorners}, the bounding box
9425 @:mp_true_corners_}{\&{truecorners} primitive@>
9426 data might not be valid for all values of this parameter.  Hence, the |bbtype|
9427 field is needed to keep track of this.
9428
9429 @d minx_val(A) mp->mem[(A)+2].sc
9430 @d miny_val(A) mp->mem[(A)+3].sc
9431 @d maxx_val(A) mp->mem[(A)+4].sc
9432 @d maxy_val(A) mp->mem[(A)+5].sc
9433 @d bblast(A) mp_link((A)+6)  /* last item considered in bounding box computation */
9434 @d bbtype(A) mp_info((A)+6)  /* tells how bounding box data depends on \&{truecorners} */
9435 @d dummy_loc(A) ((A)+7)  /* where the object list begins in an edge header */
9436 @d no_bounds 0
9437   /* |bbtype| value when bounding box data is valid for all \&{truecorners} values */
9438 @d bounds_set 1
9439   /* |bbtype| value when bounding box data is for \&{truecorners}${}\le 0$ */
9440 @d bounds_unset 2
9441   /* |bbtype| value when bounding box data is for \&{truecorners}${}>0$ */
9442
9443 @c 
9444 static void mp_init_bbox (MP mp,pointer h) {
9445   /* Initialize the bounding box information in edge structure |h| */
9446   bblast(h)=dummy_loc(h);
9447   bbtype(h)=no_bounds;
9448   minx_val(h)=el_gordo;
9449   miny_val(h)=el_gordo;
9450   maxx_val(h)=-el_gordo;
9451   maxy_val(h)=-el_gordo;
9452 }
9453
9454 @ The only other entries in an edge header are a reference count in the first
9455 word and a pointer to the tail of the object list in the last word.
9456
9457 @d obj_tail(A) mp_info((A)+7)  /* points to the last entry in the object list */
9458 @d edge_header_size 8
9459
9460 @c 
9461 static void mp_init_edges (MP mp,pointer h) {
9462   /* initialize an edge header to null values */
9463   dash_list(h)=null_dash;
9464   obj_tail(h)=dummy_loc(h);
9465   mp_link(dummy_loc(h))=null;
9466   ref_count(h)=null;
9467   mp_init_bbox(mp, h);
9468 }
9469
9470 @ Here is how edge structures are deleted.  The process can be recursive because
9471 of the need to dereference edge structures that are used as dash patterns.
9472 @^recursion@>
9473
9474 @d add_edge_ref(A) incr(ref_count(A))
9475 @d delete_edge_ref(A) { 
9476    if ( ref_count((A))==null ) 
9477      mp_toss_edges(mp, A);
9478    else 
9479      decr(ref_count(A)); 
9480    }
9481
9482 @<Declarations@>=
9483 static void mp_flush_dash_list (MP mp,pointer h);
9484 static pointer mp_toss_gr_object (MP mp,pointer p) ;
9485 static void mp_toss_edges (MP mp,pointer h) ;
9486
9487 @ @c void mp_toss_edges (MP mp,pointer h) {
9488   pointer p,q;  /* pointers that scan the list being recycled */
9489   pointer r; /* an edge structure that object |p| refers to */
9490   mp_flush_dash_list(mp, h);
9491   q=mp_link(dummy_loc(h));
9492   while ( (q!=null) ) { 
9493     p=q; q=mp_link(q);
9494     r=mp_toss_gr_object(mp, p);
9495     if ( r!=null ) delete_edge_ref(r);
9496   }
9497   mp_free_node(mp, h,edge_header_size);
9498 }
9499 void mp_flush_dash_list (MP mp,pointer h) {
9500   pointer p,q;  /* pointers that scan the list being recycled */
9501   q=dash_list(h);
9502   while ( q!=null_dash ) { 
9503     p=q; q=mp_link(q);
9504     mp_free_node(mp, p,dash_node_size);
9505   }
9506   dash_list(h)=null_dash;
9507 }
9508 pointer mp_toss_gr_object (MP mp,pointer p) {
9509   /* returns an edge structure that needs to be dereferenced */
9510   pointer e; /* the edge structure to return */
9511   e=null;
9512   @<Prepare to recycle graphical object |p|@>;
9513   mp_free_node(mp, p,mp->gr_object_size[mp_type(p)]);
9514   return e;
9515 }
9516
9517 @ @<Prepare to recycle graphical object |p|@>=
9518 switch (mp_type(p)) {
9519 case mp_fill_code: 
9520   mp_toss_knot_list(mp, mp_path_p(p));
9521   if ( mp_pen_p(p)!=null ) mp_toss_knot_list(mp, mp_pen_p(p));
9522   if ( mp_pre_script(p)!=null ) delete_str_ref(mp_pre_script(p));
9523   if ( mp_post_script(p)!=null ) delete_str_ref(mp_post_script(p));
9524   break;
9525 case mp_stroked_code: 
9526   mp_toss_knot_list(mp, mp_path_p(p));
9527   if ( mp_pen_p(p)!=null ) mp_toss_knot_list(mp, mp_pen_p(p));
9528   if ( mp_pre_script(p)!=null ) delete_str_ref(mp_pre_script(p));
9529   if ( mp_post_script(p)!=null ) delete_str_ref(mp_post_script(p));
9530   e=mp_dash_p(p);
9531   break;
9532 case mp_text_code: 
9533   delete_str_ref(mp_text_p(p));
9534   if ( mp_pre_script(p)!=null ) delete_str_ref(mp_pre_script(p));
9535   if ( mp_post_script(p)!=null ) delete_str_ref(mp_post_script(p));
9536   break;
9537 case mp_start_clip_code:
9538 case mp_start_bounds_code: 
9539   mp_toss_knot_list(mp, mp_path_p(p));
9540   break;
9541 case mp_stop_clip_code:
9542 case mp_stop_bounds_code: 
9543   break;
9544 } /* there are no other cases */
9545
9546 @ If we use |add_edge_ref| to ``copy'' edge structures, the real copying needs
9547 to be done before making a significant change to an edge structure.  Much of
9548 the work is done in a separate routine |copy_objects| that copies a list of
9549 graphical objects into a new edge header.
9550
9551 @c
9552 static pointer mp_private_edges (MP mp,pointer h) {
9553   /* make a private copy of the edge structure headed by |h| */
9554   pointer hh;  /* the edge header for the new copy */
9555   pointer p,pp;  /* pointers for copying the dash list */
9556   if ( ref_count(h)==null ) {
9557     return h;
9558   } else { 
9559     decr(ref_count(h));
9560     hh=mp_copy_objects(mp, mp_link(dummy_loc(h)),null);
9561     @<Copy the dash list from |h| to |hh|@>;
9562     @<Copy the bounding box information from |h| to |hh| and make |bblast(hh)|
9563       point into the new object list@>;
9564     return hh;
9565   }
9566 }
9567
9568 @ Here we use the fact that |dash_list(hh)=mp_link(hh)|.
9569 @^data structure assumptions@>
9570
9571 @<Copy the dash list from |h| to |hh|@>=
9572 pp=hh; p=dash_list(h);
9573 while ( (p!=null_dash) ) { 
9574   mp_link(pp)=mp_get_node(mp, dash_node_size);
9575   pp=mp_link(pp);
9576   start_x(pp)=start_x(p);
9577   stop_x(pp)=stop_x(p);
9578   p=mp_link(p);
9579 }
9580 mp_link(pp)=null_dash;
9581 dash_y(hh)=dash_y(h)
9582
9583
9584 @ |h| is an edge structure
9585
9586 @c
9587 static mp_dash_object *mp_export_dashes (MP mp, pointer q, scaled *w) {
9588   mp_dash_object *d;
9589   pointer p, h;
9590   scaled scf; /* scale factor */
9591   int *dashes = NULL;
9592   int num_dashes = 1;
9593   h = mp_dash_p(q);
9594   if (h==null ||  dash_list(h)==null_dash) 
9595         return NULL;
9596   p = dash_list(h);
9597   scf=mp_get_pen_scale(mp, mp_pen_p(q));
9598   if (scf==0) {
9599     if (*w==0) scf = dash_scale(q); else return NULL;
9600   } else {
9601     scf=mp_make_scaled(mp, *w,scf);
9602     scf=mp_take_scaled(mp, scf,dash_scale(q));
9603   }
9604   *w = scf;
9605   d = xmalloc(1,sizeof(mp_dash_object));
9606   start_x(null_dash)=start_x(p)+dash_y(h);
9607   while (p != null_dash) { 
9608         dashes = xrealloc(dashes, (num_dashes+2), sizeof(scaled));
9609         dashes[(num_dashes-1)] = 
9610       mp_take_scaled(mp,(stop_x(p)-start_x(p)),scf);
9611         dashes[(num_dashes)]   = 
9612       mp_take_scaled(mp,(start_x(mp_link(p))-stop_x(p)),scf);
9613         dashes[(num_dashes+1)] = -1; /* terminus */
9614         num_dashes+=2;
9615     p=mp_link(p);
9616   }
9617   d->array  = dashes;
9618   d->offset = mp_take_scaled(mp,mp_dash_offset(mp, h),scf);
9619   return d;
9620 }
9621
9622
9623
9624 @ @<Copy the bounding box information from |h| to |hh|...@>=
9625 minx_val(hh)=minx_val(h);
9626 miny_val(hh)=miny_val(h);
9627 maxx_val(hh)=maxx_val(h);
9628 maxy_val(hh)=maxy_val(h);
9629 bbtype(hh)=bbtype(h);
9630 p=dummy_loc(h); pp=dummy_loc(hh);
9631 while ((p!=bblast(h)) ) { 
9632   if ( p==null ) mp_confusion(mp, "bblast");
9633 @:this can't happen bblast}{\quad bblast@>
9634   p=mp_link(p); pp=mp_link(pp);
9635 }
9636 bblast(hh)=pp
9637
9638 @ Here is the promised routine for copying graphical objects into a new edge
9639 structure.  It starts copying at object~|p| and stops just before object~|q|.
9640 If |q| is null, it copies the entire sublist headed at |p|.  The resulting edge
9641 structure requires further initialization by |init_bbox|.
9642
9643 @<Declarations@>=
9644 static pointer mp_copy_objects (MP mp, pointer p, pointer q);
9645
9646 @ @c
9647 pointer mp_copy_objects (MP mp, pointer p, pointer q) {
9648   pointer hh;  /* the new edge header */
9649   pointer pp;  /* the last newly copied object */
9650   quarterword k;  /* temporary register */
9651   hh=mp_get_node(mp, edge_header_size);
9652   dash_list(hh)=null_dash;
9653   ref_count(hh)=null;
9654   pp=dummy_loc(hh);
9655   while ( (p!=q) ) {
9656     @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>;
9657   }
9658   obj_tail(hh)=pp;
9659   mp_link(pp)=null;
9660   return hh;
9661 }
9662
9663 @ @<Make |mp_link(pp)| point to a copy of object |p|, and update |p| and |pp|@>=
9664 { k=mp->gr_object_size[mp_type(p)];
9665   mp_link(pp)=mp_get_node(mp, k);
9666   pp=mp_link(pp);
9667   while ( (k>0) ) { decr(k); mp->mem[pp+k]=mp->mem[p+k];  };
9668   @<Fix anything in graphical object |pp| that should differ from the
9669     corresponding field in |p|@>;
9670   p=mp_link(p);
9671 }
9672
9673 @ @<Fix anything in graphical object |pp| that should differ from the...@>=
9674 switch (mp_type(p)) {
9675 case mp_start_clip_code:
9676 case mp_start_bounds_code: 
9677   mp_path_p(pp)=mp_copy_path(mp, mp_path_p(p));
9678   break;
9679 case mp_fill_code: 
9680   mp_path_p(pp)=mp_copy_path(mp, mp_path_p(p));
9681   if ( mp_pre_script(p)!=null )  add_str_ref(mp_pre_script(p));
9682   if ( mp_post_script(p)!=null ) add_str_ref(mp_post_script(p));
9683   if ( mp_pen_p(p)!=null ) mp_pen_p(pp)=copy_pen(mp_pen_p(p));
9684   break;
9685 case mp_stroked_code: 
9686   if ( mp_pre_script(p)!=null )  add_str_ref(mp_pre_script(p));
9687   if ( mp_post_script(p)!=null ) add_str_ref(mp_post_script(p));
9688   mp_path_p(pp)=mp_copy_path(mp, mp_path_p(p));
9689   mp_pen_p(pp)=copy_pen(mp_pen_p(p));
9690   if ( mp_dash_p(p)!=null ) add_edge_ref(mp_dash_p(pp));
9691   break;
9692 case mp_text_code: 
9693   if ( mp_pre_script(p)!=null )  add_str_ref(mp_pre_script(p));
9694   if ( mp_post_script(p)!=null ) add_str_ref(mp_post_script(p));
9695   add_str_ref(mp_text_p(pp));
9696   break;
9697 case mp_stop_clip_code:
9698 case mp_stop_bounds_code: 
9699   break;
9700 }  /* there are no other cases */
9701
9702 @ Here is one way to find an acceptable value for the second argument to
9703 |copy_objects|.  Given a non-null graphical object list, |skip_1component|
9704 skips past one picture component, where a ``picture component'' is a single
9705 graphical object, or a start bounds or start clip object and everything up
9706 through the matching stop bounds or stop clip object.  The macro version avoids
9707 procedure call overhead and error handling: |skip_component(p)(e)| advances |p|
9708 unless |p| points to a stop bounds or stop clip node, in which case it executes
9709 |e| instead.
9710
9711 @d skip_component(A)
9712     if ( ! is_start_or_stop((A)) ) (A)=mp_link((A));
9713     else if ( ! is_stop((A)) ) (A)=mp_skip_1component(mp, (A));
9714     else 
9715
9716 @c 
9717 static pointer mp_skip_1component (MP mp,pointer p) {
9718   integer lev; /* current nesting level */
9719   lev=0;
9720   do {  
9721    if ( is_start_or_stop(p) ) {
9722      if ( is_stop(p) ) decr(lev);  else incr(lev);
9723    }
9724    p=mp_link(p);
9725   } while (lev!=0);
9726   return p;
9727 }
9728
9729 @ Here is a diagnostic routine for printing an edge structure in symbolic form.
9730
9731 @<Declarations@>=
9732 static void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) ;
9733
9734 @ @c
9735 void mp_print_edges (MP mp,pointer h, const char *s, boolean nuline) {
9736   pointer p;  /* a graphical object to be printed */
9737   pointer hh,pp;  /* temporary pointers */
9738   scaled scf;  /* a scale factor for the dash pattern */
9739   boolean ok_to_dash;  /* |false| for polygonal pen strokes */
9740   mp_print_diagnostic(mp, "Edge structure",s,nuline);
9741   p=dummy_loc(h);
9742   while ( mp_link(p)!=null ) { 
9743     p=mp_link(p);
9744     mp_print_ln(mp);
9745     switch (mp_type(p)) {
9746       @<Cases for printing graphical object node |p|@>;
9747     default: 
9748           mp_print(mp, "[unknown object type!]");
9749           break;
9750     }
9751   }
9752   mp_print_nl(mp, "End edges");
9753   if ( p!=obj_tail(h) ) mp_print(mp, "?");
9754 @.End edges?@>
9755   mp_end_diagnostic(mp, true);
9756 }
9757
9758 @ @<Cases for printing graphical object node |p|@>=
9759 case mp_fill_code: 
9760   mp_print(mp, "Filled contour ");
9761   mp_print_obj_color(mp, p);
9762   mp_print_char(mp, xord(':')); mp_print_ln(mp);
9763   mp_pr_path(mp, mp_path_p(p)); mp_print_ln(mp);
9764   if ( (mp_pen_p(p)!=null) ) {
9765     @<Print join type for graphical object |p|@>;
9766     mp_print(mp, " with pen"); mp_print_ln(mp);
9767     mp_pr_pen(mp, mp_pen_p(p));
9768   }
9769   break;
9770
9771 @ @<Print join type for graphical object |p|@>=
9772 switch (ljoin_val(p)) {
9773 case 0:
9774   mp_print(mp, "mitered joins limited ");
9775   mp_print_scaled(mp, miterlim_val(p));
9776   break;
9777 case 1:
9778   mp_print(mp, "round joins");
9779   break;
9780 case 2:
9781   mp_print(mp, "beveled joins");
9782   break;
9783 default: 
9784   mp_print(mp, "?? joins");
9785 @.??@>
9786   break;
9787 }
9788
9789 @ For stroked nodes, we need to print |lcap_val(p)| as well.
9790
9791 @<Print join and cap types for stroked node |p|@>=
9792 switch (lcap_val(p)) {
9793 case 0:mp_print(mp, "butt"); break;
9794 case 1:mp_print(mp, "round"); break;
9795 case 2:mp_print(mp, "square"); break;
9796 default: mp_print(mp, "??"); break;
9797 @.??@>
9798 }
9799 mp_print(mp, " ends, ");
9800 @<Print join type for graphical object |p|@>
9801
9802 @ Here is a routine that prints the color of a graphical object if it isn't
9803 black (the default color).
9804
9805 @<Declarations@>=
9806 static void mp_print_obj_color (MP mp,pointer p) ;
9807
9808 @ @c
9809 void mp_print_obj_color (MP mp,pointer p) { 
9810   if ( mp_color_model(p)==mp_grey_model ) {
9811     if ( grey_val(p)>0 ) { 
9812       mp_print(mp, "greyed ");
9813       mp_print_compact_node(mp, obj_grey_loc(p),1);
9814     };
9815   } else if ( mp_color_model(p)==mp_cmyk_model ) {
9816     if ( (cyan_val(p)>0) || (magenta_val(p)>0) || 
9817          (yellow_val(p)>0) || (black_val(p)>0) ) { 
9818       mp_print(mp, "processcolored ");
9819       mp_print_compact_node(mp, obj_cyan_loc(p),4);
9820     };
9821   } else if ( mp_color_model(p)==mp_rgb_model ) {
9822     if ( (red_val(p)>0) || (green_val(p)>0) || (blue_val(p)>0) ) { 
9823       mp_print(mp, "colored "); 
9824       mp_print_compact_node(mp, obj_red_loc(p),3);
9825     };
9826   }
9827 }
9828
9829 @ We also need a procedure for printing consecutive scaled values as if they
9830 were a known big node.
9831
9832 @<Declarations@>=
9833 static void mp_print_compact_node (MP mp,pointer p, quarterword k) ;
9834
9835 @ @c
9836 void mp_print_compact_node (MP mp,pointer p, quarterword k) {
9837   pointer q;  /* last location to print */
9838   q=p+k-1;
9839   mp_print_char(mp, xord('('));
9840   while ( p<=q ){ 
9841     mp_print_scaled(mp, mp->mem[p].sc);
9842     if ( p<q ) mp_print_char(mp, xord(','));
9843     incr(p);
9844   }
9845   mp_print_char(mp, xord(')'));
9846 }
9847
9848 @ @<Cases for printing graphical object node |p|@>=
9849 case mp_stroked_code: 
9850   mp_print(mp, "Filled pen stroke ");
9851   mp_print_obj_color(mp, p);
9852   mp_print_char(mp, xord(':')); mp_print_ln(mp);
9853   mp_pr_path(mp, mp_path_p(p));
9854   if ( mp_dash_p(p)!=null ) { 
9855     mp_print_nl(mp, "dashed (");
9856     @<Finish printing the dash pattern that |p| refers to@>;
9857   }
9858   mp_print_ln(mp);
9859   @<Print join and cap types for stroked node |p|@>;
9860   mp_print(mp, " with pen"); mp_print_ln(mp);
9861   if ( mp_pen_p(p)==null ) mp_print(mp, "???"); /* shouldn't happen */
9862 @.???@>
9863   else mp_pr_pen(mp, mp_pen_p(p));
9864   break;
9865
9866 @ Normally, the  |dash_list| field in an edge header is set to |null_dash|
9867 when it is not known to define a suitable dash pattern.  This is disallowed
9868 here because the |mp_dash_p| field should never point to such an edge header.
9869 Note that memory is allocated for |start_x(null_dash)| and we are free to
9870 give it any convenient value.
9871
9872 @<Finish printing the dash pattern that |p| refers to@>=
9873 ok_to_dash=pen_is_elliptical(mp_pen_p(p));
9874 if ( ! ok_to_dash ) scf=unity; else scf=dash_scale(p);
9875 hh=mp_dash_p(p);
9876 pp=dash_list(hh);
9877 if ( (pp==null_dash) || (dash_y(hh)<0) ) {
9878   mp_print(mp, " ??");
9879 } else { start_x(null_dash)=start_x(pp)+dash_y(hh);
9880   while ( pp!=null_dash ) { 
9881     mp_print(mp, "on ");
9882     mp_print_scaled(mp, mp_take_scaled(mp, stop_x(pp)-start_x(pp),scf));
9883     mp_print(mp, " off ");
9884     mp_print_scaled(mp, mp_take_scaled(mp, start_x(mp_link(pp))-stop_x(pp),scf));
9885     pp = mp_link(pp);
9886     if ( pp!=null_dash ) mp_print_char(mp, xord(' '));
9887   }
9888   mp_print(mp, ") shifted ");
9889   mp_print_scaled(mp, -mp_take_scaled(mp, mp_dash_offset(mp, hh),scf));
9890   if ( ! ok_to_dash || (dash_y(hh)==0) ) mp_print(mp, " (this will be ignored)");
9891 }
9892
9893 @ @<Declarations@>=
9894 static scaled mp_dash_offset (MP mp,pointer h) ;
9895
9896 @ @c
9897 scaled mp_dash_offset (MP mp,pointer h) {
9898   scaled x;  /* the answer */
9899   if (dash_list(h)==null_dash || dash_y(h)<0) mp_confusion(mp, "dash0");
9900 @:this can't happen dash0}{\quad dash0@>
9901   if ( dash_y(h)==0 ) {
9902     x=0; 
9903   } else { 
9904     x=-(start_x(dash_list(h)) % dash_y(h));
9905     if ( x<0 ) x=x+dash_y(h);
9906   }
9907   return x;
9908 }
9909
9910 @ @<Cases for printing graphical object node |p|@>=
9911 case mp_text_code: 
9912   mp_print_char(mp, xord('"')); mp_print_str(mp,mp_text_p(p));
9913   mp_print(mp, "\" infont \""); mp_print(mp, mp->font_name[mp_font_n(p)]);
9914   mp_print_char(mp, xord('"')); mp_print_ln(mp);
9915   mp_print_obj_color(mp, p);
9916   mp_print(mp, "transformed ");
9917   mp_print_compact_node(mp, text_tx_loc(p),6);
9918   break;
9919
9920 @ @<Cases for printing graphical object node |p|@>=
9921 case mp_start_clip_code: 
9922   mp_print(mp, "clipping path:");
9923   mp_print_ln(mp);
9924   mp_pr_path(mp, mp_path_p(p));
9925   break;
9926 case mp_stop_clip_code: 
9927   mp_print(mp, "stop clipping");
9928   break;
9929
9930 @ @<Cases for printing graphical object node |p|@>=
9931 case mp_start_bounds_code: 
9932   mp_print(mp, "setbounds path:");
9933   mp_print_ln(mp);
9934   mp_pr_path(mp, mp_path_p(p));
9935   break;
9936 case mp_stop_bounds_code: 
9937   mp_print(mp, "end of setbounds");
9938   break;
9939
9940 @ To initialize the |dash_list| field in an edge header~|h|, we need a
9941 subroutine that scans an edge structure and tries to interpret it as a dash
9942 pattern.  This can only be done when there are no filled regions or clipping
9943 paths and all the pen strokes have the same color.  The first step is to let
9944 $y_0$ be the initial $y$~coordinate of the first pen stroke.  Then we implicitly
9945 project all the pen stroke paths onto the line $y=y_0$ and require that there
9946 be no retracing.  If the resulting paths cover a range of $x$~coordinates of
9947 length $\Delta x$, we set |dash_y(h)| to the length of the dash pattern by
9948 finding the maximum of $\Delta x$ and the absolute value of~$y_0$.
9949
9950 @c 
9951 static pointer mp_make_dashes (MP mp,pointer h) { /* returns |h| or |null| */
9952   pointer p;  /* this scans the stroked nodes in the object list */
9953   pointer p0;  /* if not |null| this points to the first stroked node */
9954   pointer pp,qq,rr;  /* pointers into |mp_path_p(p)| */
9955   pointer d,dd;  /* pointers used to create the dash list */
9956   scaled y0;
9957   @<Other local variables in |make_dashes|@>;
9958   y0=0;  /* the initial $y$ coordinate */
9959   if ( dash_list(h)!=null_dash ) 
9960         return h;
9961   p0=null;
9962   p=mp_link(dummy_loc(h));
9963   while ( p!=null ) { 
9964     if ( mp_type(p)!=mp_stroked_code ) {
9965       @<Compain that the edge structure contains a node of the wrong type
9966         and |goto not_found|@>;
9967     }
9968     pp=mp_path_p(p);
9969     if ( p0==null ){ p0=p; y0=mp_y_coord(pp);  };
9970     @<Make |d| point to a new dash node created from stroke |p| and path |pp|
9971       or |goto not_found| if there is an error@>;
9972     @<Insert |d| into the dash list and |goto not_found| if there is an error@>;
9973     p=mp_link(p);
9974   }
9975   if ( dash_list(h)==null_dash ) 
9976     goto NOT_FOUND; /* No error message */
9977   @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>;
9978   @<Set |dash_y(h)| and merge the first and last dashes if necessary@>;
9979   return h;
9980 NOT_FOUND: 
9981   @<Flush the dash list, recycle |h| and return |null|@>;
9982 }
9983
9984 @ @<Compain that the edge structure contains a node of the wrong type...@>=
9985
9986 print_err("Picture is too complicated to use as a dash pattern");
9987 help3("When you say `dashed p', picture p should not contain any",
9988   "text, filled regions, or clipping paths.  This time it did",
9989   "so I'll just make it a solid line instead.");
9990 mp_put_get_error(mp);
9991 goto NOT_FOUND;
9992 }
9993
9994 @ A similar error occurs when monotonicity fails.
9995
9996 @<Declarations@>=
9997 static void mp_x_retrace_error (MP mp) ;
9998
9999 @ @c
10000 void mp_x_retrace_error (MP mp) { 
10001 print_err("Picture is too complicated to use as a dash pattern");
10002 help3("When you say `dashed p', every path in p should be monotone",
10003   "in x and there must be no overlapping.  This failed",
10004   "so I'll just make it a solid line instead.");
10005 mp_put_get_error(mp);
10006 }
10007
10008 @ We stash |p| in |mp_info(d)| if |mp_dash_p(p)<>0| so that subsequent processing can
10009 handle the case where the pen stroke |p| is itself dashed.
10010
10011 @<Make |d| point to a new dash node created from stroke |p| and path...@>=
10012 @<Make sure |p| and |p0| are the same color and |goto not_found| if there is
10013   an error@>;
10014 rr=pp;
10015 if ( mp_link(pp)!=pp ) {
10016   do {  
10017     qq=rr; rr=mp_link(rr);
10018     @<Check for retracing between knots |qq| and |rr| and |goto not_found|
10019       if there is a problem@>;
10020   } while (mp_right_type(rr)!=mp_endpoint);
10021 }
10022 d=mp_get_node(mp, dash_node_size);
10023 if ( mp_dash_p(p)==0 ) mp_info(d)=0;  else mp_info(d)=p;
10024 if ( mp_x_coord(pp)<mp_x_coord(rr) ) { 
10025   start_x(d)=mp_x_coord(pp);
10026   stop_x(d)=mp_x_coord(rr);
10027 } else { 
10028   start_x(d)=mp_x_coord(rr);
10029   stop_x(d)=mp_x_coord(pp);
10030 }
10031
10032 @ We also need to check for the case where the segment from |qq| to |rr| is
10033 monotone in $x$ but is reversed relative to the path from |pp| to |qq|.
10034
10035 @<Check for retracing between knots |qq| and |rr| and |goto not_found|...@>=
10036 x0=mp_x_coord(qq);
10037 x1=mp_right_x(qq);
10038 x2=mp_left_x(rr);
10039 x3=mp_x_coord(rr);
10040 if ( (x0>x1) || (x1>x2) || (x2>x3) ) {
10041   if ( (x0<x1) || (x1<x2) || (x2<x3) ) {
10042     if ( mp_ab_vs_cd(mp, x2-x1,x2-x1,x1-x0,x3-x2)>0 ) {
10043       mp_x_retrace_error(mp); goto NOT_FOUND;
10044     }
10045   }
10046 }
10047 if ( (mp_x_coord(pp)>x0) || (x0>x3) ) {
10048   if ( (mp_x_coord(pp)<x0) || (x0<x3) ) {
10049     mp_x_retrace_error(mp); goto NOT_FOUND;
10050   }
10051 }
10052
10053 @ @<Other local variables in |make_dashes|@>=
10054   scaled x0,x1,x2,x3;  /* $x$ coordinates of the segment from |qq| to |rr| */
10055
10056 @ @<Make sure |p| and |p0| are the same color and |goto not_found|...@>=
10057 if ( (red_val(p)!=red_val(p0)) || (black_val(p)!=black_val(p0)) ||
10058   (green_val(p)!=green_val(p0)) || (blue_val(p)!=blue_val(p0)) ) {
10059   print_err("Picture is too complicated to use as a dash pattern");
10060   help3("When you say `dashed p', everything in picture p should",
10061     "be the same color.  I can\'t handle your color changes",
10062     "so I'll just make it a solid line instead.");
10063   mp_put_get_error(mp);
10064   goto NOT_FOUND;
10065 }
10066
10067 @ @<Insert |d| into the dash list and |goto not_found| if there is an error@>=
10068 start_x(null_dash)=stop_x(d);
10069 dd=h; /* this makes |mp_link(dd)=dash_list(h)| */
10070 while ( start_x(mp_link(dd))<stop_x(d) )
10071   dd=mp_link(dd);
10072 if ( dd!=h ) {
10073   if ( (stop_x(dd)>start_x(d)) )
10074     { mp_x_retrace_error(mp); goto NOT_FOUND;  };
10075 }
10076 mp_link(d)=mp_link(dd);
10077 mp_link(dd)=d
10078
10079 @ @<Set |dash_y(h)| and merge the first and last dashes if necessary@>=
10080 d=dash_list(h);
10081 while ( (mp_link(d)!=null_dash) )
10082   d=mp_link(d);
10083 dd=dash_list(h);
10084 dash_y(h)=stop_x(d)-start_x(dd);
10085 if ( abs(y0)>dash_y(h) ) {
10086   dash_y(h)=abs(y0);
10087 } else if ( d!=dd ) { 
10088   dash_list(h)=mp_link(dd);
10089   stop_x(d)=stop_x(dd)+dash_y(h);
10090   mp_free_node(mp, dd,dash_node_size);
10091 }
10092
10093 @ We get here when the argument is a null picture or when there is an error.
10094 Recovering from an error involves making |dash_list(h)| empty to indicate
10095 that |h| is not known to be a valid dash pattern.  We also dereference |h|
10096 since it is not being used for the return value.
10097
10098 @<Flush the dash list, recycle |h| and return |null|@>=
10099 mp_flush_dash_list(mp, h);
10100 delete_edge_ref(h);
10101 return null
10102
10103 @ Having carefully saved the dashed stroked nodes in the
10104 corresponding dash nodes, we must be prepared to break up these dashes into
10105 smaller dashes.
10106
10107 @<Scan |dash_list(h)| and deal with any dashes that are themselves dashed@>=
10108 d=h;  /* now |mp_link(d)=dash_list(h)| */
10109 while ( mp_link(d)!=null_dash ) {
10110   ds=mp_info(mp_link(d));
10111   if ( ds==null ) { 
10112     d=mp_link(d);
10113   } else {
10114     hh=mp_dash_p(ds);
10115     hsf=dash_scale(ds);
10116     if ( (hh==null) ) mp_confusion(mp, "dash1");
10117 @:this can't happen dash0}{\quad dash1@>
10118     if ( dash_y(hh)==0 ) {
10119       d=mp_link(d);
10120     } else { 
10121       if ( dash_list(hh)==null ) mp_confusion(mp, "dash1");
10122 @:this can't happen dash0}{\quad dash1@>
10123       @<Replace |mp_link(d)| by a dashed version as determined by edge header
10124           |hh| and scale factor |ds|@>;
10125     }
10126   }
10127 }
10128
10129 @ @<Other local variables in |make_dashes|@>=
10130 pointer dln;  /* |mp_link(d)| */
10131 pointer hh;  /* an edge header that tells how to break up |dln| */
10132 scaled hsf;  /* the dash pattern from |hh| gets scaled by this */
10133 pointer ds;  /* the stroked node from which |hh| and |hsf| are derived */
10134 scaled xoff;  /* added to $x$ values in |dash_list(hh)| to match |dln| */
10135
10136 @ @<Replace |mp_link(d)| by a dashed version as determined by edge header...@>=
10137 dln=mp_link(d);
10138 dd=dash_list(hh);
10139 xoff=start_x(dln)-mp_take_scaled(mp, hsf,start_x(dd))-
10140         mp_take_scaled(mp, hsf,mp_dash_offset(mp, hh));
10141 start_x(null_dash)=mp_take_scaled(mp, hsf,start_x(dd))
10142                    +mp_take_scaled(mp, hsf,dash_y(hh));
10143 stop_x(null_dash)=start_x(null_dash);
10144 @<Advance |dd| until finding the first dash that overlaps |dln| when
10145   offset by |xoff|@>;
10146 while ( start_x(dln)<=stop_x(dln) ) {
10147   @<If |dd| has `fallen off the end', back up to the beginning and fix |xoff|@>;
10148   @<Insert a dash between |d| and |dln| for the overlap with the offset version
10149     of |dd|@>;
10150   dd=mp_link(dd);
10151   start_x(dln)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10152 }
10153 mp_link(d)=mp_link(dln);
10154 mp_free_node(mp, dln,dash_node_size)
10155
10156 @ The name of this module is a bit of a lie because we just find the
10157 first |dd| where |take_scaled (hsf, stop_x(dd))| is large enough to make an
10158 overlap possible.  It could be that the unoffset version of dash |dln| falls
10159 in the gap between |dd| and its predecessor.
10160
10161 @<Advance |dd| until finding the first dash that overlaps |dln| when...@>=
10162 while ( xoff+mp_take_scaled(mp, hsf,stop_x(dd))<start_x(dln) ) {
10163   dd=mp_link(dd);
10164 }
10165
10166 @ @<If |dd| has `fallen off the end', back up to the beginning and fix...@>=
10167 if ( dd==null_dash ) { 
10168   dd=dash_list(hh);
10169   xoff=xoff+mp_take_scaled(mp, hsf,dash_y(hh));
10170 }
10171
10172 @ At this point we already know that
10173 |start_x(dln)<=xoff+take_scaled(hsf,stop_x(dd))|.
10174
10175 @<Insert a dash between |d| and |dln| for the overlap with the offset...@>=
10176 if ( (xoff+mp_take_scaled(mp, hsf,start_x(dd)))<=stop_x(dln) ) {
10177   mp_link(d)=mp_get_node(mp, dash_node_size);
10178   d=mp_link(d);
10179   mp_link(d)=dln;
10180   if ( start_x(dln)>(xoff+mp_take_scaled(mp, hsf,start_x(dd))))
10181     start_x(d)=start_x(dln);
10182   else 
10183     start_x(d)=xoff+mp_take_scaled(mp, hsf,start_x(dd));
10184   if ( stop_x(dln)<(xoff+mp_take_scaled(mp, hsf,stop_x(dd)))) 
10185     stop_x(d)=stop_x(dln);
10186   else 
10187     stop_x(d)=xoff+mp_take_scaled(mp, hsf,stop_x(dd));
10188 }
10189
10190 @ The next major task is to update the bounding box information in an edge
10191 header~|h|. This is done via a procedure |adjust_bbox| that enlarges an edge
10192 header's bounding box to accommodate the box computed by |path_bbox| or
10193 |pen_bbox|. (This is stored in global variables |minx|, |miny|, |maxx|, and
10194 |maxy|.)
10195
10196 @c static void mp_adjust_bbox (MP mp,pointer h) { 
10197   if ( mp_minx<minx_val(h) ) minx_val(h)=mp_minx;
10198   if ( mp_miny<miny_val(h) ) miny_val(h)=mp_miny;
10199   if ( mp_maxx>maxx_val(h) ) maxx_val(h)=mp_maxx;
10200   if ( mp_maxy>maxy_val(h) ) maxy_val(h)=mp_maxy;
10201 }
10202
10203 @ Here is a special routine for updating the bounding box information in
10204 edge header~|h| to account for the squared-off ends of a non-cyclic path~|p|
10205 that is to be stroked with the pen~|pp|.
10206
10207 @c static void mp_box_ends (MP mp, pointer p, pointer pp, pointer h) {
10208   pointer q;  /* a knot node adjacent to knot |p| */
10209   fraction dx,dy;  /* a unit vector in the direction out of the path at~|p| */
10210   scaled d;  /* a factor for adjusting the length of |(dx,dy)| */
10211   scaled z;  /* a coordinate being tested against the bounding box */
10212   scaled xx,yy;  /* the extreme pen vertex in the |(dx,dy)| direction */
10213   integer i; /* a loop counter */
10214   if ( mp_right_type(p)!=mp_endpoint ) { 
10215     q=mp_link(p);
10216     while (1) { 
10217       @<Make |(dx,dy)| the final direction for the path segment from
10218         |q| to~|p|; set~|d|@>;
10219       d=mp_pyth_add(mp, dx,dy);
10220       if ( d>0 ) { 
10221          @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>;
10222          for (i=1;i<= 2;i++) { 
10223            @<Use |(dx,dy)| to generate a vertex of the square end cap and
10224              update the bounding box to accommodate it@>;
10225            dx=-dx; dy=-dy; 
10226         }
10227       }
10228       if ( mp_right_type(p)==mp_endpoint ) {
10229          return;
10230       } else {
10231         @<Advance |p| to the end of the path and make |q| the previous knot@>;
10232       } 
10233     }
10234   }
10235 }
10236
10237 @ @<Make |(dx,dy)| the final direction for the path segment from...@>=
10238 if ( q==mp_link(p) ) { 
10239   dx=mp_x_coord(p)-mp_right_x(p);
10240   dy=mp_y_coord(p)-mp_right_y(p);
10241   if ( (dx==0)&&(dy==0) ) {
10242     dx=mp_x_coord(p)-mp_left_x(q);
10243     dy=mp_y_coord(p)-mp_left_y(q);
10244   }
10245 } else { 
10246   dx=mp_x_coord(p)-mp_left_x(p);
10247   dy=mp_y_coord(p)-mp_left_y(p);
10248   if ( (dx==0)&&(dy==0) ) {
10249     dx=mp_x_coord(p)-mp_right_x(q);
10250     dy=mp_y_coord(p)-mp_right_y(q);
10251   }
10252 }
10253 dx=mp_x_coord(p)-mp_x_coord(q);
10254 dy=mp_y_coord(p)-mp_y_coord(q)
10255
10256 @ @<Normalize the direction |(dx,dy)| and find the pen offset |(xx,yy)|@>=
10257 dx=mp_make_fraction(mp, dx,d);
10258 dy=mp_make_fraction(mp, dy,d);
10259 mp_find_offset(mp, -dy,dx,pp);
10260 xx=mp->cur_x; yy=mp->cur_y
10261
10262 @ @<Use |(dx,dy)| to generate a vertex of the square end cap and...@>=
10263 mp_find_offset(mp, dx,dy,pp);
10264 d=mp_take_fraction(mp, xx-mp->cur_x,dx)+mp_take_fraction(mp, yy-mp->cur_y,dy);
10265 if ( ((d<0)&&(i==1)) || ((d>0)&&(i==2))) 
10266   mp_confusion(mp, "box_ends");
10267 @:this can't happen box ends}{\quad\\{box\_ends}@>
10268 z=mp_x_coord(p)+mp->cur_x+mp_take_fraction(mp, d,dx);
10269 if ( z<minx_val(h) ) minx_val(h)=z;
10270 if ( z>maxx_val(h) ) maxx_val(h)=z;
10271 z=mp_y_coord(p)+mp->cur_y+mp_take_fraction(mp, d,dy);
10272 if ( z<miny_val(h) ) miny_val(h)=z;
10273 if ( z>maxy_val(h) ) maxy_val(h)=z
10274
10275 @ @<Advance |p| to the end of the path and make |q| the previous knot@>=
10276 do {  
10277   q=p;
10278   p=mp_link(p);
10279 } while (mp_right_type(p)!=mp_endpoint)
10280
10281 @ The major difficulty in finding the bounding box of an edge structure is the
10282 effect of clipping paths.  We treat them conservatively by only clipping to the
10283 clipping path's bounding box, but this still
10284 requires recursive calls to |set_bbox| in order to find the bounding box of
10285 @^recursion@>
10286 the objects to be clipped.  Such calls are distinguished by the fact that the
10287 boolean parameter |top_level| is false.
10288
10289 @c 
10290 void mp_set_bbox (MP mp,pointer h, boolean top_level) {
10291   pointer p;  /* a graphical object being considered */
10292   scaled sminx,sminy,smaxx,smaxy;
10293   /* for saving the bounding box during recursive calls */
10294   scaled x0,x1,y0,y1;  /* temporary registers */
10295   integer lev;  /* nesting level for |mp_start_bounds_code| nodes */
10296   @<Wipe out any existing bounding box information if |bbtype(h)| is
10297   incompatible with |internal[mp_true_corners]|@>;
10298   while ( mp_link(bblast(h))!=null ) { 
10299     p=mp_link(bblast(h));
10300     bblast(h)=p;
10301     switch (mp_type(p)) {
10302     case mp_stop_clip_code: 
10303       if ( top_level ) mp_confusion(mp, "bbox");  else return;
10304 @:this can't happen bbox}{\quad bbox@>
10305       break;
10306     @<Other cases for updating the bounding box based on the type of object |p|@>;
10307     } /* all cases are enumerated above */
10308   }
10309   if ( ! top_level ) mp_confusion(mp, "bbox");
10310 }
10311
10312 @ @<Declarations@>=
10313 static void mp_set_bbox (MP mp,pointer h, boolean top_level);
10314
10315 @ @<Wipe out any existing bounding box information if |bbtype(h)| is...@>=
10316 switch (bbtype(h)) {
10317 case no_bounds: 
10318   break;
10319 case bounds_set: 
10320   if ( mp->internal[mp_true_corners]>0 ) mp_init_bbox(mp, h);
10321   break;
10322 case bounds_unset: 
10323   if ( mp->internal[mp_true_corners]<=0 ) mp_init_bbox(mp, h);
10324   break;
10325 } /* there are no other cases */
10326
10327 @ @<Other cases for updating the bounding box...@>=
10328 case mp_fill_code: 
10329   mp_path_bbox(mp, mp_path_p(p));
10330   if ( mp_pen_p(p)!=null ) { 
10331     x0=mp_minx; y0=mp_miny;
10332     x1=mp_maxx; y1=mp_maxy;
10333     mp_pen_bbox(mp, mp_pen_p(p));
10334     mp_minx=mp_minx+x0;
10335     mp_miny=mp_miny+y0;
10336     mp_maxx=mp_maxx+x1;
10337     mp_maxy=mp_maxy+y1;
10338   }
10339   mp_adjust_bbox(mp, h);
10340   break;
10341
10342 @ @<Other cases for updating the bounding box...@>=
10343 case mp_start_bounds_code: 
10344   if ( mp->internal[mp_true_corners]>0 ) {
10345     bbtype(h)=bounds_unset;
10346   } else { 
10347     bbtype(h)=bounds_set;
10348     mp_path_bbox(mp, mp_path_p(p));
10349     mp_adjust_bbox(mp, h);
10350     @<Scan to the matching |mp_stop_bounds_code| node and update |p| and
10351       |bblast(h)|@>;
10352   }
10353   break;
10354 case mp_stop_bounds_code: 
10355   if ( mp->internal[mp_true_corners]<=0 ) mp_confusion(mp, "bbox2");
10356 @:this can't happen bbox2}{\quad bbox2@>
10357   break;
10358
10359 @ @<Scan to the matching |mp_stop_bounds_code| node and update |p| and...@>=
10360 lev=1;
10361 while ( lev!=0 ) { 
10362   if ( mp_link(p)==null ) mp_confusion(mp, "bbox2");
10363 @:this can't happen bbox2}{\quad bbox2@>
10364   p=mp_link(p);
10365   if ( mp_type(p)==mp_start_bounds_code ) incr(lev);
10366   else if ( mp_type(p)==mp_stop_bounds_code ) decr(lev);
10367 }
10368 bblast(h)=p
10369
10370 @ It saves a lot of grief here to be slightly conservative and not account for
10371 omitted parts of dashed lines.  We also don't worry about the material omitted
10372 when using butt end caps.  The basic computation is for round end caps and
10373 |box_ends| augments it for square end caps.
10374
10375 @<Other cases for updating the bounding box...@>=
10376 case mp_stroked_code: 
10377   mp_path_bbox(mp, mp_path_p(p));
10378   x0=mp_minx; y0=mp_miny;
10379   x1=mp_maxx; y1=mp_maxy;
10380   mp_pen_bbox(mp, mp_pen_p(p));
10381   mp_minx=mp_minx+x0;
10382   mp_miny=mp_miny+y0;
10383   mp_maxx=mp_maxx+x1;
10384   mp_maxy=mp_maxy+y1;
10385   mp_adjust_bbox(mp, h);
10386   if ( (mp_left_type(mp_path_p(p))==mp_endpoint)&&(lcap_val(p)==2) )
10387     mp_box_ends(mp, mp_path_p(p), mp_pen_p(p), h);
10388   break;
10389
10390 @ The height width and depth information stored in a text node determines a
10391 rectangle that needs to be transformed according to the transformation
10392 parameters stored in the text node.
10393
10394 @<Other cases for updating the bounding box...@>=
10395 case mp_text_code: 
10396   x1=mp_take_scaled(mp, txx_val(p),width_val(p));
10397   y0=mp_take_scaled(mp, txy_val(p),-depth_val(p));
10398   y1=mp_take_scaled(mp, txy_val(p),height_val(p));
10399   mp_minx=tx_val(p);
10400   mp_maxx=mp_minx;
10401   if ( y0<y1 ) { mp_minx=mp_minx+y0; mp_maxx=mp_maxx+y1;  }
10402   else         { mp_minx=mp_minx+y1; mp_maxx=mp_maxx+y0;  }
10403   if ( x1<0 ) mp_minx=mp_minx+x1;  else mp_maxx=mp_maxx+x1;
10404   x1=mp_take_scaled(mp, tyx_val(p),width_val(p));
10405   y0=mp_take_scaled(mp, tyy_val(p),-depth_val(p));
10406   y1=mp_take_scaled(mp, tyy_val(p),height_val(p));
10407   mp_miny=ty_val(p);
10408   mp_maxy=mp_miny;
10409   if ( y0<y1 ) { mp_miny=mp_miny+y0; mp_maxy=mp_maxy+y1;  }
10410   else         { mp_miny=mp_miny+y1; mp_maxy=mp_maxy+y0;  }
10411   if ( x1<0 ) mp_miny=mp_miny+x1;  else mp_maxy=mp_maxy+x1;
10412   mp_adjust_bbox(mp, h);
10413   break;
10414
10415 @ This case involves a recursive call that advances |bblast(h)| to the node of
10416 type |mp_stop_clip_code| that matches |p|.
10417
10418 @<Other cases for updating the bounding box...@>=
10419 case mp_start_clip_code: 
10420   mp_path_bbox(mp, mp_path_p(p));
10421   x0=mp_minx; y0=mp_miny;
10422   x1=mp_maxx; y1=mp_maxy;
10423   sminx=minx_val(h); sminy=miny_val(h);
10424   smaxx=maxx_val(h); smaxy=maxy_val(h);
10425   @<Reinitialize the bounding box in header |h| and call |set_bbox| recursively
10426     starting at |mp_link(p)|@>;
10427   @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,
10428     |y0|, |y1|@>;
10429   mp_minx=sminx; mp_miny=sminy;
10430   mp_maxx=smaxx; mp_maxy=smaxy;
10431   mp_adjust_bbox(mp, h);
10432   break;
10433
10434 @ @<Reinitialize the bounding box in header |h| and call |set_bbox|...@>=
10435 minx_val(h)=el_gordo;
10436 miny_val(h)=el_gordo;
10437 maxx_val(h)=-el_gordo;
10438 maxy_val(h)=-el_gordo;
10439 mp_set_bbox(mp, h,false)
10440
10441 @ @<Clip the bounding box in |h| to the rectangle given by |x0|, |x1|,...@>=
10442 if ( minx_val(h)<x0 ) minx_val(h)=x0;
10443 if ( miny_val(h)<y0 ) miny_val(h)=y0;
10444 if ( maxx_val(h)>x1 ) maxx_val(h)=x1;
10445 if ( maxy_val(h)>y1 ) maxy_val(h)=y1
10446
10447 @* \[22] Finding an envelope.
10448 When \MP\ has a path and a polygonal pen, it needs to express the desired
10449 shape in terms of things \ps\ can understand.  The present task is to compute
10450 a new path that describes the region to be filled.  It is convenient to
10451 define this as a two step process where the first step is determining what
10452 offset to use for each segment of the path.
10453
10454 @ Given a pointer |c| to a cyclic path,
10455 and a pointer~|h| to the first knot of a pen polygon,
10456 the |offset_prep| routine changes the path into cubics that are
10457 associated with particular pen offsets. Thus if the cubic between |p|
10458 and~|q| is associated with the |k|th offset and the cubic between |q| and~|r|
10459 has offset |l| then |mp_info(q)=zero_off+l-k|. (The constant |zero_off| is added
10460 to because |l-k| could be negative.)
10461
10462 After overwriting the type information with offset differences, we no longer
10463 have a true path so we refer to the knot list returned by |offset_prep| as an
10464 ``envelope spec.''
10465 @^envelope spec@>
10466 Since an envelope spec only determines relative changes in pen offsets,
10467 |offset_prep| sets a global variable |spec_offset| to the relative change from
10468 |h| to the first offset.
10469
10470 @d zero_off 16384 /* added to offset changes to make them positive */
10471
10472 @<Glob...@>=
10473 integer spec_offset; /* number of pen edges between |h| and the initial offset */
10474
10475 @ @c
10476 static pointer mp_offset_prep (MP mp,pointer c, pointer h) {
10477   halfword n; /* the number of vertices in the pen polygon */
10478   pointer c0,p,q,q0,r,w, ww; /* for list manipulation */
10479   integer k_needed; /* amount to be added to |mp_info(p)| when it is computed */
10480   pointer w0; /* a pointer to pen offset to use just before |p| */
10481   scaled dxin,dyin; /* the direction into knot |p| */
10482   integer turn_amt; /* change in pen offsets for the current cubic */
10483   @<Other local variables for |offset_prep|@>;
10484   dx0=0; dy0=0;
10485   @<Initialize the pen size~|n|@>;
10486   @<Initialize the incoming direction and pen offset at |c|@>;
10487   p=c; c0=c; k_needed=0;
10488   do {  
10489     q=mp_link(p);
10490     @<Split the cubic between |p| and |q|, if necessary, into cubics
10491       associated with single offsets, after which |q| should
10492       point to the end of the final such cubic@>;
10493   NOT_FOUND:
10494     @<Advance |p| to node |q|, removing any ``dead'' cubics that
10495       might have been introduced by the splitting process@>;
10496   } while (q!=c);
10497   @<Fix the offset change in |mp_info(c)| and set |c| to the return value of
10498     |offset_prep|@>;
10499   return c;
10500 }
10501
10502 @ We shall want to keep track of where certain knots on the cyclic path
10503 wind up in the envelope spec.  It doesn't suffice just to keep pointers to
10504 knot nodes because some nodes are deleted while removing dead cubics.  Thus
10505 |offset_prep| updates the following pointers
10506
10507 @<Glob...@>=
10508 pointer spec_p1;
10509 pointer spec_p2; /* pointers to distinguished knots */
10510
10511 @ @<Set init...@>=
10512 mp->spec_p1=null; mp->spec_p2=null;
10513
10514 @ @<Initialize the pen size~|n|@>=
10515 n=0; p=h;
10516 do {  
10517   incr(n);
10518   p=mp_link(p);
10519 } while (p!=h)
10520
10521 @ Since the true incoming direction isn't known yet, we just pick a direction
10522 consistent with the pen offset~|h|.  If this is wrong, it can be corrected
10523 later.
10524
10525 @<Initialize the incoming direction and pen offset at |c|@>=
10526 dxin=mp_x_coord(mp_link(h))-mp_x_coord(knil(h));
10527 dyin=mp_y_coord(mp_link(h))-mp_y_coord(knil(h));
10528 if ( (dxin==0)&&(dyin==0) ) {
10529   dxin=mp_y_coord(knil(h))-mp_y_coord(h);
10530   dyin=mp_x_coord(h)-mp_x_coord(knil(h));
10531 }
10532 w0=h
10533
10534 @ We must be careful not to remove the only cubic in a cycle.
10535
10536 But we must also be careful for another reason. If the user-supplied
10537 path starts with a set of degenerate cubics, the target node |q| can
10538 be collapsed to the initial node |p| which might be the same as the
10539 initial node |c| of the curve. This would cause the |offset_prep| routine
10540 to bail out too early, causing distress later on. (See for example
10541 the testcase reported by Bogus\l{}aw Jackowski in tracker id 267, case 52c
10542 on Sarovar.)
10543
10544 @<Advance |p| to node |q|, removing any ``dead'' cubics...@>=
10545 q0=q;
10546 do { 
10547   r=mp_link(p);
10548   if ( mp_x_coord(p)==mp_right_x(p) && mp_y_coord(p)==mp_right_y(p) &&
10549        mp_x_coord(p)==mp_left_x(r)  && mp_y_coord(p)==mp_left_y(r) &&
10550        mp_x_coord(p)==mp_x_coord(r) && mp_y_coord(p)==mp_y_coord(r) &&
10551        r!=p ) {
10552       @<Remove the cubic following |p| and update the data structures
10553         to merge |r| into |p|@>;
10554   }
10555   p=r;
10556 } while (p!=q);
10557 /* Check if we removed too much */
10558 if ((q!=q0)&&(q!=c||c==c0))
10559   q = mp_link(q)
10560
10561 @ @<Remove the cubic following |p| and update the data structures...@>=
10562 { k_needed=mp_info(p)-zero_off;
10563   if ( r==q ) { 
10564     q=p;
10565   } else { 
10566     mp_info(p)=k_needed+mp_info(r);
10567     k_needed=0;
10568   };
10569   if ( r==c ) { mp_info(p)=mp_info(c); c=p; };
10570   if ( r==mp->spec_p1 ) mp->spec_p1=p;
10571   if ( r==mp->spec_p2 ) mp->spec_p2=p;
10572   r=p; mp_remove_cubic(mp, p);
10573 }
10574
10575 @ Not setting the |info| field of the newly created knot allows the splitting
10576 routine to work for paths.
10577
10578 @<Declarations@>=
10579 static void mp_split_cubic (MP mp,pointer p, fraction t) ;
10580
10581 @ @c
10582 void mp_split_cubic (MP mp,pointer p, fraction t) { /* splits the cubic after |p| */
10583   scaled v; /* an intermediate value */
10584   pointer q,r; /* for list manipulation */
10585   q=mp_link(p); r=mp_get_node(mp, knot_node_size); mp_link(p)=r; mp_link(r)=q;
10586   mp_originator(r)=mp_program_code;
10587   mp_left_type(r)=mp_explicit; mp_right_type(r)=mp_explicit;
10588   v=t_of_the_way(mp_right_x(p),mp_left_x(q));
10589   mp_right_x(p)=t_of_the_way(mp_x_coord(p),mp_right_x(p));
10590   mp_left_x(q)=t_of_the_way(mp_left_x(q),mp_x_coord(q));
10591   mp_left_x(r)=t_of_the_way(mp_right_x(p),v);
10592   mp_right_x(r)=t_of_the_way(v,mp_left_x(q));
10593   mp_x_coord(r)=t_of_the_way(mp_left_x(r),mp_right_x(r));
10594   v=t_of_the_way(mp_right_y(p),mp_left_y(q));
10595   mp_right_y(p)=t_of_the_way(mp_y_coord(p),mp_right_y(p));
10596   mp_left_y(q)=t_of_the_way(mp_left_y(q),mp_y_coord(q));
10597   mp_left_y(r)=t_of_the_way(mp_right_y(p),v);
10598   mp_right_y(r)=t_of_the_way(v,mp_left_y(q));
10599   mp_y_coord(r)=t_of_the_way(mp_left_y(r),mp_right_y(r));
10600 }
10601
10602 @ This does not set |mp_info(p)| or |mp_right_type(p)|.
10603
10604 @<Declarations@>=
10605 static void mp_remove_cubic (MP mp,pointer p) ; 
10606
10607 @ @c
10608 void mp_remove_cubic (MP mp,pointer p) { /* removes the dead cubic following~|p| */
10609   pointer q; /* the node that disappears */
10610   q=mp_link(p); mp_link(p)=mp_link(q);
10611   mp_right_x(p)=mp_right_x(q); mp_right_y(p)=mp_right_y(q);
10612   mp_free_node(mp, q,knot_node_size);
10613 }
10614
10615 @ Let $d\prec d'$ mean that the counter-clockwise angle from $d$ to~$d'$ is
10616 strictly between zero and $180^\circ$.  Then we can define $d\preceq d'$ to
10617 mean that the angle could be zero or $180^\circ$. If $w_k=(u_k,v_k)$ is the
10618 $k$th pen offset, the $k$th pen edge direction is defined by the formula
10619 $$d_k=(u\k-u_k,\,v\k-v_k).$$
10620 When listed by increasing $k$, these directions occur in counter-clockwise
10621 order so that $d_k\preceq d\k$ for all~$k$.
10622 The goal of |offset_prep| is to find an offset index~|k| to associate with
10623 each cubic, such that the direction $d(t)$ of the cubic satisfies
10624 $$d_{k-1}\preceq d(t)\preceq d_k\qquad\hbox{for $0\le t\le 1$.}\eqno(*)$$
10625 We may have to split a cubic into many pieces before each
10626 piece corresponds to a unique offset.
10627
10628 @<Split the cubic between |p| and |q|, if necessary, into cubics...@>=
10629 mp_info(p)=zero_off+k_needed;
10630 k_needed=0;
10631 @<Prepare for derivative computations;
10632   |goto not_found| if the current cubic is dead@>;
10633 @<Find the initial direction |(dx,dy)|@>;
10634 @<Update |mp_info(p)| and find the offset $w_k$ such that
10635   $d_{k-1}\preceq(\\{dx},\\{dy})\prec d_k$; also advance |w0| for
10636   the direction change at |p|@>;
10637 @<Find the final direction |(dxin,dyin)|@>;
10638 @<Decide on the net change in pen offsets and set |turn_amt|@>;
10639 @<Complete the offset splitting process@>;
10640 w0=mp_pen_walk(mp, w0,turn_amt)
10641
10642 @ @<Declarations@>=
10643 static pointer mp_pen_walk (MP mp,pointer w, integer k) ;
10644
10645 @ @c
10646 pointer mp_pen_walk (MP mp,pointer w, integer k) {
10647   /* walk |k| steps around a pen from |w| */
10648   while ( k>0 ) { w=mp_link(w); decr(k);  };
10649   while ( k<0 ) { w=knil(w); incr(k);  };
10650   return w;
10651 }
10652
10653 @ The direction of a cubic $B(z_0,z_1,z_2,z_3;t)=\bigl(x(t),y(t)\bigr)$ can be
10654 calculated from the quadratic polynomials
10655 ${1\over3}x'(t)=B(x_1-x_0,x_2-x_1,x_3-x_2;t)$ and
10656 ${1\over3}y'(t)=B(y_1-y_0,y_2-y_1,y_3-y_2;t)$.
10657 Since we may be calculating directions from several cubics
10658 split from the current one, it is desirable to do these calculations
10659 without losing too much precision. ``Scaled up'' values of the
10660 derivatives, which will be less tainted by accumulated errors than
10661 derivatives found from the cubics themselves, are maintained in
10662 local variables |x0|, |x1|, and |x2|, representing $X_0=2^l(x_1-x_0)$,
10663 $X_1=2^l(x_2-x_1)$, and $X_2=2^l(x_3-x_2)$; similarly |y0|, |y1|, and~|y2|
10664 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)$.
10665
10666 @<Other local variables for |offset_prep|@>=
10667 integer x0,x1,x2,y0,y1,y2; /* representatives of derivatives */
10668 integer t0,t1,t2; /* coefficients of polynomial for slope testing */
10669 integer du,dv,dx,dy; /* for directions of the pen and the curve */
10670 integer dx0,dy0; /* initial direction for the first cubic in the curve */
10671 integer max_coef; /* used while scaling */
10672 integer x0a,x1a,x2a,y0a,y1a,y2a; /* intermediate values */
10673 fraction t; /* where the derivative passes through zero */
10674 fraction s; /* a temporary value */
10675
10676 @ @<Prepare for derivative computations...@>=
10677 x0=mp_right_x(p)-mp_x_coord(p);
10678 x2=mp_x_coord(q)-mp_left_x(q);
10679 x1=mp_left_x(q)-mp_right_x(p);
10680 y0=mp_right_y(p)-mp_y_coord(p); y2=mp_y_coord(q)-mp_left_y(q);
10681 y1=mp_left_y(q)-mp_right_y(p);
10682 max_coef=abs(x0);
10683 if ( abs(x1)>max_coef ) max_coef=abs(x1);
10684 if ( abs(x2)>max_coef ) max_coef=abs(x2);
10685 if ( abs(y0)>max_coef ) max_coef=abs(y0);
10686 if ( abs(y1)>max_coef ) max_coef=abs(y1);
10687 if ( abs(y2)>max_coef ) max_coef=abs(y2);
10688 if ( max_coef==0 ) goto NOT_FOUND;
10689 while ( max_coef<fraction_half ) {
10690   double(max_coef);
10691   double(x0); double(x1); double(x2);
10692   double(y0); double(y1); double(y2);
10693 }
10694
10695 @ Let us first solve a special case of the problem: Suppose we
10696 know an index~$k$ such that either (i)~$d(t)\succeq d_{k-1}$ for all~$t$
10697 and $d(0)\prec d_k$, or (ii)~$d(t)\preceq d_k$ for all~$t$ and
10698 $d(0)\succ d_{k-1}$.
10699 Then, in a sense, we're halfway done, since one of the two relations
10700 in $(*)$ is satisfied, and the other couldn't be satisfied for
10701 any other value of~|k|.
10702
10703 Actually, the conditions can be relaxed somewhat since a relation such as
10704 $d(t)\succeq d_{k-1}$ restricts $d(t)$ to a half plane when all that really
10705 matters is whether $d(t)$ crosses the ray in the $d_{k-1}$ direction from
10706 the origin.  The condition for case~(i) becomes $d_{k-1}\preceq d(0)\prec d_k$
10707 and $d(t)$ never crosses the $d_{k-1}$ ray in the clockwise direction.
10708 Case~(ii) is similar except $d(t)$ cannot cross the $d_k$ ray in the
10709 counterclockwise direction.
10710
10711 The |fin_offset_prep| subroutine solves the stated subproblem.
10712 It has a parameter called |rise| that is |1| in
10713 case~(i), |-1| in case~(ii). Parameters |x0| through |y2| represent
10714 the derivative of the cubic following |p|.
10715 The |w| parameter should point to offset~$w_k$ and |mp_info(p)| should already
10716 be set properly.  The |turn_amt| parameter gives the absolute value of the
10717 overall net change in pen offsets.
10718
10719 @<Declarations@>=
10720 static void mp_fin_offset_prep (MP mp,pointer p, pointer w, integer 
10721   x0,integer x1, integer x2, integer y0, integer y1, integer y2, 
10722   integer rise, integer turn_amt) ;
10723
10724 @ @c
10725 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   pointer ww; /* for list manipulation */
10729   scaled du,dv; /* for slope calculation */
10730   integer t0,t1,t2; /* test coefficients */
10731   fraction t; /* place where the derivative passes a critical slope */
10732   fraction s; /* slope or reciprocal slope */
10733   integer v; /* intermediate value for updating |x0..y2| */
10734   pointer q; /* original |mp_link(p)| */
10735   q=mp_link(p);
10736   while (1)  { 
10737     if ( rise>0 ) ww=mp_link(w); /* a pointer to $w\k$ */
10738     else  ww=knil(w); /* a pointer to $w_{k-1}$ */
10739     @<Compute test coefficients |(t0,t1,t2)|
10740       for $d(t)$ versus $d_k$ or $d_{k-1}$@>;
10741     t=mp_crossing_point(mp, t0,t1,t2);
10742     if ( t>=fraction_one ) {
10743       if ( turn_amt>0 ) t=fraction_one;  else return;
10744     }
10745     @<Split the cubic at $t$,
10746       and split off another cubic if the derivative crosses back@>;
10747     w=ww;
10748   }
10749 }
10750
10751 @ We want $B(\\{t0},\\{t1},\\{t2};t)$ to be the dot product of $d(t)$ with a
10752 $-90^\circ$ rotation of the vector from |w| to |ww|.  This makes the resulting
10753 function cross from positive to negative when $d_{k-1}\preceq d(t)\preceq d_k$
10754 begins to fail.
10755
10756 @<Compute test coefficients |(t0,t1,t2)| for $d(t)$ versus...@>=
10757 du=mp_x_coord(ww)-mp_x_coord(w); dv=mp_y_coord(ww)-mp_y_coord(w);
10758 if ( abs(du)>=abs(dv) ) {
10759   s=mp_make_fraction(mp, dv,du);
10760   t0=mp_take_fraction(mp, x0,s)-y0;
10761   t1=mp_take_fraction(mp, x1,s)-y1;
10762   t2=mp_take_fraction(mp, x2,s)-y2;
10763   if ( du<0 ) { negate(t0); negate(t1); negate(t2);  }
10764 } else { 
10765   s=mp_make_fraction(mp, du,dv);
10766   t0=x0-mp_take_fraction(mp, y0,s);
10767   t1=x1-mp_take_fraction(mp, y1,s);
10768   t2=x2-mp_take_fraction(mp, y2,s);
10769   if ( dv<0 ) { negate(t0); negate(t1); negate(t2);  }
10770 }
10771 if ( t0<0 ) t0=0 /* should be positive without rounding error */
10772
10773 @ The curve has crossed $d_k$ or $d_{k-1}$; its initial segment satisfies
10774 $(*)$, and it might cross again and return towards $s_{k-1}$ or $s_k$,
10775 respectively, yielding another solution of $(*)$.
10776
10777 @<Split the cubic at $t$, and split off another...@>=
10778
10779 mp_split_cubic(mp, p,t); p=mp_link(p); mp_info(p)=zero_off+rise;
10780 decr(turn_amt);
10781 v=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10782 x0=t_of_the_way(v,x1);
10783 v=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10784 y0=t_of_the_way(v,y1);
10785 if ( turn_amt<0 ) {
10786   t1=t_of_the_way(t1,t2);
10787   if ( t1>0 ) t1=0; /* without rounding error, |t1| would be |<=0| */
10788   t=mp_crossing_point(mp, 0,-t1,-t2);
10789   if ( t>fraction_one ) t=fraction_one;
10790   incr(turn_amt);
10791   if ( (t==fraction_one)&&(mp_link(p)!=q) ) {
10792     mp_info(mp_link(p))=mp_info(mp_link(p))-rise;
10793   } else { 
10794     mp_split_cubic(mp, p,t); mp_info(mp_link(p))=zero_off-rise;
10795     v=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10796     x2=t_of_the_way(x1,v);
10797     v=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10798     y2=t_of_the_way(y1,v);
10799   }
10800 }
10801 }
10802
10803 @ Now we must consider the general problem of |offset_prep|, when
10804 nothing is known about a given cubic. We start by finding its
10805 direction in the vicinity of |t=0|.
10806
10807 If $z'(t)=0$, the given cubic is numerically unstable but |offset_prep|
10808 has not yet introduced any more numerical errors.  Thus we can compute
10809 the true initial direction for the given cubic, even if it is almost
10810 degenerate.
10811
10812 @<Find the initial direction |(dx,dy)|@>=
10813 dx=x0; dy=y0;
10814 if ( dx==0 && dy==0 ) { 
10815   dx=x1; dy=y1;
10816   if ( dx==0 && dy==0 ) { 
10817     dx=x2; dy=y2;
10818   }
10819 }
10820 if ( p==c ) { dx0=dx; dy0=dy;  }
10821
10822 @ @<Find the final direction |(dxin,dyin)|@>=
10823 dxin=x2; dyin=y2;
10824 if ( dxin==0 && dyin==0 ) {
10825   dxin=x1; dyin=y1;
10826   if ( dxin==0 && dyin==0 ) {
10827     dxin=x0; dyin=y0;
10828   }
10829 }
10830
10831 @ The next step is to bracket the initial direction between consecutive
10832 edges of the pen polygon.  We must be careful to turn clockwise only if
10833 this makes the turn less than $180^\circ$. (A $180^\circ$ turn must be
10834 counter-clockwise in order to make \&{doublepath} envelopes come out
10835 @:double_path_}{\&{doublepath} primitive@>
10836 right.) This code depends on |w0| being the offset for |(dxin,dyin)|.
10837
10838 @<Update |mp_info(p)| and find the offset $w_k$ such that...@>=
10839 turn_amt=mp_get_turn_amt(mp,w0,dx,dy,(mp_ab_vs_cd(mp, dy,dxin,dx,dyin)>=0));
10840 w=mp_pen_walk(mp, w0, turn_amt);
10841 w0=w;
10842 mp_info(p)=mp_info(p)+turn_amt
10843
10844 @ Decide how many pen offsets to go away from |w| in order to find the offset
10845 for |(dx,dy)|, going counterclockwise if |ccw| is |true|.  This assumes that
10846 |w| is the offset for some direction $(x',y')$ from which the angle to |(dx,dy)|
10847 in the sense determined by |ccw| is less than or equal to $180^\circ$.
10848
10849 If the pen polygon has only two edges, they could both be parallel
10850 to |(dx,dy)|.  In this case, we must be careful to stop after crossing the first
10851 such edge in order to avoid an infinite loop.
10852
10853 @<Declarations@>=
10854 static integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10855                          scaled dy, boolean  ccw);
10856
10857 @ @c
10858 integer mp_get_turn_amt (MP mp,pointer w, scaled  dx,
10859                          scaled dy, boolean  ccw) {
10860   pointer ww; /* a neighbor of knot~|w| */
10861   integer s; /* turn amount so far */
10862   integer t; /* |ab_vs_cd| result */
10863   s=0;
10864   if ( ccw ) { 
10865     ww=mp_link(w);
10866     do {  
10867       t=mp_ab_vs_cd(mp, dy,(mp_x_coord(ww)-mp_x_coord(w)),
10868                         dx,(mp_y_coord(ww)-mp_y_coord(w)));
10869       if ( t<0 ) break;
10870       incr(s);
10871       w=ww; ww=mp_link(ww);
10872     } while (t>0);
10873   } else { 
10874     ww=knil(w);
10875     while ( mp_ab_vs_cd(mp, dy,(mp_x_coord(w)-mp_x_coord(ww)),
10876                             dx,(mp_y_coord(w)-mp_y_coord(ww))) < 0) { 
10877       decr(s);
10878       w=ww; ww=knil(ww);
10879     }
10880   }
10881   return s;
10882 }
10883
10884 @ When we're all done, the final offset is |w0| and the final curve direction
10885 is |(dxin,dyin)|.  With this knowledge of the incoming direction at |c|, we
10886 can correct |mp_info(c)| which was erroneously based on an incoming offset
10887 of~|h|.
10888
10889 @d fix_by(A) mp_info(c)=mp_info(c)+(A)
10890
10891 @<Fix the offset change in |mp_info(c)| and set |c| to the return value of...@>=
10892 mp->spec_offset=mp_info(c)-zero_off;
10893 if ( mp_link(c)==c ) {
10894   mp_info(c)=zero_off+n;
10895 } else { 
10896   fix_by(k_needed);
10897   while ( w0!=h ) { fix_by(1); w0=mp_link(w0);  };
10898   while ( mp_info(c)<=zero_off-n ) fix_by(n);
10899   while ( mp_info(c)>zero_off ) fix_by(-n);
10900   if ( (mp_info(c)!=zero_off)&&(mp_ab_vs_cd(mp, dy0,dxin,dx0,dyin)>=0) ) fix_by(n);
10901 }
10902
10903 @ Finally we want to reduce the general problem to situations that
10904 |fin_offset_prep| can handle. We split the cubic into at most three parts
10905 with respect to $d_{k-1}$, and apply |fin_offset_prep| to each part.
10906
10907 @<Complete the offset splitting process@>=
10908 ww=knil(w);
10909 @<Compute test coeff...@>;
10910 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set
10911   |t:=fraction_one+1|@>;
10912 if ( t>fraction_one ) {
10913   mp_fin_offset_prep(mp, p,w,x0,x1,x2,y0,y1,y2,1,turn_amt);
10914 } else {
10915   mp_split_cubic(mp, p,t); r=mp_link(p);
10916   x1a=t_of_the_way(x0,x1); x1=t_of_the_way(x1,x2);
10917   x2a=t_of_the_way(x1a,x1);
10918   y1a=t_of_the_way(y0,y1); y1=t_of_the_way(y1,y2);
10919   y2a=t_of_the_way(y1a,y1);
10920   mp_fin_offset_prep(mp, p,w,x0,x1a,x2a,y0,y1a,y2a,1,0); x0=x2a; y0=y2a;
10921   mp_info(r)=zero_off-1;
10922   if ( turn_amt>=0 ) {
10923     t1=t_of_the_way(t1,t2);
10924     if ( t1>0 ) t1=0;
10925     t=mp_crossing_point(mp, 0,-t1,-t2);
10926     if ( t>fraction_one ) t=fraction_one;
10927     @<Split off another rising cubic for |fin_offset_prep|@>;
10928     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,0);
10929   } else {
10930     mp_fin_offset_prep(mp, r,ww,x0,x1,x2,y0,y1,y2,-1,(-1-turn_amt));
10931   }
10932 }
10933
10934 @ @<Split off another rising cubic for |fin_offset_prep|@>=
10935 mp_split_cubic(mp, r,t); mp_info(mp_link(r))=zero_off+1;
10936 x1a=t_of_the_way(x1,x2); x1=t_of_the_way(x0,x1);
10937 x0a=t_of_the_way(x1,x1a);
10938 y1a=t_of_the_way(y1,y2); y1=t_of_the_way(y0,y1);
10939 y0a=t_of_the_way(y1,y1a);
10940 mp_fin_offset_prep(mp, mp_link(r),w,x0a,x1a,x2,y0a,y1a,y2,1,turn_amt);
10941 x2=x0a; y2=y0a
10942
10943 @ At this point, the direction of the incoming pen edge is |(-du,-dv)|.
10944 When the component of $d(t)$ perpendicular to |(-du,-dv)| crosses zero, we
10945 need to decide whether the directions are parallel or antiparallel.  We
10946 can test this by finding the dot product of $d(t)$ and |(-du,-dv)|, but this
10947 should be avoided when the value of |turn_amt| already determines the
10948 answer.  If |t2<0|, there is one crossing and it is antiparallel only if
10949 |turn_amt>=0|.  If |turn_amt<0|, there should always be at least one
10950 crossing and the first crossing cannot be antiparallel.
10951
10952 @<Find the first |t| where $d(t)$ crosses $d_{k-1}$ or set...@>=
10953 t=mp_crossing_point(mp, t0,t1,t2);
10954 if ( turn_amt>=0 ) {
10955   if ( t2<0 ) {
10956     t=fraction_one+1;
10957   } else { 
10958     u0=t_of_the_way(x0,x1);
10959     u1=t_of_the_way(x1,x2);
10960     ss=mp_take_fraction(mp, -du,t_of_the_way(u0,u1));
10961     v0=t_of_the_way(y0,y1);
10962     v1=t_of_the_way(y1,y2);
10963     ss=ss+mp_take_fraction(mp, -dv,t_of_the_way(v0,v1));
10964     if ( ss<0 ) t=fraction_one+1;
10965   }
10966 } else if ( t>fraction_one ) {
10967   t=fraction_one;
10968 }
10969
10970 @ @<Other local variables for |offset_prep|@>=
10971 integer u0,u1,v0,v1; /* intermediate values for $d(t)$ calculation */
10972 integer ss = 0; /* the part of the dot product computed so far */
10973 int d_sign; /* sign of overall change in direction for this cubic */
10974
10975 @ If the cubic almost has a cusp, it is a numerically ill-conditioned
10976 problem to decide which way it loops around but that's OK as long we're
10977 consistent.  To make \&{doublepath} envelopes work properly, reversing
10978 the path should always change the sign of |turn_amt|.
10979
10980 @<Decide on the net change in pen offsets and set |turn_amt|@>=
10981 d_sign=mp_ab_vs_cd(mp, dx,dyin, dxin,dy);
10982 if ( d_sign==0 ) {
10983   @<Check rotation direction based on node position@>
10984 }
10985 if ( d_sign==0 ) {
10986   if ( dx==0 ) {
10987     if ( dy>0 ) d_sign=1;  else d_sign=-1;
10988   } else {
10989     if ( dx>0 ) d_sign=1;  else d_sign=-1; 
10990   }
10991 }
10992 @<Make |ss| negative if and only if the total change in direction is
10993   more than $180^\circ$@>;
10994 turn_amt=mp_get_turn_amt(mp, w, dxin, dyin, (d_sign>0));
10995 if ( ss<0 ) turn_amt=turn_amt-d_sign*n
10996
10997 @ We check rotation direction by looking at the vector connecting the current
10998 node with the next. If its angle with incoming and outgoing tangents has the
10999 same sign, we pick this as |d_sign|, since it means we have a flex, not a cusp.
11000 Otherwise we proceed to the cusp code.
11001
11002 @<Check rotation direction based on node position@>=
11003 u0=mp_x_coord(q)-mp_x_coord(p);
11004 u1=mp_y_coord(q)-mp_y_coord(p);
11005 d_sign = half(mp_ab_vs_cd(mp, dx, u1, u0, dy)+
11006   mp_ab_vs_cd(mp, u0, dyin, dxin, u1));
11007
11008 @ In order to be invariant under path reversal, the result of this computation
11009 should not change when |x0|, |y0|, $\ldots$ are all negated and |(x0,y0)| is
11010 then swapped with |(x2,y2)|.  We make use of the identities
11011 |take_fraction(-a,-b)=take_fraction(a,b)| and
11012 |t_of_the_way(-a,-b)=-(t_of_the_way(a,b))|.
11013
11014 @<Make |ss| negative if and only if the total change in direction is...@>=
11015 t0=half(mp_take_fraction(mp, x0,y2))-half(mp_take_fraction(mp, x2,y0));
11016 t1=half(mp_take_fraction(mp, x1,(y0+y2)))-half(mp_take_fraction(mp, y1,(x0+x2)));
11017 if ( t0==0 ) t0=d_sign; /* path reversal always negates |d_sign| */
11018 if ( t0>0 ) {
11019   t=mp_crossing_point(mp, t0,t1,-t0);
11020   u0=t_of_the_way(x0,x1);
11021   u1=t_of_the_way(x1,x2);
11022   v0=t_of_the_way(y0,y1);
11023   v1=t_of_the_way(y1,y2);
11024 } else { 
11025   t=mp_crossing_point(mp, -t0,t1,t0);
11026   u0=t_of_the_way(x2,x1);
11027   u1=t_of_the_way(x1,x0);
11028   v0=t_of_the_way(y2,y1);
11029   v1=t_of_the_way(y1,y0);
11030 }
11031 ss=mp_take_fraction(mp, (x0+x2),t_of_the_way(u0,u1))+
11032    mp_take_fraction(mp, (y0+y2),t_of_the_way(v0,v1))
11033
11034 @ Here's a routine that prints an envelope spec in symbolic form.  It assumes
11035 that the |cur_pen| has not been walked around to the first offset.
11036
11037 @c 
11038 static void mp_print_spec (MP mp,pointer cur_spec, pointer cur_pen, const char *s) {
11039   pointer p,q; /* list traversal */
11040   pointer w; /* the current pen offset */
11041   mp_print_diagnostic(mp, "Envelope spec",s,true);
11042   p=cur_spec; w=mp_pen_walk(mp, cur_pen,mp->spec_offset);
11043   mp_print_ln(mp);
11044   mp_print_two(mp, mp_x_coord(cur_spec),mp_y_coord(cur_spec));
11045   mp_print(mp, " % beginning with offset ");
11046   mp_print_two(mp, mp_x_coord(w),mp_y_coord(w));
11047   do { 
11048     while (1) {  
11049       q=mp_link(p);
11050       @<Print the cubic between |p| and |q|@>;
11051       p=q;
11052           if ((p==cur_spec) || (mp_info(p)!=zero_off)) 
11053         break;
11054     }
11055     if ( mp_info(p)!=zero_off ) {
11056       @<Update |w| as indicated by |mp_info(p)| and print an explanation@>;
11057     }
11058   } while (p!=cur_spec);
11059   mp_print_nl(mp, " & cycle");
11060   mp_end_diagnostic(mp, true);
11061 }
11062
11063 @ @<Update |w| as indicated by |mp_info(p)| and print an explanation@>=
11064
11065   w=mp_pen_walk(mp, w, (mp_info(p)-zero_off));
11066   mp_print(mp, " % ");
11067   if ( mp_info(p)>zero_off ) mp_print(mp, "counter");
11068   mp_print(mp, "clockwise to offset ");
11069   mp_print_two(mp, mp_x_coord(w),mp_y_coord(w));
11070 }
11071
11072 @ @<Print the cubic between |p| and |q|@>=
11073
11074   mp_print_nl(mp, "   ..controls ");
11075   mp_print_two(mp, mp_right_x(p),mp_right_y(p));
11076   mp_print(mp, " and ");
11077   mp_print_two(mp, mp_left_x(q),mp_left_y(q));
11078   mp_print_nl(mp, " ..");
11079   mp_print_two(mp, mp_x_coord(q),mp_y_coord(q));
11080 }
11081
11082 @ Once we have an envelope spec, the remaining task to construct the actual
11083 envelope by offsetting each cubic as determined by the |info| fields in
11084 the knots.  First we use |offset_prep| to convert the |c| into an envelope
11085 spec. Then we add the offsets so that |c| becomes a cyclic path that represents
11086 the envelope.
11087
11088 The |ljoin| and |miterlim| parameters control the treatment of points where the
11089 pen offset changes, and |lcap| controls the endpoints of a \&{doublepath}.
11090 The endpoints are easily located because |c| is given in undoubled form
11091 and then doubled in this procedure.  We use |spec_p1| and |spec_p2| to keep
11092 track of the endpoints and treat them like very sharp corners.
11093 Butt end caps are treated like beveled joins; round end caps are treated like
11094 round joins; and square end caps are achieved by setting |join_type:=3|.
11095
11096 None of these parameters apply to inside joins where the convolution tracing
11097 has retrograde lines.  In such cases we use a simple connect-the-endpoints
11098 approach that is achieved by setting |join_type:=2|.
11099
11100 @c
11101 static pointer mp_make_envelope (MP mp,pointer c, pointer h, quarterword ljoin,
11102   quarterword lcap, scaled miterlim) {
11103   pointer p,q,r,q0; /* for manipulating the path */
11104   int join_type=0; /* codes |0..3| for mitered, round, beveled, or square */
11105   pointer w,w0; /* the pen knot for the current offset */
11106   scaled qx,qy; /* unshifted coordinates of |q| */
11107   halfword k,k0; /* controls pen edge insertion */
11108   @<Other local variables for |make_envelope|@>;
11109   dxin=0; dyin=0; dxout=0; dyout=0;
11110   mp->spec_p1=null; mp->spec_p2=null;
11111   @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>;
11112   @<Use |offset_prep| to compute the envelope spec then walk |h| around to
11113     the initial offset@>;
11114   w=h;
11115   p=c;
11116   do {  
11117     q=mp_link(p); q0=q;
11118     qx=mp_x_coord(q); qy=mp_y_coord(q);
11119     k=mp_info(q);
11120     k0=k; w0=w;
11121     if ( k!=zero_off ) {
11122       @<Set |join_type| to indicate how to handle offset changes at~|q|@>;
11123     }
11124     @<Add offset |w| to the cubic from |p| to |q|@>;
11125     while ( k!=zero_off ) { 
11126       @<Step |w| and move |k| one step closer to |zero_off|@>;
11127       if ( (join_type==1)||(k==zero_off) )
11128          q=mp_insert_knot(mp, q,qx+mp_x_coord(w),qy+mp_y_coord(w));
11129     };
11130     if ( q!=mp_link(p) ) {
11131       @<Set |p=mp_link(p)| and add knots between |p| and |q| as
11132         required by |join_type|@>;
11133     }
11134     p=q;
11135   } while (q0!=c);
11136   return c;
11137 }
11138
11139 @ @<Use |offset_prep| to compute the envelope spec then walk |h| around to...@>=
11140 c=mp_offset_prep(mp, c,h);
11141 if ( mp->internal[mp_tracing_specs]>0 ) 
11142   mp_print_spec(mp, c,h,"");
11143 h=mp_pen_walk(mp, h,mp->spec_offset)
11144
11145 @ Mitered and squared-off joins depend on path directions that are difficult to
11146 compute for degenerate cubics.  The envelope spec computed by |offset_prep| can
11147 have degenerate cubics only if the entire cycle collapses to a single
11148 degenerate cubic.  Setting |join_type:=2| in this case makes the computed
11149 envelope degenerate as well.
11150
11151 @<Set |join_type| to indicate how to handle offset changes at~|q|@>=
11152 if ( k<zero_off ) {
11153   join_type=2;
11154 } else {
11155   if ( (q!=mp->spec_p1)&&(q!=mp->spec_p2) ) join_type=ljoin;
11156   else if ( lcap==2 ) join_type=3;
11157   else join_type=2-lcap;
11158   if ( (join_type==0)||(join_type==3) ) {
11159     @<Set the incoming and outgoing directions at |q|; in case of
11160       degeneracy set |join_type:=2|@>;
11161     if ( join_type==0 ) {
11162       @<If |miterlim| is less than the secant of half the angle at |q|
11163         then set |join_type:=2|@>;
11164     }
11165   }
11166 }
11167
11168 @ @<If |miterlim| is less than the secant of half the angle at |q|...@>=
11169
11170   tmp=mp_take_fraction(mp, miterlim,fraction_half+
11171       half(mp_take_fraction(mp, dxin,dxout)+mp_take_fraction(mp, dyin,dyout)));
11172   if ( tmp<unity )
11173     if ( mp_take_scaled(mp, miterlim,tmp)<unity ) join_type=2;
11174 }
11175
11176 @ @<Other local variables for |make_envelope|@>=
11177 fraction dxin,dyin,dxout,dyout; /* directions at |q| when square or mitered */
11178 scaled tmp; /* a temporary value */
11179
11180 @ The coordinates of |p| have already been shifted unless |p| is the first
11181 knot in which case they get shifted at the very end.
11182
11183 @<Add offset |w| to the cubic from |p| to |q|@>=
11184 mp_right_x(p)=mp_right_x(p)+mp_x_coord(w);
11185 mp_right_y(p)=mp_right_y(p)+mp_y_coord(w);
11186 mp_left_x(q)=mp_left_x(q)+mp_x_coord(w);
11187 mp_left_y(q)=mp_left_y(q)+mp_y_coord(w);
11188 mp_x_coord(q)=mp_x_coord(q)+mp_x_coord(w);
11189 mp_y_coord(q)=mp_y_coord(q)+mp_y_coord(w);
11190 mp_left_type(q)=mp_explicit;
11191 mp_right_type(q)=mp_explicit
11192
11193 @ @<Step |w| and move |k| one step closer to |zero_off|@>=
11194 if ( k>zero_off ){ w=mp_link(w); decr(k);  }
11195 else { w=knil(w); incr(k);  }
11196
11197 @ The cubic from |q| to the new knot at |(x,y)| becomes a line segment and
11198 the |mp_right_x| and |mp_right_y| fields of |r| are set from |q|.  This is done in
11199 case the cubic containing these control points is ``yet to be examined.''
11200
11201 @<Declarations@>=
11202 static pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y);
11203
11204 @ @c
11205 pointer mp_insert_knot (MP mp,pointer q, scaled x, scaled y) {
11206   /* returns the inserted knot */
11207   pointer r; /* the new knot */
11208   r=mp_get_node(mp, knot_node_size);
11209   mp_link(r)=mp_link(q); mp_link(q)=r;
11210   mp_right_x(r)=mp_right_x(q);
11211   mp_right_y(r)=mp_right_y(q);
11212   mp_x_coord(r)=x;
11213   mp_y_coord(r)=y;
11214   mp_right_x(q)=mp_x_coord(q);
11215   mp_right_y(q)=mp_y_coord(q);
11216   mp_left_x(r)=mp_x_coord(r);
11217   mp_left_y(r)=mp_y_coord(r);
11218   mp_left_type(r)=mp_explicit;
11219   mp_right_type(r)=mp_explicit;
11220   mp_originator(r)=mp_program_code;
11221   return r;
11222 }
11223
11224 @ After setting |p:=mp_link(p)|, either |join_type=1| or |q=mp_link(p)|.
11225
11226 @<Set |p=mp_link(p)| and add knots between |p| and |q| as...@>=
11227
11228   p=mp_link(p);
11229   if ( (join_type==0)||(join_type==3) ) {
11230     if ( join_type==0 ) {
11231       @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>
11232     } else {
11233       @<Make |r| the last of two knots inserted between |p| and |q| to form a
11234         squared join@>;
11235     }
11236     if ( r!=null ) { 
11237       mp_right_x(r)=mp_x_coord(r);
11238       mp_right_y(r)=mp_y_coord(r);
11239     }
11240   }
11241 }
11242
11243 @ For very small angles, adding a knot is unnecessary and would cause numerical
11244 problems, so we just set |r:=null| in that case.
11245
11246 @<Insert a new knot |r| between |p| and |q| as required for a mitered join@>=
11247
11248   det=mp_take_fraction(mp, dyout,dxin)-mp_take_fraction(mp, dxout,dyin);
11249   if ( abs(det)<26844 ) { 
11250      r=null; /* sine $<10^{-4}$ */
11251   } else { 
11252     tmp=mp_take_fraction(mp, mp_x_coord(q)-mp_x_coord(p),dyout)-
11253         mp_take_fraction(mp, mp_y_coord(q)-mp_y_coord(p),dxout);
11254     tmp=mp_make_fraction(mp, tmp,det);
11255     r=mp_insert_knot(mp, p,mp_x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11256       mp_y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11257   }
11258 }
11259
11260 @ @<Other local variables for |make_envelope|@>=
11261 fraction det; /* a determinant used for mitered join calculations */
11262
11263 @ @<Make |r| the last of two knots inserted between |p| and |q| to form a...@>=
11264
11265   ht_x=mp_y_coord(w)-mp_y_coord(w0);
11266   ht_y=mp_x_coord(w0)-mp_x_coord(w);
11267   while ( (abs(ht_x)<fraction_half)&&(abs(ht_y)<fraction_half) ) { 
11268     ht_x+=ht_x; ht_y+=ht_y;
11269   }
11270   @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range dot
11271     product with |(ht_x,ht_y)|@>;
11272   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxin,ht_x)+
11273                                   mp_take_fraction(mp, dyin,ht_y));
11274   r=mp_insert_knot(mp, p,mp_x_coord(p)+mp_take_fraction(mp, tmp,dxin),
11275                          mp_y_coord(p)+mp_take_fraction(mp, tmp,dyin));
11276   tmp=mp_make_fraction(mp, max_ht,mp_take_fraction(mp, dxout,ht_x)+
11277                                   mp_take_fraction(mp, dyout,ht_y));
11278   r=mp_insert_knot(mp, r,mp_x_coord(q)+mp_take_fraction(mp, tmp,dxout),
11279                          mp_y_coord(q)+mp_take_fraction(mp, tmp,dyout));
11280 }
11281
11282 @ @<Other local variables for |make_envelope|@>=
11283 fraction ht_x,ht_y; /* perpendicular to the segment from |p| to |q| */
11284 scaled max_ht; /* maximum height of the pen polygon above the |w0|-|w| line */
11285 halfword kk; /* keeps track of the pen vertices being scanned */
11286 pointer ww; /* the pen vertex being tested */
11287
11288 @ The dot product of the vector from |w0| to |ww| with |(ht_x,ht_y)| ranges
11289 from zero to |max_ht|.
11290
11291 @<Scan the pen polygon between |w0| and |w| and make |max_ht| the range...@>=
11292 max_ht=0;
11293 kk=zero_off;
11294 ww=w;
11295 while (1)  { 
11296   @<Step |ww| and move |kk| one step closer to |k0|@>;
11297   if ( kk==k0 ) break;
11298   tmp=mp_take_fraction(mp, (mp_x_coord(ww)-mp_x_coord(w0)),ht_x)+
11299       mp_take_fraction(mp, (mp_y_coord(ww)-mp_y_coord(w0)),ht_y);
11300   if ( tmp>max_ht ) max_ht=tmp;
11301 }
11302
11303
11304 @ @<Step |ww| and move |kk| one step closer to |k0|@>=
11305 if ( kk>k0 ) { ww=mp_link(ww); decr(kk);  }
11306 else { ww=knil(ww); incr(kk);  }
11307
11308 @ @<If endpoint, double the path |c|, and set |spec_p1| and |spec_p2|@>=
11309 if ( mp_left_type(c)==mp_endpoint ) { 
11310   mp->spec_p1=mp_htap_ypoc(mp, c);
11311   mp->spec_p2=mp->path_tail;
11312   mp_originator(mp->spec_p1)=mp_program_code;
11313   mp_link(mp->spec_p2)=mp_link(mp->spec_p1);
11314   mp_link(mp->spec_p1)=c;
11315   mp_remove_cubic(mp, mp->spec_p1);
11316   c=mp->spec_p1;
11317   if ( c!=mp_link(c) ) {
11318     mp_originator(mp->spec_p2)=mp_program_code;
11319     mp_remove_cubic(mp, mp->spec_p2);
11320   } else {
11321     @<Make |c| look like a cycle of length one@>;
11322   }
11323 }
11324
11325 @ @<Make |c| look like a cycle of length one@>=
11326
11327   mp_left_type(c)=mp_explicit; mp_right_type(c)=mp_explicit;
11328   mp_left_x(c)=mp_x_coord(c); mp_left_y(c)=mp_y_coord(c);
11329   mp_right_x(c)=mp_x_coord(c); mp_right_y(c)=mp_y_coord(c);
11330 }
11331
11332 @ In degenerate situations we might have to look at the knot preceding~|q|.
11333 That knot is |p| but if |p<>c|, its coordinates have already been offset by |w|.
11334
11335 @<Set the incoming and outgoing directions at |q|; in case of...@>=
11336 dxin=mp_x_coord(q)-mp_left_x(q);
11337 dyin=mp_y_coord(q)-mp_left_y(q);
11338 if ( (dxin==0)&&(dyin==0) ) {
11339   dxin=mp_x_coord(q)-mp_right_x(p);
11340   dyin=mp_y_coord(q)-mp_right_y(p);
11341   if ( (dxin==0)&&(dyin==0) ) {
11342     dxin=mp_x_coord(q)-mp_x_coord(p);
11343     dyin=mp_y_coord(q)-mp_y_coord(p);
11344     if ( p!=c ) { /* the coordinates of |p| have been offset by |w| */
11345       dxin=dxin+mp_x_coord(w);
11346       dyin=dyin+mp_y_coord(w);
11347     }
11348   }
11349 }
11350 tmp=mp_pyth_add(mp, dxin,dyin);
11351 if ( tmp==0 ) {
11352   join_type=2;
11353 } else { 
11354   dxin=mp_make_fraction(mp, dxin,tmp);
11355   dyin=mp_make_fraction(mp, dyin,tmp);
11356   @<Set the outgoing direction at |q|@>;
11357 }
11358
11359 @ If |q=c| then the coordinates of |r| and the control points between |q|
11360 and~|r| have already been offset by |h|.
11361
11362 @<Set the outgoing direction at |q|@>=
11363 dxout=mp_right_x(q)-mp_x_coord(q);
11364 dyout=mp_right_y(q)-mp_y_coord(q);
11365 if ( (dxout==0)&&(dyout==0) ) {
11366   r=mp_link(q);
11367   dxout=mp_left_x(r)-mp_x_coord(q);
11368   dyout=mp_left_y(r)-mp_y_coord(q);
11369   if ( (dxout==0)&&(dyout==0) ) {
11370     dxout=mp_x_coord(r)-mp_x_coord(q);
11371     dyout=mp_y_coord(r)-mp_y_coord(q);
11372   }
11373 }
11374 if ( q==c ) {
11375   dxout=dxout-mp_x_coord(h);
11376   dyout=dyout-mp_y_coord(h);
11377 }
11378 tmp=mp_pyth_add(mp, dxout,dyout);
11379 if ( tmp==0 ) mp_confusion(mp, "degenerate spec");
11380 @:this can't happen degerate spec}{\quad degenerate spec@>
11381 dxout=mp_make_fraction(mp, dxout,tmp);
11382 dyout=mp_make_fraction(mp, dyout,tmp)
11383
11384 @* \[23] Direction and intersection times.
11385 A path of length $n$ is defined parametrically by functions $x(t)$ and
11386 $y(t)$, for |0<=t<=n|; we can regard $t$ as the ``time'' at which the path
11387 reaches the point $\bigl(x(t),y(t)\bigr)$.  In this section of the program
11388 we shall consider operations that determine special times associated with
11389 given paths: the first time that a path travels in a given direction, and
11390 a pair of times at which two paths cross each other.
11391
11392 @ Let's start with the easier task. The function |find_direction_time| is
11393 given a direction |(x,y)| and a path starting at~|h|. If the path never
11394 travels in direction |(x,y)|, the direction time will be~|-1|; otherwise
11395 it will be nonnegative.
11396
11397 Certain anomalous cases can arise: If |(x,y)=(0,0)|, so that the given
11398 direction is undefined, the direction time will be~0. If $\bigl(x'(t),
11399 y'(t)\bigr)=(0,0)$, so that the path direction is undefined, it will be
11400 assumed to match any given direction at time~|t|.
11401
11402 The routine solves this problem in nondegenerate cases by rotating the path
11403 and the given direction so that |(x,y)=(1,0)|; i.e., the main task will be
11404 to find when a given path first travels ``due east.''
11405
11406 @c 
11407 static scaled mp_find_direction_time (MP mp,scaled x, scaled y, pointer h) {
11408   scaled max; /* $\max\bigl(\vert x\vert,\vert y\vert\bigr)$ */
11409   pointer p,q; /* for list traversal */
11410   scaled n; /* the direction time at knot |p| */
11411   scaled tt; /* the direction time within a cubic */
11412   @<Other local variables for |find_direction_time|@>;
11413   @<Normalize the given direction for better accuracy;
11414     but |return| with zero result if it's zero@>;
11415   n=0; p=h; phi=0;
11416   while (1) { 
11417     if ( mp_right_type(p)==mp_endpoint ) break;
11418     q=mp_link(p);
11419     @<Rotate the cubic between |p| and |q|; then
11420       |goto found| if the rotated cubic travels due east at some time |tt|;
11421       but |break| if an entire cyclic path has been traversed@>;
11422     p=q; n=n+unity;
11423   }
11424   return (-unity);
11425 FOUND: 
11426   return (n+tt);
11427 }
11428
11429 @ @<Normalize the given direction for better accuracy...@>=
11430 if ( abs(x)<abs(y) ) { 
11431   x=mp_make_fraction(mp, x,abs(y));
11432   if ( y>0 ) y=fraction_one; else y=-fraction_one;
11433 } else if ( x==0 ) { 
11434   return 0;
11435 } else  { 
11436   y=mp_make_fraction(mp, y,abs(x));
11437   if ( x>0 ) x=fraction_one; else x=-fraction_one;
11438 }
11439
11440 @ Since we're interested in the tangent directions, we work with the
11441 derivative $${1\over3}B'(x_0,x_1,x_2,x_3;t)=
11442 B(x_1-x_0,x_2-x_1,x_3-x_2;t)$$ instead of
11443 $B(x_0,x_1,x_2,x_3;t)$ itself. The derived coefficients are also scaled up
11444 in order to achieve better accuracy.
11445
11446 The given path may turn abruptly at a knot, and it might pass the critical
11447 tangent direction at such a time. Therefore we remember the direction |phi|
11448 in which the previous rotated cubic was traveling. (The value of |phi| will be
11449 undefined on the first cubic, i.e., when |n=0|.)
11450
11451 @<Rotate the cubic between |p| and |q|; then...@>=
11452 tt=0;
11453 @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples of the control
11454   points of the rotated derivatives@>;
11455 if ( y1==0 ) if ( x1>=0 ) goto FOUND;
11456 if ( n>0 ) { 
11457   @<Exit to |found| if an eastward direction occurs at knot |p|@>;
11458   if ( p==h ) break;
11459   };
11460 if ( (x3!=0)||(y3!=0) ) phi=mp_n_arg(mp, x3,y3);
11461 @<Exit to |found| if the curve whose derivatives are specified by
11462   |x1,x2,x3,y1,y2,y3| travels eastward at some time~|tt|@>
11463
11464 @ @<Other local variables for |find_direction_time|@>=
11465 scaled x1,x2,x3,y1,y2,y3;  /* multiples of rotated derivatives */
11466 angle theta,phi; /* angles of exit and entry at a knot */
11467 fraction t; /* temp storage */
11468
11469 @ @<Set local variables |x1,x2,x3| and |y1,y2,y3| to multiples...@>=
11470 x1=mp_right_x(p)-mp_x_coord(p); x2=mp_left_x(q)-mp_right_x(p);
11471 x3=mp_x_coord(q)-mp_left_x(q);
11472 y1=mp_right_y(p)-mp_y_coord(p); y2=mp_left_y(q)-mp_right_y(p);
11473 y3=mp_y_coord(q)-mp_left_y(q);
11474 max=abs(x1);
11475 if ( abs(x2)>max ) max=abs(x2);
11476 if ( abs(x3)>max ) max=abs(x3);
11477 if ( abs(y1)>max ) max=abs(y1);
11478 if ( abs(y2)>max ) max=abs(y2);
11479 if ( abs(y3)>max ) max=abs(y3);
11480 if ( max==0 ) goto FOUND;
11481 while ( max<fraction_half ){ 
11482   max+=max; x1+=x1; x2+=x2; x3+=x3;
11483   y1+=y1; y2+=y2; y3+=y3;
11484 }
11485 t=x1; x1=mp_take_fraction(mp, x1,x)+mp_take_fraction(mp, y1,y);
11486 y1=mp_take_fraction(mp, y1,x)-mp_take_fraction(mp, t,y);
11487 t=x2; x2=mp_take_fraction(mp, x2,x)+mp_take_fraction(mp, y2,y);
11488 y2=mp_take_fraction(mp, y2,x)-mp_take_fraction(mp, t,y);
11489 t=x3; x3=mp_take_fraction(mp, x3,x)+mp_take_fraction(mp, y3,y);
11490 y3=mp_take_fraction(mp, y3,x)-mp_take_fraction(mp, t,y)
11491
11492 @ @<Exit to |found| if an eastward direction occurs at knot |p|@>=
11493 theta=mp_n_arg(mp, x1,y1);
11494 if ( theta>=0 ) if ( phi<=0 ) if ( phi>=theta-one_eighty_deg ) goto FOUND;
11495 if ( theta<=0 ) if ( phi>=0 ) if ( phi<=theta+one_eighty_deg ) goto FOUND
11496
11497 @ In this step we want to use the |crossing_point| routine to find the
11498 roots of the quadratic equation $B(y_1,y_2,y_3;t)=0$.
11499 Several complications arise: If the quadratic equation has a double root,
11500 the curve never crosses zero, and |crossing_point| will find nothing;
11501 this case occurs iff $y_1y_3=y_2^2$ and $y_1y_2<0$. If the quadratic
11502 equation has simple roots, or only one root, we may have to negate it
11503 so that $B(y_1,y_2,y_3;t)$ crosses from positive to negative at its first root.
11504 And finally, we need to do special things if $B(y_1,y_2,y_3;t)$ is
11505 identically zero.
11506
11507 @ @<Exit to |found| if the curve whose derivatives are specified by...@>=
11508 if ( x1<0 ) if ( x2<0 ) if ( x3<0 ) goto DONE;
11509 if ( mp_ab_vs_cd(mp, y1,y3,y2,y2)==0 ) {
11510   @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11511     either |goto found| or |goto done|@>;
11512 }
11513 if ( y1<=0 ) {
11514   if ( y1<0 ) { y1=-y1; y2=-y2; y3=-y3; }
11515   else if ( y2>0 ){ y2=-y2; y3=-y3; };
11516 }
11517 @<Check the places where $B(y_1,y_2,y_3;t)=0$ to see if
11518   $B(x_1,x_2,x_3;t)\ge0$@>;
11519 DONE:
11520
11521 @ The quadratic polynomial $B(y_1,y_2,y_3;t)$ begins |>=0| and has at most
11522 two roots, because we know that it isn't identically zero.
11523
11524 It must be admitted that the |crossing_point| routine is not perfectly accurate;
11525 rounding errors might cause it to find a root when $y_1y_3>y_2^2$, or to
11526 miss the roots when $y_1y_3<y_2^2$. The rotation process is itself
11527 subject to rounding errors. Yet this code optimistically tries to
11528 do the right thing.
11529
11530 @d we_found_it { tt=(t+04000) / 010000; goto FOUND; }
11531
11532 @<Check the places where $B(y_1,y_2,y_3;t)=0$...@>=
11533 t=mp_crossing_point(mp, y1,y2,y3);
11534 if ( t>fraction_one ) goto DONE;
11535 y2=t_of_the_way(y2,y3);
11536 x1=t_of_the_way(x1,x2);
11537 x2=t_of_the_way(x2,x3);
11538 x1=t_of_the_way(x1,x2);
11539 if ( x1>=0 ) we_found_it;
11540 if ( y2>0 ) y2=0;
11541 tt=t; t=mp_crossing_point(mp, 0,-y2,-y3);
11542 if ( t>fraction_one ) goto DONE;
11543 x1=t_of_the_way(x1,x2);
11544 x2=t_of_the_way(x2,x3);
11545 if ( t_of_the_way(x1,x2)>=0 ) { 
11546   t=t_of_the_way(tt,fraction_one); we_found_it;
11547 }
11548
11549 @ @<Handle the test for eastward directions when $y_1y_3=y_2^2$;
11550     either |goto found| or |goto done|@>=
11551
11552   if ( mp_ab_vs_cd(mp, y1,y2,0,0)<0 ) {
11553     t=mp_make_fraction(mp, y1,y1-y2);
11554     x1=t_of_the_way(x1,x2);
11555     x2=t_of_the_way(x2,x3);
11556     if ( t_of_the_way(x1,x2)>=0 ) we_found_it;
11557   } else if ( y3==0 ) {
11558     if ( y1==0 ) {
11559       @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|@>;
11560     } else if ( x3>=0 ) {
11561       tt=unity; goto FOUND;
11562     }
11563   }
11564   goto DONE;
11565 }
11566
11567 @ At this point we know that the derivative of |y(t)| is identically zero,
11568 and that |x1<0|; but either |x2>=0| or |x3>=0|, so there's some hope of
11569 traveling east.
11570
11571 @<Exit to |found| if the derivative $B(x_1,x_2,x_3;t)$ becomes |>=0|...@>=
11572
11573   t=mp_crossing_point(mp, -x1,-x2,-x3);
11574   if ( t<=fraction_one ) we_found_it;
11575   if ( mp_ab_vs_cd(mp, x1,x3,x2,x2)<=0 ) { 
11576     t=mp_make_fraction(mp, x1,x1-x2); we_found_it;
11577   }
11578 }
11579
11580 @ The intersection of two cubics can be found by an interesting variant
11581 of the general bisection scheme described in the introduction to
11582 |crossing_point|.\
11583 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)$,
11584 we wish to find a pair of times $(t_1,t_2)$ such that $w(t_1)=z(t_2)$,
11585 if an intersection exists. First we find the smallest rectangle that
11586 encloses the points $\{w_0,w_1,w_2,w_3\}$ and check that it overlaps
11587 the smallest rectangle that encloses
11588 $\{z_0,z_1,z_2,z_3\}$; if not, the cubics certainly don't intersect.
11589 But if the rectangles do overlap, we bisect the intervals, getting
11590 new cubics $w'$ and~$w''$, $z'$~and~$z''$; the intersection routine first
11591 tries for an intersection between $w'$ and~$z'$, then (if unsuccessful)
11592 between $w'$ and~$z''$, then (if still unsuccessful) between $w''$ and~$z'$,
11593 finally (if thrice unsuccessful) between $w''$ and~$z''$. After $l$~successful
11594 levels of bisection we will have determined the intersection times $t_1$
11595 and~$t_2$ to $l$~bits of accuracy.
11596
11597 \def\submin{_{\rm min}} \def\submax{_{\rm max}}
11598 As before, it is better to work with the numbers $W_k=2^l(w_k-w_{k-1})$
11599 and $Z_k=2^l(z_k-z_{k-1})$ rather than the coefficients $w_k$ and $z_k$
11600 themselves. We also need one other quantity, $\Delta=2^l(w_0-z_0)$,
11601 to determine when the enclosing rectangles overlap. Here's why:
11602 The $x$~coordinates of~$w(t)$ are between $u\submin$ and $u\submax$,
11603 and the $x$~coordinates of~$z(t)$ are between $x\submin$ and $x\submax$,
11604 if we write $w_k=(u_k,v_k)$ and $z_k=(x_k,y_k)$ and $u\submin=
11605 \min(u_0,u_1,u_2,u_3)$, etc. These intervals of $x$~coordinates
11606 overlap if and only if $u\submin\L x\submax$ and
11607 $x\submin\L u\submax$. Letting
11608 $$U\submin=\min(0,U_1,U_1+U_2,U_1+U_2+U_3),\;
11609   U\submax=\max(0,U_1,U_1+U_2,U_1+U_2+U_3),$$
11610 we have $2^lu\submin=2^lu_0+U\submin$, etc.; the condition for overlap
11611 reduces to
11612 $$X\submin-U\submax\L 2^l(u_0-x_0)\L X\submax-U\submin.$$
11613 Thus we want to maintain the quantity $2^l(u_0-x_0)$; similarly,
11614 the quantity $2^l(v_0-y_0)$ accounts for the $y$~coordinates. The
11615 coordinates of $\Delta=2^l(w_0-z_0)$ must stay bounded as $l$ increases,
11616 because of the overlap condition; i.e., we know that $X\submin$,
11617 $X\submax$, and their relatives are bounded, hence $X\submax-
11618 U\submin$ and $X\submin-U\submax$ are bounded.
11619
11620 @ Incidentally, if the given cubics intersect more than once, the process
11621 just sketched will not necessarily find the lexicographically smallest pair
11622 $(t_1,t_2)$. The solution actually obtained will be smallest in ``shuffled
11623 order''; i.e., if $t_1=(.a_1a_2\ldots a_{16})_2$ and
11624 $t_2=(.b_1b_2\ldots b_{16})_2$, then we will minimize
11625 $a_1b_1a_2b_2\ldots a_{16}b_{16}$, not
11626 $a_1a_2\ldots a_{16}b_1b_2\ldots b_{16}$.
11627 Shuffled order agrees with lexicographic order if all pairs of solutions
11628 $(t_1,t_2)$ and $(t_1',t_2')$ have the property that $t_1<t_1'$ iff
11629 $t_2<t_2'$; but in general, lexicographic order can be quite different,
11630 and the bisection algorithm would be substantially less efficient if it were
11631 constrained by lexicographic order.
11632
11633 For example, suppose that an overlap has been found for $l=3$ and
11634 $(t_1,t_2)= (.101,.011)$ in binary, but that no overlap is produced by
11635 either of the alternatives $(.1010,.0110)$, $(.1010,.0111)$ at level~4.
11636 Then there is probably an intersection in one of the subintervals
11637 $(.1011,.011x)$; but lexicographic order would require us to explore
11638 $(.1010,.1xxx)$ and $(.1011,.00xx)$ and $(.1011,.010x)$ first. We wouldn't
11639 want to store all of the subdivision data for the second path, so the
11640 subdivisions would have to be regenerated many times. Such inefficiencies
11641 would be associated with every `1' in the binary representation of~$t_1$.
11642
11643 @ The subdivision process introduces rounding errors, hence we need to
11644 make a more liberal test for overlap. It is not hard to show that the
11645 computed values of $U_i$ differ from the truth by at most~$l$, on
11646 level~$l$, hence $U\submin$ and $U\submax$ will be at most $3l$ in error.
11647 If $\beta$ is an upper bound on the absolute error in the computed
11648 components of $\Delta=(|delx|,|dely|)$ on level~$l$, we will replace
11649 the test `$X\submin-U\submax\L|delx|$' by the more liberal test
11650 `$X\submin-U\submax\L|delx|+|tol|$', where $|tol|=6l+\beta$.
11651
11652 More accuracy is obtained if we try the algorithm first with |tol=0|;
11653 the more liberal tolerance is used only if an exact approach fails.
11654 It is convenient to do this double-take by letting `3' in the preceding
11655 paragraph be a parameter, which is first 0, then 3.
11656
11657 @<Glob...@>=
11658 unsigned int tol_step; /* either 0 or 3, usually */
11659
11660 @ We shall use an explicit stack to implement the recursive bisection
11661 method described above. The |bisect_stack| array will contain numerous 5-word
11662 packets like $(U_1,U_2,U_3,U\submin,U\submax)$, as well as 20-word packets
11663 comprising the 5-word packets for $U$, $V$, $X$, and~$Y$.
11664
11665 The following macros define the allocation of stack positions to
11666 the quantities needed for bisection-intersection.
11667
11668 @d stack_1(A) mp->bisect_stack[(A)] /* $U_1$, $V_1$, $X_1$, or $Y_1$ */
11669 @d stack_2(A) mp->bisect_stack[(A)+1] /* $U_2$, $V_2$, $X_2$, or $Y_2$ */
11670 @d stack_3(A) mp->bisect_stack[(A)+2] /* $U_3$, $V_3$, $X_3$, or $Y_3$ */
11671 @d stack_min(A) mp->bisect_stack[(A)+3]
11672   /* $U\submin$, $V\submin$, $X\submin$, or $Y\submin$ */
11673 @d stack_max(A) mp->bisect_stack[(A)+4]
11674   /* $U\submax$, $V\submax$, $X\submax$, or $Y\submax$ */
11675 @d int_packets 20 /* number of words to represent $U_k$, $V_k$, $X_k$, and $Y_k$ */
11676 @#
11677 @d u_packet(A) ((A)-5)
11678 @d v_packet(A) ((A)-10)
11679 @d x_packet(A) ((A)-15)
11680 @d y_packet(A) ((A)-20)
11681 @d l_packets (mp->bisect_ptr-int_packets)
11682 @d r_packets mp->bisect_ptr
11683 @d ul_packet u_packet(l_packets) /* base of $U'_k$ variables */
11684 @d vl_packet v_packet(l_packets) /* base of $V'_k$ variables */
11685 @d xl_packet x_packet(l_packets) /* base of $X'_k$ variables */
11686 @d yl_packet y_packet(l_packets) /* base of $Y'_k$ variables */
11687 @d ur_packet u_packet(r_packets) /* base of $U''_k$ variables */
11688 @d vr_packet v_packet(r_packets) /* base of $V''_k$ variables */
11689 @d xr_packet x_packet(r_packets) /* base of $X''_k$ variables */
11690 @d yr_packet y_packet(r_packets) /* base of $Y''_k$ variables */
11691 @#
11692 @d u1l stack_1(ul_packet) /* $U'_1$ */
11693 @d u2l stack_2(ul_packet) /* $U'_2$ */
11694 @d u3l stack_3(ul_packet) /* $U'_3$ */
11695 @d v1l stack_1(vl_packet) /* $V'_1$ */
11696 @d v2l stack_2(vl_packet) /* $V'_2$ */
11697 @d v3l stack_3(vl_packet) /* $V'_3$ */
11698 @d x1l stack_1(xl_packet) /* $X'_1$ */
11699 @d x2l stack_2(xl_packet) /* $X'_2$ */
11700 @d x3l stack_3(xl_packet) /* $X'_3$ */
11701 @d y1l stack_1(yl_packet) /* $Y'_1$ */
11702 @d y2l stack_2(yl_packet) /* $Y'_2$ */
11703 @d y3l stack_3(yl_packet) /* $Y'_3$ */
11704 @d u1r stack_1(ur_packet) /* $U''_1$ */
11705 @d u2r stack_2(ur_packet) /* $U''_2$ */
11706 @d u3r stack_3(ur_packet) /* $U''_3$ */
11707 @d v1r stack_1(vr_packet) /* $V''_1$ */
11708 @d v2r stack_2(vr_packet) /* $V''_2$ */
11709 @d v3r stack_3(vr_packet) /* $V''_3$ */
11710 @d x1r stack_1(xr_packet) /* $X''_1$ */
11711 @d x2r stack_2(xr_packet) /* $X''_2$ */
11712 @d x3r stack_3(xr_packet) /* $X''_3$ */
11713 @d y1r stack_1(yr_packet) /* $Y''_1$ */
11714 @d y2r stack_2(yr_packet) /* $Y''_2$ */
11715 @d y3r stack_3(yr_packet) /* $Y''_3$ */
11716 @#
11717 @d stack_dx mp->bisect_stack[mp->bisect_ptr] /* stacked value of |delx| */
11718 @d stack_dy mp->bisect_stack[mp->bisect_ptr+1] /* stacked value of |dely| */
11719 @d stack_tol mp->bisect_stack[mp->bisect_ptr+2] /* stacked value of |tol| */
11720 @d stack_uv mp->bisect_stack[mp->bisect_ptr+3] /* stacked value of |uv| */
11721 @d stack_xy mp->bisect_stack[mp->bisect_ptr+4] /* stacked value of |xy| */
11722 @d int_increment (int_packets+int_packets+5) /* number of stack words per level */
11723
11724 @<Glob...@>=
11725 integer *bisect_stack;
11726 integer bisect_ptr;
11727
11728 @ @<Allocate or initialize ...@>=
11729 mp->bisect_stack = xmalloc((bistack_size+1),sizeof(integer));
11730
11731 @ @<Dealloc variables@>=
11732 xfree(mp->bisect_stack);
11733
11734 @ @<Check the ``constant''...@>=
11735 if ( int_packets+17*int_increment>bistack_size ) mp->bad=19;
11736
11737 @ Computation of the min and max is a tedious but fairly fast sequence of
11738 instructions; exactly four comparisons are made in each branch.
11739
11740 @d set_min_max(A) 
11741   if ( stack_1((A))<0 ) {
11742     if ( stack_3((A))>=0 ) {
11743       if ( stack_2((A))<0 ) stack_min((A))=stack_1((A))+stack_2((A));
11744       else stack_min((A))=stack_1((A));
11745       stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11746       if ( stack_max((A))<0 ) stack_max((A))=0;
11747     } else { 
11748       stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11749       if ( stack_min((A))>stack_1((A)) ) stack_min((A))=stack_1((A));
11750       stack_max((A))=stack_1((A))+stack_2((A));
11751       if ( stack_max((A))<0 ) stack_max((A))=0;
11752     }
11753   } else if ( stack_3((A))<=0 ) {
11754     if ( stack_2((A))>0 ) stack_max((A))=stack_1((A))+stack_2((A));
11755     else stack_max((A))=stack_1((A));
11756     stack_min((A))=stack_1((A))+stack_2((A))+stack_3((A));
11757     if ( stack_min((A))>0 ) stack_min((A))=0;
11758   } else  { 
11759     stack_max((A))=stack_1((A))+stack_2((A))+stack_3((A));
11760     if ( stack_max((A))<stack_1((A)) ) stack_max((A))=stack_1((A));
11761     stack_min((A))=stack_1((A))+stack_2((A));
11762     if ( stack_min((A))>0 ) stack_min((A))=0;
11763   }
11764
11765 @ It's convenient to keep the current values of $l$, $t_1$, and $t_2$ in
11766 the integer form $2^l+2^lt_1$ and $2^l+2^lt_2$. The |cubic_intersection|
11767 routine uses global variables |cur_t| and |cur_tt| for this purpose;
11768 after successful completion, |cur_t| and |cur_tt| will contain |unity|
11769 plus the |scaled| values of $t_1$ and~$t_2$.
11770
11771 The values of |cur_t| and |cur_tt| will be set to zero if |cubic_intersection|
11772 finds no intersection. The routine gives up and gives an approximate answer
11773 if it has backtracked
11774 more than 5000 times (otherwise there are cases where several minutes
11775 of fruitless computation would be possible).
11776
11777 @d max_patience 5000
11778
11779 @<Glob...@>=
11780 integer cur_t;integer cur_tt; /* controls and results of |cubic_intersection| */
11781 integer time_to_go; /* this many backtracks before giving up */
11782 integer max_t; /* maximum of $2^{l+1}$ so far achieved */
11783
11784 @ The given cubics $B(w_0,w_1,w_2,w_3;t)$ and
11785 $B(z_0,z_1,z_2,z_3;t)$ are specified in adjacent knot nodes |(p,mp_link(p))|
11786 and |(pp,mp_link(pp))|, respectively.
11787
11788 @c 
11789 static void mp_cubic_intersection (MP mp,pointer p, pointer pp) {
11790   pointer q,qq; /* |mp_link(p)|, |mp_link(pp)| */
11791   mp->time_to_go=max_patience; mp->max_t=2;
11792   @<Initialize for intersections at level zero@>;
11793 CONTINUE:
11794   while (1) { 
11795     if ( mp->delx-mp->tol<=stack_max(x_packet(mp->xy))-stack_min(u_packet(mp->uv)))
11796     if ( mp->delx+mp->tol>=stack_min(x_packet(mp->xy))-stack_max(u_packet(mp->uv)))
11797     if ( mp->dely-mp->tol<=stack_max(y_packet(mp->xy))-stack_min(v_packet(mp->uv)))
11798     if ( mp->dely+mp->tol>=stack_min(y_packet(mp->xy))-stack_max(v_packet(mp->uv))) 
11799     { 
11800       if ( mp->cur_t>=mp->max_t ){ 
11801         if ( mp->max_t==two ) { /* we've done 17 bisections */ 
11802            mp->cur_t=halfp(mp->cur_t+1); 
11803                mp->cur_tt=halfp(mp->cur_tt+1); 
11804            return;
11805         }
11806         mp->max_t+=mp->max_t; mp->appr_t=mp->cur_t; mp->appr_tt=mp->cur_tt;
11807       }
11808       @<Subdivide for a new level of intersection@>;
11809       goto CONTINUE;
11810     }
11811     if ( mp->time_to_go>0 ) {
11812       decr(mp->time_to_go);
11813     } else { 
11814       while ( mp->appr_t<unity ) { 
11815         mp->appr_t+=mp->appr_t; mp->appr_tt+=mp->appr_tt;
11816       }
11817       mp->cur_t=mp->appr_t; mp->cur_tt=mp->appr_tt; return;
11818     }
11819     @<Advance to the next pair |(cur_t,cur_tt)|@>;
11820   }
11821 }
11822
11823 @ The following variables are global, although they are used only by
11824 |cubic_intersection|, because it is necessary on some machines to
11825 split |cubic_intersection| up into two procedures.
11826
11827 @<Glob...@>=
11828 integer delx;integer dely; /* the components of $\Delta=2^l(w_0-z_0)$ */
11829 integer tol; /* bound on the uncertainty in the overlap test */
11830 integer uv;
11831 integer xy; /* pointers to the current packets of interest */
11832 integer three_l; /* |tol_step| times the bisection level */
11833 integer appr_t;integer appr_tt; /* best approximations known to the answers */
11834
11835 @ We shall assume that the coordinates are sufficiently non-extreme that
11836 integer overflow will not occur.
11837 @^overflow in arithmetic@>
11838
11839 @<Initialize for intersections at level zero@>=
11840 q=mp_link(p); qq=mp_link(pp); mp->bisect_ptr=int_packets;
11841 u1r=mp_right_x(p)-mp_x_coord(p); u2r=mp_left_x(q)-mp_right_x(p);
11842 u3r=mp_x_coord(q)-mp_left_x(q); set_min_max(ur_packet);
11843 v1r=mp_right_y(p)-mp_y_coord(p); v2r=mp_left_y(q)-mp_right_y(p);
11844 v3r=mp_y_coord(q)-mp_left_y(q); set_min_max(vr_packet);
11845 x1r=mp_right_x(pp)-mp_x_coord(pp); x2r=mp_left_x(qq)-mp_right_x(pp);
11846 x3r=mp_x_coord(qq)-mp_left_x(qq); set_min_max(xr_packet);
11847 y1r=mp_right_y(pp)-mp_y_coord(pp); y2r=mp_left_y(qq)-mp_right_y(pp);
11848 y3r=mp_y_coord(qq)-mp_left_y(qq); set_min_max(yr_packet);
11849 mp->delx=mp_x_coord(p)-mp_x_coord(pp); mp->dely=mp_y_coord(p)-mp_y_coord(pp);
11850 mp->tol=0; mp->uv=r_packets; mp->xy=r_packets; 
11851 mp->three_l=0; mp->cur_t=1; mp->cur_tt=1
11852
11853 @ @<Subdivide for a new level of intersection@>=
11854 stack_dx=mp->delx; stack_dy=mp->dely; stack_tol=mp->tol; 
11855 stack_uv=mp->uv; stack_xy=mp->xy;
11856 mp->bisect_ptr=mp->bisect_ptr+int_increment;
11857 mp->cur_t+=mp->cur_t; mp->cur_tt+=mp->cur_tt;
11858 u1l=stack_1(u_packet(mp->uv)); u3r=stack_3(u_packet(mp->uv));
11859 u2l=half(u1l+stack_2(u_packet(mp->uv)));
11860 u2r=half(u3r+stack_2(u_packet(mp->uv)));
11861 u3l=half(u2l+u2r); u1r=u3l;
11862 set_min_max(ul_packet); set_min_max(ur_packet);
11863 v1l=stack_1(v_packet(mp->uv)); v3r=stack_3(v_packet(mp->uv));
11864 v2l=half(v1l+stack_2(v_packet(mp->uv)));
11865 v2r=half(v3r+stack_2(v_packet(mp->uv)));
11866 v3l=half(v2l+v2r); v1r=v3l;
11867 set_min_max(vl_packet); set_min_max(vr_packet);
11868 x1l=stack_1(x_packet(mp->xy)); x3r=stack_3(x_packet(mp->xy));
11869 x2l=half(x1l+stack_2(x_packet(mp->xy)));
11870 x2r=half(x3r+stack_2(x_packet(mp->xy)));
11871 x3l=half(x2l+x2r); x1r=x3l;
11872 set_min_max(xl_packet); set_min_max(xr_packet);
11873 y1l=stack_1(y_packet(mp->xy)); y3r=stack_3(y_packet(mp->xy));
11874 y2l=half(y1l+stack_2(y_packet(mp->xy)));
11875 y2r=half(y3r+stack_2(y_packet(mp->xy)));
11876 y3l=half(y2l+y2r); y1r=y3l;
11877 set_min_max(yl_packet); set_min_max(yr_packet);
11878 mp->uv=l_packets; mp->xy=l_packets;
11879 mp->delx+=mp->delx; mp->dely+=mp->dely;
11880 mp->tol=mp->tol-mp->three_l+mp->tol_step; 
11881 mp->tol+=mp->tol; mp->three_l=mp->three_l+mp->tol_step
11882
11883 @ @<Advance to the next pair |(cur_t,cur_tt)|@>=
11884 NOT_FOUND: 
11885 if ( odd(mp->cur_tt) ) {
11886   if ( odd(mp->cur_t) ) {
11887      @<Descend to the previous level and |goto not_found|@>;
11888   } else { 
11889     incr(mp->cur_t);
11890     mp->delx=mp->delx+stack_1(u_packet(mp->uv))+stack_2(u_packet(mp->uv))
11891       +stack_3(u_packet(mp->uv));
11892     mp->dely=mp->dely+stack_1(v_packet(mp->uv))+stack_2(v_packet(mp->uv))
11893       +stack_3(v_packet(mp->uv));
11894     mp->uv=mp->uv+int_packets; /* switch from |l_packets| to |r_packets| */
11895     decr(mp->cur_tt); mp->xy=mp->xy-int_packets; 
11896          /* switch from |r_packets| to |l_packets| */
11897     mp->delx=mp->delx+stack_1(x_packet(mp->xy))+stack_2(x_packet(mp->xy))
11898       +stack_3(x_packet(mp->xy));
11899     mp->dely=mp->dely+stack_1(y_packet(mp->xy))+stack_2(y_packet(mp->xy))
11900       +stack_3(y_packet(mp->xy));
11901   }
11902 } else { 
11903   incr(mp->cur_tt); mp->tol=mp->tol+mp->three_l;
11904   mp->delx=mp->delx-stack_1(x_packet(mp->xy))-stack_2(x_packet(mp->xy))
11905     -stack_3(x_packet(mp->xy));
11906   mp->dely=mp->dely-stack_1(y_packet(mp->xy))-stack_2(y_packet(mp->xy))
11907     -stack_3(y_packet(mp->xy));
11908   mp->xy=mp->xy+int_packets; /* switch from |l_packets| to |r_packets| */
11909 }
11910
11911 @ @<Descend to the previous level...@>=
11912
11913   mp->cur_t=halfp(mp->cur_t); mp->cur_tt=halfp(mp->cur_tt);
11914   if ( mp->cur_t==0 ) return;
11915   mp->bisect_ptr=mp->bisect_ptr-int_increment; 
11916   mp->three_l=mp->three_l-mp->tol_step;
11917   mp->delx=stack_dx; mp->dely=stack_dy; mp->tol=stack_tol; 
11918   mp->uv=stack_uv; mp->xy=stack_xy;
11919   goto NOT_FOUND;
11920 }
11921
11922 @ The |path_intersection| procedure is much simpler.
11923 It invokes |cubic_intersection| in lexicographic order until finding a
11924 pair of cubics that intersect. The final intersection times are placed in
11925 |cur_t| and~|cur_tt|.
11926
11927 @c 
11928 static void mp_path_intersection (MP mp,pointer h, pointer hh) {
11929   pointer p,pp; /* link registers that traverse the given paths */
11930   integer n,nn; /* integer parts of intersection times, minus |unity| */
11931   @<Change one-point paths into dead cycles@>;
11932   mp->tol_step=0;
11933   do {  
11934     n=-unity; p=h;
11935     do {  
11936       if ( mp_right_type(p)!=mp_endpoint ) { 
11937         nn=-unity; pp=hh;
11938         do {  
11939           if ( mp_right_type(pp)!=mp_endpoint )  { 
11940             mp_cubic_intersection(mp, p,pp);
11941             if ( mp->cur_t>0 ) { 
11942               mp->cur_t=mp->cur_t+n; mp->cur_tt=mp->cur_tt+nn; 
11943               return;
11944             }
11945           }
11946           nn=nn+unity; pp=mp_link(pp);
11947         } while (pp!=hh);
11948       }
11949       n=n+unity; p=mp_link(p);
11950     } while (p!=h);
11951     mp->tol_step=mp->tol_step+3;
11952   } while (mp->tol_step<=3);
11953   mp->cur_t=-unity; mp->cur_tt=-unity;
11954 }
11955
11956 @ @<Change one-point paths...@>=
11957 if ( mp_right_type(h)==mp_endpoint ) {
11958   mp_right_x(h)=mp_x_coord(h); mp_left_x(h)=mp_x_coord(h);
11959   mp_right_y(h)=mp_y_coord(h); mp_left_y(h)=mp_y_coord(h); mp_right_type(h)=mp_explicit;
11960 }
11961 if ( mp_right_type(hh)==mp_endpoint ) {
11962   mp_right_x(hh)=mp_x_coord(hh); mp_left_x(hh)=mp_x_coord(hh);
11963   mp_right_y(hh)=mp_y_coord(hh); mp_left_y(hh)=mp_y_coord(hh); mp_right_type(hh)=mp_explicit;
11964 }
11965
11966 @* \[24] Dynamic linear equations.
11967 \MP\ users define variables implicitly by stating equations that should be
11968 satisfied; the computer is supposed to be smart enough to solve those equations.
11969 And indeed, the computer tries valiantly to do so, by distinguishing five
11970 different types of numeric values:
11971
11972 \smallskip\hang
11973 |type(p)=mp_known| is the nice case, when |value(p)| is the |scaled| value
11974 of the variable whose address is~|p|.
11975
11976 \smallskip\hang
11977 |type(p)=mp_dependent| means that |value(p)| is not present, but |dep_list(p)|
11978 points to a {\sl dependency list\/} that expresses the value of variable~|p|
11979 as a |scaled| number plus a sum of independent variables with |fraction|
11980 coefficients.
11981
11982 \smallskip\hang
11983 |type(p)=mp_independent| means that |value(p)=64s+m|, where |s>0| is a ``serial
11984 number'' reflecting the time this variable was first used in an equation;
11985 also |0<=m<64|, and each dependent variable
11986 that refers to this one is actually referring to the future value of
11987 this variable times~$2^m$. (Usually |m=0|, but higher degrees of
11988 scaling are sometimes needed to keep the coefficients in dependency lists
11989 from getting too large. The value of~|m| will always be even.)
11990
11991 \smallskip\hang
11992 |type(p)=mp_numeric_type| means that variable |p| hasn't appeared in an
11993 equation before, but it has been explicitly declared to be numeric.
11994
11995 \smallskip\hang
11996 |type(p)=undefined| means that variable |p| hasn't appeared before.
11997
11998 \smallskip\noindent
11999 We have actually discussed these five types in the reverse order of their
12000 history during a computation: Once |known|, a variable never again
12001 becomes |dependent|; once |dependent|, it almost never again becomes
12002 |mp_independent|; once |mp_independent|, it never again becomes |mp_numeric_type|;
12003 and once |mp_numeric_type|, it never again becomes |undefined| (except
12004 of course when the user specifically decides to scrap the old value
12005 and start again). A backward step may, however, take place: Sometimes
12006 a |dependent| variable becomes |mp_independent| again, when one of the
12007 independent variables it depends on is reverting to |undefined|.
12008
12009
12010 The next patch detects overflow of independent-variable serial
12011 numbers. Diagnosed and patched by Thorsten Dahlheimer.
12012
12013 @d s_scale 64 /* the serial numbers are multiplied by this factor */
12014 @d new_indep(A)  /* create a new independent variable */
12015   { if ( mp->serial_no>el_gordo-s_scale )
12016     mp_fatal_error(mp, "variable instance identifiers exhausted");
12017   mp_type((A))=mp_independent; mp->serial_no=mp->serial_no+s_scale;
12018   value((A))=mp->serial_no;
12019   }
12020
12021 @<Glob...@>=
12022 integer serial_no; /* the most recent serial number, times |s_scale| */
12023
12024 @ @<Make variable |q+s| newly independent@>=new_indep(q+s)
12025
12026 @ But how are dependency lists represented? It's simple: The linear combination
12027 $\alpha_1v_1+\cdots+\alpha_kv_k+\beta$ appears in |k+1| value nodes. If
12028 |q=dep_list(p)| points to this list, and if |k>0|, then |value(q)=
12029 @t$\alpha_1$@>| (which is a |fraction|); |mp_info(q)| points to the location
12030 of $\alpha_1$; and |mp_link(p)| points to the dependency list
12031 $\alpha_2v_2+\cdots+\alpha_kv_k+\beta$. On the other hand if |k=0|,
12032 then |value(q)=@t$\beta$@>| (which is |scaled|) and |mp_info(q)=null|.
12033 The independent variables $v_1$, \dots,~$v_k$ have been sorted so that
12034 they appear in decreasing order of their |value| fields (i.e., of
12035 their serial numbers). \ (It is convenient to use decreasing order,
12036 since |value(null)=0|. If the independent variables were not sorted by
12037 serial number but by some other criterion, such as their location in |mem|,
12038 the equation-solving mechanism would be too system-dependent, because
12039 the ordering can affect the computed results.)
12040
12041 The |link| field in the node that contains the constant term $\beta$ is
12042 called the {\sl final link\/} of the dependency list. \MP\ maintains
12043 a doubly-linked master list of all dependency lists, in terms of a permanently
12044 allocated node
12045 in |mem| called |dep_head|. If there are no dependencies, we have
12046 |mp_link(dep_head)=dep_head| and |prev_dep(dep_head)=dep_head|;
12047 otherwise |mp_link(dep_head)| points to the first dependent variable, say~|p|,
12048 and |prev_dep(p)=dep_head|. We have |type(p)=mp_dependent|, and |dep_list(p)|
12049 points to its dependency list. If the final link of that dependency list
12050 occurs in location~|q|, then |mp_link(q)| points to the next dependent
12051 variable (say~|r|); and we have |prev_dep(r)=q|, etc.
12052
12053 @d dep_list(A) mp_link(value_loc((A)))
12054   /* half of the |value| field in a |dependent| variable */
12055 @d prev_dep(A) mp_info(value_loc((A)))
12056   /* the other half; makes a doubly linked list */
12057 @d dep_node_size 2 /* the number of words per dependency node */
12058
12059 @<Initialize table entries...@>= mp->serial_no=0;
12060 mp_link(dep_head)=dep_head; prev_dep(dep_head)=dep_head;
12061 mp_info(dep_head)=null; dep_list(dep_head)=null;
12062
12063 @ Actually the description above contains a little white lie. There's
12064 another kind of variable called |mp_proto_dependent|, which is
12065 just like a |dependent| one except that the $\alpha$ coefficients
12066 in its dependency list are |scaled| instead of being fractions.
12067 Proto-dependency lists are mixed with dependency lists in the
12068 nodes reachable from |dep_head|.
12069
12070 @ Here is a procedure that prints a dependency list in symbolic form.
12071 The second parameter should be either |dependent| or |mp_proto_dependent|,
12072 to indicate the scaling of the coefficients.
12073
12074 @<Declarations@>=
12075 static void mp_print_dependency (MP mp,pointer p, quarterword t);
12076
12077 @ @c
12078 void mp_print_dependency (MP mp,pointer p, quarterword t) {
12079   integer v; /* a coefficient */
12080   pointer pp,q; /* for list manipulation */
12081   pp=p;
12082   while (true) { 
12083     v=abs(value(p)); q=mp_info(p);
12084     if ( q==null ) { /* the constant term */
12085       if ( (v!=0)||(p==pp) ) {
12086          if ( value(p)>0 ) if ( p!=pp ) mp_print_char(mp, xord('+'));
12087          mp_print_scaled(mp, value(p));
12088       }
12089       return;
12090     }
12091     @<Print the coefficient, unless it's $\pm1.0$@>;
12092     if ( mp_type(q)!=mp_independent ) mp_confusion(mp, "dep");
12093 @:this can't happen dep}{\quad dep@>
12094     mp_print_variable_name(mp, q); v=value(q) % s_scale;
12095     while ( v>0 ) { mp_print(mp, "*4"); v=v-2; }
12096     p=mp_link(p);
12097   }
12098 }
12099
12100 @ @<Print the coefficient, unless it's $\pm1.0$@>=
12101 if ( value(p)<0 ) mp_print_char(mp, xord('-'));
12102 else if ( p!=pp ) mp_print_char(mp, xord('+'));
12103 if ( t==mp_dependent ) v=mp_round_fraction(mp, v);
12104 if ( v!=unity ) mp_print_scaled(mp, v)
12105
12106 @ The maximum absolute value of a coefficient in a given dependency list
12107 is returned by the following simple function.
12108
12109 @c 
12110 static fraction mp_max_coef (MP mp,pointer p) {
12111   fraction x; /* the maximum so far */
12112   x=0;
12113   while ( mp_info(p)!=null ) {
12114     if ( abs(value(p))>x ) x=abs(value(p));
12115     p=mp_link(p);
12116   }
12117   return x;
12118 }
12119
12120 @ One of the main operations needed on dependency lists is to add a multiple
12121 of one list to the other; we call this |p_plus_fq|, where |p| and~|q| point
12122 to dependency lists and |f| is a fraction.
12123
12124 If the coefficient of any independent variable becomes |coef_bound| or
12125 more, in absolute value, this procedure changes the type of that variable
12126 to `|independent_needing_fix|', and sets the global variable |fix_needed|
12127 to~|true|. The value of $|coef_bound|=\mu$ is chosen so that
12128 $\mu^2+\mu<8$; this means that the numbers we deal with won't
12129 get too large. (Instead of the ``optimum'' $\mu=(\sqrt{33}-1)/2\approx
12130 2.3723$, the safer value 7/3 is taken as the threshold.)
12131
12132 The changes mentioned in the preceding paragraph are actually done only if
12133 the global variable |watch_coefs| is |true|. But it usually is; in fact,
12134 it is |false| only when \MP\ is making a dependency list that will soon
12135 be equated to zero.
12136
12137 Several procedures that act on dependency lists, including |p_plus_fq|,
12138 set the global variable |dep_final| to the final (constant term) node of
12139 the dependency list that they produce.
12140
12141 @d coef_bound 04525252525 /* |fraction| approximation to 7/3 */
12142 @d independent_needing_fix 0
12143
12144 @<Glob...@>=
12145 boolean fix_needed; /* does at least one |independent| variable need scaling? */
12146 boolean watch_coefs; /* should we scale coefficients that exceed |coef_bound|? */
12147 pointer dep_final; /* location of the constant term and final link */
12148
12149 @ @<Set init...@>=
12150 mp->fix_needed=false; mp->watch_coefs=true;
12151
12152 @ The |p_plus_fq| procedure has a fourth parameter, |t|, that should be
12153 set to |mp_proto_dependent| if |p| is a proto-dependency list. In this
12154 case |f| will be |scaled|, not a |fraction|. Similarly, the fifth parameter~|tt|
12155 should be |mp_proto_dependent| if |q| is a proto-dependency list.
12156
12157 List |q| is unchanged by the operation; but list |p| is totally destroyed.
12158
12159 The final link of the dependency list or proto-dependency list returned
12160 by |p_plus_fq| is the same as the original final link of~|p|. Indeed, the
12161 constant term of the result will be located in the same |mem| location
12162 as the original constant term of~|p|.
12163
12164 Coefficients of the result are assumed to be zero if they are less than
12165 a certain threshold. This compensates for inevitable rounding errors,
12166 and tends to make more variables `|known|'. The threshold is approximately
12167 $10^{-5}$ in the case of normal dependency lists, $10^{-4}$ for
12168 proto-dependencies.
12169
12170 @d fraction_threshold 2685 /* a |fraction| coefficient less than this is zeroed */
12171 @d half_fraction_threshold 1342 /* half of |fraction_threshold| */
12172 @d scaled_threshold 8 /* a |scaled| coefficient less than this is zeroed */
12173 @d half_scaled_threshold 4 /* half of |scaled_threshold| */
12174
12175 @<Declarations@>=
12176 static pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12177                       pointer q, quarterword t, quarterword tt) ;
12178
12179 @ @c
12180 pointer mp_p_plus_fq ( MP mp, pointer p, integer f, 
12181                       pointer q, quarterword t, quarterword tt) {
12182   pointer pp,qq; /* |mp_info(p)| and |mp_info(q)|, respectively */
12183   pointer r,s; /* for list manipulation */
12184   integer threshold; /* defines a neighborhood of zero */
12185   integer v; /* temporary register */
12186   if ( t==mp_dependent ) threshold=fraction_threshold;
12187   else threshold=scaled_threshold;
12188   r=temp_head; pp=mp_info(p); qq=mp_info(q);
12189   while (1) {
12190     if ( pp==qq ) {
12191       if ( pp==null ) {
12192        break;
12193       } else {
12194         @<Contribute a term from |p|, plus |f| times the
12195           corresponding term from |q|@>
12196       }
12197     } else if ( value(pp)<value(qq) ) {
12198       @<Contribute a term from |q|, multiplied by~|f|@>
12199     } else { 
12200      mp_link(r)=p; r=p; p=mp_link(p); pp=mp_info(p);
12201     }
12202   }
12203   if ( t==mp_dependent )
12204     value(p)=mp_slow_add(mp, value(p),mp_take_fraction(mp, value(q),f));
12205   else  
12206     value(p)=mp_slow_add(mp, value(p),mp_take_scaled(mp, value(q),f));
12207   mp_link(r)=p; mp->dep_final=p; 
12208   return mp_link(temp_head);
12209 }
12210
12211 @ @<Contribute a term from |p|, plus |f|...@>=
12212
12213   if ( tt==mp_dependent ) v=value(p)+mp_take_fraction(mp, f,value(q));
12214   else v=value(p)+mp_take_scaled(mp, f,value(q));
12215   value(p)=v; s=p; p=mp_link(p);
12216   if ( abs(v)<threshold ) {
12217     mp_free_node(mp, s,dep_node_size);
12218   } else {
12219     if ( (abs(v)>=coef_bound)  && mp->watch_coefs ) { 
12220       mp_type(qq)=independent_needing_fix; mp->fix_needed=true;
12221     }
12222     mp_link(r)=s; r=s;
12223   };
12224   pp=mp_info(p); q=mp_link(q); qq=mp_info(q);
12225 }
12226
12227 @ @<Contribute a term from |q|, multiplied by~|f|@>=
12228
12229   if ( tt==mp_dependent ) v=mp_take_fraction(mp, f,value(q));
12230   else v=mp_take_scaled(mp, f,value(q));
12231   if ( abs(v)>halfp(threshold) ) { 
12232     s=mp_get_node(mp, dep_node_size); mp_info(s)=qq; value(s)=v;
12233     if ( (abs(v)>=coef_bound) && mp->watch_coefs ) { 
12234       mp_type(qq)=independent_needing_fix; mp->fix_needed=true;
12235     }
12236     mp_link(r)=s; r=s;
12237   }
12238   q=mp_link(q); qq=mp_info(q);
12239 }
12240
12241 @ It is convenient to have another subroutine for the special case
12242 of |p_plus_fq| when |f=1.0|. In this routine lists |p| and |q| are
12243 both of the same type~|t| (either |dependent| or |mp_proto_dependent|).
12244
12245 @c 
12246 static pointer mp_p_plus_q (MP mp,pointer p, pointer q, quarterword t) {
12247   pointer pp,qq; /* |mp_info(p)| and |mp_info(q)|, respectively */
12248   pointer r,s; /* for list manipulation */
12249   integer threshold; /* defines a neighborhood of zero */
12250   integer v; /* temporary register */
12251   if ( t==mp_dependent ) threshold=fraction_threshold;
12252   else threshold=scaled_threshold;
12253   r=temp_head; pp=mp_info(p); qq=mp_info(q);
12254   while (1) {
12255     if ( pp==qq ) {
12256       if ( pp==null ) {
12257         break;
12258       } else {
12259         @<Contribute a term from |p|, plus the
12260           corresponding term from |q|@>
12261       }
12262     } else { 
12263           if ( value(pp)<value(qq) ) {
12264         s=mp_get_node(mp, dep_node_size); mp_info(s)=qq; value(s)=value(q);
12265         q=mp_link(q); qq=mp_info(q); mp_link(r)=s; r=s;
12266       } else { 
12267         mp_link(r)=p; r=p; p=mp_link(p); pp=mp_info(p);
12268       }
12269     }
12270   }
12271   value(p)=mp_slow_add(mp, value(p),value(q));
12272   mp_link(r)=p; mp->dep_final=p; 
12273   return mp_link(temp_head);
12274 }
12275
12276 @ @<Contribute a term from |p|, plus the...@>=
12277
12278   v=value(p)+value(q);
12279   value(p)=v; s=p; p=mp_link(p); pp=mp_info(p);
12280   if ( abs(v)<threshold ) {
12281     mp_free_node(mp, s,dep_node_size);
12282   } else { 
12283     if ( (abs(v)>=coef_bound ) && mp->watch_coefs ) {
12284       mp_type(qq)=independent_needing_fix; mp->fix_needed=true;
12285     }
12286     mp_link(r)=s; r=s;
12287   }
12288   q=mp_link(q); qq=mp_info(q);
12289 }
12290
12291 @ A somewhat simpler routine will multiply a dependency list
12292 by a given constant~|v|. The constant is either a |fraction| less than
12293 |fraction_one|, or it is |scaled|. In the latter case we might be forced to
12294 convert a dependency list to a proto-dependency list.
12295 Parameters |t0| and |t1| are the list types before and after;
12296 they should agree unless |t0=mp_dependent| and |t1=mp_proto_dependent|
12297 and |v_is_scaled=true|.
12298
12299 @c 
12300 static pointer mp_p_times_v (MP mp,pointer p, integer v, quarterword t0,
12301                          quarterword t1, boolean v_is_scaled) {
12302   pointer r,s; /* for list manipulation */
12303   integer w; /* tentative coefficient */
12304   integer threshold;
12305   boolean scaling_down;
12306   if ( t0!=t1 ) scaling_down=true; else scaling_down=(!v_is_scaled);
12307   if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12308   else threshold=half_scaled_threshold;
12309   r=temp_head;
12310   while ( mp_info(p)!=null ) {    
12311     if ( scaling_down ) w=mp_take_fraction(mp, v,value(p));
12312     else w=mp_take_scaled(mp, v,value(p));
12313     if ( abs(w)<=threshold ) { 
12314       s=mp_link(p); mp_free_node(mp, p,dep_node_size); p=s;
12315     } else {
12316       if ( abs(w)>=coef_bound ) { 
12317         mp->fix_needed=true; mp_type(mp_info(p))=independent_needing_fix;
12318       }
12319       mp_link(r)=p; r=p; value(p)=w; p=mp_link(p);
12320     }
12321   }
12322   mp_link(r)=p;
12323   if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
12324   else value(p)=mp_take_fraction(mp, value(p),v);
12325   return mp_link(temp_head);
12326 }
12327
12328 @ Similarly, we sometimes need to divide a dependency list
12329 by a given |scaled| constant.
12330
12331 @<Declarations@>=
12332 static pointer mp_p_over_v (MP mp,pointer p, scaled v, quarterword 
12333   t0, quarterword t1) ;
12334
12335 @ @c
12336 pointer mp_p_over_v (MP mp,pointer p, scaled v, quarterword 
12337   t0, quarterword t1) {
12338   pointer r,s; /* for list manipulation */
12339   integer w; /* tentative coefficient */
12340   integer threshold;
12341   boolean scaling_down;
12342   if ( t0!=t1 ) scaling_down=true; else scaling_down=false;
12343   if ( t1==mp_dependent ) threshold=half_fraction_threshold;
12344   else threshold=half_scaled_threshold;
12345   r=temp_head;
12346   while ( mp_info( p)!=null ) {
12347     if ( scaling_down ) {
12348       if ( abs(v)<02000000 ) w=mp_make_scaled(mp, value(p),v*010000);
12349       else w=mp_make_scaled(mp, mp_round_fraction(mp, value(p)),v);
12350     } else {
12351       w=mp_make_scaled(mp, value(p),v);
12352     }
12353     if ( abs(w)<=threshold ) {
12354       s=mp_link(p); mp_free_node(mp, p,dep_node_size); p=s;
12355     } else { 
12356       if ( abs(w)>=coef_bound ) {
12357          mp->fix_needed=true; mp_type(mp_info(p))=independent_needing_fix;
12358       }
12359       mp_link(r)=p; r=p; value(p)=w; p=mp_link(p);
12360     }
12361   }
12362   mp_link(r)=p; value(p)=mp_make_scaled(mp, value(p),v);
12363   return mp_link(temp_head);
12364 }
12365
12366 @ Here's another utility routine for dependency lists. When an independent
12367 variable becomes dependent, we want to remove it from all existing
12368 dependencies. The |p_with_x_becoming_q| function computes the
12369 dependency list of~|p| after variable~|x| has been replaced by~|q|.
12370
12371 This procedure has basically the same calling conventions as |p_plus_fq|:
12372 List~|q| is unchanged; list~|p| is destroyed; the constant node and the
12373 final link are inherited from~|p|; and the fourth parameter tells whether
12374 or not |p| is |mp_proto_dependent|. However, the global variable |dep_final|
12375 is not altered if |x| does not occur in list~|p|.
12376
12377 @c 
12378 static pointer mp_p_with_x_becoming_q (MP mp,pointer p,
12379            pointer x, pointer q, quarterword t) {
12380   pointer r,s; /* for list manipulation */
12381   integer v; /* coefficient of |x| */
12382   integer sx; /* serial number of |x| */
12383   s=p; r=temp_head; sx=value(x);
12384   while ( value(mp_info(s))>sx ) { r=s; s=mp_link(s); };
12385   if ( mp_info(s)!=x ) { 
12386     return p;
12387   } else { 
12388     mp_link(temp_head)=p; mp_link(r)=mp_link(s); v=value(s);
12389     mp_free_node(mp, s,dep_node_size);
12390     return mp_p_plus_fq(mp, mp_link(temp_head),v,q,t,mp_dependent);
12391   }
12392 }
12393
12394 @ Here's a simple procedure that reports an error when a variable
12395 has just received a known value that's out of the required range.
12396
12397 @<Declarations@>=
12398 static void mp_val_too_big (MP mp,scaled x) ;
12399
12400 @ @c void mp_val_too_big (MP mp,scaled x) { 
12401   if ( mp->internal[mp_warning_check]>0 ) { 
12402     print_err("Value is too large ("); mp_print_scaled(mp, x); mp_print_char(mp, xord(')'));
12403 @.Value is too large@>
12404     help4("The equation I just processed has given some variable",
12405       "a value of 4096 or more. Continue and I'll try to cope",
12406       "with that big value; but it might be dangerous.",
12407       "(Set warningcheck:=0 to suppress this message.)");
12408     mp_error(mp);
12409   }
12410 }
12411
12412 @ When a dependent variable becomes known, the following routine
12413 removes its dependency list. Here |p| points to the variable, and
12414 |q| points to the dependency list (which is one node long).
12415
12416 @<Declarations@>=
12417 static void mp_make_known (MP mp,pointer p, pointer q) ;
12418
12419 @ @c void mp_make_known (MP mp,pointer p, pointer q) {
12420   int t; /* the previous type */
12421   prev_dep(mp_link(q))=prev_dep(p);
12422   mp_link(prev_dep(p))=mp_link(q); t=mp_type(p);
12423   mp_type(p)=mp_known; value(p)=value(q); mp_free_node(mp, q,dep_node_size);
12424   if ( abs(value(p))>=fraction_one ) mp_val_too_big(mp, value(p));
12425   if (( mp->internal[mp_tracing_equations]>0) && mp_interesting(mp, p) ) {
12426     mp_begin_diagnostic(mp); mp_print_nl(mp, "#### ");
12427 @:]]]\#\#\#\#_}{\.{\#\#\#\#}@>
12428     mp_print_variable_name(mp, p); 
12429     mp_print_char(mp, xord('=')); mp_print_scaled(mp, value(p));
12430     mp_end_diagnostic(mp, false);
12431   }
12432   if (( mp->cur_exp==p ) && mp->cur_type==t ) {
12433     mp->cur_type=mp_known; mp->cur_exp=value(p);
12434     mp_free_node(mp, p,value_node_size);
12435   }
12436 }
12437
12438 @ The |fix_dependencies| routine is called into action when |fix_needed|
12439 has been triggered. The program keeps a list~|s| of independent variables
12440 whose coefficients must be divided by~4.
12441
12442 In unusual cases, this fixup process might reduce one or more coefficients
12443 to zero, so that a variable will become known more or less by default.
12444
12445 @<Declarations@>=
12446 static void mp_fix_dependencies (MP mp);
12447
12448 @ @c 
12449 static void mp_fix_dependencies (MP mp) {
12450   pointer p,q,r,s,t; /* list manipulation registers */
12451   pointer x; /* an independent variable */
12452   r=mp_link(dep_head); s=null;
12453   while ( r!=dep_head ){ 
12454     t=r;
12455     @<Run through the dependency list for variable |t|, fixing
12456       all nodes, and ending with final link~|q|@>;
12457     r=mp_link(q);
12458     if ( q==dep_list(t) ) mp_make_known(mp, t,q);
12459   }
12460   while ( s!=null ) { 
12461     p=mp_link(s); x=mp_info(s); free_avail(s); s=p;
12462     mp_type(x)=mp_independent; value(x)=value(x)+2;
12463   }
12464   mp->fix_needed=false;
12465 }
12466
12467 @ @d independent_being_fixed 1 /* this variable already appears in |s| */
12468
12469 @<Run through the dependency list for variable |t|...@>=
12470 r=value_loc(t); /* |mp_link(r)=dep_list(t)| */
12471 while (1) { 
12472   q=mp_link(r); x=mp_info(q);
12473   if ( x==null ) break;
12474   if ( mp_type(x)<=independent_being_fixed ) {
12475     if ( mp_type(x)<independent_being_fixed ) {
12476       p=mp_get_avail(mp); mp_link(p)=s; s=p;
12477       mp_info(s)=x; mp_type(x)=independent_being_fixed;
12478     }
12479     value(q)=value(q) / 4;
12480     if ( value(q)==0 ) {
12481       mp_link(r)=mp_link(q); mp_free_node(mp, q,dep_node_size); q=r;
12482     }
12483   }
12484   r=q;
12485 }
12486
12487
12488 @ The |new_dep| routine installs a dependency list~|p| into the value node~|q|,
12489 linking it into the list of all known dependencies. We assume that
12490 |dep_final| points to the final node of list~|p|.
12491
12492 @c 
12493 static void mp_new_dep (MP mp,pointer q, pointer p) {
12494   pointer r; /* what used to be the first dependency */
12495   dep_list(q)=p; prev_dep(q)=dep_head;
12496   r=mp_link(dep_head); mp_link(mp->dep_final)=r; prev_dep(r)=mp->dep_final;
12497   mp_link(dep_head)=q;
12498 }
12499
12500 @ Here is one of the ways a dependency list gets started.
12501 The |const_dependency| routine produces a list that has nothing but
12502 a constant term.
12503
12504 @c static pointer mp_const_dependency (MP mp, scaled v) {
12505   mp->dep_final=mp_get_node(mp, dep_node_size);
12506   value(mp->dep_final)=v; mp_info(mp->dep_final)=null;
12507   return mp->dep_final;
12508 }
12509
12510 @ And here's a more interesting way to start a dependency list from scratch:
12511 The parameter to |single_dependency| is the location of an
12512 independent variable~|x|, and the result is the simple dependency list
12513 `|x+0|'.
12514
12515 In the unlikely event that the given independent variable has been doubled so
12516 often that we can't refer to it with a nonzero coefficient,
12517 |single_dependency| returns the simple list `0'.  This case can be
12518 recognized by testing that the returned list pointer is equal to
12519 |dep_final|.
12520
12521 @c 
12522 static pointer mp_single_dependency (MP mp,pointer p) {
12523   pointer q; /* the new dependency list */
12524   integer m; /* the number of doublings */
12525   m=value(p) % s_scale;
12526   if ( m>28 ) {
12527     return mp_const_dependency(mp, 0);
12528   } else { 
12529     q=mp_get_node(mp, dep_node_size);
12530     value(q)=(integer)two_to_the(28-m); mp_info(q)=p;
12531     mp_link(q)=mp_const_dependency(mp, 0);
12532     return q;
12533   }
12534 }
12535
12536 @ We sometimes need to make an exact copy of a dependency list.
12537
12538 @c 
12539 static pointer mp_copy_dep_list (MP mp,pointer p) {
12540   pointer q; /* the new dependency list */
12541   q=mp_get_node(mp, dep_node_size); mp->dep_final=q;
12542   while (1) { 
12543     mp_info(mp->dep_final)=mp_info(p); value(mp->dep_final)=value(p);
12544     if ( mp_info(mp->dep_final)==null ) break;
12545     mp_link(mp->dep_final)=mp_get_node(mp, dep_node_size);
12546     mp->dep_final=mp_link(mp->dep_final); p=mp_link(p);
12547   }
12548   return q;
12549 }
12550
12551 @ But how do variables normally become known? Ah, now we get to the heart of the
12552 equation-solving mechanism. The |linear_eq| procedure is given a |dependent|
12553 or |mp_proto_dependent| list,~|p|, in which at least one independent variable
12554 appears. It equates this list to zero, by choosing an independent variable
12555 with the largest coefficient and making it dependent on the others. The
12556 newly dependent variable is eliminated from all current dependencies,
12557 thereby possibly making other dependent variables known.
12558
12559 The given list |p| is, of course, totally destroyed by all this processing.
12560
12561 @c 
12562 static void mp_linear_eq (MP mp, pointer p, quarterword t) {
12563   pointer q,r,s; /* for link manipulation */
12564   pointer x; /* the variable that loses its independence */
12565   integer n; /* the number of times |x| had been halved */
12566   integer v; /* the coefficient of |x| in list |p| */
12567   pointer prev_r; /* lags one step behind |r| */
12568   pointer final_node; /* the constant term of the new dependency list */
12569   integer w; /* a tentative coefficient */
12570    @<Find a node |q| in list |p| whose coefficient |v| is largest@>;
12571   x=mp_info(q); n=value(x) % s_scale;
12572   @<Divide list |p| by |-v|, removing node |q|@>;
12573   if ( mp->internal[mp_tracing_equations]>0 ) {
12574     @<Display the new dependency@>;
12575   }
12576   @<Simplify all existing dependencies by substituting for |x|@>;
12577   @<Change variable |x| from |independent| to |dependent| or |known|@>;
12578   if ( mp->fix_needed ) mp_fix_dependencies(mp);
12579 }
12580
12581 @ @<Find a node |q| in list |p| whose coefficient |v| is largest@>=
12582 q=p; r=mp_link(p); v=value(q);
12583 while ( mp_info(r)!=null ) { 
12584   if ( abs(value(r))>abs(v) ) { q=r; v=value(r); };
12585   r=mp_link(r);
12586 }
12587
12588 @ Here we want to change the coefficients from |scaled| to |fraction|,
12589 except in the constant term. In the common case of a trivial equation
12590 like `\.{x=3.14}', we will have |v=-fraction_one|, |q=p|, and |t=mp_dependent|.
12591
12592 @<Divide list |p| by |-v|, removing node |q|@>=
12593 s=temp_head; mp_link(s)=p; r=p;
12594 do { 
12595   if ( r==q ) {
12596     mp_link(s)=mp_link(r); mp_free_node(mp, r,dep_node_size);
12597   } else  { 
12598     w=mp_make_fraction(mp, value(r),v);
12599     if ( abs(w)<=half_fraction_threshold ) {
12600       mp_link(s)=mp_link(r); mp_free_node(mp, r,dep_node_size);
12601     } else { 
12602       value(r)=-w; s=r;
12603     }
12604   }
12605   r=mp_link(s);
12606 } while (mp_info(r)!=null);
12607 if ( t==mp_proto_dependent ) {
12608   value(r)=-mp_make_scaled(mp, value(r),v);
12609 } else if ( v!=-fraction_one ) {
12610   value(r)=-mp_make_fraction(mp, value(r),v);
12611 }
12612 final_node=r; p=mp_link(temp_head)
12613
12614 @ @<Display the new dependency@>=
12615 if ( mp_interesting(mp, x) ) {
12616   mp_begin_diagnostic(mp); mp_print_nl(mp, "## "); 
12617   mp_print_variable_name(mp, x);
12618 @:]]]\#\#_}{\.{\#\#}@>
12619   w=n;
12620   while ( w>0 ) { mp_print(mp, "*4"); w=w-2;  };
12621   mp_print_char(mp, xord('=')); mp_print_dependency(mp, p,mp_dependent); 
12622   mp_end_diagnostic(mp, false);
12623 }
12624
12625 @ @<Simplify all existing dependencies by substituting for |x|@>=
12626 prev_r=dep_head; r=mp_link(dep_head);
12627 while ( r!=dep_head ) {
12628   s=dep_list(r); q=mp_p_with_x_becoming_q(mp, s,x,p,mp_type(r));
12629   if ( mp_info(q)==null ) {
12630     mp_make_known(mp, r,q);
12631   } else { 
12632     dep_list(r)=q;
12633     do {  q=mp_link(q); } while (mp_info(q)!=null);
12634     prev_r=q;
12635   }
12636   r=mp_link(prev_r);
12637 }
12638
12639 @ @<Change variable |x| from |independent| to |dependent| or |known|@>=
12640 if ( n>0 ) @<Divide list |p| by $2^n$@>;
12641 if ( mp_info(p)==null ) {
12642   mp_type(x)=mp_known;
12643   value(x)=value(p);
12644   if ( abs(value(x))>=fraction_one ) mp_val_too_big(mp, value(x));
12645   mp_free_node(mp, p,dep_node_size);
12646   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) {
12647     mp->cur_exp=value(x); mp->cur_type=mp_known;
12648     mp_free_node(mp, x,value_node_size);
12649   }
12650 } else { 
12651   mp_type(x)=mp_dependent; mp->dep_final=final_node; mp_new_dep(mp, x,p);
12652   if ( mp->cur_exp==x ) if ( mp->cur_type==mp_independent ) mp->cur_type=mp_dependent;
12653 }
12654
12655 @ @<Divide list |p| by $2^n$@>=
12656
12657   s=temp_head; mp_link(temp_head)=p; r=p;
12658   do {  
12659     if ( n>30 ) w=0;
12660     else w=value(r) / two_to_the(n);
12661     if ( (abs(w)<=half_fraction_threshold)&&(mp_info(r)!=null) ) {
12662       mp_link(s)=mp_link(r);
12663       mp_free_node(mp, r,dep_node_size);
12664     } else { 
12665       value(r)=w; s=r;
12666     }
12667     r=mp_link(s);
12668   } while (mp_info(s)!=null);
12669   p=mp_link(temp_head);
12670 }
12671
12672 @ The |check_mem| procedure, which is used only when \MP\ is being
12673 debugged, makes sure that the current dependency lists are well formed.
12674
12675 @<Check the list of linear dependencies@>=
12676 q=dep_head; p=mp_link(q);
12677 while ( p!=dep_head ) {
12678   if ( prev_dep(p)!=q ) {
12679     mp_print_nl(mp, "Bad PREVDEP at "); mp_print_int(mp, p);
12680 @.Bad PREVDEP...@>
12681   }
12682   p=dep_list(p);
12683   while (1) {
12684     r=mp_info(p); q=p; p=mp_link(q);
12685     if ( r==null ) break;
12686     if ( value(mp_info(p))>=value(r) ) {
12687       mp_print_nl(mp, "Out of order at "); mp_print_int(mp, p);
12688 @.Out of order...@>
12689     }
12690   }
12691 }
12692
12693 @* \[25] Dynamic nonlinear equations.
12694 Variables of numeric type are maintained by the general scheme of
12695 independent, dependent, and known values that we have just studied;
12696 and the components of pair and transform variables are handled in the
12697 same way. But \MP\ also has five other types of values: \&{boolean},
12698 \&{string}, \&{pen}, \&{path}, and \&{picture}; what about them?
12699
12700 Equations are allowed between nonlinear quantities, but only in a
12701 simple form. Two variables that haven't yet been assigned values are
12702 either equal to each other, or they're not.
12703
12704 Before a boolean variable has received a value, its type is |mp_unknown_boolean|;
12705 similarly, there are variables whose type is |mp_unknown_string|, |mp_unknown_pen|,
12706 |mp_unknown_path|, and |mp_unknown_picture|. In such cases the value is either
12707 |null| (which means that no other variables are equivalent to this one), or
12708 it points to another variable of the same undefined type. The pointers in the
12709 latter case form a cycle of nodes, which we shall call a ``ring.''
12710 Rings of undefined variables may include capsules, which arise as
12711 intermediate results within expressions or as \&{expr} parameters to macros.
12712
12713 When one member of a ring receives a value, the same value is given to
12714 all the other members. In the case of paths and pictures, this implies
12715 making separate copies of a potentially large data structure; users should
12716 restrain their enthusiasm for such generality, unless they have lots and
12717 lots of memory space.
12718
12719 @ The following procedure is called when a capsule node is being
12720 added to a ring (e.g., when an unknown variable is mentioned in an expression).
12721
12722 @c 
12723 static pointer mp_new_ring_entry (MP mp,pointer p) {
12724   pointer q; /* the new capsule node */
12725   q=mp_get_node(mp, value_node_size); mp_name_type(q)=mp_capsule;
12726   mp_type(q)=mp_type(p);
12727   if ( value(p)==null ) value(q)=p; else value(q)=value(p);
12728   value(p)=q;
12729   return q;
12730 }
12731
12732 @ Conversely, we might delete a capsule or a variable before it becomes known.
12733 The following procedure simply detaches a quantity from its ring,
12734 without recycling the storage.
12735
12736 @<Declarations@>=
12737 static void mp_ring_delete (MP mp,pointer p);
12738
12739 @ @c
12740 void mp_ring_delete (MP mp,pointer p) {
12741   pointer q; 
12742   q=value(p);
12743   if ( q!=null ) if ( q!=p ){ 
12744     while ( value(q)!=p ) q=value(q);
12745     value(q)=value(p);
12746   }
12747 }
12748
12749 @ Eventually there might be an equation that assigns values to all of the
12750 variables in a ring. The |nonlinear_eq| subroutine does the necessary
12751 propagation of values.
12752
12753 If the parameter |flush_p| is |true|, node |p| itself needn't receive a
12754 value, it will soon be recycled.
12755
12756 @c 
12757 static void mp_nonlinear_eq (MP mp,integer v, pointer p, boolean flush_p) {
12758   quarterword t; /* the type of ring |p| */
12759   pointer q,r; /* link manipulation registers */
12760   t=mp_type(p)-unknown_tag; q=value(p);
12761   if ( flush_p ) mp_type(p)=mp_vacuous; else p=q;
12762   do {  
12763     r=value(q); mp_type(q)=t;
12764     switch (t) {
12765     case mp_boolean_type: value(q)=v; break;
12766     case mp_string_type: value(q)=v; add_str_ref(v); break;
12767     case mp_pen_type: value(q)=copy_pen(v); break;
12768     case mp_path_type: value(q)=mp_copy_path(mp, v); break;
12769     case mp_picture_type: value(q)=v; add_edge_ref(v); break;
12770     } /* there ain't no more cases */
12771     q=r;
12772   } while (q!=p);
12773 }
12774
12775 @ If two members of rings are equated, and if they have the same type,
12776 the |ring_merge| procedure is called on to make them equivalent.
12777
12778 @c 
12779 static void mp_ring_merge (MP mp,pointer p, pointer q) {
12780   pointer r; /* traverses one list */
12781   r=value(p);
12782   while ( r!=p ) {
12783     if ( r==q ) {
12784       @<Exclaim about a redundant equation@>;
12785       return;
12786     };
12787     r=value(r);
12788   }
12789   r=value(p); value(p)=value(q); value(q)=r;
12790 }
12791
12792 @ @<Exclaim about a redundant equation@>=
12793
12794   print_err("Redundant equation");
12795 @.Redundant equation@>
12796   help2("I already knew that this equation was true.",
12797         "But perhaps no harm has been done; let's continue.");
12798   mp_put_get_error(mp);
12799 }
12800
12801 @* \[26] Introduction to the syntactic routines.
12802 Let's pause a moment now and try to look at the Big Picture.
12803 The \MP\ program consists of three main parts: syntactic routines,
12804 semantic routines, and output routines. The chief purpose of the
12805 syntactic routines is to deliver the user's input to the semantic routines,
12806 while parsing expressions and locating operators and operands. The
12807 semantic routines act as an interpreter responding to these operators,
12808 which may be regarded as commands. And the output routines are
12809 periodically called on to produce compact font descriptions that can be
12810 used for typesetting or for making interim proof drawings. We have
12811 discussed the basic data structures and many of the details of semantic
12812 operations, so we are good and ready to plunge into the part of \MP\ that
12813 actually controls the activities.
12814
12815 Our current goal is to come to grips with the |get_next| procedure,
12816 which is the keystone of \MP's input mechanism. Each call of |get_next|
12817 sets the value of three variables |cur_cmd|, |cur_mod|, and |cur_sym|,
12818 representing the next input token.
12819 $$\vbox{\halign{#\hfil\cr
12820   \hbox{|cur_cmd| denotes a command code from the long list of codes
12821    given earlier;}\cr
12822   \hbox{|cur_mod| denotes a modifier of the command code;}\cr
12823   \hbox{|cur_sym| is the hash address of the symbolic token that was
12824    just scanned,}\cr
12825   \hbox{\qquad or zero in the case of a numeric or string
12826    or capsule token.}\cr}}$$
12827 Underlying this external behavior of |get_next| is all the machinery
12828 necessary to convert from character files to tokens. At a given time we
12829 may be only partially finished with the reading of several files (for
12830 which \&{input} was specified), and partially finished with the expansion
12831 of some user-defined macros and/or some macro parameters, and partially
12832 finished reading some text that the user has inserted online,
12833 and so on. When reading a character file, the characters must be
12834 converted to tokens; comments and blank spaces must
12835 be removed, numeric and string tokens must be evaluated.
12836
12837 To handle these situations, which might all be present simultaneously,
12838 \MP\ uses various stacks that hold information about the incomplete
12839 activities, and there is a finite state control for each level of the
12840 input mechanism. These stacks record the current state of an implicitly
12841 recursive process, but the |get_next| procedure is not recursive.
12842
12843 @<Glob...@>=
12844 integer cur_cmd; /* current command set by |get_next| */
12845 integer cur_mod; /* operand of current command */
12846 halfword cur_sym; /* hash address of current symbol */
12847
12848 @ The |print_cmd_mod| routine prints a symbolic interpretation of a
12849 command code and its modifier.
12850 It consists of a rather tedious sequence of print
12851 commands, and most of it is essentially an inverse to the |primitive|
12852 routine that enters a \MP\ primitive into |hash| and |eqtb|. Therefore almost
12853 all of this procedure appears elsewhere in the program, together with the
12854 corresponding |primitive| calls.
12855
12856 @<Declarations@>=
12857 static void mp_print_cmd_mod (MP mp,integer c, integer m) ;
12858
12859 @ @c
12860 void mp_print_cmd_mod (MP mp,integer c, integer m) { 
12861  switch (c) {
12862   @<Cases of |print_cmd_mod| for symbolic printing of primitives@>
12863   default: mp_print(mp, "[unknown command code!]"); break;
12864   }
12865 }
12866
12867 @ Here is a procedure that displays a given command in braces, in the
12868 user's transcript file.
12869
12870 @d show_cur_cmd_mod mp_show_cmd_mod(mp, mp->cur_cmd,mp->cur_mod)
12871
12872 @c 
12873 static void mp_show_cmd_mod (MP mp,integer c, integer m) { 
12874   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
12875   mp_print_cmd_mod(mp, c,m); mp_print_char(mp, xord('}'));
12876   mp_end_diagnostic(mp, false);
12877 }
12878
12879 @* \[27] Input stacks and states.
12880 The state of \MP's input mechanism appears in the input stack, whose
12881 entries are records with five fields, called |index|, |start|, |loc|,
12882 |limit|, and |name|. The top element of this stack is maintained in a
12883 global variable for which no subscripting needs to be done; the other
12884 elements of the stack appear in an array. Hence the stack is declared thus:
12885
12886 @<Types...@>=
12887 typedef struct {
12888   quarterword index_field;
12889   halfword start_field, loc_field, limit_field, name_field;
12890 } in_state_record;
12891
12892 @ @<Glob...@>=
12893 in_state_record *input_stack;
12894 integer input_ptr; /* first unused location of |input_stack| */
12895 integer max_in_stack; /* largest value of |input_ptr| when pushing */
12896 in_state_record cur_input; /* the ``top'' input state */
12897 int stack_size; /* maximum number of simultaneous input sources */
12898
12899 @ @<Allocate or initialize ...@>=
12900 mp->stack_size = 300;
12901 mp->input_stack = xmalloc((mp->stack_size+1),sizeof(in_state_record));
12902
12903 @ @<Dealloc variables@>=
12904 xfree(mp->input_stack);
12905
12906 @ We've already defined the special variable |loc==cur_input.loc_field|
12907 in our discussion of basic input-output routines. The other components of
12908 |cur_input| are defined in the same way:
12909
12910 @d iindex mp->cur_input.index_field /* reference for buffer information */
12911 @d start mp->cur_input.start_field /* starting position in |buffer| */
12912 @d limit mp->cur_input.limit_field /* end of current line in |buffer| */
12913 @d name mp->cur_input.name_field /* name of the current file */
12914
12915 @ Let's look more closely now at the five control variables
12916 (|index|,~|start|,~|loc|,~|limit|,~|name|),
12917 assuming that \MP\ is reading a line of characters that have been input
12918 from some file or from the user's terminal. There is an array called
12919 |buffer| that acts as a stack of all lines of characters that are
12920 currently being read from files, including all lines on subsidiary
12921 levels of the input stack that are not yet completed. \MP\ will return to
12922 the other lines when it is finished with the present input file.
12923
12924 (Incidentally, on a machine with byte-oriented addressing, it would be
12925 appropriate to combine |buffer| with the |str_pool| array,
12926 letting the buffer entries grow downward from the top of the string pool
12927 and checking that these two tables don't bump into each other.)
12928
12929 The line we are currently working on begins in position |start| of the
12930 buffer; the next character we are about to read is |buffer[loc]|; and
12931 |limit| is the location of the last character present. We always have
12932 |loc<=limit|. For convenience, |buffer[limit]| has been set to |"%"|, so
12933 that the end of a line is easily sensed.
12934
12935 The |name| variable is a string number that designates the name of
12936 the current file, if we are reading an ordinary text file.  Special codes
12937 |is_term..max_spec_src| indicate other sources of input text.
12938
12939 @d is_term 0 /* |name| value when reading from the terminal for normal input */
12940 @d is_read 1 /* |name| value when executing a \&{readstring} or \&{readfrom} */
12941 @d is_scantok 2 /* |name| value when reading text generated by \&{scantokens} */
12942 @d max_spec_src is_scantok
12943
12944 @ Additional information about the current line is available via the
12945 |index| variable, which counts how many lines of characters are present
12946 in the buffer below the current level. We have |index=0| when reading
12947 from the terminal and prompting the user for each line; then if the user types,
12948 e.g., `\.{input figs}', we will have |index=1| while reading
12949 the file \.{figs.mp}. However, it does not follow that |index| is the
12950 same as the input stack pointer, since many of the levels on the input
12951 stack may come from token lists and some |index| values may correspond
12952 to \.{MPX} files that are not currently on the stack.
12953
12954 The global variable |in_open| is equal to the highest |index| value counting
12955 \.{MPX} files but excluding token-list input levels.  Thus, the number of
12956 partially read lines in the buffer is |in_open+1| and we have |in_open>=index|
12957 when we are not reading a token list.
12958
12959 If we are not currently reading from the terminal,
12960 we are reading from the file variable |input_file[index]|. We use
12961 the notation |terminal_input| as a convenient abbreviation for |name=is_term|,
12962 and |cur_file| as an abbreviation for |input_file[index]|.
12963
12964 When \MP\ is not reading from the terminal, the global variable |line| contains
12965 the line number in the current file, for use in error messages. More precisely,
12966 |line| is a macro for |line_stack[index]| and the |line_stack| array gives
12967 the line number for each file in the |input_file| array.
12968
12969 When an \.{MPX} file is opened the file name is stored in the |mpx_name|
12970 array so that the name doesn't get lost when the file is temporarily removed
12971 from the input stack.
12972 Thus when |input_file[k]| is an \.{MPX} file, its name is |mpx_name[k]|
12973 and it contains translated \TeX\ pictures for |input_file[k-1]|.
12974 Since this is not an \.{MPX} file, we have
12975 $$ \hbox{|mpx_name[k-1]<=absent|}. $$
12976 This |name| field is set to |finished| when |input_file[k]| is completely
12977 read.
12978
12979 If more information about the input state is needed, it can be
12980 included in small arrays like those shown here. For example,
12981 the current page or segment number in the input file might be put
12982 into a variable |page|, that is really a macro for the current entry
12983 in `\ignorespaces|page_stack:array[0..max_in_open] of integer|\unskip'
12984 by analogy with |line_stack|.
12985 @^system dependencies@>
12986
12987 @d terminal_input (name==is_term) /* are we reading from the terminal? */
12988 @d cur_file mp->input_file[iindex] /* the current |void *| variable */
12989 @d line mp->line_stack[iindex] /* current line number in the current source file */
12990 @d in_name mp->iname_stack[iindex] /* a string used to construct \.{MPX} file names */
12991 @d in_area mp->iarea_stack[iindex] /* another string for naming \.{MPX} files */
12992 @d absent 1 /* |name_field| value for unused |mpx_in_stack| entries */
12993 @d mpx_reading (mp->mpx_name[iindex]>absent)
12994   /* when reading a file, is it an \.{MPX} file? */
12995 @d mpx_finished 0
12996   /* |name_field| value when the corresponding \.{MPX} file is finished */
12997
12998 @<Glob...@>=
12999 integer in_open; /* the number of lines in the buffer, less one */
13000 unsigned int open_parens; /* the number of open text files */
13001 void  * *input_file ;
13002 integer *line_stack ; /* the line number for each file */
13003 char *  *iname_stack; /* used for naming \.{MPX} files */
13004 char *  *iarea_stack; /* used for naming \.{MPX} files */
13005 halfword*mpx_name  ;
13006
13007 @ @<Allocate or ...@>=
13008 mp->input_file  = xmalloc((mp->max_in_open+1),sizeof(void *));
13009 mp->line_stack  = xmalloc((mp->max_in_open+1),sizeof(integer));
13010 mp->iname_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
13011 mp->iarea_stack = xmalloc((mp->max_in_open+1),sizeof(char *));
13012 mp->mpx_name    = xmalloc((mp->max_in_open+1),sizeof(halfword));
13013 {
13014   int k;
13015   for (k=0;k<=mp->max_in_open;k++) {
13016     mp->iname_stack[k] =NULL;
13017     mp->iarea_stack[k] =NULL;
13018   }
13019 }
13020
13021 @ @<Dealloc variables@>=
13022 {
13023   int l;
13024   for (l=0;l<=mp->max_in_open;l++) {
13025     xfree(mp->iname_stack[l]);
13026     xfree(mp->iarea_stack[l]);
13027   }
13028 }
13029 xfree(mp->input_file);
13030 xfree(mp->line_stack);
13031 xfree(mp->iname_stack);
13032 xfree(mp->iarea_stack);
13033 xfree(mp->mpx_name);
13034
13035
13036 @ However, all this discussion about input state really applies only to the
13037 case that we are inputting from a file. There is another important case,
13038 namely when we are currently getting input from a token list. In this case
13039 |iindex>max_in_open|, and the conventions about the other state variables
13040 are different:
13041
13042 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
13043 the node that will be read next. If |loc=null|, the token list has been
13044 fully read.
13045
13046 \yskip\hang|start| points to the first node of the token list; this node
13047 may or may not contain a reference count, depending on the type of token
13048 list involved.
13049
13050 \yskip\hang|token_type|, which takes the place of |iindex| in the
13051 discussion above, is a code number that explains what kind of token list
13052 is being scanned.
13053
13054 \yskip\hang|name| points to the |eqtb| address of the control sequence
13055 being expanded, if the current token list is a macro not defined by
13056 \&{vardef}. Macros defined by \&{vardef} have |name=null|; their name
13057 can be deduced by looking at their first two parameters.
13058
13059 \yskip\hang|param_start|, which takes the place of |limit|, tells where
13060 the parameters of the current macro or loop text begin in the |param_stack|.
13061
13062 \yskip\noindent The |token_type| can take several values, depending on
13063 where the current token list came from:
13064
13065 \yskip
13066 \indent|forever_text|, if the token list being scanned is the body of
13067 a \&{forever} loop;
13068
13069 \indent|loop_text|, if the token list being scanned is the body of
13070 a \&{for} or \&{forsuffixes} loop;
13071
13072 \indent|parameter|, if a \&{text} or \&{suffix} parameter is being scanned;
13073
13074 \indent|backed_up|, if the token list being scanned has been inserted as
13075 `to be read again'.
13076
13077 \indent|inserted|, if the token list being scanned has been inserted as
13078 part of error recovery;
13079
13080 \indent|macro|, if the expansion of a user-defined symbolic token is being
13081 scanned.
13082
13083 \yskip\noindent
13084 The token list begins with a reference count if and only if |token_type=
13085 macro|.
13086 @^reference counts@>
13087
13088 @d token_type iindex /* type of current token list */
13089 @d token_state (iindex>(int)mp->max_in_open) /* are we scanning a token list? */
13090 @d file_state (iindex<=(int)mp->max_in_open) /* are we scanning a file line? */
13091 @d param_start limit /* base of macro parameters in |param_stack| */
13092 @d forever_text (mp->max_in_open+1) /* |token_type| code for loop texts */
13093 @d loop_text (mp->max_in_open+2) /* |token_type| code for loop texts */
13094 @d parameter (mp->max_in_open+3) /* |token_type| code for parameter texts */
13095 @d backed_up (mp->max_in_open+4) /* |token_type| code for texts to be reread */
13096 @d inserted (mp->max_in_open+5) /* |token_type| code for inserted texts */
13097 @d macro (mp->max_in_open+6) /* |token_type| code for macro replacement texts */
13098
13099 @ The |param_stack| is an auxiliary array used to hold pointers to the token
13100 lists for parameters at the current level and subsidiary levels of input.
13101 This stack grows at a different rate from the others.
13102
13103 @<Glob...@>=
13104 pointer *param_stack;  /* token list pointers for parameters */
13105 integer param_ptr; /* first unused entry in |param_stack| */
13106 integer max_param_stack;  /* largest value of |param_ptr| */
13107
13108 @ @<Allocate or initialize ...@>=
13109 mp->param_stack = xmalloc((mp->param_size+1),sizeof(pointer));
13110
13111 @ @<Dealloc variables@>=
13112 xfree(mp->param_stack);
13113
13114 @ Notice that the |line| isn't valid when |token_state| is true because it
13115 depends on |iindex|.  If we really need to know the line number for the
13116 topmost file in the iindex stack we use the following function.  If a page
13117 number or other information is needed, this routine should be modified to
13118 compute it as well.
13119 @^system dependencies@>
13120
13121 @<Declarations@>=
13122 static integer mp_true_line (MP mp) ;
13123
13124 @ @c
13125 integer mp_true_line (MP mp) {
13126   int k; /* an index into the input stack */
13127   if ( file_state && (name>max_spec_src) ) {
13128     return line;
13129   } else { 
13130     k=mp->input_ptr;
13131     while ((k>0) &&
13132            ((mp->input_stack[(k-1)].index_field>mp->max_in_open)||
13133             (mp->input_stack[(k-1)].name_field<=max_spec_src))) {
13134       decr(k);
13135     }
13136     return (k>0 ? mp->line_stack[(k-1)] : 0 );
13137   }
13138 }
13139
13140 @ Thus, the ``current input state'' can be very complicated indeed; there
13141 can be many levels and each level can arise in a variety of ways. The
13142 |show_context| procedure, which is used by \MP's error-reporting routine to
13143 print out the current input state on all levels down to the most recent
13144 line of characters from an input file, illustrates most of these conventions.
13145 The global variable |file_ptr| contains the lowest level that was
13146 displayed by this procedure.
13147
13148 @<Glob...@>=
13149 integer file_ptr; /* shallowest level shown by |show_context| */
13150
13151 @ The status at each level is indicated by printing two lines, where the first
13152 line indicates what was read so far and the second line shows what remains
13153 to be read. The context is cropped, if necessary, so that the first line
13154 contains at most |half_error_line| characters, and the second contains
13155 at most |error_line|. Non-current input levels whose |token_type| is
13156 `|backed_up|' are shown only if they have not been fully read.
13157
13158 @c void mp_show_context (MP mp) { /* prints where the scanner is */
13159   unsigned old_setting; /* saved |selector| setting */
13160   @<Local variables for formatting calculations@>
13161   mp->file_ptr=mp->input_ptr; mp->input_stack[mp->file_ptr]=mp->cur_input;
13162   /* store current state */
13163   while (1) { 
13164     mp->cur_input=mp->input_stack[mp->file_ptr]; /* enter into the context */
13165     @<Display the current context@>;
13166     if ( file_state )
13167       if ( (name>max_spec_src) || (mp->file_ptr==0) ) break;
13168     decr(mp->file_ptr);
13169   }
13170   mp->cur_input=mp->input_stack[mp->input_ptr]; /* restore original state */
13171 }
13172
13173 @ @<Display the current context@>=
13174 if ( (mp->file_ptr==mp->input_ptr) || file_state ||
13175    (token_type!=backed_up) || (loc!=null) ) {
13176     /* we omit backed-up token lists that have already been read */
13177   mp->tally=0; /* get ready to count characters */
13178   old_setting=mp->selector;
13179   if ( file_state ) {
13180     @<Print location of current line@>;
13181     @<Pseudoprint the line@>;
13182   } else { 
13183     @<Print type of token list@>;
13184     @<Pseudoprint the token list@>;
13185   }
13186   mp->selector=old_setting; /* stop pseudoprinting */
13187   @<Print two lines using the tricky pseudoprinted information@>;
13188 }
13189
13190 @ This routine should be changed, if necessary, to give the best possible
13191 indication of where the current line resides in the input file.
13192 For example, on some systems it is best to print both a page and line number.
13193 @^system dependencies@>
13194
13195 @<Print location of current line@>=
13196 if ( name>max_spec_src ) {
13197   mp_print_nl(mp, "l."); mp_print_int(mp, mp_true_line(mp));
13198 } else if ( terminal_input ) {
13199   if ( mp->file_ptr==0 ) mp_print_nl(mp, "<*>");
13200   else mp_print_nl(mp, "<insert>");
13201 } else if ( name==is_scantok ) {
13202   mp_print_nl(mp, "<scantokens>");
13203 } else {
13204   mp_print_nl(mp, "<read>");
13205 }
13206 mp_print_char(mp, xord(' '))
13207
13208 @ Can't use case statement here because the |token_type| is not
13209 a constant expression.
13210
13211 @<Print type of token list@>=
13212 {
13213   if(token_type==forever_text) {
13214     mp_print_nl(mp, "<forever> ");
13215   } else if (token_type==loop_text) {
13216     @<Print the current loop value@>;
13217   } else if (token_type==parameter) {
13218     mp_print_nl(mp, "<argument> "); 
13219   } else if (token_type==backed_up) { 
13220     if ( loc==null ) mp_print_nl(mp, "<recently read> ");
13221     else mp_print_nl(mp, "<to be read again> ");
13222   } else if (token_type==inserted) {
13223     mp_print_nl(mp, "<inserted text> ");
13224   } else if (token_type==macro) {
13225     mp_print_ln(mp);
13226     if ( name!=null ) mp_print_text(name);
13227     else @<Print the name of a \&{vardef}'d macro@>;
13228     mp_print(mp, "->");
13229   } else {
13230     mp_print_nl(mp, "?");/* this should never happen */
13231 @.?\relax@>
13232   }
13233 }
13234
13235 @ The parameter that corresponds to a loop text is either a token list
13236 (in the case of \&{forsuffixes}) or a ``capsule'' (in the case of \&{for}).
13237 We'll discuss capsules later; for now, all we need to know is that
13238 the |link| field in a capsule parameter is |void| and that
13239 |print_exp(p,0)| displays the value of capsule~|p| in abbreviated form.
13240
13241 @<Print the current loop value@>=
13242 { mp_print_nl(mp, "<for("); p=mp->param_stack[param_start];
13243   if ( p!=null ) {
13244     if ( mp_link(p)==mp_void ) mp_print_exp(mp, p,0); /* we're in a \&{for} loop */
13245     else mp_show_token_list(mp, p,null,20,mp->tally);
13246   }
13247   mp_print(mp, ")> ");
13248 }
13249
13250 @ The first two parameters of a macro defined by \&{vardef} will be token
13251 lists representing the macro's prefix and ``at point.'' By putting these
13252 together, we get the macro's full name.
13253
13254 @<Print the name of a \&{vardef}'d macro@>=
13255 { p=mp->param_stack[param_start];
13256   if ( p==null ) {
13257     mp_show_token_list(mp, mp->param_stack[param_start+1],null,20,mp->tally);
13258   } else { 
13259     q=p;
13260     while ( mp_link(q)!=null ) q=mp_link(q);
13261     mp_link(q)=mp->param_stack[param_start+1];
13262     mp_show_token_list(mp, p,null,20,mp->tally);
13263     mp_link(q)=null;
13264   }
13265 }
13266
13267 @ Now it is necessary to explain a little trick. We don't want to store a long
13268 string that corresponds to a token list, because that string might take up
13269 lots of memory; and we are printing during a time when an error message is
13270 being given, so we dare not do anything that might overflow one of \MP's
13271 tables. So `pseudoprinting' is the answer: We enter a mode of printing
13272 that stores characters into a buffer of length |error_line|, where character
13273 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
13274 |k<trick_count|, otherwise character |k| is dropped. Initially we set
13275 |tally:=0| and |trick_count:=1000000|; then when we reach the
13276 point where transition from line 1 to line 2 should occur, we
13277 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
13278 tally+1+error_line-half_error_line)|. At the end of the
13279 pseudoprinting, the values of |first_count|, |tally|, and
13280 |trick_count| give us all the information we need to print the two lines,
13281 and all of the necessary text is in |trick_buf|.
13282
13283 Namely, let |l| be the length of the descriptive information that appears
13284 on the first line. The length of the context information gathered for that
13285 line is |k=first_count|, and the length of the context information
13286 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
13287 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
13288 descriptive information on line~1, and set |n:=l+k|; here |n| is the
13289 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
13290 and print `\.{...}' followed by
13291 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
13292 where subscripts of |trick_buf| are circular modulo |error_line|. The
13293 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
13294 unless |n+m>error_line|; in the latter case, further cropping is done.
13295 This is easier to program than to explain.
13296
13297 @<Local variables for formatting...@>=
13298 int i; /* index into |buffer| */
13299 integer l; /* length of descriptive information on line 1 */
13300 integer m; /* context information gathered for line 2 */
13301 int n; /* length of line 1 */
13302 integer p; /* starting or ending place in |trick_buf| */
13303 integer q; /* temporary index */
13304
13305 @ The following code tells the print routines to gather
13306 the desired information.
13307
13308 @d begin_pseudoprint { 
13309   l=mp->tally; mp->tally=0; mp->selector=pseudo;
13310   mp->trick_count=1000000;
13311 }
13312 @d set_trick_count {
13313   mp->first_count=mp->tally;
13314   mp->trick_count=mp->tally+1+mp->error_line-mp->half_error_line;
13315   if ( mp->trick_count<mp->error_line ) mp->trick_count=mp->error_line;
13316 }
13317
13318 @ And the following code uses the information after it has been gathered.
13319
13320 @<Print two lines using the tricky pseudoprinted information@>=
13321 if ( mp->trick_count==1000000 ) set_trick_count;
13322   /* |set_trick_count| must be performed */
13323 if ( mp->tally<mp->trick_count ) m=mp->tally-mp->first_count;
13324 else m=mp->trick_count-mp->first_count; /* context on line 2 */
13325 if ( l+mp->first_count<=mp->half_error_line ) {
13326   p=0; n=l+mp->first_count;
13327 } else  { 
13328   mp_print(mp, "..."); p=l+mp->first_count-mp->half_error_line+3;
13329   n=mp->half_error_line;
13330 }
13331 for (q=p;q<=mp->first_count-1;q++) {
13332   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13333 }
13334 mp_print_ln(mp);
13335 for (q=1;q<=n;q++) {
13336   mp_print_char(mp, xord(' ')); /* print |n| spaces to begin line~2 */
13337 }
13338 if ( m+n<=mp->error_line ) p=mp->first_count+m; 
13339 else p=mp->first_count+(mp->error_line-n-3);
13340 for (q=mp->first_count;q<=p-1;q++) {
13341   mp_print_char(mp, mp->trick_buf[q % mp->error_line]);
13342 }
13343 if ( m+n>mp->error_line ) mp_print(mp, "...")
13344
13345 @ But the trick is distracting us from our current goal, which is to
13346 understand the input state. So let's concentrate on the data structures that
13347 are being pseudoprinted as we finish up the |show_context| procedure.
13348
13349 @<Pseudoprint the line@>=
13350 begin_pseudoprint;
13351 if ( limit>0 ) {
13352   for (i=start;i<=limit-1;i++) {
13353     if ( i==loc ) set_trick_count;
13354     mp_print_str(mp, mp->buffer[i]);
13355   }
13356 }
13357
13358 @ @<Pseudoprint the token list@>=
13359 begin_pseudoprint;
13360 if ( token_type!=macro ) mp_show_token_list(mp, start,loc,100000,0);
13361 else mp_show_macro(mp, start,loc,100000)
13362
13363 @ Here is the missing piece of |show_token_list| that is activated when the
13364 token beginning line~2 is about to be shown:
13365
13366 @<Do magic computation@>=set_trick_count
13367
13368 @* \[28] Maintaining the input stacks.
13369 The following subroutines change the input status in commonly needed ways.
13370
13371 First comes |push_input|, which stores the current state and creates a
13372 new level (having, initially, the same properties as the old).
13373
13374 @d push_input  { /* enter a new input level, save the old */
13375   if ( mp->input_ptr>mp->max_in_stack ) {
13376     mp->max_in_stack=mp->input_ptr;
13377     if ( mp->input_ptr==mp->stack_size ) {
13378       int l = (mp->stack_size+(mp->stack_size/4));
13379       XREALLOC(mp->input_stack, l, in_state_record);
13380       mp->stack_size = l;
13381     }         
13382   }
13383   mp->input_stack[mp->input_ptr]=mp->cur_input; /* stack the record */
13384   incr(mp->input_ptr);
13385 }
13386
13387 @ And of course what goes up must come down.
13388
13389 @d pop_input { /* leave an input level, re-enter the old */
13390     decr(mp->input_ptr); mp->cur_input=mp->input_stack[mp->input_ptr];
13391   }
13392
13393 @ Here is a procedure that starts a new level of token-list input, given
13394 a token list |p| and its type |t|. If |t=macro|, the calling routine should
13395 set |name|, reset~|loc|, and increase the macro's reference count.
13396
13397 @d back_list(A) mp_begin_token_list(mp, (A),backed_up) /* backs up a simple token list */
13398
13399 @c 
13400 static void mp_begin_token_list (MP mp,pointer p, quarterword t)  { 
13401   push_input; start=p; token_type=t;
13402   param_start=mp->param_ptr; loc=p;
13403 }
13404
13405 @ When a token list has been fully scanned, the following computations
13406 should be done as we leave that level of input.
13407 @^inner loop@>
13408
13409 @c 
13410 static void mp_end_token_list (MP mp) { /* leave a token-list input level */
13411   pointer p; /* temporary register */
13412   if ( token_type>=backed_up ) { /* token list to be deleted */
13413     if ( token_type<=inserted ) { 
13414       mp_flush_token_list(mp, start); goto DONE;
13415     } else {
13416       mp_delete_mac_ref(mp, start); /* update reference count */
13417     }
13418   }
13419   while ( mp->param_ptr>param_start ) { /* parameters must be flushed */
13420     decr(mp->param_ptr);
13421     p=mp->param_stack[mp->param_ptr];
13422     if ( p!=null ) {
13423       if ( mp_link(p)==mp_void ) { /* it's an \&{expr} parameter */
13424         mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
13425       } else {
13426         mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
13427       }
13428     }
13429   }
13430 DONE: 
13431   pop_input; check_interrupt;
13432 }
13433
13434 @ The contents of |cur_cmd,cur_mod,cur_sym| are placed into an equivalent
13435 token by the |cur_tok| routine.
13436 @^inner loop@>
13437
13438 @c @<Declare the procedure called |make_exp_copy|@>
13439 static pointer mp_cur_tok (MP mp) {
13440   pointer p; /* a new token node */
13441   quarterword save_type; /* |cur_type| to be restored */
13442   integer save_exp; /* |cur_exp| to be restored */
13443   if ( mp->cur_sym==0 ) {
13444     if ( mp->cur_cmd==capsule_token ) {
13445       save_type=mp->cur_type; save_exp=mp->cur_exp;
13446       mp_make_exp_copy(mp, mp->cur_mod); p=mp_stash_cur_exp(mp); mp_link(p)=null;
13447       mp->cur_type=save_type; mp->cur_exp=save_exp;
13448     } else { 
13449       p=mp_get_node(mp, token_node_size);
13450       value(p)=mp->cur_mod; mp_name_type(p)=mp_token;
13451       if ( mp->cur_cmd==numeric_token ) mp_type(p)=mp_known;
13452       else mp_type(p)=mp_string_type;
13453     }
13454   } else { 
13455     fast_get_avail(p); mp_info(p)=mp->cur_sym;
13456   }
13457   return p;
13458 }
13459
13460 @ Sometimes \MP\ has read too far and wants to ``unscan'' what it has
13461 seen. The |back_input| procedure takes care of this by putting the token
13462 just scanned back into the input stream, ready to be read again.
13463 If |cur_sym<>0|, the values of |cur_cmd| and |cur_mod| are irrelevant.
13464
13465 @<Declarations@>= 
13466 static void mp_back_input (MP mp);
13467
13468 @ @c void mp_back_input (MP mp) {/* undoes one token of input */
13469   pointer p; /* a token list of length one */
13470   p=mp_cur_tok(mp);
13471   while ( token_state &&(loc==null) ) 
13472     mp_end_token_list(mp); /* conserve stack space */
13473   back_list(p);
13474 }
13475
13476 @ The |back_error| routine is used when we want to restore or replace an
13477 offending token just before issuing an error message.  We disable interrupts
13478 during the call of |back_input| so that the help message won't be lost.
13479
13480 @ @c static void mp_back_error (MP mp) { /* back up one token and call |error| */
13481   mp->OK_to_interrupt=false; 
13482   mp_back_input(mp); 
13483   mp->OK_to_interrupt=true; mp_error(mp);
13484 }
13485 static void mp_ins_error (MP mp) { /* back up one inserted token and call |error| */
13486   mp->OK_to_interrupt=false; 
13487   mp_back_input(mp); token_type=inserted;
13488   mp->OK_to_interrupt=true; mp_error(mp);
13489 }
13490
13491 @ The |begin_file_reading| procedure starts a new level of input for lines
13492 of characters to be read from a file, or as an insertion from the
13493 terminal. It does not take care of opening the file, nor does it set |loc|
13494 or |limit| or |line|.
13495 @^system dependencies@>
13496
13497 @c void mp_begin_file_reading (MP mp) { 
13498   if ( mp->in_open==mp->max_in_open ) 
13499     mp_overflow(mp, "text input levels",mp->max_in_open);
13500 @:MetaPost capacity exceeded text input levels}{\quad text input levels@>
13501   if ( mp->first==mp->buf_size ) 
13502     mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
13503   incr(mp->in_open); push_input; iindex=mp->in_open;
13504   mp->mpx_name[iindex]=absent;
13505   start=(halfword)mp->first;
13506   name=is_term; /* |terminal_input| is now |true| */
13507 }
13508
13509 @ Conversely, the variables must be downdated when such a level of input
13510 is finished.  Any associated \.{MPX} file must also be closed and popped
13511 off the file stack.
13512
13513 @c static void mp_end_file_reading (MP mp) { 
13514   if ( mp->in_open>iindex ) {
13515     if ( (mp->mpx_name[mp->in_open]==absent)||(name<=max_spec_src) ) {
13516       mp_confusion(mp, "endinput");
13517 @:this can't happen endinput}{\quad endinput@>
13518     } else { 
13519       (mp->close_file)(mp,mp->input_file[mp->in_open]); /* close an \.{MPX} file */
13520       delete_str_ref(mp->mpx_name[mp->in_open]);
13521       decr(mp->in_open);
13522     }
13523   }
13524   mp->first=(size_t)start;
13525   if ( iindex!=mp->in_open ) mp_confusion(mp, "endinput");
13526   if ( name>max_spec_src ) {
13527     (mp->close_file)(mp,cur_file);
13528     delete_str_ref(name);
13529     xfree(in_name); 
13530     xfree(in_area);
13531   }
13532   pop_input; decr(mp->in_open);
13533 }
13534
13535 @ Here is a function that tries to resume input from an \.{MPX} file already
13536 associated with the current input file.  It returns |false| if this doesn't
13537 work.
13538
13539 @c static boolean mp_begin_mpx_reading (MP mp) { 
13540   if ( mp->in_open!=iindex+1 ) {
13541      return false;
13542   } else { 
13543     if ( mp->mpx_name[mp->in_open]<=absent ) mp_confusion(mp, "mpx");
13544 @:this can't happen mpx}{\quad mpx@>
13545     if ( mp->first==mp->buf_size ) 
13546       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
13547     push_input; iindex=mp->in_open;
13548     start=(halfword)mp->first;
13549     name=mp->mpx_name[mp->in_open]; add_str_ref(name);
13550     @<Put an empty line in the input buffer@>;
13551     return true;
13552   }
13553 }
13554
13555 @ This procedure temporarily stops reading an \.{MPX} file.
13556
13557 @c static void mp_end_mpx_reading (MP mp) { 
13558   if ( mp->in_open!=iindex ) mp_confusion(mp, "mpx");
13559 @:this can't happen mpx}{\quad mpx@>
13560   if ( loc<limit ) {
13561     @<Complain that we are not at the end of a line in the \.{MPX} file@>;
13562   }
13563   mp->first=(size_t)start;
13564   pop_input;
13565 }
13566
13567 @ Here we enforce a restriction that simplifies the input stacks considerably.
13568 This should not inconvenience the user because \.{MPX} files are generated
13569 by an auxiliary program called \.{DVItoMP}.
13570
13571 @ @<Complain that we are not at the end of a line in the \.{MPX} file@>=
13572
13573 print_err("`mpxbreak' must be at the end of a line");
13574 help4("This file contains picture expressions for btex...etex",
13575   "blocks.  Such files are normally generated automatically",
13576   "but this one seems to be messed up.  I'm going to ignore",
13577   "the rest of this line.");
13578 mp_error(mp);
13579 }
13580
13581 @ In order to keep the stack from overflowing during a long sequence of
13582 inserted `\.{show}' commands, the following routine removes completed
13583 error-inserted lines from memory.
13584
13585 @c void mp_clear_for_error_prompt (MP mp) { 
13586   while ( file_state && terminal_input &&
13587     (mp->input_ptr>0)&&(loc==limit) ) mp_end_file_reading(mp);
13588   mp_print_ln(mp); clear_terminal;
13589 }
13590
13591 @ To get \MP's whole input mechanism going, we perform the following
13592 actions.
13593
13594 @<Initialize the input routines@>=
13595 { mp->input_ptr=0; mp->max_in_stack=0;
13596   mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
13597   mp->param_ptr=0; mp->max_param_stack=0;
13598   mp->first=1;
13599   start=1; iindex=0; line=0; name=is_term;
13600   mp->mpx_name[0]=absent;
13601   mp->force_eof=false;
13602   if ( ! mp_init_terminal(mp) ) mp_jump_out(mp);
13603   limit=(halfword)mp->last; mp->first=mp->last+1; 
13604   /* |init_terminal| has set |loc| and |last| */
13605 }
13606
13607 @* \[29] Getting the next token.
13608 The heart of \MP's input mechanism is the |get_next| procedure, which
13609 we shall develop in the next few sections of the program. Perhaps we
13610 shouldn't actually call it the ``heart,'' however; it really acts as \MP's
13611 eyes and mouth, reading the source files and gobbling them up. And it also
13612 helps \MP\ to regurgitate stored token lists that are to be processed again.
13613
13614 The main duty of |get_next| is to input one token and to set |cur_cmd|
13615 and |cur_mod| to that token's command code and modifier. Furthermore, if
13616 the input token is a symbolic token, that token's |hash| address
13617 is stored in |cur_sym|; otherwise |cur_sym| is set to zero.
13618
13619 Underlying this simple description is a certain amount of complexity
13620 because of all the cases that need to be handled.
13621 However, the inner loop of |get_next| is reasonably short and fast.
13622
13623 @ Before getting into |get_next|, we need to consider a mechanism by which
13624 \MP\ helps keep errors from propagating too far. Whenever the program goes
13625 into a mode where it keeps calling |get_next| repeatedly until a certain
13626 condition is met, it sets |scanner_status| to some value other than |normal|.
13627 Then if an input file ends, or if an `\&{outer}' symbol appears,
13628 an appropriate error recovery will be possible.
13629
13630 The global variable |warning_info| helps in this error recovery by providing
13631 additional information. For example, |warning_info| might indicate the
13632 name of a macro whose replacement text is being scanned.
13633
13634 @d normal 0 /* |scanner_status| at ``quiet times'' */
13635 @d skipping 1 /* |scanner_status| when false conditional text is being skipped */
13636 @d flushing 2 /* |scanner_status| when junk after a statement is being ignored */
13637 @d absorbing 3 /* |scanner_status| when a \&{text} parameter is being scanned */
13638 @d var_defining 4 /* |scanner_status| when a \&{vardef} is being scanned */
13639 @d op_defining 5 /* |scanner_status| when a macro \&{def} is being scanned */
13640 @d loop_defining 6 /* |scanner_status| when a \&{for} loop is being scanned */
13641 @d tex_flushing 7 /* |scanner_status| when skipping \TeX\ material */
13642
13643 @<Glob...@>=
13644 integer scanner_status; /* are we scanning at high speed? */
13645 integer warning_info; /* if so, what else do we need to know,
13646     in case an error occurs? */
13647
13648 @ @<Initialize the input routines@>=
13649 mp->scanner_status=normal;
13650
13651 @ The following subroutine
13652 is called when an `\&{outer}' symbolic token has been scanned or
13653 when the end of a file has been reached. These two cases are distinguished
13654 by |cur_sym|, which is zero at the end of a file.
13655
13656 @c
13657 static boolean mp_check_outer_validity (MP mp) {
13658   pointer p; /* points to inserted token list */
13659   if ( mp->scanner_status==normal ) {
13660     return true;
13661   } else if ( mp->scanner_status==tex_flushing ) {
13662     @<Check if the file has ended while flushing \TeX\ material and set the
13663       result value for |check_outer_validity|@>;
13664   } else { 
13665     mp->deletions_allowed=false;
13666     @<Back up an outer symbolic token so that it can be reread@>;
13667     if ( mp->scanner_status>skipping ) {
13668       @<Tell the user what has run away and try to recover@>;
13669     } else { 
13670       print_err("Incomplete if; all text was ignored after line ");
13671 @.Incomplete if...@>
13672       mp_print_int(mp, mp->warning_info);
13673       help3("A forbidden `outer' token occurred in skipped text.",
13674         "This kind of error happens when you say `if...' and forget",
13675         "the matching `fi'. I've inserted a `fi'; this might work.");
13676       if ( mp->cur_sym==0 ) 
13677         mp->help_line[2]="The file ended while I was skipping conditional text.";
13678       mp->cur_sym=frozen_fi; mp_ins_error(mp);
13679     }
13680     mp->deletions_allowed=true; 
13681         return false;
13682   }
13683 }
13684
13685 @ @<Check if the file has ended while flushing \TeX\ material and set...@>=
13686 if ( mp->cur_sym!=0 ) { 
13687    return true;
13688 } else { 
13689   mp->deletions_allowed=false;
13690   print_err("TeX mode didn't end; all text was ignored after line ");
13691   mp_print_int(mp, mp->warning_info);
13692   help2("The file ended while I was looking for the `etex' to",
13693         "finish this TeX material.  I've inserted `etex' now.");
13694   mp->cur_sym = frozen_etex;
13695   mp_ins_error(mp);
13696   mp->deletions_allowed=true;
13697   return false;
13698 }
13699
13700 @ @<Back up an outer symbolic token so that it can be reread@>=
13701 if ( mp->cur_sym!=0 ) {
13702   p=mp_get_avail(mp); mp_info(p)=mp->cur_sym;
13703   back_list(p); /* prepare to read the symbolic token again */
13704 }
13705
13706 @ @<Tell the user what has run away...@>=
13707
13708   mp_runaway(mp); /* print the definition-so-far */
13709   if ( mp->cur_sym==0 ) {
13710     print_err("File ended");
13711 @.File ended while scanning...@>
13712   } else { 
13713     print_err("Forbidden token found");
13714 @.Forbidden token found...@>
13715   }
13716   mp_print(mp, " while scanning ");
13717   help4("I suspect you have forgotten an `enddef',",
13718     "causing me to read past where you wanted me to stop.",
13719     "I'll try to recover; but if the error is serious,",
13720     "you'd better type `E' or `X' now and fix your file.");
13721   switch (mp->scanner_status) {
13722     @<Complete the error message,
13723       and set |cur_sym| to a token that might help recover from the error@>
13724   } /* there are no other cases */
13725   mp_ins_error(mp);
13726 }
13727
13728 @ As we consider various kinds of errors, it is also appropriate to
13729 change the first line of the help message just given; |help_line[3]|
13730 points to the string that might be changed.
13731
13732 @<Complete the error message,...@>=
13733 case flushing: 
13734   mp_print(mp, "to the end of the statement");
13735   mp->help_line[3]="A previous error seems to have propagated,";
13736   mp->cur_sym=frozen_semicolon;
13737   break;
13738 case absorbing: 
13739   mp_print(mp, "a text argument");
13740   mp->help_line[3]="It seems that a right delimiter was left out,";
13741   if ( mp->warning_info==0 ) {
13742     mp->cur_sym=frozen_end_group;
13743   } else { 
13744     mp->cur_sym=frozen_right_delimiter;
13745     equiv(frozen_right_delimiter)=mp->warning_info;
13746   }
13747   break;
13748 case var_defining:
13749 case op_defining: 
13750   mp_print(mp, "the definition of ");
13751   if ( mp->scanner_status==op_defining ) 
13752      mp_print_text(mp->warning_info);
13753   else 
13754      mp_print_variable_name(mp, mp->warning_info);
13755   mp->cur_sym=frozen_end_def;
13756   break;
13757 case loop_defining: 
13758   mp_print(mp, "the text of a "); 
13759   mp_print_text(mp->warning_info);
13760   mp_print(mp, " loop");
13761   mp->help_line[3]="I suspect you have forgotten an `endfor',";
13762   mp->cur_sym=frozen_end_for;
13763   break;
13764
13765 @ The |runaway| procedure displays the first part of the text that occurred
13766 when \MP\ began its special |scanner_status|, if that text has been saved.
13767
13768 @<Declarations@>=
13769 static void mp_runaway (MP mp) ;
13770
13771 @ @c
13772 void mp_runaway (MP mp) { 
13773   if ( mp->scanner_status>flushing ) { 
13774      mp_print_nl(mp, "Runaway ");
13775          switch (mp->scanner_status) { 
13776          case absorbing: mp_print(mp, "text?"); break;
13777          case var_defining: 
13778      case op_defining: mp_print(mp,"definition?"); break;
13779      case loop_defining: mp_print(mp, "loop?"); break;
13780      } /* there are no other cases */
13781      mp_print_ln(mp); 
13782      mp_show_token_list(mp, mp_link(hold_head),null,mp->error_line-10,0);
13783   }
13784 }
13785
13786 @ We need to mention a procedure that may be called by |get_next|.
13787
13788 @<Declarations@>= 
13789 static void mp_firm_up_the_line (MP mp);
13790
13791 @ And now we're ready to take the plunge into |get_next| itself.
13792 Note that the behavior depends on the |scanner_status| because percent signs
13793 and double quotes need to be passed over when skipping TeX material.
13794
13795 @c 
13796 void mp_get_next (MP mp) {
13797   /* sets |cur_cmd|, |cur_mod|, |cur_sym| to next token */
13798 @^inner loop@>
13799   /*restart*/ /* go here to get the next input token */
13800   /*exit*/ /* go here when the next input token has been got */
13801   /*|common_ending|*/ /* go here to finish getting a symbolic token */
13802   /*found*/ /* go here when the end of a symbolic token has been found */
13803   /*switch*/ /* go here to branch on the class of an input character */
13804   /*|start_numeric_token|,|start_decimal_token|,|fin_numeric_token|,|done|*/
13805     /* go here at crucial stages when scanning a number */
13806   int k; /* an index into |buffer| */
13807   ASCII_code c; /* the current character in the buffer */
13808   int class; /* its class number */
13809   integer n,f; /* registers for decimal-to-binary conversion */
13810 RESTART: 
13811   mp->cur_sym=0;
13812   if ( file_state ) {
13813     @<Input from external file; |goto restart| if no input found,
13814     or |return| if a non-symbolic token is found@>;
13815   } else {
13816     @<Input from token list; |goto restart| if end of list or
13817       if a parameter needs to be expanded,
13818       or |return| if a non-symbolic token is found@>;
13819   }
13820 COMMON_ENDING: 
13821   @<Finish getting the symbolic token in |cur_sym|;
13822    |goto restart| if it is illegal@>;
13823 }
13824
13825 @ When a symbolic token is declared to be `\&{outer}', its command code
13826 is increased by |outer_tag|.
13827 @^inner loop@>
13828
13829 @<Finish getting the symbolic token in |cur_sym|...@>=
13830 mp->cur_cmd=eq_type(mp->cur_sym); mp->cur_mod=equiv(mp->cur_sym);
13831 if ( mp->cur_cmd>=outer_tag ) {
13832   if ( mp_check_outer_validity(mp) ) 
13833     mp->cur_cmd=mp->cur_cmd-outer_tag;
13834   else 
13835     goto RESTART;
13836 }
13837
13838 @ A percent sign appears in |buffer[limit]|; this makes it unnecessary
13839 to have a special test for end-of-line.
13840 @^inner loop@>
13841
13842 @<Input from external file;...@>=
13843
13844 SWITCH: 
13845   c=mp->buffer[loc]; incr(loc); class=mp->char_class[c];
13846   switch (class) {
13847   case digit_class: goto START_NUMERIC_TOKEN; break;
13848   case period_class: 
13849     class=mp->char_class[mp->buffer[loc]];
13850     if ( class>period_class ) {
13851       goto SWITCH;
13852     } else if ( class<period_class ) { /* |class=digit_class| */
13853       n=0; goto START_DECIMAL_TOKEN;
13854     }
13855 @:. }{\..\ token@>
13856     break;
13857   case space_class: goto SWITCH; break;
13858   case percent_class: 
13859     if ( mp->scanner_status==tex_flushing ) {
13860       if ( loc<limit ) goto SWITCH;
13861     }
13862     @<Move to next line of file, or |goto restart| if there is no next line@>;
13863     check_interrupt;
13864     goto SWITCH;
13865     break;
13866   case string_class: 
13867     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13868     else @<Get a string token and |return|@>;
13869     break;
13870   case isolated_classes: 
13871     k=loc-1; goto FOUND; break;
13872   case invalid_class: 
13873     if ( mp->scanner_status==tex_flushing ) goto SWITCH;
13874     else @<Decry the invalid character and |goto restart|@>;
13875     break;
13876   default: break; /* letters, etc. */
13877   }
13878   k=loc-1;
13879   while ( mp->char_class[mp->buffer[loc]]==class ) incr(loc);
13880   goto FOUND;
13881 START_NUMERIC_TOKEN:
13882   @<Get the integer part |n| of a numeric token;
13883     set |f:=0| and |goto fin_numeric_token| if there is no decimal point@>;
13884 START_DECIMAL_TOKEN:
13885   @<Get the fraction part |f| of a numeric token@>;
13886 FIN_NUMERIC_TOKEN:
13887   @<Pack the numeric and fraction parts of a numeric token
13888     and |return|@>;
13889 FOUND: 
13890   mp->cur_sym=mp_id_lookup(mp, k,loc-k);
13891 }
13892
13893 @ We go to |restart| instead of to |SWITCH|, because we might enter
13894 |token_state| after the error has been dealt with
13895 (cf.\ |clear_for_error_prompt|).
13896
13897 @<Decry the invalid...@>=
13898
13899   print_err("Text line contains an invalid character");
13900 @.Text line contains...@>
13901   help2("A funny symbol that I can\'t read has just been input.",
13902         "Continue, and I'll forget that it ever happened.");
13903   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13904   goto RESTART;
13905 }
13906
13907 @ @<Get a string token and |return|@>=
13908
13909   if ( mp->buffer[loc]=='"' ) {
13910     mp->cur_mod=null_str;
13911   } else { 
13912     k=loc; mp->buffer[limit+1]=xord('"');
13913     do {  
13914      incr(loc);
13915     } while (mp->buffer[loc]!='"');
13916     if ( loc>limit ) {
13917       @<Decry the missing string delimiter and |goto restart|@>;
13918     }
13919     if ( loc==k+1 ) {
13920       mp->cur_mod=mp->buffer[k];
13921     } else { 
13922       str_room(loc-k);
13923       do {  
13924         append_char(mp->buffer[k]); incr(k);
13925       } while (k!=loc);
13926       mp->cur_mod=mp_make_string(mp);
13927     }
13928   }
13929   incr(loc); mp->cur_cmd=string_token; 
13930   return;
13931 }
13932
13933 @ We go to |restart| after this error message, not to |SWITCH|,
13934 because the |clear_for_error_prompt| routine might have reinstated
13935 |token_state| after |error| has finished.
13936
13937 @<Decry the missing string delimiter and |goto restart|@>=
13938
13939   loc=limit; /* the next character to be read on this line will be |"%"| */
13940   print_err("Incomplete string token has been flushed");
13941 @.Incomplete string token...@>
13942   help3("Strings should finish on the same line as they began.",
13943     "I've deleted the partial string; you might want to",
13944     "insert another by typing, e.g., `I\"new string\"'.");
13945   mp->deletions_allowed=false; mp_error(mp);
13946   mp->deletions_allowed=true; 
13947   goto RESTART;
13948 }
13949
13950 @ @<Get the integer part |n| of a numeric token...@>=
13951 n=c-'0';
13952 while ( mp->char_class[mp->buffer[loc]]==digit_class ) {
13953   if ( n<32768 ) n=10*n+mp->buffer[loc]-'0';
13954   incr(loc);
13955 }
13956 if ( mp->buffer[loc]=='.' ) 
13957   if ( mp->char_class[mp->buffer[loc+1]]==digit_class ) 
13958     goto DONE;
13959 f=0; 
13960 goto FIN_NUMERIC_TOKEN;
13961 DONE: incr(loc)
13962
13963 @ @<Get the fraction part |f| of a numeric token@>=
13964 k=0;
13965 do { 
13966   if ( k<17 ) { /* digits for |k>=17| cannot affect the result */
13967     mp->dig[k]=mp->buffer[loc]-'0'; incr(k);
13968   }
13969   incr(loc);
13970 } while (mp->char_class[mp->buffer[loc]]==digit_class);
13971 f=mp_round_decimals(mp, k);
13972 if ( f==unity ) {
13973   incr(n); f=0;
13974 }
13975
13976 @ @<Pack the numeric and fraction parts of a numeric token and |return|@>=
13977 if ( n<32768 ) {
13978   @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>;
13979 } else if ( mp->scanner_status!=tex_flushing ) {
13980   print_err("Enormous number has been reduced");
13981 @.Enormous number...@>
13982   help2("I can\'t handle numbers bigger than 32767.99998;",
13983         "so I've changed your constant to that maximum amount.");
13984   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
13985   mp->cur_mod=el_gordo;
13986 }
13987 mp->cur_cmd=numeric_token; return
13988
13989 @ @<Set |cur_mod:=n*unity+f| and check if it is uncomfortably large@>=
13990
13991   mp->cur_mod=n*unity+f;
13992   if ( mp->cur_mod>=fraction_one ) {
13993     if ( (mp->internal[mp_warning_check]>0) &&
13994          (mp->scanner_status!=tex_flushing) ) {
13995       print_err("Number is too large (");
13996       mp_print_scaled(mp, mp->cur_mod);
13997       mp_print_char(mp, xord(')'));
13998       help3("It is at least 4096. Continue and I'll try to cope",
13999       "with that big value; but it might be dangerous.",
14000       "(Set warningcheck:=0 to suppress this message.)");
14001       mp_error(mp);
14002     }
14003   }
14004 }
14005
14006 @ Let's consider now what happens when |get_next| is looking at a token list.
14007 @^inner loop@>
14008
14009 @<Input from token list;...@>=
14010 if ( loc>=mp->hi_mem_min ) { /* one-word token */
14011   mp->cur_sym=mp_info(loc); loc=mp_link(loc); /* move to next */
14012   if ( mp->cur_sym>=expr_base ) {
14013     if ( mp->cur_sym>=suffix_base ) {
14014       @<Insert a suffix or text parameter and |goto restart|@>;
14015     } else { 
14016       mp->cur_cmd=capsule_token;
14017       mp->cur_mod=mp->param_stack[param_start+mp->cur_sym-(expr_base)];
14018       mp->cur_sym=0; return;
14019     }
14020   }
14021 } else if ( loc>null ) {
14022   @<Get a stored numeric or string or capsule token and |return|@>
14023 } else { /* we are done with this token list */
14024   mp_end_token_list(mp); goto RESTART; /* resume previous level */
14025 }
14026
14027 @ @<Insert a suffix or text parameter...@>=
14028
14029   if ( mp->cur_sym>=text_base ) mp->cur_sym=mp->cur_sym-mp->param_size;
14030   /* |param_size=text_base-suffix_base| */
14031   mp_begin_token_list(mp,
14032                       mp->param_stack[param_start+mp->cur_sym-(suffix_base)],
14033                       parameter);
14034   goto RESTART;
14035 }
14036
14037 @ @<Get a stored numeric or string or capsule token...@>=
14038
14039   if ( mp_name_type(loc)==mp_token ) {
14040     mp->cur_mod=value(loc);
14041     if ( mp_type(loc)==mp_known ) {
14042       mp->cur_cmd=numeric_token;
14043     } else { 
14044       mp->cur_cmd=string_token; add_str_ref(mp->cur_mod);
14045     }
14046   } else { 
14047     mp->cur_mod=loc; mp->cur_cmd=capsule_token;
14048   };
14049   loc=mp_link(loc); return;
14050 }
14051
14052 @ All of the easy branches of |get_next| have now been taken care of.
14053 There is one more branch.
14054
14055 @<Move to next line of file, or |goto restart|...@>=
14056 if ( name>max_spec_src) {
14057   @<Read next line of file into |buffer|, or
14058     |goto restart| if the file has ended@>;
14059 } else { 
14060   if ( mp->input_ptr>0 ) {
14061      /* text was inserted during error recovery or by \&{scantokens} */
14062     mp_end_file_reading(mp); goto RESTART; /* resume previous level */
14063   }
14064   if (mp->job_name == NULL && ( mp->selector<log_only || mp->selector>=write_file))  
14065     mp_open_log_file(mp);
14066   if ( mp->interaction>mp_nonstop_mode ) {
14067     if ( limit==start ) /* previous line was empty */
14068       mp_print_nl(mp, "(Please type a command or say `end')");
14069 @.Please type...@>
14070     mp_print_ln(mp); mp->first=(size_t)start;
14071     prompt_input("*"); /* input on-line into |buffer| */
14072 @.*\relax@>
14073     limit=(halfword)mp->last; mp->buffer[limit]=xord('%');
14074     mp->first=(size_t)(limit+1); loc=start;
14075   } else {
14076     mp_fatal_error(mp, "*** (job aborted, no legal end found)");
14077 @.job aborted@>
14078     /* nonstop mode, which is intended for overnight batch processing,
14079        never waits for on-line input */
14080   }
14081 }
14082
14083 @ The global variable |force_eof| is normally |false|; it is set |true|
14084 by an \&{endinput} command.
14085
14086 @<Glob...@>=
14087 boolean force_eof; /* should the next \&{input} be aborted early? */
14088
14089 @ We must decrement |loc| in order to leave the buffer in a valid state
14090 when an error condition causes us to |goto restart| without calling
14091 |end_file_reading|.
14092
14093 @<Read next line of file into |buffer|, or
14094   |goto restart| if the file has ended@>=
14095
14096   incr(line); mp->first=(size_t)start;
14097   if ( ! mp->force_eof ) {
14098     if ( mp_input_ln(mp, cur_file ) ) /* not end of file */
14099       mp_firm_up_the_line(mp); /* this sets |limit| */
14100     else 
14101       mp->force_eof=true;
14102   };
14103   if ( mp->force_eof ) {
14104     mp->force_eof=false;
14105     decr(loc);
14106     if ( mpx_reading ) {
14107       @<Complain that the \.{MPX} file ended unexpectly; then set
14108         |cur_sym:=frozen_mpx_break| and |goto comon_ending|@>;
14109     } else { 
14110       mp_print_char(mp, xord(')')); decr(mp->open_parens);
14111       update_terminal; /* show user that file has been read */
14112       mp_end_file_reading(mp); /* resume previous level */
14113       if ( mp_check_outer_validity(mp) ) goto  RESTART;  
14114       else goto RESTART;
14115     }
14116   }
14117   mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start; /* ready to read */
14118 }
14119
14120 @ We should never actually come to the end of an \.{MPX} file because such
14121 files should have an \&{mpxbreak} after the translation of the last
14122 \&{btex}$\,\ldots\,$\&{etex} block.
14123
14124 @<Complain that the \.{MPX} file ended unexpectly; then set...@>=
14125
14126   mp->mpx_name[iindex]=mpx_finished;
14127   print_err("mpx file ended unexpectedly");
14128   help4("The file had too few picture expressions for btex...etex",
14129     "blocks.  Such files are normally generated automatically",
14130     "but this one got messed up.  You might want to insert a",
14131     "picture expression now.");
14132   mp->deletions_allowed=false; mp_error(mp); mp->deletions_allowed=true;
14133   mp->cur_sym=frozen_mpx_break; goto COMMON_ENDING;
14134 }
14135
14136 @ Sometimes we want to make it look as though we have just read a blank line
14137 without really doing so.
14138
14139 @<Put an empty line in the input buffer@>=
14140 mp->last=mp->first; limit=(halfword)mp->last; 
14141   /* simulate |input_ln| and |firm_up_the_line| */
14142 mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start
14143
14144 @ If the user has set the |mp_pausing| parameter to some positive value,
14145 and if nonstop mode has not been selected, each line of input is displayed
14146 on the terminal and the transcript file, followed by `\.{=>}'.
14147 \MP\ waits for a response. If the response is null (i.e., if nothing is
14148 typed except perhaps a few blank spaces), the original
14149 line is accepted as it stands; otherwise the line typed is
14150 used instead of the line in the file.
14151
14152 @c void mp_firm_up_the_line (MP mp) {
14153   size_t k; /* an index into |buffer| */
14154   limit=(halfword)mp->last;
14155   if ((!mp->noninteractive)   
14156       && (mp->internal[mp_pausing]>0 )
14157       && (mp->interaction>mp_nonstop_mode )) {
14158     wake_up_terminal; mp_print_ln(mp);
14159     if ( start<limit ) {
14160       for (k=(size_t)start;k<=(size_t)(limit-1);k++) {
14161         mp_print_str(mp, mp->buffer[k]);
14162       } 
14163     }
14164     mp->first=(size_t)limit; prompt_input("=>"); /* wait for user response */
14165 @.=>@>
14166     if ( mp->last>mp->first ) {
14167       for (k=mp->first;k<=mp->last-1;k++) { /* move line down in buffer */
14168         mp->buffer[k+start-mp->first]=mp->buffer[k];
14169       }
14170       limit=(halfword)(start+mp->last-mp->first);
14171     }
14172   }
14173 }
14174
14175 @* \[30] Dealing with \TeX\ material.
14176 The \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}$\,\ldots\,$\&{etex}
14177 features need to be implemented at a low level in the scanning process
14178 so that \MP\ can stay in synch with the a preprocessor that treats
14179 blocks of \TeX\ material as they occur in the input file without trying
14180 to expand \MP\ macros.  Thus we need a special version of |get_next|
14181 that does not expand macros and such but does handle \&{btex},
14182 \&{verbatimtex}, etc.
14183
14184 The special version of |get_next| is called |get_t_next|.  It works by flushing
14185 \&{btex}$\,\ldots\,$\&{etex} and \&{verbatimtex}\allowbreak
14186 $\,\ldots\,$\&{etex} blocks, switching to the \.{MPX} file when it sees
14187 \&{btex}, and switching back when it sees \&{mpxbreak}.
14188
14189 @d btex_code 0
14190 @d verbatim_code 1
14191
14192 @ @<Put each...@>=
14193 mp_primitive(mp, "btex",start_tex,btex_code);
14194 @:btex_}{\&{btex} primitive@>
14195 mp_primitive(mp, "verbatimtex",start_tex,verbatim_code);
14196 @:verbatimtex_}{\&{verbatimtex} primitive@>
14197 mp_primitive(mp, "etex",etex_marker,0); mp->eqtb[frozen_etex]=mp->eqtb[mp->cur_sym];
14198 @:etex_}{\&{etex} primitive@>
14199 mp_primitive(mp, "mpxbreak",mpx_break,0); mp->eqtb[frozen_mpx_break]=mp->eqtb[mp->cur_sym];
14200 @:mpx_break_}{\&{mpxbreak} primitive@>
14201
14202 @ @<Cases of |print_cmd...@>=
14203 case start_tex: if ( m==btex_code ) mp_print(mp, "btex");
14204   else mp_print(mp, "verbatimtex"); break;
14205 case etex_marker: mp_print(mp, "etex"); break;
14206 case mpx_break: mp_print(mp, "mpxbreak"); break;
14207
14208 @ Actually, |get_t_next| is a macro that avoids procedure overhead except
14209 in the unusual case where \&{btex}, \&{verbatimtex}, \&{etex}, or \&{mpxbreak}
14210 is encountered.
14211
14212 @d get_t_next {mp_get_next(mp); if ( mp->cur_cmd<=max_pre_command ) mp_t_next(mp); }
14213
14214 @<Declarations@>=
14215 static void mp_start_mpx_input (MP mp);
14216
14217 @ @c 
14218 static void mp_t_next (MP mp) {
14219   int old_status; /* saves the |scanner_status| */
14220   integer old_info; /* saves the |warning_info| */
14221   while ( mp->cur_cmd<=max_pre_command ) {
14222     if ( mp->cur_cmd==mpx_break ) {
14223       if ( ! file_state || (mp->mpx_name[iindex]==absent) ) {
14224         @<Complain about a misplaced \&{mpxbreak}@>;
14225       } else { 
14226         mp_end_mpx_reading(mp); 
14227         goto TEX_FLUSH;
14228       }
14229     } else if ( mp->cur_cmd==start_tex ) {
14230       if ( token_state || (name<=max_spec_src) ) {
14231         @<Complain that we are not reading a file@>;
14232       } else if ( mpx_reading ) {
14233         @<Complain that \.{MPX} files cannot contain \TeX\ material@>;
14234       } else if ( (mp->cur_mod!=verbatim_code)&&
14235                   (mp->mpx_name[iindex]!=mpx_finished) ) {
14236         if ( ! mp_begin_mpx_reading(mp) ) mp_start_mpx_input(mp);
14237       } else {
14238         goto TEX_FLUSH;
14239       }
14240     } else {
14241        @<Complain about a misplaced \&{etex}@>;
14242     }
14243     goto COMMON_ENDING;
14244   TEX_FLUSH: 
14245     @<Flush the \TeX\ material@>;
14246   COMMON_ENDING: 
14247     mp_get_next(mp);
14248   }
14249 }
14250
14251 @ We could be in the middle of an operation such as skipping false conditional
14252 text when \TeX\ material is encountered, so we must be careful to save the
14253 |scanner_status|.
14254
14255 @<Flush the \TeX\ material@>=
14256 old_status=mp->scanner_status;
14257 old_info=mp->warning_info;
14258 mp->scanner_status=tex_flushing;
14259 mp->warning_info=line;
14260 do {  mp_get_next(mp); } while (mp->cur_cmd!=etex_marker);
14261 mp->scanner_status=old_status;
14262 mp->warning_info=old_info
14263
14264 @ @<Complain that \.{MPX} files cannot contain \TeX\ material@>=
14265 { print_err("An mpx file cannot contain btex or verbatimtex blocks");
14266 help4("This file contains picture expressions for btex...etex",
14267   "blocks.  Such files are normally generated automatically",
14268   "but this one seems to be messed up.  I'll just keep going",
14269   "and hope for the best.");
14270 mp_error(mp);
14271 }
14272
14273 @ @<Complain that we are not reading a file@>=
14274 { print_err("You can only use `btex' or `verbatimtex' in a file");
14275 help3("I'll have to ignore this preprocessor command because it",
14276   "only works when there is a file to preprocess.  You might",
14277   "want to delete everything up to the next `etex`.");
14278 mp_error(mp);
14279 }
14280
14281 @ @<Complain about a misplaced \&{mpxbreak}@>=
14282 { print_err("Misplaced mpxbreak");
14283 help2("I'll ignore this preprocessor command because it",
14284       "doesn't belong here");
14285 mp_error(mp);
14286 }
14287
14288 @ @<Complain about a misplaced \&{etex}@>=
14289 { print_err("Extra etex will be ignored");
14290 help1("There is no btex or verbatimtex for this to match");
14291 mp_error(mp);
14292 }
14293
14294 @* \[31] Scanning macro definitions.
14295 \MP\ has a variety of ways to tuck tokens away into token lists for later
14296 use: Macros can be defined with \&{def}, \&{vardef}, \&{primarydef}, etc.;
14297 repeatable code can be defined with \&{for}, \&{forever}, \&{forsuffixes}.
14298 All such operations are handled by the routines in this part of the program.
14299
14300 The modifier part of each command code is zero for the ``ending delimiters''
14301 like \&{enddef} and \&{endfor}.
14302
14303 @d start_def 1 /* command modifier for \&{def} */
14304 @d var_def 2 /* command modifier for \&{vardef} */
14305 @d end_def 0 /* command modifier for \&{enddef} */
14306 @d start_forever 1 /* command modifier for \&{forever} */
14307 @d end_for 0 /* command modifier for \&{endfor} */
14308
14309 @<Put each...@>=
14310 mp_primitive(mp, "def",macro_def,start_def);
14311 @:def_}{\&{def} primitive@>
14312 mp_primitive(mp, "vardef",macro_def,var_def);
14313 @:var_def_}{\&{vardef} primitive@>
14314 mp_primitive(mp, "primarydef",macro_def,secondary_primary_macro);
14315 @:primary_def_}{\&{primarydef} primitive@>
14316 mp_primitive(mp, "secondarydef",macro_def,tertiary_secondary_macro);
14317 @:secondary_def_}{\&{secondarydef} primitive@>
14318 mp_primitive(mp, "tertiarydef",macro_def,expression_tertiary_macro);
14319 @:tertiary_def_}{\&{tertiarydef} primitive@>
14320 mp_primitive(mp, "enddef",macro_def,end_def); mp->eqtb[frozen_end_def]=mp->eqtb[mp->cur_sym];
14321 @:end_def_}{\&{enddef} primitive@>
14322 @#
14323 mp_primitive(mp, "for",iteration,expr_base);
14324 @:for_}{\&{for} primitive@>
14325 mp_primitive(mp, "forsuffixes",iteration,suffix_base);
14326 @:for_suffixes_}{\&{forsuffixes} primitive@>
14327 mp_primitive(mp, "forever",iteration,start_forever);
14328 @:forever_}{\&{forever} primitive@>
14329 mp_primitive(mp, "endfor",iteration,end_for); mp->eqtb[frozen_end_for]=mp->eqtb[mp->cur_sym];
14330 @:end_for_}{\&{endfor} primitive@>
14331
14332 @ @<Cases of |print_cmd...@>=
14333 case macro_def:
14334   if ( m<=var_def ) {
14335     if ( m==start_def ) mp_print(mp, "def");
14336     else if ( m<start_def ) mp_print(mp, "enddef");
14337     else mp_print(mp, "vardef");
14338   } else if ( m==secondary_primary_macro ) { 
14339     mp_print(mp, "primarydef");
14340   } else if ( m==tertiary_secondary_macro ) { 
14341     mp_print(mp, "secondarydef");
14342   } else { 
14343     mp_print(mp, "tertiarydef");
14344   }
14345   break;
14346 case iteration: 
14347   if ( m<=start_forever ) {
14348     if ( m==start_forever ) mp_print(mp, "forever"); 
14349     else mp_print(mp, "endfor");
14350   } else if ( m==expr_base ) {
14351     mp_print(mp, "for"); 
14352   } else { 
14353     mp_print(mp, "forsuffixes");
14354   }
14355   break;
14356
14357 @ Different macro-absorbing operations have different syntaxes, but they
14358 also have a lot in common. There is a list of special symbols that are to
14359 be replaced by parameter tokens; there is a special command code that
14360 ends the definition; the quotation conventions are identical.  Therefore
14361 it makes sense to have most of the work done by a single subroutine. That
14362 subroutine is called |scan_toks|.
14363
14364 The first parameter to |scan_toks| is the command code that will
14365 terminate scanning (either |macro_def| or |iteration|).
14366
14367 The second parameter, |subst_list|, points to a (possibly empty) list
14368 of two-word nodes whose |info| and |value| fields specify symbol tokens
14369 before and after replacement. The list will be returned to free storage
14370 by |scan_toks|.
14371
14372 The third parameter is simply appended to the token list that is built.
14373 And the final parameter tells how many of the special operations
14374 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#} are to be replaced by suffix parameters.
14375 When such parameters are present, they are called \.{(SUFFIX0)},
14376 \.{(SUFFIX1)}, and \.{(SUFFIX2)}.
14377
14378 @c static pointer mp_scan_toks (MP mp,command_code terminator, pointer 
14379   subst_list, pointer tail_end, quarterword suffix_count) {
14380   pointer p; /* tail of the token list being built */
14381   pointer q; /* temporary for link management */
14382   integer balance; /* left delimiters minus right delimiters */
14383   p=hold_head; balance=1; mp_link(hold_head)=null;
14384   while (1) { 
14385     get_t_next;
14386     if ( mp->cur_sym>0 ) {
14387       @<Substitute for |cur_sym|, if it's on the |subst_list|@>;
14388       if ( mp->cur_cmd==terminator ) {
14389         @<Adjust the balance; |break| if it's zero@>;
14390       } else if ( mp->cur_cmd==macro_special ) {
14391         @<Handle quoted symbols, \.{\#\AT!}, \.{\AT!}, or \.{\AT!\#}@>;
14392       }
14393     }
14394     mp_link(p)=mp_cur_tok(mp); p=mp_link(p);
14395   }
14396   mp_link(p)=tail_end; mp_flush_node_list(mp, subst_list);
14397   return mp_link(hold_head);
14398 }
14399
14400 @ @<Substitute for |cur_sym|...@>=
14401
14402   q=subst_list;
14403   while ( q!=null ) {
14404     if ( mp_info(q)==mp->cur_sym ) {
14405       mp->cur_sym=value(q); mp->cur_cmd=relax; break;
14406     }
14407     q=mp_link(q);
14408   }
14409 }
14410
14411 @ @<Adjust the balance; |break| if it's zero@>=
14412 if ( mp->cur_mod>0 ) {
14413   incr(balance);
14414 } else { 
14415   decr(balance);
14416   if ( balance==0 )
14417     break;
14418 }
14419
14420 @ Four commands are intended to be used only within macro texts: \&{quote},
14421 \.{\#\AT!}, \.{\AT!}, and \.{\AT!\#}. They are variants of a single command
14422 code called |macro_special|.
14423
14424 @d quote 0 /* |macro_special| modifier for \&{quote} */
14425 @d macro_prefix 1 /* |macro_special| modifier for \.{\#\AT!} */
14426 @d macro_at 2 /* |macro_special| modifier for \.{\AT!} */
14427 @d macro_suffix 3 /* |macro_special| modifier for \.{\AT!\#} */
14428
14429 @<Put each...@>=
14430 mp_primitive(mp, "quote",macro_special,quote);
14431 @:quote_}{\&{quote} primitive@>
14432 mp_primitive(mp, "#@@",macro_special,macro_prefix);
14433 @:]]]\#\AT!_}{\.{\#\AT!} primitive@>
14434 mp_primitive(mp, "@@",macro_special,macro_at);
14435 @:]]]\AT!_}{\.{\AT!} primitive@>
14436 mp_primitive(mp, "@@#",macro_special,macro_suffix);
14437 @:]]]\AT!\#_}{\.{\AT!\#} primitive@>
14438
14439 @ @<Cases of |print_cmd...@>=
14440 case macro_special: 
14441   switch (m) {
14442   case macro_prefix: mp_print(mp, "#@@"); break;
14443   case macro_at: mp_print_char(mp, xord('@@')); break;
14444   case macro_suffix: mp_print(mp, "@@#"); break;
14445   default: mp_print(mp, "quote"); break;
14446   }
14447   break;
14448
14449 @ @<Handle quoted...@>=
14450
14451   if ( mp->cur_mod==quote ) { get_t_next; } 
14452   else if ( mp->cur_mod<=suffix_count ) 
14453     mp->cur_sym=suffix_base-1+mp->cur_mod;
14454 }
14455
14456 @ Here is a routine that's used whenever a token will be redefined. If
14457 the user's token is unredefinable, the `|frozen_inaccessible|' token is
14458 substituted; the latter is redefinable but essentially impossible to use,
14459 hence \MP's tables won't get fouled up.
14460
14461 @c static void mp_get_symbol (MP mp) { /* sets |cur_sym| to a safe symbol */
14462 RESTART: 
14463   get_t_next;
14464   if ( (mp->cur_sym==0)||(mp->cur_sym>(integer)frozen_inaccessible) ) {
14465     print_err("Missing symbolic token inserted");
14466 @.Missing symbolic token...@>
14467     help3("Sorry: You can\'t redefine a number, string, or expr.",
14468       "I've inserted an inaccessible symbol so that your",
14469       "definition will be completed without mixing me up too badly.");
14470     if ( mp->cur_sym>0 )
14471       mp->help_line[2]="Sorry: You can\'t redefine my error-recovery tokens.";
14472     else if ( mp->cur_cmd==string_token ) 
14473       delete_str_ref(mp->cur_mod);
14474     mp->cur_sym=frozen_inaccessible; mp_ins_error(mp); goto RESTART;
14475   }
14476 }
14477
14478 @ Before we actually redefine a symbolic token, we need to clear away its
14479 former value, if it was a variable. The following stronger version of
14480 |get_symbol| does that.
14481
14482 @c static void mp_get_clear_symbol (MP mp) { 
14483   mp_get_symbol(mp); mp_clear_symbol(mp, mp->cur_sym,false);
14484 }
14485
14486 @ Here's another little subroutine; it checks that an equals sign
14487 or assignment sign comes along at the proper place in a macro definition.
14488
14489 @c static void mp_check_equals (MP mp) { 
14490   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
14491      mp_missing_err(mp, "=");
14492 @.Missing `='@>
14493     help5("The next thing in this `def' should have been `=',",
14494           "because I've already looked at the definition heading.",
14495           "But don't worry; I'll pretend that an equals sign",
14496           "was present. Everything from here to `enddef'",
14497           "will be the replacement text of this macro.");
14498     mp_back_error(mp);
14499   }
14500 }
14501
14502 @ A \&{primarydef}, \&{secondarydef}, or \&{tertiarydef} is rather easily
14503 handled now that we have |scan_toks|.  In this case there are
14504 two parameters, which will be \.{EXPR0} and \.{EXPR1} (i.e.,
14505 |expr_base| and |expr_base+1|).
14506
14507 @c static void mp_make_op_def (MP mp) {
14508   command_code m; /* the type of definition */
14509   pointer p,q,r; /* for list manipulation */
14510   m=mp->cur_mod;
14511   mp_get_symbol(mp); q=mp_get_node(mp, token_node_size);
14512   mp_info(q)=mp->cur_sym; value(q)=expr_base;
14513   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym;
14514   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
14515   mp_info(p)=mp->cur_sym; value(p)=expr_base+1; mp_link(p)=q;
14516   get_t_next; mp_check_equals(mp);
14517   mp->scanner_status=op_defining; q=mp_get_avail(mp); ref_count(q)=null;
14518   r=mp_get_avail(mp); mp_link(q)=r; mp_info(r)=general_macro;
14519   mp_link(r)=mp_scan_toks(mp, macro_def,p,null,0);
14520   mp->scanner_status=normal; eq_type(mp->warning_info)=m;
14521   equiv(mp->warning_info)=q; mp_get_x_next(mp);
14522 }
14523
14524 @ Parameters to macros are introduced by the keywords \&{expr},
14525 \&{suffix}, \&{text}, \&{primary}, \&{secondary}, and \&{tertiary}.
14526
14527 @<Put each...@>=
14528 mp_primitive(mp, "expr",param_type,expr_base);
14529 @:expr_}{\&{expr} primitive@>
14530 mp_primitive(mp, "suffix",param_type,suffix_base);
14531 @:suffix_}{\&{suffix} primitive@>
14532 mp_primitive(mp, "text",param_type,text_base);
14533 @:text_}{\&{text} primitive@>
14534 mp_primitive(mp, "primary",param_type,primary_macro);
14535 @:primary_}{\&{primary} primitive@>
14536 mp_primitive(mp, "secondary",param_type,secondary_macro);
14537 @:secondary_}{\&{secondary} primitive@>
14538 mp_primitive(mp, "tertiary",param_type,tertiary_macro);
14539 @:tertiary_}{\&{tertiary} primitive@>
14540
14541 @ @<Cases of |print_cmd...@>=
14542 case param_type:
14543   if ( m>=expr_base ) {
14544     if ( m==expr_base ) mp_print(mp, "expr");
14545     else if ( m==suffix_base ) mp_print(mp, "suffix");
14546     else mp_print(mp, "text");
14547   } else if ( m<secondary_macro ) {
14548     mp_print(mp, "primary");
14549   } else if ( m==secondary_macro ) {
14550     mp_print(mp, "secondary");
14551   } else {
14552     mp_print(mp, "tertiary");
14553   }
14554   break;
14555
14556 @ Let's turn next to the more complex processing associated with \&{def}
14557 and \&{vardef}. When the following procedure is called, |cur_mod|
14558 should be either |start_def| or |var_def|.
14559
14560 @c 
14561 static void mp_scan_def (MP mp) {
14562   int m; /* the type of definition */
14563   int n; /* the number of special suffix parameters */
14564   int k; /* the total number of parameters */
14565   int c; /* the kind of macro we're defining */
14566   pointer r; /* parameter-substitution list */
14567   pointer q; /* tail of the macro token list */
14568   pointer p; /* temporary storage */
14569   halfword base; /* |expr_base|, |suffix_base|, or |text_base| */
14570   pointer l_delim,r_delim; /* matching delimiters */
14571   m=mp->cur_mod; c=general_macro; mp_link(hold_head)=null;
14572   q=mp_get_avail(mp); ref_count(q)=null; r=null;
14573   @<Scan the token or variable to be defined;
14574     set |n|, |scanner_status|, and |warning_info|@>;
14575   k=n;
14576   if ( mp->cur_cmd==left_delimiter ) {
14577     @<Absorb delimited parameters, putting them into lists |q| and |r|@>;
14578   }
14579   if ( mp->cur_cmd==param_type ) {
14580     @<Absorb undelimited parameters, putting them into list |r|@>;
14581   }
14582   mp_check_equals(mp);
14583   p=mp_get_avail(mp); mp_info(p)=c; mp_link(q)=p;
14584   @<Attach the replacement text to the tail of node |p|@>;
14585   mp->scanner_status=normal; mp_get_x_next(mp);
14586 }
14587
14588 @ We don't put `|frozen_end_group|' into the replacement text of
14589 a \&{vardef}, because the user may want to redefine `\.{endgroup}'.
14590
14591 @<Attach the replacement text to the tail of node |p|@>=
14592 if ( m==start_def ) {
14593   mp_link(p)=mp_scan_toks(mp, macro_def,r,null,n);
14594 } else { 
14595   q=mp_get_avail(mp); mp_info(q)=mp->bg_loc; mp_link(p)=q;
14596   p=mp_get_avail(mp); mp_info(p)=mp->eg_loc;
14597   mp_link(q)=mp_scan_toks(mp, macro_def,r,p,n);
14598 }
14599 if ( mp->warning_info==bad_vardef ) 
14600   mp_flush_token_list(mp, value(bad_vardef))
14601
14602 @ @<Glob...@>=
14603 int bg_loc;
14604 int eg_loc; /* hash addresses of `\.{begingroup}' and `\.{endgroup}' */
14605
14606 @ @<Scan the token or variable to be defined;...@>=
14607 if ( m==start_def ) {
14608   mp_get_clear_symbol(mp); mp->warning_info=mp->cur_sym; get_t_next;
14609   mp->scanner_status=op_defining; n=0;
14610   eq_type(mp->warning_info)=defined_macro; equiv(mp->warning_info)=q;
14611 } else { 
14612   p=mp_scan_declared_variable(mp);
14613   mp_flush_variable(mp, equiv(mp_info(p)),mp_link(p),true);
14614   mp->warning_info=mp_find_variable(mp, p); mp_flush_list(mp, p);
14615   if ( mp->warning_info==null ) @<Change to `\.{a bad variable}'@>;
14616   mp->scanner_status=var_defining; n=2;
14617   if ( mp->cur_cmd==macro_special ) if ( mp->cur_mod==macro_suffix ) {/* \.{\AT!\#} */
14618     n=3; get_t_next;
14619   }
14620   mp_type(mp->warning_info)=mp_unsuffixed_macro-2+n; value(mp->warning_info)=q;
14621 } /* |mp_suffixed_macro=mp_unsuffixed_macro+1| */
14622
14623 @ @<Change to `\.{a bad variable}'@>=
14624
14625   print_err("This variable already starts with a macro");
14626 @.This variable already...@>
14627   help2("After `vardef a' you can\'t say `vardef a.b'.",
14628         "So I'll have to discard this definition.");
14629   mp_error(mp); mp->warning_info=bad_vardef;
14630 }
14631
14632 @ @<Initialize table entries...@>=
14633 mp_name_type(bad_vardef)=mp_root; mp_link(bad_vardef)=frozen_bad_vardef;
14634 equiv(frozen_bad_vardef)=bad_vardef; eq_type(frozen_bad_vardef)=tag_token;
14635
14636 @ @<Absorb delimited parameters, putting them into lists |q| and |r|@>=
14637 do {  
14638   l_delim=mp->cur_sym; r_delim=mp->cur_mod; get_t_next;
14639   if ( (mp->cur_cmd==param_type)&&(mp->cur_mod>=expr_base) ) {
14640    base=mp->cur_mod;
14641   } else { 
14642     print_err("Missing parameter type; `expr' will be assumed");
14643 @.Missing parameter type@>
14644     help1("You should've had `expr' or `suffix' or `text' here.");
14645     mp_back_error(mp); base=expr_base;
14646   }
14647   @<Absorb parameter tokens for type |base|@>;
14648   mp_check_delimiter(mp, l_delim,r_delim);
14649   get_t_next;
14650 } while (mp->cur_cmd==left_delimiter)
14651
14652 @ @<Absorb parameter tokens for type |base|@>=
14653 do { 
14654   mp_link(q)=mp_get_avail(mp); q=mp_link(q); mp_info(q)=base+k;
14655   mp_get_symbol(mp); p=mp_get_node(mp, token_node_size); 
14656   value(p)=base+k; mp_info(p)=mp->cur_sym;
14657   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14658 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
14659   incr(k); mp_link(p)=r; r=p; get_t_next;
14660 } while (mp->cur_cmd==comma)
14661
14662 @ @<Absorb undelimited parameters, putting them into list |r|@>=
14663
14664   p=mp_get_node(mp, token_node_size);
14665   if ( mp->cur_mod<expr_base ) {
14666     c=mp->cur_mod; value(p)=expr_base+k;
14667   } else { 
14668     value(p)=mp->cur_mod+k;
14669     if ( mp->cur_mod==expr_base ) c=expr_macro;
14670     else if ( mp->cur_mod==suffix_base ) c=suffix_macro;
14671     else c=text_macro;
14672   }
14673   if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14674   incr(k); mp_get_symbol(mp); mp_info(p)=mp->cur_sym; mp_link(p)=r; r=p; get_t_next;
14675   if ( c==expr_macro ) if ( mp->cur_cmd==of_token ) {
14676     c=of_macro; p=mp_get_node(mp, token_node_size);
14677     if ( k==mp->param_size ) mp_overflow(mp, "parameter stack size",mp->param_size);
14678     value(p)=expr_base+k; mp_get_symbol(mp); mp_info(p)=mp->cur_sym;
14679     mp_link(p)=r; r=p; get_t_next;
14680   }
14681 }
14682
14683 @* \[32] Expanding the next token.
14684 Only a few command codes |<min_command| can possibly be returned by
14685 |get_t_next|; in increasing order, they are
14686 |if_test|, |fi_or_else|, |input|, |iteration|, |repeat_loop|,
14687 |exit_test|, |relax|, |scan_tokens|, |expand_after|, and |defined_macro|.
14688
14689 \MP\ usually gets the next token of input by saying |get_x_next|. This is
14690 like |get_t_next| except that it keeps getting more tokens until
14691 finding |cur_cmd>=min_command|. In other words, |get_x_next| expands
14692 macros and removes conditionals or iterations or input instructions that
14693 might be present.
14694
14695 It follows that |get_x_next| might invoke itself recursively. In fact,
14696 there is massive recursion, since macro expansion can involve the
14697 scanning of arbitrarily complex expressions, which in turn involve
14698 macro expansion and conditionals, etc.
14699 @^recursion@>
14700
14701 Therefore it's necessary to declare a whole bunch of |forward|
14702 procedures at this point, and to insert some other procedures
14703 that will be invoked by |get_x_next|.
14704
14705 @<Declarations@>= 
14706 static void mp_scan_primary (MP mp);
14707 static void mp_scan_secondary (MP mp);
14708 static void mp_scan_tertiary (MP mp);
14709 static void mp_scan_expression (MP mp);
14710 static void mp_scan_suffix (MP mp);
14711 static void mp_get_boolean (MP mp);
14712 static void mp_pass_text (MP mp);
14713 static void mp_conditional (MP mp);
14714 static void mp_start_input (MP mp);
14715 static void mp_begin_iteration (MP mp);
14716 static void mp_resume_iteration (MP mp);
14717 static void mp_stop_iteration (MP mp);
14718
14719 @ An auxiliary subroutine called |expand| is used by |get_x_next|
14720 when it has to do exotic expansion commands.
14721
14722 @c 
14723 static void mp_expand (MP mp) {
14724   pointer p; /* for list manipulation */
14725   size_t k; /* something that we hope is |<=buf_size| */
14726   pool_pointer j; /* index into |str_pool| */
14727   if ( mp->internal[mp_tracing_commands]>unity ) 
14728     if ( mp->cur_cmd!=defined_macro )
14729       show_cur_cmd_mod;
14730   switch (mp->cur_cmd)  {
14731   case if_test:
14732     mp_conditional(mp); /* this procedure is discussed in Part 36 below */
14733     break;
14734   case fi_or_else:
14735     @<Terminate the current conditional and skip to \&{fi}@>;
14736     break;
14737   case input:
14738     @<Initiate or terminate input from a file@>;
14739     break;
14740   case iteration:
14741     if ( mp->cur_mod==end_for ) {
14742       @<Scold the user for having an extra \&{endfor}@>;
14743     } else {
14744       mp_begin_iteration(mp); /* this procedure is discussed in Part 37 below */
14745     }
14746     break;
14747   case repeat_loop: 
14748     @<Repeat a loop@>;
14749     break;
14750   case exit_test: 
14751     @<Exit a loop if the proper time has come@>;
14752     break;
14753   case relax: 
14754     break;
14755   case expand_after: 
14756     @<Expand the token after the next token@>;
14757     break;
14758   case scan_tokens: 
14759     @<Put a string into the input buffer@>;
14760     break;
14761   case defined_macro:
14762    mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14763    break;
14764   }; /* there are no other cases */
14765 }
14766
14767 @ @<Scold the user...@>=
14768
14769   print_err("Extra `endfor'");
14770 @.Extra `endfor'@>
14771   help2("I'm not currently working on a for loop,",
14772         "so I had better not try to end anything.");
14773   mp_error(mp);
14774 }
14775
14776 @ The processing of \&{input} involves the |start_input| subroutine,
14777 which will be declared later; the processing of \&{endinput} is trivial.
14778
14779 @<Put each...@>=
14780 mp_primitive(mp, "input",input,0);
14781 @:input_}{\&{input} primitive@>
14782 mp_primitive(mp, "endinput",input,1);
14783 @:end_input_}{\&{endinput} primitive@>
14784
14785 @ @<Cases of |print_cmd_mod|...@>=
14786 case input: 
14787   if ( m==0 ) mp_print(mp, "input");
14788   else mp_print(mp, "endinput");
14789   break;
14790
14791 @ @<Initiate or terminate input...@>=
14792 if ( mp->cur_mod>0 ) mp->force_eof=true;
14793 else mp_start_input(mp)
14794
14795 @ We'll discuss the complicated parts of loop operations later. For now
14796 it suffices to know that there's a global variable called |loop_ptr|
14797 that will be |null| if no loop is in progress.
14798
14799 @<Repeat a loop@>=
14800 { while ( token_state &&(loc==null) ) 
14801     mp_end_token_list(mp); /* conserve stack space */
14802   if ( mp->loop_ptr==null ) {
14803     print_err("Lost loop");
14804 @.Lost loop@>
14805     help2("I'm confused; after exiting from a loop, I still seem",
14806           "to want to repeat it. I'll try to forget the problem.");
14807     mp_error(mp);
14808   } else {
14809     mp_resume_iteration(mp); /* this procedure is in Part 37 below */
14810   }
14811 }
14812
14813 @ @<Exit a loop if the proper time has come@>=
14814 { mp_get_boolean(mp);
14815   if ( mp->internal[mp_tracing_commands]>unity ) 
14816     mp_show_cmd_mod(mp, nullary,mp->cur_exp);
14817   if ( mp->cur_exp==true_code ) {
14818     if ( mp->loop_ptr==null ) {
14819       print_err("No loop is in progress");
14820 @.No loop is in progress@>
14821       help1("Why say `exitif' when there's nothing to exit from?");
14822       if ( mp->cur_cmd==semicolon ) mp_error(mp); else mp_back_error(mp);
14823     } else {
14824      @<Exit prematurely from an iteration@>;
14825     }
14826   } else if ( mp->cur_cmd!=semicolon ) {
14827     mp_missing_err(mp, ";");
14828 @.Missing `;'@>
14829     help2("After `exitif <boolean exp>' I expect to see a semicolon.",
14830           "I shall pretend that one was there."); mp_back_error(mp);
14831   }
14832 }
14833
14834 @ Here we use the fact that |forever_text| is the only |token_type| that
14835 is less than |loop_text|.
14836
14837 @<Exit prematurely...@>=
14838 { p=null;
14839   do {  
14840     if ( file_state ) {
14841       mp_end_file_reading(mp);
14842     } else { 
14843       if ( token_type<=loop_text ) p=start;
14844       mp_end_token_list(mp);
14845     }
14846   } while (p==null);
14847   if ( p!=mp_info(mp->loop_ptr) ) mp_fatal_error(mp, "*** (loop confusion)");
14848 @.loop confusion@>
14849   mp_stop_iteration(mp); /* this procedure is in Part 34 below */
14850 }
14851
14852 @ @<Expand the token after the next token@>=
14853 { get_t_next;
14854   p=mp_cur_tok(mp); get_t_next;
14855   if ( mp->cur_cmd<min_command ) mp_expand(mp); 
14856   else mp_back_input(mp);
14857   back_list(p);
14858 }
14859
14860 @ @<Put a string into the input buffer@>=
14861 { mp_get_x_next(mp); mp_scan_primary(mp);
14862   if ( mp->cur_type!=mp_string_type ) {
14863     mp_disp_err(mp, null,"Not a string");
14864 @.Not a string@>
14865     help2("I'm going to flush this expression, since",
14866           "scantokens should be followed by a known string.");
14867     mp_put_get_flush_error(mp, 0);
14868   } else { 
14869     mp_back_input(mp);
14870     if ( length(mp->cur_exp)>0 )
14871        @<Pretend we're reading a new one-line file@>;
14872   }
14873 }
14874
14875 @ @<Pretend we're reading a new one-line file@>=
14876 { mp_begin_file_reading(mp); name=is_scantok;
14877   k=mp->first+length(mp->cur_exp);
14878   if ( k>=mp->max_buf_stack ) {
14879     while ( k>=mp->buf_size ) {
14880       mp_reallocate_buffer(mp,(mp->buf_size+(mp->buf_size/4)));
14881     }
14882     mp->max_buf_stack=k+1;
14883   }
14884   j=mp->str_start[mp->cur_exp]; limit=(halfword)k;
14885   while ( mp->first<(size_t)limit ) {
14886     mp->buffer[mp->first]=mp->str_pool[j]; incr(j); incr(mp->first);
14887   }
14888   mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start; 
14889   mp_flush_cur_exp(mp, 0);
14890 }
14891
14892 @ Here finally is |get_x_next|.
14893
14894 The expression scanning routines to be considered later
14895 communicate via the global quantities |cur_type| and |cur_exp|;
14896 we must be very careful to save and restore these quantities while
14897 macros are being expanded.
14898 @^inner loop@>
14899
14900 @<Declarations@>=
14901 static void mp_get_x_next (MP mp);
14902
14903 @ @c void mp_get_x_next (MP mp) {
14904   pointer save_exp; /* a capsule to save |cur_type| and |cur_exp| */
14905   get_t_next;
14906   if ( mp->cur_cmd<min_command ) {
14907     save_exp=mp_stash_cur_exp(mp);
14908     do {  
14909       if ( mp->cur_cmd==defined_macro ) 
14910         mp_macro_call(mp, mp->cur_mod,null,mp->cur_sym);
14911       else 
14912         mp_expand(mp);
14913       get_t_next;
14914      } while (mp->cur_cmd<min_command);
14915      mp_unstash_cur_exp(mp, save_exp); /* that restores |cur_type| and |cur_exp| */
14916   }
14917 }
14918
14919 @ Now let's consider the |macro_call| procedure, which is used to start up
14920 all user-defined macros. Since the arguments to a macro might be expressions,
14921 |macro_call| is recursive.
14922 @^recursion@>
14923
14924 The first parameter to |macro_call| points to the reference count of the
14925 token list that defines the macro. The second parameter contains any
14926 arguments that have already been parsed (see below).  The third parameter
14927 points to the symbolic token that names the macro. If the third parameter
14928 is |null|, the macro was defined by \&{vardef}, so its name can be
14929 reconstructed from the prefix and ``at'' arguments found within the
14930 second parameter.
14931
14932 What is this second parameter? It's simply a linked list of one-word items,
14933 whose |info| fields point to the arguments. In other words, if |arg_list=null|,
14934 no arguments have been scanned yet; otherwise |mp_info(arg_list)| points to
14935 the first scanned argument, and |mp_link(arg_list)| points to the list of
14936 further arguments (if any).
14937
14938 Arguments of type \&{expr} are so-called capsules, which we will
14939 discuss later when we concentrate on expressions; they can be
14940 recognized easily because their |link| field is |void|. Arguments of type
14941 \&{suffix} and \&{text} are token lists without reference counts.
14942
14943 @ After argument scanning is complete, the arguments are moved to the
14944 |param_stack|. (They can't be put on that stack any sooner, because
14945 the stack is growing and shrinking in unpredictable ways as more arguments
14946 are being acquired.)  Then the macro body is fed to the scanner; i.e.,
14947 the replacement text of the macro is placed at the top of the \MP's
14948 input stack, so that |get_t_next| will proceed to read it next.
14949
14950 @<Declarations@>=
14951 static void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14952                     pointer macro_name) ;
14953
14954 @ @c
14955 void mp_macro_call (MP mp,pointer def_ref, pointer arg_list, 
14956                     pointer macro_name) {
14957   /* invokes a user-defined control sequence */
14958   pointer r; /* current node in the macro's token list */
14959   pointer p,q; /* for list manipulation */
14960   integer n; /* the number of arguments */
14961   pointer tail = 0; /* tail of the argument list */
14962   pointer l_delim=0,r_delim=0; /* a delimiter pair */
14963   r=mp_link(def_ref); add_mac_ref(def_ref);
14964   if ( arg_list==null ) {
14965     n=0;
14966   } else {
14967    @<Determine the number |n| of arguments already supplied,
14968     and set |tail| to the tail of |arg_list|@>;
14969   }
14970   if ( mp->internal[mp_tracing_macros]>0 ) {
14971     @<Show the text of the macro being expanded, and the existing arguments@>;
14972   }
14973   @<Scan the remaining arguments, if any; set |r| to the first token
14974     of the replacement text@>;
14975   @<Feed the arguments and replacement text to the scanner@>;
14976 }
14977
14978 @ @<Show the text of the macro...@>=
14979 mp_begin_diagnostic(mp); mp_print_ln(mp); 
14980 mp_print_macro_name(mp, arg_list,macro_name);
14981 if ( n==3 ) mp_print(mp, "@@#"); /* indicate a suffixed macro */
14982 mp_show_macro(mp, def_ref,null,100000);
14983 if ( arg_list!=null ) {
14984   n=0; p=arg_list;
14985   do {  
14986     q=mp_info(p);
14987     mp_print_arg(mp, q,n,0);
14988     incr(n); p=mp_link(p);
14989   } while (p!=null);
14990 }
14991 mp_end_diagnostic(mp, false)
14992
14993
14994 @ @<Declarations@>=
14995 static void mp_print_macro_name (MP mp,pointer a, pointer n);
14996
14997 @ @c
14998 void mp_print_macro_name (MP mp,pointer a, pointer n) {
14999   pointer p,q; /* they traverse the first part of |a| */
15000   if ( n!=null ) {
15001     mp_print_text(n);
15002   } else  { 
15003     p=mp_info(a);
15004     if ( p==null ) {
15005       mp_print_text(mp_info(mp_info(mp_link(a))));
15006     } else { 
15007       q=p;
15008       while ( mp_link(q)!=null ) q=mp_link(q);
15009       mp_link(q)=mp_info(mp_link(a));
15010       mp_show_token_list(mp, p,null,1000,0);
15011       mp_link(q)=null;
15012     }
15013   }
15014 }
15015
15016 @ @<Declarations@>=
15017 static void mp_print_arg (MP mp,pointer q, integer n, pointer b) ;
15018
15019 @ @c
15020 void mp_print_arg (MP mp,pointer q, integer n, pointer b) {
15021   if ( mp_link(q)==mp_void ) mp_print_nl(mp, "(EXPR");
15022   else if ( (b<text_base)&&(b!=text_macro) ) mp_print_nl(mp, "(SUFFIX");
15023   else mp_print_nl(mp, "(TEXT");
15024   mp_print_int(mp, n); mp_print(mp, ")<-");
15025   if ( mp_link(q)==mp_void ) mp_print_exp(mp, q,1);
15026   else mp_show_token_list(mp, q,null,1000,0);
15027 }
15028
15029 @ @<Determine the number |n| of arguments already supplied...@>=
15030 {  
15031   n=1; tail=arg_list;
15032   while ( mp_link(tail)!=null ) { 
15033     incr(n); tail=mp_link(tail);
15034   }
15035 }
15036
15037 @ @<Scan the remaining arguments, if any; set |r|...@>=
15038 mp->cur_cmd=comma+1; /* anything |<>comma| will do */
15039 while ( mp_info(r)>=expr_base ) { 
15040   @<Scan the delimited argument represented by |mp_info(r)|@>;
15041   r=mp_link(r);
15042 }
15043 if ( mp->cur_cmd==comma ) {
15044   print_err("Too many arguments to ");
15045 @.Too many arguments...@>
15046   mp_print_macro_name(mp, arg_list,macro_name); mp_print_char(mp, xord(';'));
15047   mp_print_nl(mp, "  Missing `"); mp_print_text(r_delim);
15048 @.Missing `)'...@>
15049   mp_print(mp, "' has been inserted");
15050   help3("I'm going to assume that the comma I just read was a",
15051    "right delimiter, and then I'll begin expanding the macro.",
15052    "You might want to delete some tokens before continuing.");
15053   mp_error(mp);
15054 }
15055 if ( mp_info(r)!=general_macro ) {
15056   @<Scan undelimited argument(s)@>;
15057 }
15058 r=mp_link(r)
15059
15060 @ At this point, the reader will find it advisable to review the explanation
15061 of token list format that was presented earlier, paying special attention to
15062 the conventions that apply only at the beginning of a macro's token list.
15063
15064 On the other hand, the reader will have to take the expression-parsing
15065 aspects of the following program on faith; we will explain |cur_type|
15066 and |cur_exp| later. (Several things in this program depend on each other,
15067 and it's necessary to jump into the circle somewhere.)
15068
15069 @<Scan the delimited argument represented by |mp_info(r)|@>=
15070 if ( mp->cur_cmd!=comma ) {
15071   mp_get_x_next(mp);
15072   if ( mp->cur_cmd!=left_delimiter ) {
15073     print_err("Missing argument to ");
15074 @.Missing argument...@>
15075     mp_print_macro_name(mp, arg_list,macro_name);
15076     help3("That macro has more parameters than you thought.",
15077      "I'll continue by pretending that each missing argument",
15078      "is either zero or null.");
15079     if ( mp_info(r)>=suffix_base ) {
15080       mp->cur_exp=null; mp->cur_type=mp_token_list;
15081     } else { 
15082       mp->cur_exp=0; mp->cur_type=mp_known;
15083     }
15084     mp_back_error(mp); mp->cur_cmd=right_delimiter; 
15085     goto FOUND;
15086   }
15087   l_delim=mp->cur_sym; r_delim=mp->cur_mod;
15088 }
15089 @<Scan the argument represented by |mp_info(r)|@>;
15090 if ( mp->cur_cmd!=comma ) 
15091   @<Check that the proper right delimiter was present@>;
15092 FOUND:  
15093 @<Append the current expression to |arg_list|@>
15094
15095 @ @<Check that the proper right delim...@>=
15096 if ( (mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15097   if ( mp_info(mp_link(r))>=expr_base ) {
15098     mp_missing_err(mp, ",");
15099 @.Missing `,'@>
15100     help3("I've finished reading a macro argument and am about to",
15101       "read another; the arguments weren't delimited correctly.",
15102       "You might want to delete some tokens before continuing.");
15103     mp_back_error(mp); mp->cur_cmd=comma;
15104   } else { 
15105     mp_missing_err(mp, str(text(r_delim)));
15106 @.Missing `)'@>
15107     help2("I've gotten to the end of the macro parameter list.",
15108           "You might want to delete some tokens before continuing.");
15109     mp_back_error(mp);
15110   }
15111 }
15112
15113 @ A \&{suffix} or \&{text} parameter will have been scanned as
15114 a token list pointed to by |cur_exp|, in which case we will have
15115 |cur_type=token_list|.
15116
15117 @<Append the current expression to |arg_list|@>=
15118
15119   p=mp_get_avail(mp);
15120   if ( mp->cur_type==mp_token_list ) mp_info(p)=mp->cur_exp;
15121   else mp_info(p)=mp_stash_cur_exp(mp);
15122   if ( mp->internal[mp_tracing_macros]>0 ) {
15123     mp_begin_diagnostic(mp); mp_print_arg(mp, mp_info(p),n,mp_info(r)); 
15124     mp_end_diagnostic(mp, false);
15125   }
15126   if ( arg_list==null ) arg_list=p;
15127   else mp_link(tail)=p;
15128   tail=p; incr(n);
15129 }
15130
15131 @ @<Scan the argument represented by |mp_info(r)|@>=
15132 if ( mp_info(r)>=text_base ) {
15133   mp_scan_text_arg(mp, l_delim,r_delim);
15134 } else { 
15135   mp_get_x_next(mp);
15136   if ( mp_info(r)>=suffix_base ) mp_scan_suffix(mp);
15137   else mp_scan_expression(mp);
15138 }
15139
15140 @ The parameters to |scan_text_arg| are either a pair of delimiters
15141 or zero; the latter case is for undelimited text arguments, which
15142 end with the first semicolon or \&{endgroup} or \&{end} that is not
15143 contained in a group.
15144
15145 @<Declarations@>=
15146 static void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) ;
15147
15148 @ @c
15149 void mp_scan_text_arg (MP mp,pointer l_delim, pointer r_delim) {
15150   integer balance; /* excess of |l_delim| over |r_delim| */
15151   pointer p; /* list tail */
15152   mp->warning_info=l_delim; mp->scanner_status=absorbing;
15153   p=hold_head; balance=1; mp_link(hold_head)=null;
15154   while (1)  { 
15155     get_t_next;
15156     if ( l_delim==0 ) {
15157       @<Adjust the balance for an undelimited argument; |break| if done@>;
15158     } else {
15159           @<Adjust the balance for a delimited argument; |break| if done@>;
15160     }
15161     mp_link(p)=mp_cur_tok(mp); p=mp_link(p);
15162   }
15163   mp->cur_exp=mp_link(hold_head); mp->cur_type=mp_token_list;
15164   mp->scanner_status=normal;
15165 }
15166
15167 @ @<Adjust the balance for a delimited argument...@>=
15168 if ( mp->cur_cmd==right_delimiter ) { 
15169   if ( mp->cur_mod==l_delim ) { 
15170     decr(balance);
15171     if ( balance==0 ) break;
15172   }
15173 } else if ( mp->cur_cmd==left_delimiter ) {
15174   if ( mp->cur_mod==r_delim ) incr(balance);
15175 }
15176
15177 @ @<Adjust the balance for an undelimited...@>=
15178 if ( end_of_statement ) { /* |cur_cmd=semicolon|, |end_group|, or |stop| */
15179   if ( balance==1 ) { break; }
15180   else  { if ( mp->cur_cmd==end_group ) decr(balance); }
15181 } else if ( mp->cur_cmd==begin_group ) { 
15182   incr(balance); 
15183 }
15184
15185 @ @<Scan undelimited argument(s)@>=
15186
15187   if ( mp_info(r)<text_macro ) {
15188     mp_get_x_next(mp);
15189     if ( mp_info(r)!=suffix_macro ) {
15190       if ( (mp->cur_cmd==equals)||(mp->cur_cmd==assignment) ) mp_get_x_next(mp);
15191     }
15192   }
15193   switch (mp_info(r)) {
15194   case primary_macro:mp_scan_primary(mp); break;
15195   case secondary_macro:mp_scan_secondary(mp); break;
15196   case tertiary_macro:mp_scan_tertiary(mp); break;
15197   case expr_macro:mp_scan_expression(mp); break;
15198   case of_macro:
15199     @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>;
15200     break;
15201   case suffix_macro:
15202     @<Scan a suffix with optional delimiters@>;
15203     break;
15204   case text_macro:mp_scan_text_arg(mp, 0,0); break;
15205   } /* there are no other cases */
15206   mp_back_input(mp); 
15207   @<Append the current expression to |arg_list|@>;
15208 }
15209
15210 @ @<Scan an expression followed by `\&{of} $\langle$primary$\rangle$'@>=
15211
15212   mp_scan_expression(mp); p=mp_get_avail(mp); mp_info(p)=mp_stash_cur_exp(mp);
15213   if ( mp->internal[mp_tracing_macros]>0 ) { 
15214     mp_begin_diagnostic(mp); mp_print_arg(mp, mp_info(p),n,0); 
15215     mp_end_diagnostic(mp, false);
15216   }
15217   if ( arg_list==null ) arg_list=p; else mp_link(tail)=p;
15218   tail=p;incr(n);
15219   if ( mp->cur_cmd!=of_token ) {
15220     mp_missing_err(mp, "of"); mp_print(mp, " for ");
15221 @.Missing `of'@>
15222     mp_print_macro_name(mp, arg_list,macro_name);
15223     help1("I've got the first argument; will look now for the other.");
15224     mp_back_error(mp);
15225   }
15226   mp_get_x_next(mp); mp_scan_primary(mp);
15227 }
15228
15229 @ @<Scan a suffix with optional delimiters@>=
15230
15231   if ( mp->cur_cmd!=left_delimiter ) {
15232     l_delim=null;
15233   } else { 
15234     l_delim=mp->cur_sym; r_delim=mp->cur_mod; mp_get_x_next(mp);
15235   };
15236   mp_scan_suffix(mp);
15237   if ( l_delim!=null ) {
15238     if ((mp->cur_cmd!=right_delimiter)||(mp->cur_mod!=l_delim) ) {
15239       mp_missing_err(mp, str(text(r_delim)));
15240 @.Missing `)'@>
15241       help2("I've gotten to the end of the macro parameter list.",
15242             "You might want to delete some tokens before continuing.");
15243       mp_back_error(mp);
15244     }
15245     mp_get_x_next(mp);
15246   }
15247 }
15248
15249 @ Before we put a new token list on the input stack, it is wise to clean off
15250 all token lists that have recently been depleted. Then a user macro that ends
15251 with a call to itself will not require unbounded stack space.
15252
15253 @<Feed the arguments and replacement text to the scanner@>=
15254 while ( token_state &&(loc==null) ) mp_end_token_list(mp); /* conserve stack space */
15255 if ( mp->param_ptr+n>mp->max_param_stack ) {
15256   mp->max_param_stack=mp->param_ptr+n;
15257   if ( mp->max_param_stack>mp->param_size )
15258     mp_overflow(mp, "parameter stack size",mp->param_size);
15259 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15260 }
15261 mp_begin_token_list(mp, def_ref,macro); name=macro_name; loc=r;
15262 if ( n>0 ) {
15263   p=arg_list;
15264   do {  
15265    mp->param_stack[mp->param_ptr]=mp_info(p); incr(mp->param_ptr); p=mp_link(p);
15266   } while (p!=null);
15267   mp_flush_list(mp, arg_list);
15268 }
15269
15270 @ It's sometimes necessary to put a single argument onto |param_stack|.
15271 The |stack_argument| subroutine does this.
15272
15273 @c 
15274 static void mp_stack_argument (MP mp,pointer p) { 
15275   if ( mp->param_ptr==mp->max_param_stack ) {
15276     incr(mp->max_param_stack);
15277     if ( mp->max_param_stack>mp->param_size )
15278       mp_overflow(mp, "parameter stack size",mp->param_size);
15279 @:MetaPost capacity exceeded parameter stack size}{\quad parameter stack size@>
15280   }
15281   mp->param_stack[mp->param_ptr]=p; incr(mp->param_ptr);
15282 }
15283
15284 @* \[33] Conditional processing.
15285 Let's consider now the way \&{if} commands are handled.
15286
15287 Conditions can be inside conditions, and this nesting has a stack
15288 that is independent of other stacks.
15289 Four global variables represent the top of the condition stack:
15290 |cond_ptr| points to pushed-down entries, if~any; |cur_if| tells whether
15291 we are processing \&{if} or \&{elseif}; |if_limit| specifies
15292 the largest code of a |fi_or_else| command that is syntactically legal;
15293 and |if_line| is the line number at which the current conditional began.
15294
15295 If no conditions are currently in progress, the condition stack has the
15296 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
15297 Otherwise |cond_ptr| points to a two-word node; the |type|, |name_type|, and
15298 |link| fields of the first word contain |if_limit|, |cur_if|, and
15299 |cond_ptr| at the next level, and the second word contains the
15300 corresponding |if_line|.
15301
15302 @d if_node_size 2 /* number of words in stack entry for conditionals */
15303 @d if_line_field(A) mp->mem[(A)+1].cint
15304 @d if_code 1 /* code for \&{if} being evaluated */
15305 @d fi_code 2 /* code for \&{fi} */
15306 @d else_code 3 /* code for \&{else} */
15307 @d else_if_code 4 /* code for \&{elseif} */
15308
15309 @<Glob...@>=
15310 pointer cond_ptr; /* top of the condition stack */
15311 integer if_limit; /* upper bound on |fi_or_else| codes */
15312 quarterword cur_if; /* type of conditional being worked on */
15313 integer if_line; /* line where that conditional began */
15314
15315 @ @<Set init...@>=
15316 mp->cond_ptr=null; mp->if_limit=normal; mp->cur_if=0; mp->if_line=0;
15317
15318 @ @<Put each...@>=
15319 mp_primitive(mp, "if",if_test,if_code);
15320 @:if_}{\&{if} primitive@>
15321 mp_primitive(mp, "fi",fi_or_else,fi_code); mp->eqtb[frozen_fi]=mp->eqtb[mp->cur_sym];
15322 @:fi_}{\&{fi} primitive@>
15323 mp_primitive(mp, "else",fi_or_else,else_code);
15324 @:else_}{\&{else} primitive@>
15325 mp_primitive(mp, "elseif",fi_or_else,else_if_code);
15326 @:else_if_}{\&{elseif} primitive@>
15327
15328 @ @<Cases of |print_cmd_mod|...@>=
15329 case if_test:
15330 case fi_or_else: 
15331   switch (m) {
15332   case if_code:mp_print(mp, "if"); break;
15333   case fi_code:mp_print(mp, "fi");  break;
15334   case else_code:mp_print(mp, "else"); break;
15335   default: mp_print(mp, "elseif"); break;
15336   }
15337   break;
15338
15339 @ Here is a procedure that ignores text until coming to an \&{elseif},
15340 \&{else}, or \&{fi} at level zero of $\&{if}\ldots\&{fi}$
15341 nesting. After it has acted, |cur_mod| will indicate the token that
15342 was found.
15343
15344 \MP's smallest two command codes are |if_test| and |fi_or_else|; this
15345 makes the skipping process a bit simpler.
15346
15347 @c 
15348 void mp_pass_text (MP mp) {
15349   integer l = 0;
15350   mp->scanner_status=skipping;
15351   mp->warning_info=mp_true_line(mp);
15352   while (1)  { 
15353     get_t_next;
15354     if ( mp->cur_cmd<=fi_or_else ) {
15355       if ( mp->cur_cmd<fi_or_else ) {
15356         incr(l);
15357       } else { 
15358         if ( l==0 ) break;
15359         if ( mp->cur_mod==fi_code ) decr(l);
15360       }
15361     } else {
15362       @<Decrease the string reference count,
15363        if the current token is a string@>;
15364     }
15365   }
15366   mp->scanner_status=normal;
15367 }
15368
15369 @ @<Decrease the string reference count...@>=
15370 if ( mp->cur_cmd==string_token ) { delete_str_ref(mp->cur_mod); }
15371
15372 @ When we begin to process a new \&{if}, we set |if_limit:=if_code|; then
15373 if \&{elseif} or \&{else} or \&{fi} occurs before the current \&{if}
15374 condition has been evaluated, a colon will be inserted.
15375 A construction like `\.{if fi}' would otherwise get \MP\ confused.
15376
15377 @<Push the condition stack@>=
15378 { p=mp_get_node(mp, if_node_size); mp_link(p)=mp->cond_ptr; mp_type(p)=mp->if_limit;
15379   mp_name_type(p)=mp->cur_if; if_line_field(p)=mp->if_line;
15380   mp->cond_ptr=p; mp->if_limit=if_code; mp->if_line=mp_true_line(mp); 
15381   mp->cur_if=if_code;
15382 }
15383
15384 @ @<Pop the condition stack@>=
15385 { p=mp->cond_ptr; mp->if_line=if_line_field(p);
15386   mp->cur_if=mp_name_type(p); mp->if_limit=mp_type(p); mp->cond_ptr=mp_link(p);
15387   mp_free_node(mp, p,if_node_size);
15388 }
15389
15390 @ Here's a procedure that changes the |if_limit| code corresponding to
15391 a given value of |cond_ptr|.
15392
15393 @c 
15394 static void mp_change_if_limit (MP mp,quarterword l, pointer p) {
15395   pointer q;
15396   if ( p==mp->cond_ptr ) {
15397     mp->if_limit=l; /* that's the easy case */
15398   } else  { 
15399     q=mp->cond_ptr;
15400     while (1) { 
15401       if ( q==null ) mp_confusion(mp, "if");
15402 @:this can't happen if}{\quad if@>
15403       if ( mp_link(q)==p ) { 
15404         mp_type(q)=l; return;
15405       }
15406       q=mp_link(q);
15407     }
15408   }
15409 }
15410
15411 @ The user is supposed to put colons into the proper parts of conditional
15412 statements. Therefore, \MP\ has to check for their presence.
15413
15414 @c 
15415 static void mp_check_colon (MP mp) { 
15416   if ( mp->cur_cmd!=colon ) { 
15417     mp_missing_err(mp, ":");
15418 @.Missing `:'@>
15419     help2("There should've been a colon after the condition.",
15420           "I shall pretend that one was there.");
15421     mp_back_error(mp);
15422   }
15423 }
15424
15425 @ A condition is started when the |get_x_next| procedure encounters
15426 an |if_test| command; in that case |get_x_next| calls |conditional|,
15427 which is a recursive procedure.
15428 @^recursion@>
15429
15430 @c 
15431 void mp_conditional (MP mp) {
15432   pointer save_cond_ptr; /* |cond_ptr| corresponding to this conditional */
15433   int new_if_limit; /* future value of |if_limit| */
15434   pointer p; /* temporary register */
15435   @<Push the condition stack@>; 
15436   save_cond_ptr=mp->cond_ptr;
15437 RESWITCH: 
15438   mp_get_boolean(mp); new_if_limit=else_if_code;
15439   if ( mp->internal[mp_tracing_commands]>unity ) {
15440     @<Display the boolean value of |cur_exp|@>;
15441   }
15442 FOUND: 
15443   mp_check_colon(mp);
15444   if ( mp->cur_exp==true_code ) {
15445     mp_change_if_limit(mp, new_if_limit,save_cond_ptr);
15446     return; /* wait for \&{elseif}, \&{else}, or \&{fi} */
15447   };
15448   @<Skip to \&{elseif} or \&{else} or \&{fi}, then |goto done|@>;
15449 DONE: 
15450   mp->cur_if=mp->cur_mod; mp->if_line=mp_true_line(mp);
15451   if ( mp->cur_mod==fi_code ) {
15452     @<Pop the condition stack@>
15453   } else if ( mp->cur_mod==else_if_code ) {
15454     goto RESWITCH;
15455   } else  { 
15456     mp->cur_exp=true_code; new_if_limit=fi_code; mp_get_x_next(mp); 
15457     goto FOUND;
15458   }
15459 }
15460
15461 @ In a construction like `\&{if} \&{if} \&{true}: $0=1$: \\{foo}
15462 \&{else}: \\{bar} \&{fi}', the first \&{else}
15463 that we come to after learning that the \&{if} is false is not the
15464 \&{else} we're looking for. Hence the following curious logic is needed.
15465
15466 @<Skip to \&{elseif}...@>=
15467 while (1) { 
15468   mp_pass_text(mp);
15469   if ( mp->cond_ptr==save_cond_ptr ) goto DONE;
15470   else if ( mp->cur_mod==fi_code ) @<Pop the condition stack@>;
15471 }
15472
15473
15474 @ @<Display the boolean value...@>=
15475 { mp_begin_diagnostic(mp);
15476   if ( mp->cur_exp==true_code ) mp_print(mp, "{true}");
15477   else mp_print(mp, "{false}");
15478   mp_end_diagnostic(mp, false);
15479 }
15480
15481 @ The processing of conditionals is complete except for the following
15482 code, which is actually part of |get_x_next|. It comes into play when
15483 \&{elseif}, \&{else}, or \&{fi} is scanned.
15484
15485 @<Terminate the current conditional and skip to \&{fi}@>=
15486 if ( mp->cur_mod>mp->if_limit ) {
15487   if ( mp->if_limit==if_code ) { /* condition not yet evaluated */
15488     mp_missing_err(mp, ":");
15489 @.Missing `:'@>
15490     mp_back_input(mp); mp->cur_sym=frozen_colon; mp_ins_error(mp);
15491   } else  { 
15492     print_err("Extra "); mp_print_cmd_mod(mp, fi_or_else,mp->cur_mod);
15493 @.Extra else@>
15494 @.Extra elseif@>
15495 @.Extra fi@>
15496     help1("I'm ignoring this; it doesn't match any if.");
15497     mp_error(mp);
15498   }
15499 } else  { 
15500   while ( mp->cur_mod!=fi_code ) mp_pass_text(mp); /* skip to \&{fi} */
15501   @<Pop the condition stack@>;
15502 }
15503
15504 @* \[34] Iterations.
15505 To bring our treatment of |get_x_next| to a close, we need to consider what
15506 \MP\ does when it sees \&{for}, \&{forsuffixes}, and \&{forever}.
15507
15508 There's a global variable |loop_ptr| that keeps track of the \&{for} loops
15509 that are currently active. If |loop_ptr=null|, no loops are in progress;
15510 otherwise |mp_info(loop_ptr)| points to the iterative text of the current
15511 (innermost) loop, and |mp_link(loop_ptr)| points to the data for any other
15512 loops that enclose the current one.
15513
15514 A loop-control node also has two other fields, called |loop_type| and
15515 |loop_list|, whose contents depend on the type of loop:
15516
15517 \yskip\indent|loop_type(loop_ptr)=null| means that |loop_list(loop_ptr)|
15518 points to a list of one-word nodes whose |info| fields point to the
15519 remaining argument values of a suffix list and expression list.
15520
15521 \yskip\indent|loop_type(loop_ptr)=mp_void| means that the current loop is
15522 `\&{forever}'.
15523
15524 \yskip\indent|loop_type(loop_ptr)=progression_flag| means that
15525 |p=loop_list(loop_ptr)| points to a ``progression node'' and |value(p)|,
15526 |step_size(p)|, and |final_value(p)| contain the data for an arithmetic
15527 progression.
15528
15529 \yskip\indent|loop_type(loop_ptr)=p>mp_void| means that |p| points to an edge
15530 header and |loop_list(loop_ptr)| points into the graphical object list for
15531 that edge header.
15532
15533 \yskip\noindent In the case of a progression node, the first word is not used
15534 because the link field of words in the dynamic memory area cannot be arbitrary.
15535
15536 @d loop_list_loc(A) ((A)+1) /* where the |loop_list| field resides */
15537 @d loop_type(A) mp_info(loop_list_loc((A))) /* the type of \&{for} loop */
15538 @d loop_list(A) mp_link(loop_list_loc((A))) /* the remaining list elements */
15539 @d loop_node_size 2 /* the number of words in a loop control node */
15540 @d progression_node_size 4 /* the number of words in a progression node */
15541 @d step_size(A) mp->mem[(A)+2].sc /* the step size in an arithmetic progression */
15542 @d final_value(A) mp->mem[(A)+3].sc /* the final value in an arithmetic progression */
15543 @d progression_flag (null+2)
15544   /* |loop_type| value when |loop_list| points to a progression node */
15545
15546 @<Glob...@>=
15547 pointer loop_ptr; /* top of the loop-control-node stack */
15548
15549 @ @<Set init...@>=
15550 mp->loop_ptr=null;
15551
15552 @ If the expressions that define an arithmetic progression in
15553 a \&{for} loop don't have known numeric values, the |bad_for|
15554 subroutine screams at the user.
15555
15556 @c 
15557 static void mp_bad_for (MP mp, const char * s) {
15558   mp_disp_err(mp, null,"Improper "); /* show the bad expression above the message */
15559 @.Improper...replaced by 0@>
15560   mp_print(mp, s); mp_print(mp, " has been replaced by 0");
15561   help4("When you say `for x=a step b until c',",
15562     "the initial value `a' and the step size `b'",
15563     "and the final value `c' must have known numeric values.",
15564     "I'm zeroing this one. Proceed, with fingers crossed.");
15565   mp_put_get_flush_error(mp, 0);
15566 }
15567
15568 @ Here's what \MP\ does when \&{for}, \&{forsuffixes}, or \&{forever}
15569 has just been scanned. (This code requires slight familiarity with
15570 expression-parsing routines that we have not yet discussed; but it seems
15571 to belong in the present part of the program, even though the original author
15572 didn't write it until later. The reader may wish to come back to it.)
15573
15574 @c void mp_begin_iteration (MP mp) {
15575   halfword m; /* |expr_base| (\&{for}) or |suffix_base| (\&{forsuffixes}) */
15576   halfword n; /* hash address of the current symbol */
15577   pointer s; /* the new loop-control node */
15578   pointer p; /* substitution list for |scan_toks| */
15579   pointer q;  /* link manipulation register */
15580   pointer pp; /* a new progression node */
15581   m=mp->cur_mod; n=mp->cur_sym; s=mp_get_node(mp, loop_node_size);
15582   if ( m==start_forever ){ 
15583     loop_type(s)=mp_void; p=null; mp_get_x_next(mp);
15584   } else { 
15585     mp_get_symbol(mp); p=mp_get_node(mp, token_node_size);
15586     mp_info(p)=mp->cur_sym; value(p)=m;
15587     mp_get_x_next(mp);
15588     if ( mp->cur_cmd==within_token ) {
15589       @<Set up a picture iteration@>;
15590     } else { 
15591       @<Check for the |"="| or |":="| in a loop header@>;
15592       @<Scan the values to be used in the loop@>;
15593     }
15594   }
15595   @<Check for the presence of a colon@>;
15596   @<Scan the loop text and put it on the loop control stack@>;
15597   mp_resume_iteration(mp);
15598 }
15599
15600 @ @<Check for the |"="| or |":="| in a loop header@>=
15601 if ( (mp->cur_cmd!=equals)&&(mp->cur_cmd!=assignment) ) { 
15602   mp_missing_err(mp, "=");
15603 @.Missing `='@>
15604   help3("The next thing in this loop should have been `=' or `:='.",
15605     "But don't worry; I'll pretend that an equals sign",
15606     "was present, and I'll look for the values next.");
15607   mp_back_error(mp);
15608 }
15609
15610 @ @<Check for the presence of a colon@>=
15611 if ( mp->cur_cmd!=colon ) { 
15612   mp_missing_err(mp, ":");
15613 @.Missing `:'@>
15614   help3("The next thing in this loop should have been a `:'.",
15615     "So I'll pretend that a colon was present;",
15616     "everything from here to `endfor' will be iterated.");
15617   mp_back_error(mp);
15618 }
15619
15620 @ We append a special |frozen_repeat_loop| token in place of the
15621 `\&{endfor}' at the end of the loop. This will come through \MP's scanner
15622 at the proper time to cause the loop to be repeated.
15623
15624 (If the user tries some shenanigan like `\&{for} $\ldots$ \&{let} \&{endfor}',
15625 he will be foiled by the |get_symbol| routine, which keeps frozen
15626 tokens unchanged. Furthermore the |frozen_repeat_loop| is an \&{outer}
15627 token, so it won't be lost accidentally.)
15628
15629 @ @<Scan the loop text...@>=
15630 q=mp_get_avail(mp); mp_info(q)=frozen_repeat_loop;
15631 mp->scanner_status=loop_defining; mp->warning_info=n;
15632 mp_info(s)=mp_scan_toks(mp, iteration,p,q,0); mp->scanner_status=normal;
15633 mp_link(s)=mp->loop_ptr; mp->loop_ptr=s
15634
15635 @ @<Initialize table...@>=
15636 eq_type(frozen_repeat_loop)=repeat_loop+outer_tag;
15637 text(frozen_repeat_loop)=intern(" ENDFOR");
15638
15639 @ The loop text is inserted into \MP's scanning apparatus by the
15640 |resume_iteration| routine.
15641
15642 @c void mp_resume_iteration (MP mp) {
15643   pointer p,q; /* link registers */
15644   p=loop_type(mp->loop_ptr);
15645   if ( p==progression_flag ) { 
15646     p=loop_list(mp->loop_ptr); /* now |p| points to a progression node */
15647     mp->cur_exp=value(p);
15648     if ( @<The arithmetic progression has ended@> ) {
15649       mp_stop_iteration(mp);
15650       return;
15651     }
15652     mp->cur_type=mp_known; q=mp_stash_cur_exp(mp); /* make |q| an \&{expr} argument */
15653     value(p)=mp->cur_exp+step_size(p); /* set |value(p)| for the next iteration */
15654   } else if ( p==null ) { 
15655     p=loop_list(mp->loop_ptr);
15656     if ( p==null ) {
15657       mp_stop_iteration(mp);
15658       return;
15659     }
15660     loop_list(mp->loop_ptr)=mp_link(p); q=mp_info(p); free_avail(p);
15661   } else if ( p==mp_void ) { 
15662     mp_begin_token_list(mp, mp_info(mp->loop_ptr),forever_text); return;
15663   } else {
15664     @<Make |q| a capsule containing the next picture component from
15665       |loop_list(loop_ptr)| or |goto not_found|@>;
15666   }
15667   mp_begin_token_list(mp, mp_info(mp->loop_ptr),loop_text);
15668   mp_stack_argument(mp, q);
15669   if ( mp->internal[mp_tracing_commands]>unity ) {
15670      @<Trace the start of a loop@>;
15671   }
15672   return;
15673 NOT_FOUND:
15674   mp_stop_iteration(mp);
15675 }
15676
15677 @ @<The arithmetic progression has ended@>=
15678 ((step_size(p)>0)&&(mp->cur_exp>final_value(p)))||
15679  ((step_size(p)<0)&&(mp->cur_exp<final_value(p)))
15680
15681 @ @<Trace the start of a loop@>=
15682
15683   mp_begin_diagnostic(mp); mp_print_nl(mp, "{loop value=");
15684 @.loop value=n@>
15685   if ( (q!=null)&&(mp_link(q)==mp_void) ) mp_print_exp(mp, q,1);
15686   else mp_show_token_list(mp, q,null,50,0);
15687   mp_print_char(mp, xord('}')); mp_end_diagnostic(mp, false);
15688 }
15689
15690 @ @<Make |q| a capsule containing the next picture component from...@>=
15691 { q=loop_list(mp->loop_ptr);
15692   if ( q==null ) goto NOT_FOUND;
15693   skip_component(q) goto NOT_FOUND;
15694   mp->cur_exp=mp_copy_objects(mp, loop_list(mp->loop_ptr),q);
15695   mp_init_bbox(mp, mp->cur_exp);
15696   mp->cur_type=mp_picture_type;
15697   loop_list(mp->loop_ptr)=q;
15698   q=mp_stash_cur_exp(mp);
15699 }
15700
15701 @ A level of loop control disappears when |resume_iteration| has decided
15702 not to resume, or when an \&{exitif} construction has removed the loop text
15703 from the input stack.
15704
15705 @c void mp_stop_iteration (MP mp) {
15706   pointer p,q; /* the usual */
15707   p=loop_type(mp->loop_ptr);
15708   if ( p==progression_flag )  {
15709     mp_free_node(mp, loop_list(mp->loop_ptr),progression_node_size);
15710   } else if ( p==null ){ 
15711     q=loop_list(mp->loop_ptr);
15712     while ( q!=null ) {
15713       p=mp_info(q);
15714       if ( p!=null ) {
15715         if ( mp_link(p)==mp_void ) { /* it's an \&{expr} parameter */
15716           mp_recycle_value(mp, p); mp_free_node(mp, p,value_node_size);
15717         } else {
15718           mp_flush_token_list(mp, p); /* it's a \&{suffix} or \&{text} parameter */
15719         }
15720       }
15721       p=q; q=mp_link(q); free_avail(p);
15722     }
15723   } else if ( p>progression_flag ) {
15724     delete_edge_ref(p);
15725   }
15726   p=mp->loop_ptr; mp->loop_ptr=mp_link(p); mp_flush_token_list(mp, mp_info(p));
15727   mp_free_node(mp, p,loop_node_size);
15728 }
15729
15730 @ Now that we know all about loop control, we can finish up
15731 the missing portion of |begin_iteration| and we'll be done.
15732
15733 The following code is performed after the `\.=' has been scanned in
15734 a \&{for} construction (if |m=expr_base|) or a \&{forsuffixes} construction
15735 (if |m=suffix_base|).
15736
15737 @<Scan the values to be used in the loop@>=
15738 loop_type(s)=null; q=loop_list_loc(s); mp_link(q)=null; /* |mp_link(q)=loop_list(s)| */
15739 do {  
15740   mp_get_x_next(mp);
15741   if ( m!=expr_base ) {
15742     mp_scan_suffix(mp);
15743   } else { 
15744     if ( mp->cur_cmd>=colon ) if ( mp->cur_cmd<=comma ) 
15745           goto CONTINUE;
15746     mp_scan_expression(mp);
15747     if ( mp->cur_cmd==step_token ) if ( q==loop_list_loc(s) ) {
15748       @<Prepare for step-until construction and |break|@>;
15749     }
15750     mp->cur_exp=mp_stash_cur_exp(mp);
15751   }
15752   mp_link(q)=mp_get_avail(mp); q=mp_link(q); 
15753   mp_info(q)=mp->cur_exp; mp->cur_type=mp_vacuous;
15754 CONTINUE:
15755   ;
15756 } while (mp->cur_cmd==comma)
15757
15758 @ @<Prepare for step-until construction and |break|@>=
15759
15760   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "initial value");
15761   pp=mp_get_node(mp, progression_node_size); value(pp)=mp->cur_exp;
15762   mp_get_x_next(mp); mp_scan_expression(mp);
15763   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "step size");
15764   step_size(pp)=mp->cur_exp;
15765   if ( mp->cur_cmd!=until_token ) { 
15766     mp_missing_err(mp, "until");
15767 @.Missing `until'@>
15768     help2("I assume you meant to say `until' after `step'.",
15769           "So I'll look for the final value and colon next.");
15770     mp_back_error(mp);
15771   }
15772   mp_get_x_next(mp); mp_scan_expression(mp);
15773   if ( mp->cur_type!=mp_known ) mp_bad_for(mp, "final value");
15774   final_value(pp)=mp->cur_exp; loop_list(s)=pp;
15775   loop_type(s)=progression_flag; 
15776   break;
15777 }
15778
15779 @ The last case is when we have just seen ``\&{within}'', and we need to
15780 parse a picture expression and prepare to iterate over it.
15781
15782 @<Set up a picture iteration@>=
15783 { mp_get_x_next(mp);
15784   mp_scan_expression(mp);
15785   @<Make sure the current expression is a known picture@>;
15786   loop_type(s)=mp->cur_exp; mp->cur_type=mp_vacuous;
15787   q=mp_link(dummy_loc(mp->cur_exp));
15788   if ( q!= null ) 
15789     if ( is_start_or_stop(q) )
15790       if ( mp_skip_1component(mp, q)==null ) q=mp_link(q);
15791   loop_list(s)=q;
15792 }
15793
15794 @ @<Make sure the current expression is a known picture@>=
15795 if ( mp->cur_type!=mp_picture_type ) {
15796   mp_disp_err(mp, null,"Improper iteration spec has been replaced by nullpicture");
15797   help1("When you say `for x in p', p must be a known picture.");
15798   mp_put_get_flush_error(mp, mp_get_node(mp, edge_header_size));
15799   mp_init_edges(mp, mp->cur_exp); mp->cur_type=mp_picture_type;
15800 }
15801
15802 @* \[35] File names.
15803 It's time now to fret about file names.  Besides the fact that different
15804 operating systems treat files in different ways, we must cope with the
15805 fact that completely different naming conventions are used by different
15806 groups of people. The following programs show what is required for one
15807 particular operating system; similar routines for other systems are not
15808 difficult to devise.
15809 @^system dependencies@>
15810
15811 \MP\ assumes that a file name has three parts: the name proper; its
15812 ``extension''; and a ``file area'' where it is found in an external file
15813 system.  The extension of an input file is assumed to be
15814 `\.{.mp}' unless otherwise specified; it is `\.{.log}' on the
15815 transcript file that records each run of \MP; it is `\.{.tfm}' on the font
15816 metric files that describe characters in any fonts created by \MP; it is
15817 `\.{.ps}' or `.{\it nnn}' for some number {\it nnn} on the \ps\ output files;
15818 and it is `\.{.mem}' on the mem files written by \.{INIMP} to initialize \MP.
15819 The file area can be arbitrary on input files, but files are usually
15820 output to the user's current area.  If an input file cannot be
15821 found on the specified area, \MP\ will look for it on a special system
15822 area; this special area is intended for commonly used input files.
15823
15824 Simple uses of \MP\ refer only to file names that have no explicit
15825 extension or area. For example, a person usually says `\.{input} \.{cmr10}'
15826 instead of `\.{input} \.{cmr10.new}'. Simple file
15827 names are best, because they make the \MP\ source files portable;
15828 whenever a file name consists entirely of letters and digits, it should be
15829 treated in the same way by all implementations of \MP. However, users
15830 need the ability to refer to other files in their environment, especially
15831 when responding to error messages concerning unopenable files; therefore
15832 we want to let them use the syntax that appears in their favorite
15833 operating system.
15834
15835 @ \MP\ uses the same conventions that have proved to be satisfactory for
15836 \TeX\ and \MF. In order to isolate the system-dependent aspects of file names,
15837 @^system dependencies@>
15838 the system-independent parts of \MP\ are expressed in terms
15839 of three system-dependent
15840 procedures called |begin_name|, |more_name|, and |end_name|. In
15841 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
15842 the system-independent driver program does the operations
15843 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
15844 \,|end_name|.$$
15845 These three procedures communicate with each other via global variables.
15846 Afterwards the file name will appear in the string pool as three strings
15847 called |cur_name|\penalty10000\hskip-.05em,
15848 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
15849 |""|), unless they were explicitly specified by the user.
15850
15851 Actually the situation is slightly more complicated, because \MP\ needs
15852 to know when the file name ends. The |more_name| routine is a function
15853 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
15854 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
15855 returns |false|; or, it returns |true| and $c_n$ is the last character
15856 on the current input line. In other words,
15857 |more_name| is supposed to return |true| unless it is sure that the
15858 file name has been completely scanned; and |end_name| is supposed to be able
15859 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
15860 whether $|more_name|(c_n)$ returned |true| or |false|.
15861
15862 @<Glob...@>=
15863 char * cur_name; /* name of file just scanned */
15864 char * cur_area; /* file area just scanned, or \.{""} */
15865 char * cur_ext; /* file extension just scanned, or \.{""} */
15866
15867 @ It is easier to maintain reference counts if we assign initial values.
15868
15869 @<Set init...@>=
15870 mp->cur_name=xstrdup(""); 
15871 mp->cur_area=xstrdup(""); 
15872 mp->cur_ext=xstrdup("");
15873
15874 @ @<Dealloc variables@>=
15875 xfree(mp->cur_area);
15876 xfree(mp->cur_name);
15877 xfree(mp->cur_ext);
15878
15879 @ The file names we shall deal with for illustrative purposes have the
15880 following structure:  If the name contains `\.>' or `\.:', the file area
15881 consists of all characters up to and including the final such character;
15882 otherwise the file area is null.  If the remaining file name contains
15883 `\..', the file extension consists of all such characters from the first
15884 remaining `\..' to the end, otherwise the file extension is null.
15885 @^system dependencies@>
15886
15887 We can scan such file names easily by using two global variables that keep track
15888 of the occurrences of area and extension delimiters.  Note that these variables
15889 cannot be of type |pool_pointer| because a string pool compaction could occur
15890 while scanning a file name.
15891
15892 @<Glob...@>=
15893 integer area_delimiter;
15894   /* most recent `\.>' or `\.:' relative to |str_start[str_ptr]| */
15895 integer ext_delimiter; /* the relevant `\..', if any */
15896
15897 @ Here now is the first of the system-dependent routines for file name scanning.
15898 @^system dependencies@>
15899
15900 The file name length is limited to |file_name_size|. That is good, because
15901 in the current configuration we cannot call |mp_do_compaction| while a name 
15902 is being scanned, |mp->area_delimiter| and |mp->ext_delimiter| are direct
15903 offsets into |mp->str_pool|. I am not in a great hurry to fix this, because 
15904 calling |str_room()| just once is more efficient anyway. TODO.
15905
15906 @<Declarations@>=
15907 static void mp_begin_name (MP mp);
15908 static boolean mp_more_name (MP mp, ASCII_code c);
15909 static void mp_end_name (MP mp);
15910
15911 @ @c
15912 void mp_begin_name (MP mp) { 
15913   xfree(mp->cur_name); 
15914   xfree(mp->cur_area); 
15915   xfree(mp->cur_ext);
15916   mp->area_delimiter=-1; 
15917   mp->ext_delimiter=-1;
15918   str_room(file_name_size); 
15919 }
15920
15921 @ And here's the second.
15922 @^system dependencies@>
15923
15924 @c 
15925 boolean mp_more_name (MP mp, ASCII_code c) {
15926   if (c==' ') {
15927     return false;
15928   } else { 
15929     if ( (c=='>')||(c==':') ) { 
15930       mp->area_delimiter=mp->pool_ptr; 
15931       mp->ext_delimiter=-1;
15932     } else if ( (c=='.')&&(mp->ext_delimiter<0) ) {
15933       mp->ext_delimiter=mp->pool_ptr;
15934     }
15935     append_char(c); /* contribute |c| to the current string */
15936     return true;
15937   }
15938 }
15939
15940 @ The third.
15941 @^system dependencies@>
15942
15943 @d copy_pool_segment(A,B,C) { 
15944       A = xmalloc(C+1,sizeof(char)); 
15945       strncpy(A,(char *)(mp->str_pool+B),C);  
15946       A[C] = 0;}
15947
15948 @c
15949 void mp_end_name (MP mp) {
15950   pool_pointer s; /* length of area, name, and extension */
15951   unsigned int len;
15952   /* "my/w.mp" */
15953   s = mp->str_start[mp->str_ptr];
15954   if ( mp->area_delimiter<0 ) {    
15955     mp->cur_area=xstrdup("");
15956   } else {
15957     len = (unsigned)(mp->area_delimiter-s); 
15958     copy_pool_segment(mp->cur_area,s,len);
15959     s += len+1;
15960   }
15961   if ( mp->ext_delimiter<0 ) {
15962     mp->cur_ext=xstrdup("");
15963     len = (unsigned)(mp->pool_ptr-s); 
15964   } else {
15965     copy_pool_segment(mp->cur_ext,mp->ext_delimiter,(size_t)(mp->pool_ptr-mp->ext_delimiter));
15966     len = (unsigned)(mp->ext_delimiter-s);
15967   }
15968   copy_pool_segment(mp->cur_name,s,len);
15969   mp->pool_ptr=s; /* don't need this partial string */
15970 }
15971
15972 @ Conversely, here is a routine that takes three strings and prints a file
15973 name that might have produced them. (The routine is system dependent, because
15974 some operating systems put the file area last instead of first.)
15975 @^system dependencies@>
15976
15977 @<Basic printing...@>=
15978 static void mp_print_file_name (MP mp, char * n, char * a, char * e) { 
15979   mp_print(mp, a); mp_print(mp, n); mp_print(mp, e);
15980 }
15981
15982 @ Another system-dependent routine is needed to convert three internal
15983 \MP\ strings
15984 to the |name_of_file| value that is used to open files. The present code
15985 allows both lowercase and uppercase letters in the file name.
15986 @^system dependencies@>
15987
15988 @d append_to_name(A) { c=xord((int)(A)); 
15989   if ( k<file_name_size ) {
15990     mp->name_of_file[k]=(char)xchr(c);
15991     incr(k);
15992   }
15993 }
15994
15995 @ @c
15996 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) {
15997   integer k; /* number of positions filled in |name_of_file| */
15998   ASCII_code c; /* character being packed */
15999   const char *j; /* a character  index */
16000   k=0;
16001   assert(n!=NULL);
16002   if (a!=NULL) {
16003     for (j=a;*j!='\0';j++) { append_to_name(*j); }
16004   }
16005   for (j=n;*j!='\0';j++) { append_to_name(*j); }
16006   if (e!=NULL) {
16007     for (j=e;*j!='\0';j++) { append_to_name(*j); }
16008   }
16009   mp->name_of_file[k]=0;
16010   mp->name_length=k; 
16011 }
16012
16013 @ @<Internal library declarations@>=
16014 void mp_pack_file_name (MP mp, const char *n, const char *a, const char *e) ;
16015
16016 @ @<Option variables@>=
16017 char *mem_name; /* for commandline */
16018
16019 @ @<Find constant sizes@>=
16020 mp->mem_name = xstrdup(opt->mem_name);
16021 if (mp->mem_name) {
16022   size_t l = strlen(mp->mem_name);
16023   if (l>4) {
16024     char *test = strstr(mp->mem_name,".mem");
16025     if (test == mp->mem_name+l-4) {
16026       *test = 0;
16027     }
16028   }
16029 }
16030
16031
16032 @ @<Dealloc variables@>=
16033 xfree(mp->mem_name);
16034
16035 @ This part of the program becomes active when a ``virgin'' \MP\ is
16036 trying to get going, just after the preliminary initialization, or
16037 when the user is substituting another mem file by typing `\.\&' after
16038 the initial `\.{**}' prompt.  The buffer contains the first line of
16039 input in |buffer[loc..(last-1)]|, where |loc<last| and |buffer[loc]<>""|.
16040
16041 @<Declarations@>=
16042 static boolean mp_open_mem_name (MP mp) ;
16043 static boolean mp_open_mem_file (MP mp) ;
16044
16045 @ @c
16046 boolean mp_open_mem_name (MP mp) {
16047   if (mp->mem_name!=NULL) {
16048     size_t l = strlen(mp->mem_name);
16049     char *s = xstrdup (mp->mem_name);
16050     if (l>4) {
16051       char *test = strstr(s,".mem");
16052       if (test == NULL || test != s+l-4) {
16053         s = xrealloc (s, l+5, 1);       
16054         strcat (s, ".mem");
16055       }
16056     } else {
16057       s = xrealloc (s, l+5, 1);
16058       strcat (s, ".mem");
16059     }
16060     mp->mem_file = (mp->open_file)(mp,s, "r", mp_filetype_memfile);
16061     xfree(s);
16062     if ( mp->mem_file ) return true;
16063   }
16064   return false;
16065 }
16066 boolean mp_open_mem_file (MP mp) {
16067   if (mp->mem_file != NULL)
16068     return true;
16069   if (mp_open_mem_name(mp)) 
16070     return true;
16071   if (mp_xstrcmp(mp->mem_name, "plain")) {
16072     wake_up_terminal;
16073     wterm_ln("Sorry, I can\'t find that mem file; will try PLAIN.");
16074 @.Sorry, I can't find...@>
16075     update_terminal;
16076     /* now pull out all the stops: try for the system \.{plain} file */
16077     xfree(mp->mem_name);
16078     mp->mem_name = xstrdup("plain");
16079     if (mp_open_mem_name(mp))
16080       return true;
16081   }
16082   wake_up_terminal;
16083   wterm_ln("I can\'t find the PLAIN mem file!");
16084 @.I can't find PLAIN...@>
16085 @.plain@>
16086   return false;
16087 }
16088
16089 @ Operating systems often make it possible to determine the exact name (and
16090 possible version number) of a file that has been opened. The following routine,
16091 which simply makes a \MP\ string from the value of |name_of_file|, should
16092 ideally be changed to deduce the full name of file~|f|, which is the file
16093 most recently opened, if it is possible to do this.
16094 @^system dependencies@>
16095
16096 @<Declarations@>=
16097 #define mp_a_make_name_string(A,B)  mp_make_name_string(A)
16098 #define mp_b_make_name_string(A,B)  mp_make_name_string(A)
16099 #define mp_w_make_name_string(A,B)  mp_make_name_string(A)
16100
16101 @ @c 
16102 static str_number mp_make_name_string (MP mp) {
16103   int k; /* index into |name_of_file| */
16104   str_room(mp->name_length);
16105   for (k=0;k<mp->name_length;k++) {
16106     append_char(xord((int)mp->name_of_file[k]));
16107   }
16108   return mp_make_string(mp);
16109 }
16110
16111 @ Now let's consider the ``driver''
16112 routines by which \MP\ deals with file names
16113 in a system-independent manner.  First comes a procedure that looks for a
16114 file name in the input by taking the information from the input buffer.
16115 (We can't use |get_next|, because the conversion to tokens would
16116 destroy necessary information.)
16117
16118 This procedure doesn't allow semicolons or percent signs to be part of
16119 file names, because of other conventions of \MP.
16120 {\sl The {\logos METAFONT\/}book} doesn't
16121 use semicolons or percents immediately after file names, but some users
16122 no doubt will find it natural to do so; therefore system-dependent
16123 changes to allow such characters in file names should probably
16124 be made with reluctance, and only when an entire file name that
16125 includes special characters is ``quoted'' somehow.
16126 @^system dependencies@>
16127
16128 @c 
16129 static void mp_scan_file_name (MP mp) { 
16130   mp_begin_name(mp);
16131   while ( mp->buffer[loc]==' ' ) incr(loc);
16132   while (1) { 
16133     if ( (mp->buffer[loc]==';')||(mp->buffer[loc]=='%') ) break;
16134     if ( ! mp_more_name(mp, mp->buffer[loc]) ) break;
16135     incr(loc);
16136   }
16137   mp_end_name(mp);
16138 }
16139
16140 @ Here is another version that takes its input from a string.
16141
16142 @<Declare subroutines for parsing file names@>=
16143 void mp_str_scan_file (MP mp,  str_number s) ;
16144
16145 @ @c
16146 void mp_str_scan_file (MP mp,  str_number s) {
16147   pool_pointer p,q; /* current position and stopping point */
16148   mp_begin_name(mp);
16149   p=mp->str_start[s]; q=str_stop(s);
16150   while ( p<q ){ 
16151     if ( ! mp_more_name(mp, mp->str_pool[p]) ) break;
16152     incr(p);
16153   }
16154   mp_end_name(mp);
16155 }
16156
16157 @ And one that reads from a |char*|.
16158
16159 @<Declare subroutines for parsing file names@>=
16160 extern void mp_ptr_scan_file (MP mp,  char *s);
16161
16162 @ @c
16163 void mp_ptr_scan_file (MP mp,  char *s) {
16164   char *p, *q; /* current position and stopping point */
16165   mp_begin_name(mp);
16166   p=s; q=p+strlen(s);
16167   while ( p<q ){ 
16168     if ( ! mp_more_name(mp, xord((int)(*p)))) break;
16169     p++;
16170   }
16171   mp_end_name(mp);
16172 }
16173
16174
16175 @ The global variable |job_name| contains the file name that was first
16176 \&{input} by the user. This name is extended by `\.{.log}' and `\.{ps}' and
16177 `\.{.mem}' and `\.{.tfm}' in order to make the names of \MP's output files.
16178
16179 @<Glob...@>=
16180 boolean log_opened; /* has the transcript file been opened? */
16181 char *log_name; /* full name of the log file */
16182
16183 @ @<Option variables@>=
16184 char *job_name; /* principal file name */
16185
16186 @ Initially |job_name=NULL|; it becomes nonzero as soon as the true name is known.
16187 We have |job_name=NULL| if and only if the `\.{log}' file has not been opened,
16188 except of course for a short time just after |job_name| has become nonzero.
16189
16190 @<Allocate or ...@>=
16191 mp->job_name=mp_xstrdup(mp, opt->job_name); 
16192 if (opt->noninteractive && opt->ini_version) {
16193   if (mp->job_name == NULL)
16194     mp->job_name=mp_xstrdup(mp,mp->mem_name); 
16195   if (mp->job_name != NULL) {
16196     size_t l = strlen(mp->job_name);
16197     if (l>4) {
16198       char *test = strstr(mp->job_name,".mem");
16199       if (test == mp->job_name+l-4)
16200         *test = 0;
16201     }
16202   }
16203 }
16204 mp->log_opened=false;
16205
16206 @ @<Dealloc variables@>=
16207 xfree(mp->job_name);
16208
16209 @ Here is a routine that manufactures the output file names, assuming that
16210 |job_name<>0|. It ignores and changes the current settings of |cur_area|
16211 and |cur_ext|.
16212
16213 @d pack_cur_name mp_pack_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext)
16214
16215 @<Internal library ...@>=
16216 void mp_pack_job_name (MP mp, const char *s) ;
16217
16218 @ @c 
16219 void mp_pack_job_name (MP mp, const char  *s) { /* |s = ".log"|, |".mem"|, |".ps"|, or .\\{nnn} */
16220   xfree(mp->cur_name); mp->cur_name=xstrdup(mp->job_name);
16221   xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16222   xfree(mp->cur_ext);  mp->cur_ext=xstrdup(s);
16223   pack_cur_name;
16224 }
16225
16226 @ If some trouble arises when \MP\ tries to open a file, the following
16227 routine calls upon the user to supply another file name. Parameter~|s|
16228 is used in the error message to identify the type of file; parameter~|e|
16229 is the default extension if none is given. Upon exit from the routine,
16230 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
16231 ready for another attempt at file opening.
16232
16233 @<Internal library ...@>=
16234 void mp_prompt_file_name (MP mp, const char * s, const char * e) ;
16235
16236 @ @c void mp_prompt_file_name (MP mp, const char * s, const char * e) {
16237   size_t k; /* index into |buffer| */
16238   char * saved_cur_name;
16239   if ( mp->interaction==mp_scroll_mode ) 
16240         wake_up_terminal;
16241   if (strcmp(s,"input file name")==0) {
16242         print_err("I can\'t find file `");
16243 @.I can't find file x@>
16244   } else {
16245         print_err("I can\'t write on file `");
16246 @.I can't write on file x@>
16247   }
16248   mp_print_file_name(mp, mp->cur_name,mp->cur_area,mp->cur_ext); 
16249   mp_print(mp, "'.");
16250   if (strcmp(e,"")==0) 
16251         mp_show_context(mp);
16252   mp_print_nl(mp, "Please type another "); mp_print(mp, s);
16253 @.Please type...@>
16254   if (mp->noninteractive || mp->interaction<mp_scroll_mode )
16255     mp_fatal_error(mp, "*** (job aborted, file error in nonstop mode)");
16256 @.job aborted, file error...@>
16257   saved_cur_name = xstrdup(mp->cur_name);
16258   clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
16259   if (strcmp(mp->cur_ext,"")==0) 
16260         mp->cur_ext=xstrdup(e);
16261   if (strlen(mp->cur_name)==0) {
16262     mp->cur_name=saved_cur_name;
16263   } else {
16264     xfree(saved_cur_name);
16265   }
16266   pack_cur_name;
16267 }
16268
16269 @ @<Scan file name in the buffer@>=
16270
16271   mp_begin_name(mp); k=mp->first;
16272   while ( (mp->buffer[k]==' ')&&(k<mp->last) ) incr(k);
16273   while (1) { 
16274     if ( k==mp->last ) break;
16275     if ( ! mp_more_name(mp, mp->buffer[k]) ) break;
16276     incr(k);
16277   }
16278   mp_end_name(mp);
16279 }
16280
16281 @ The |open_log_file| routine is used to open the transcript file and to help
16282 it catch up to what has previously been printed on the terminal.
16283
16284 @c void mp_open_log_file (MP mp) {
16285   unsigned old_setting; /* previous |selector| setting */
16286   int k; /* index into |months| and |buffer| */
16287   int l; /* end of first input line */
16288   integer m; /* the current month */
16289   const char *months="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; 
16290     /* abbreviations of month names */
16291   old_setting=mp->selector;
16292   if ( mp->job_name==NULL ) {
16293      mp->job_name=xstrdup("mpout");
16294   }
16295   mp_pack_job_name(mp,".log");
16296   while ( ! mp_a_open_out(mp, &mp->log_file, mp_filetype_log) ) {
16297     @<Try to get a different log file name@>;
16298   }
16299   mp->log_name=xstrdup(mp->name_of_file);
16300   mp->selector=log_only; mp->log_opened=true;
16301   @<Print the banner line, including the date and time@>;
16302   mp->input_stack[mp->input_ptr]=mp->cur_input; 
16303     /* make sure bottom level is in memory */
16304   if (!mp->noninteractive) {
16305     mp_print_nl(mp, "**");
16306 @.**@>
16307     l=mp->input_stack[0].limit_field-1; /* last position of first line */
16308     for (k=0;k<=l;k++) mp_print_str(mp, mp->buffer[k]);
16309     mp_print_ln(mp); /* now the transcript file contains the first line of input */
16310   }
16311   mp->selector=old_setting+2; /* |log_only| or |term_and_log| */
16312 }
16313
16314 @ @<Dealloc variables@>=
16315 xfree(mp->log_name);
16316
16317 @ Sometimes |open_log_file| is called at awkward moments when \MP\ is
16318 unable to print error messages or even to |show_context|.
16319 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
16320 routine will not be invoked because |log_opened| will be false.
16321
16322 The normal idea of |mp_batch_mode| is that nothing at all should be written
16323 on the terminal. However, in the unusual case that
16324 no log file could be opened, we make an exception and allow
16325 an explanatory message to be seen.
16326
16327 Incidentally, the program always refers to the log file as a `\.{transcript
16328 file}', because some systems cannot use the extension `\.{.log}' for
16329 this file.
16330
16331 @<Try to get a different log file name@>=
16332 {  
16333   mp->selector=term_only;
16334   mp_prompt_file_name(mp, "transcript file name",".log");
16335 }
16336
16337 @ @<Print the banner...@>=
16338
16339   wlog(mp->banner);
16340   mp_print(mp, mp->mem_ident); mp_print(mp, "  ");
16341   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_day])); 
16342   mp_print_char(mp, xord(' '));
16343   m=mp_round_unscaled(mp, mp->internal[mp_month]);
16344   for (k=3*m-3;k<3*m;k++) { wlog_chr((unsigned char)months[k]); }
16345   mp_print_char(mp, xord(' ')); 
16346   mp_print_int(mp, mp_round_unscaled(mp, mp->internal[mp_year])); 
16347   mp_print_char(mp, xord(' '));
16348   m=mp_round_unscaled(mp, mp->internal[mp_time]);
16349   mp_print_dd(mp, m / 60); mp_print_char(mp, xord(':')); mp_print_dd(mp, m % 60);
16350 }
16351
16352 @ The |try_extension| function tries to open an input file determined by
16353 |cur_name|, |cur_area|, and the argument |ext|.  It returns |false| if it
16354 can't find the file in |cur_area| or the appropriate system area.
16355
16356 @c
16357 static boolean mp_try_extension (MP mp, const char *ext) { 
16358   mp_pack_file_name(mp, mp->cur_name,mp->cur_area, ext);
16359   in_name=xstrdup(mp->cur_name); 
16360   in_area=xstrdup(mp->cur_area);
16361   if ( mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16362     return true;
16363   } else { 
16364     mp_pack_file_name(mp, mp->cur_name,NULL,ext);
16365     return mp_a_open_in(mp, &cur_file, mp_filetype_program);
16366   }
16367 }
16368
16369 @ Let's turn now to the procedure that is used to initiate file reading
16370 when an `\.{input}' command is being processed.
16371
16372 @c void mp_start_input (MP mp) { /* \MP\ will \.{input} something */
16373   char *fname = NULL;
16374   @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>;
16375   while (1) { 
16376     mp_begin_file_reading(mp); /* set up |cur_file| and new level of input */
16377     if ( strlen(mp->cur_ext)==0 ) {
16378       if ( mp_try_extension(mp, ".mp") ) break;
16379       else if ( mp_try_extension(mp, "") ) break;
16380       else if ( mp_try_extension(mp, ".mf") ) break;
16381       /* |else do_nothing; | */
16382     } else if ( mp_try_extension(mp, mp->cur_ext) ) {
16383       break;
16384     }
16385     mp_end_file_reading(mp); /* remove the level that didn't work */
16386     mp_prompt_file_name(mp, "input file name","");
16387   }
16388   name=mp_a_make_name_string(mp, cur_file);
16389   fname = xstrdup(mp->name_of_file);
16390   if ( mp->job_name==NULL ) {
16391     mp->job_name=xstrdup(mp->cur_name); 
16392     mp_open_log_file(mp);
16393   } /* |open_log_file| doesn't |show_context|, so |limit|
16394         and |loc| needn't be set to meaningful values yet */
16395   if ( ((int)mp->term_offset+(int)strlen(fname)) > (mp->max_print_line-2)) mp_print_ln(mp);
16396   else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, xord(' '));
16397   mp_print_char(mp, xord('(')); incr(mp->open_parens); mp_print(mp, fname); 
16398   xfree(fname);
16399   update_terminal;
16400   @<Flush |name| and replace it with |cur_name| if it won't be needed@>;
16401   @<Read the first line of the new file@>;
16402 }
16403
16404 @ This code should be omitted if |a_make_name_string| returns something other
16405 than just a copy of its argument and the full file name is needed for opening
16406 \.{MPX} files or implementing the switch-to-editor option.
16407 @^system dependencies@>
16408
16409 @<Flush |name| and replace it with |cur_name| if it won't be needed@>=
16410 mp_flush_string(mp, name); name=rts(mp->cur_name); xfree(mp->cur_name)
16411
16412 @ If the file is empty, it is considered to contain a single blank line,
16413 so there is no need to test the return value.
16414
16415 @<Read the first line...@>=
16416
16417   line=1;
16418   (void)mp_input_ln(mp, cur_file ); 
16419   mp_firm_up_the_line(mp);
16420   mp->buffer[limit]=xord('%'); mp->first=(size_t)(limit+1); loc=start;
16421 }
16422
16423 @ @<Put the desired file name in |(cur_name,cur_ext,cur_area)|@>=
16424 while ( token_state &&(loc==null) ) mp_end_token_list(mp);
16425 if ( token_state ) { 
16426   print_err("File names can't appear within macros");
16427 @.File names can't...@>
16428   help3("Sorry...I've converted what follows to tokens,",
16429     "possibly garbaging the name you gave.",
16430     "Please delete the tokens and insert the name again.");
16431   mp_error(mp);
16432 }
16433 if ( file_state ) {
16434   mp_scan_file_name(mp);
16435 } else { 
16436    xfree(mp->cur_name); mp->cur_name=xstrdup(""); 
16437    xfree(mp->cur_ext);  mp->cur_ext =xstrdup(""); 
16438    xfree(mp->cur_area); mp->cur_area=xstrdup(""); 
16439 }
16440
16441 @ The following simple routine starts reading the \.{MPX} file associated
16442 with the current input file.
16443
16444 @c void mp_start_mpx_input (MP mp) {
16445   char *origname = NULL; /* a copy of nameoffile */
16446   mp_pack_file_name(mp, in_name, in_area, ".mpx");
16447   @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16448     |goto not_found| if there is a problem@>;
16449   mp_begin_file_reading(mp);
16450   if ( ! mp_a_open_in(mp, &cur_file, mp_filetype_program) ) {
16451     mp_end_file_reading(mp);
16452     goto NOT_FOUND;
16453   }
16454   name=mp_a_make_name_string(mp, cur_file);
16455   mp->mpx_name[iindex]=name; add_str_ref(name);
16456   @<Read the first line of the new file@>;
16457   xfree(origname);
16458   return;
16459 NOT_FOUND: 
16460     @<Explain that the \.{MPX} file can't be read and |succumb|@>;
16461   xfree(origname);
16462 }
16463
16464 @ This should ideally be changed to do whatever is necessary to create the
16465 \.{MPX} file given by |name_of_file| if it does not exist or if it is out
16466 of date.  This requires invoking \.{MPtoTeX} on the |origname| and passing
16467 the results through \TeX\ and \.{DVItoMP}.  (It is possible to use a
16468 completely different typesetting program if suitable postprocessor is
16469 available to perform the function of \.{DVItoMP}.)
16470 @^system dependencies@>
16471
16472 @ @<Exported types@>=
16473 typedef int (*mp_makempx_cmd)(MP mp, char *origname, char *mtxname);
16474
16475 @ @<Option variables@>=
16476 mp_makempx_cmd run_make_mpx;
16477
16478 @ @<Allocate or initialize ...@>=
16479 set_callback_option(run_make_mpx);
16480
16481 @ @<Declarations@>=
16482 static int mp_run_make_mpx (MP mp, char *origname, char *mtxname);
16483
16484 @ The default does nothing.
16485 @c 
16486 int mp_run_make_mpx (MP mp, char *origname, char *mtxname) {
16487   (void)mp;
16488   (void)origname;
16489   (void)mtxname;
16490   return false;
16491 }
16492
16493 @ @<Try to make sure |name_of_file| refers to a valid \.{MPX} file and
16494   |goto not_found| if there is a problem@>=
16495 origname = mp_xstrdup(mp,mp->name_of_file);
16496 *(origname+strlen(origname)-1)=0; /* drop the x */
16497 if (!(mp->run_make_mpx)(mp, origname, mp->name_of_file))
16498   goto NOT_FOUND 
16499
16500 @ @<Explain that the \.{MPX} file can't be read and |succumb|@>=
16501 if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16502 mp_print_nl(mp, ">> ");
16503 mp_print(mp, origname);
16504 mp_print_nl(mp, ">> ");
16505 mp_print(mp, mp->name_of_file);
16506 mp_print_nl(mp, "! Unable to make mpx file");
16507 help4("The two files given above are one of your source files",
16508   "and an auxiliary file I need to read to find out what your",
16509   "btex..etex blocks mean. If you don't know why I had trouble,",
16510   "try running it manually through MPtoTeX, TeX, and DVItoMP");
16511 succumb;
16512
16513 @ The last file-opening commands are for files accessed via the \&{readfrom}
16514 @:read_from_}{\&{readfrom} primitive@>
16515 operator and the \&{write} command.  Such files are stored in separate arrays.
16516 @:write_}{\&{write} primitive@>
16517
16518 @<Types in the outer block@>=
16519 typedef unsigned int readf_index; /* |0..max_read_files| */
16520 typedef unsigned int write_index;  /* |0..max_write_files| */
16521
16522 @ @<Glob...@>=
16523 readf_index max_read_files; /* maximum number of simultaneously open \&{readfrom} files */
16524 void ** rd_file; /* \&{readfrom} files */
16525 char ** rd_fname; /* corresponding file name or 0 if file not open */
16526 readf_index read_files; /* number of valid entries in the above arrays */
16527 write_index max_write_files; /* maximum number of simultaneously open \&{write} */
16528 void ** wr_file; /* \&{write} files */
16529 char ** wr_fname; /* corresponding file name or 0 if file not open */
16530 write_index write_files; /* number of valid entries in the above arrays */
16531
16532 @ @<Allocate or initialize ...@>=
16533 mp->max_read_files=8;
16534 mp->rd_file = xmalloc((mp->max_read_files+1),sizeof(void *));
16535 mp->rd_fname = xmalloc((mp->max_read_files+1),sizeof(char *));
16536 memset(mp->rd_fname, 0, sizeof(char *)*(mp->max_read_files+1));
16537 mp->max_write_files=8;
16538 mp->wr_file = xmalloc((mp->max_write_files+1),sizeof(void *));
16539 mp->wr_fname = xmalloc((mp->max_write_files+1),sizeof(char *));
16540 memset(mp->wr_fname, 0, sizeof(char *)*(mp->max_write_files+1));
16541
16542
16543 @ This routine starts reading the file named by string~|s| without setting
16544 |loc|, |limit|, or |name|.  It returns |false| if the file is empty or cannot
16545 be opened.  Otherwise it updates |rd_file[n]| and |rd_fname[n]|.
16546
16547 @c 
16548 static boolean mp_start_read_input (MP mp,char *s, readf_index  n) {
16549   mp_ptr_scan_file(mp, s);
16550   pack_cur_name;
16551   mp_begin_file_reading(mp);
16552   if ( ! mp_a_open_in(mp, &mp->rd_file[n], (int)(mp_filetype_text+n)) ) 
16553         goto NOT_FOUND;
16554   if ( ! mp_input_ln(mp, mp->rd_file[n] ) ) {
16555     (mp->close_file)(mp,mp->rd_file[n]); 
16556         goto NOT_FOUND; 
16557   }
16558   mp->rd_fname[n]=xstrdup(s);
16559   return true;
16560 NOT_FOUND: 
16561   mp_end_file_reading(mp);
16562   return false;
16563 }
16564
16565 @ Open |wr_file[n]| using file name~|s| and update |wr_fname[n]|.
16566
16567 @<Declarations@>=
16568 static void mp_open_write_file (MP mp, char *s, readf_index  n) ;
16569
16570 @ @c void mp_open_write_file (MP mp,char *s, readf_index  n) {
16571   mp_ptr_scan_file(mp, s);
16572   pack_cur_name;
16573   while ( ! mp_a_open_out(mp, &mp->wr_file[n], (int)(mp_filetype_text+n)) )
16574     mp_prompt_file_name(mp, "file name for write output","");
16575   mp->wr_fname[n]=xstrdup(s);
16576 }
16577
16578
16579 @* \[36] Introduction to the parsing routines.
16580 We come now to the central nervous system that sparks many of \MP's activities.
16581 By evaluating expressions, from their primary constituents to ever larger
16582 subexpressions, \MP\ builds the structures that ultimately define complete
16583 pictures or fonts of type.
16584
16585 Four mutually recursive subroutines are involved in this process: We call them
16586 $$\hbox{|scan_primary|, |scan_secondary|, |scan_tertiary|,
16587 and |scan_expression|.}$$
16588 @^recursion@>
16589 Each of them is parameterless and begins with the first token to be scanned
16590 already represented in |cur_cmd|, |cur_mod|, and |cur_sym|. After execution,
16591 the value of the primary or secondary or tertiary or expression that was
16592 found will appear in the global variables |cur_type| and |cur_exp|. The
16593 token following the expression will be represented in |cur_cmd|, |cur_mod|,
16594 and |cur_sym|.
16595
16596 Technically speaking, the parsing algorithms are ``LL(1),'' more or less;
16597 backup mechanisms have been added in order to provide reasonable error
16598 recovery.
16599
16600 @<Glob...@>=
16601 quarterword cur_type; /* the type of the expression just found */
16602 integer cur_exp; /* the value of the expression just found */
16603
16604 @ @<Set init...@>=
16605 mp->cur_exp=0;
16606
16607 @ Many different kinds of expressions are possible, so it is wise to have
16608 precise descriptions of what |cur_type| and |cur_exp| mean in all cases:
16609
16610 \smallskip\hang
16611 |cur_type=mp_vacuous| means that this expression didn't turn out to have a
16612 value at all, because it arose from a \&{begingroup}$\,\ldots\,$\&{endgroup}
16613 construction in which there was no expression before the \&{endgroup}.
16614 In this case |cur_exp| has some irrelevant value.
16615
16616 \smallskip\hang
16617 |cur_type=mp_boolean_type| means that |cur_exp| is either |true_code|
16618 or |false_code|.
16619
16620 \smallskip\hang
16621 |cur_type=mp_unknown_boolean| means that |cur_exp| points to a capsule
16622 node that is in 
16623 a ring of equivalent booleans whose value has not yet been defined.
16624
16625 \smallskip\hang
16626 |cur_type=mp_string_type| means that |cur_exp| is a string number (i.e., an
16627 integer in the range |0<=cur_exp<str_ptr|). That string's reference count
16628 includes this particular reference.
16629
16630 \smallskip\hang
16631 |cur_type=mp_unknown_string| means that |cur_exp| points to a capsule
16632 node that is in
16633 a ring of equivalent strings whose value has not yet been defined.
16634
16635 \smallskip\hang
16636 |cur_type=mp_pen_type| means that |cur_exp| points to a node in a pen.  Nobody
16637 else points to any of the nodes in this pen.  The pen may be polygonal or
16638 elliptical.
16639
16640 \smallskip\hang
16641 |cur_type=mp_unknown_pen| means that |cur_exp| points to a capsule
16642 node that is in
16643 a ring of equivalent pens whose value has not yet been defined.
16644
16645 \smallskip\hang
16646 |cur_type=mp_path_type| means that |cur_exp| points to a the first node of
16647 a path; nobody else points to this particular path. The control points of
16648 the path will have been chosen.
16649
16650 \smallskip\hang
16651 |cur_type=mp_unknown_path| means that |cur_exp| points to a capsule
16652 node that is in
16653 a ring of equivalent paths whose value has not yet been defined.
16654
16655 \smallskip\hang
16656 |cur_type=mp_picture_type| means that |cur_exp| points to an edge header node.
16657 There may be other pointers to this particular set of edges.  The header node
16658 contains a reference count that includes this particular reference.
16659
16660 \smallskip\hang
16661 |cur_type=mp_unknown_picture| means that |cur_exp| points to a capsule
16662 node that is in
16663 a ring of equivalent pictures whose value has not yet been defined.
16664
16665 \smallskip\hang
16666 |cur_type=mp_transform_type| means that |cur_exp| points to a |mp_transform_type|
16667 capsule node. The |value| part of this capsule
16668 points to a transform node that contains six numeric values,
16669 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16670
16671 \smallskip\hang
16672 |cur_type=mp_color_type| means that |cur_exp| points to a |color_type|
16673 capsule node. The |value| part of this capsule
16674 points to a color node that contains three numeric values,
16675 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16676
16677 \smallskip\hang
16678 |cur_type=mp_cmykcolor_type| means that |cur_exp| points to a |mp_cmykcolor_type|
16679 capsule node. The |value| part of this capsule
16680 points to a color node that contains four numeric values,
16681 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16682
16683 \smallskip\hang
16684 |cur_type=mp_pair_type| means that |cur_exp| points to a capsule
16685 node whose type is |mp_pair_type|. The |value| part of this capsule
16686 points to a pair node that contains two numeric values,
16687 each of which is |independent|, |dependent|, |mp_proto_dependent|, or |known|.
16688
16689 \smallskip\hang
16690 |cur_type=mp_known| means that |cur_exp| is a |scaled| value.
16691
16692 \smallskip\hang
16693 |cur_type=mp_dependent| means that |cur_exp| points to a capsule node whose type
16694 is |dependent|. The |dep_list| field in this capsule points to the associated
16695 dependency list.
16696
16697 \smallskip\hang
16698 |cur_type=mp_proto_dependent| means that |cur_exp| points to a |mp_proto_dependent|
16699 capsule node. The |dep_list| field in this capsule
16700 points to the associated dependency list.
16701
16702 \smallskip\hang
16703 |cur_type=independent| means that |cur_exp| points to a capsule node
16704 whose type is |independent|. This somewhat unusual case can arise, for
16705 example, in the expression
16706 `$x+\&{begingroup}\penalty0\,\&{string}\,x; 0\,\&{endgroup}$'.
16707
16708 \smallskip\hang
16709 |cur_type=mp_token_list| means that |cur_exp| points to a linked list of
16710 tokens. 
16711
16712 \smallskip\noindent
16713 The possible settings of |cur_type| have been listed here in increasing
16714 numerical order. Notice that |cur_type| will never be |mp_numeric_type| or
16715 |suffixed_macro| or |mp_unsuffixed_macro|, although variables of those types
16716 are allowed.  Conversely, \MP\ has no variables of type |mp_vacuous| or
16717 |token_list|.
16718
16719 @ Capsules are two-word nodes that have a similar meaning
16720 to |cur_type| and |cur_exp|. Such nodes have |name_type=capsule|,
16721 and their |type| field is one of the possibilities for |cur_type| listed above.
16722 Also |link<=void| in capsules that aren't part of a token list.
16723
16724 The |value| field of a capsule is, in most cases, the value that
16725 corresponds to its |type|, as |cur_exp| corresponds to |cur_type|.
16726 However, when |cur_exp| would point to a capsule,
16727 no extra layer of indirection is present; the |value|
16728 field is what would have been called |value(cur_exp)| if it had not been
16729 encapsulated.  Furthermore, if the type is |dependent| or
16730 |mp_proto_dependent|, the |value| field of a capsule is replaced by
16731 |dep_list| and |prev_dep| fields, since dependency lists in capsules are
16732 always part of the general |dep_list| structure.
16733
16734 The |get_x_next| routine is careful not to change the values of |cur_type|
16735 and |cur_exp| when it gets an expanded token. However, |get_x_next| might
16736 call a macro, which might parse an expression, which might execute lots of
16737 commands in a group; hence it's possible that |cur_type| might change
16738 from, say, |mp_unknown_boolean| to |mp_boolean_type|, or from |dependent| to
16739 |known| or |independent|, during the time |get_x_next| is called. The
16740 programs below are careful to stash sensitive intermediate results in
16741 capsules, so that \MP's generality doesn't cause trouble.
16742
16743 Here's a procedure that illustrates these conventions. It takes
16744 the contents of $(|cur_type|\kern-.3pt,|cur_exp|\kern-.3pt)$
16745 and stashes them away in a
16746 capsule. It is not used when |cur_type=mp_token_list|.
16747 After the operation, |cur_type=mp_vacuous|; hence there is no need to
16748 copy path lists or to update reference counts, etc.
16749
16750 The special link |mp_void| is put on the capsule returned by
16751 |stash_cur_exp|, because this procedure is used to store macro parameters
16752 that must be easily distinguishable from token lists.
16753
16754 @<Declare the stashing/unstashing routines@>=
16755 static pointer mp_stash_cur_exp (MP mp) {
16756   pointer p; /* the capsule that will be returned */
16757   switch (mp->cur_type) {
16758   case unknown_types:
16759   case mp_transform_type:
16760   case mp_color_type:
16761   case mp_pair_type:
16762   case mp_dependent:
16763   case mp_proto_dependent:
16764   case mp_independent: 
16765   case mp_cmykcolor_type:
16766     p=mp->cur_exp;
16767     break;
16768   default: 
16769     p=mp_get_node(mp, value_node_size); mp_name_type(p)=mp_capsule;
16770     mp_type(p)=mp->cur_type; value(p)=mp->cur_exp;
16771     break;
16772   }
16773   mp->cur_type=mp_vacuous; mp_link(p)=mp_void; 
16774   return p;
16775 }
16776
16777 @ The inverse of |stash_cur_exp| is the following procedure, which
16778 deletes an unnecessary capsule and puts its contents into |cur_type|
16779 and |cur_exp|.
16780
16781 The program steps of \MP\ can be divided into two categories: those in
16782 which |cur_type| and |cur_exp| are ``alive'' and those in which they are
16783 ``dead,'' in the sense that |cur_type| and |cur_exp| contain relevant
16784 information or not. It's important not to ignore them when they're alive,
16785 and it's important not to pay attention to them when they're dead.
16786
16787 There's also an intermediate category: If |cur_type=mp_vacuous|, then
16788 |cur_exp| is irrelevant, hence we can proceed without caring if |cur_type|
16789 and |cur_exp| are alive or dead. In such cases we say that |cur_type|
16790 and |cur_exp| are {\sl dormant}. It is permissible to call |get_x_next|
16791 only when they are alive or dormant.
16792
16793 The \\{stash} procedure above assumes that |cur_type| and |cur_exp|
16794 are alive or dormant. The \\{unstash} procedure assumes that they are
16795 dead or dormant; it resuscitates them.
16796
16797 @<Declare the stashing/unstashing...@>=
16798 static void mp_unstash_cur_exp (MP mp,pointer p) ;
16799
16800 @ @c
16801 void mp_unstash_cur_exp (MP mp,pointer p) { 
16802   mp->cur_type=mp_type(p);
16803   switch (mp->cur_type) {
16804   case unknown_types:
16805   case mp_transform_type:
16806   case mp_color_type:
16807   case mp_pair_type:
16808   case mp_dependent: 
16809   case mp_proto_dependent:
16810   case mp_independent:
16811   case mp_cmykcolor_type: 
16812     mp->cur_exp=p;
16813     break;
16814   default:
16815     mp->cur_exp=value(p);
16816     mp_free_node(mp, p,value_node_size);
16817     break;
16818   }
16819 }
16820
16821 @ The following procedure prints the values of expressions in an
16822 abbreviated format. If its first parameter |p| is null, the value of
16823 |(cur_type,cur_exp)| is displayed; otherwise |p| should be a capsule
16824 containing the desired value. The second parameter controls the amount of
16825 output. If it is~0, dependency lists will be abbreviated to
16826 `\.{linearform}' unless they consist of a single term.  If it is greater
16827 than~1, complicated structures (pens, pictures, and paths) will be displayed
16828 in full.
16829 @.linearform@>
16830
16831 @<Declarations@>=
16832 @<Declare the procedure called |print_dp|@>
16833 @<Declare the stashing/unstashing routines@>
16834 static void mp_print_exp (MP mp,pointer p, quarterword verbosity) ;
16835
16836 @ @c
16837 void mp_print_exp (MP mp,pointer p, quarterword verbosity) {
16838   boolean restore_cur_exp; /* should |cur_exp| be restored? */
16839   quarterword t; /* the type of the expression */
16840   pointer q; /* a big node being displayed */
16841   integer v=0; /* the value of the expression */
16842   if ( p!=null ) {
16843     restore_cur_exp=false;
16844   } else { 
16845     p=mp_stash_cur_exp(mp); restore_cur_exp=true;
16846   }
16847   t=mp_type(p);
16848   if ( t<mp_dependent ) v=value(p); else if ( t<mp_independent ) v=dep_list(p);
16849   @<Print an abbreviated value of |v| with format depending on |t|@>;
16850   if ( restore_cur_exp ) mp_unstash_cur_exp(mp, p);
16851 }
16852
16853 @ @<Print an abbreviated value of |v| with format depending on |t|@>=
16854 switch (t) {
16855 case mp_vacuous:mp_print(mp, "mp_vacuous"); break;
16856 case mp_boolean_type:
16857   if ( v==true_code ) mp_print(mp, "true"); else mp_print(mp, "false");
16858   break;
16859 case unknown_types: case mp_numeric_type:
16860   @<Display a variable that's been declared but not defined@>;
16861   break;
16862 case mp_string_type:
16863   mp_print_char(mp, xord('"')); mp_print_str(mp, v); mp_print_char(mp, xord('"'));
16864   break;
16865 case mp_pen_type: case mp_path_type: case mp_picture_type:
16866   @<Display a complex type@>;
16867   break;
16868 case mp_transform_type: case mp_color_type: case mp_pair_type: case mp_cmykcolor_type:
16869   if ( v==null ) mp_print_type(mp, t);
16870   else @<Display a big node@>;
16871   break;
16872 case mp_known:mp_print_scaled(mp, v); break;
16873 case mp_dependent: case mp_proto_dependent:
16874   mp_print_dp(mp, t,v,verbosity);
16875   break;
16876 case mp_independent:mp_print_variable_name(mp, p); break;
16877 default: mp_confusion(mp, "exp"); break;
16878 @:this can't happen exp}{\quad exp@>
16879 }
16880
16881 @ @<Display a big node@>=
16882
16883   mp_print_char(mp, xord('(')); q=v+mp->big_node_size[t];
16884   do {  
16885     if ( mp_type(v)==mp_known ) mp_print_scaled(mp, value(v));
16886     else if ( mp_type(v)==mp_independent ) mp_print_variable_name(mp, v);
16887     else mp_print_dp(mp, mp_type(v),dep_list(v),verbosity);
16888     v=v+2;
16889     if ( v!=q ) mp_print_char(mp, xord(','));
16890   } while (v!=q);
16891   mp_print_char(mp, xord(')'));
16892 }
16893
16894 @ Values of type \&{picture}, \&{path}, and \&{pen} are displayed verbosely
16895 in the log file only, unless the user has given a positive value to
16896 \\{tracingonline}.
16897
16898 @<Display a complex type@>=
16899 if ( verbosity<=1 ) {
16900   mp_print_type(mp, t);
16901 } else { 
16902   if ( mp->selector==term_and_log )
16903    if ( mp->internal[mp_tracing_online]<=0 ) {
16904     mp->selector=term_only;
16905     mp_print_type(mp, t); mp_print(mp, " (see the transcript file)");
16906     mp->selector=term_and_log;
16907   };
16908   switch (t) {
16909   case mp_pen_type:mp_print_pen(mp, v,"",false); break;
16910   case mp_path_type:mp_print_path(mp, v,"",false); break;
16911   case mp_picture_type:mp_print_edges(mp, v,"",false); break;
16912   } /* there are no other cases */
16913 }
16914
16915 @ @<Declare the procedure called |print_dp|@>=
16916 static void mp_print_dp (MP mp, quarterword t, pointer p, 
16917                   quarterword verbosity)  {
16918   pointer q; /* the node following |p| */
16919   q=mp_link(p);
16920   if ( (mp_info(q)==null) || (verbosity>0) ) mp_print_dependency(mp, p,t);
16921   else mp_print(mp, "linearform");
16922 }
16923
16924 @ The displayed name of a variable in a ring will not be a capsule unless
16925 the ring consists entirely of capsules.
16926
16927 @<Display a variable that's been declared but not defined@>=
16928 { mp_print_type(mp, t);
16929 if ( v!=null )
16930   { mp_print_char(mp, xord(' '));
16931   while ( (mp_name_type(v)==mp_capsule) && (v!=p) ) v=value(v);
16932   mp_print_variable_name(mp, v);
16933   };
16934 }
16935
16936 @ When errors are detected during parsing, it is often helpful to
16937 display an expression just above the error message, using |exp_err|
16938 or |disp_err| instead of |print_err|.
16939
16940 @d exp_err(A) mp_disp_err(mp, null,(A)) /* displays the current expression */
16941
16942 @<Declarations@>=
16943 static void mp_disp_err (MP mp,pointer p, const char *s) ;
16944
16945 @ @c
16946 void mp_disp_err (MP mp,pointer p, const char *s) { 
16947   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
16948   mp_print_nl(mp, ">> ");
16949 @.>>@>
16950   mp_print_exp(mp, p,1); /* ``medium verbose'' printing of the expression */
16951   if (strlen(s)>0) { 
16952     mp_print_nl(mp, "! "); mp_print(mp, s);
16953 @.!\relax@>
16954   }
16955 }
16956
16957 @ If |cur_type| and |cur_exp| contain relevant information that should
16958 be recycled, we will use the following procedure, which changes |cur_type|
16959 to |known| and stores a given value in |cur_exp|. We can think of |cur_type|
16960 and |cur_exp| as either alive or dormant after this has been done,
16961 because |cur_exp| will not contain a pointer value.
16962
16963 @ @c 
16964 static void mp_flush_cur_exp (MP mp,scaled v) { 
16965   switch (mp->cur_type) {
16966   case unknown_types: case mp_transform_type: case mp_color_type: case mp_pair_type:
16967   case mp_dependent: case mp_proto_dependent: case mp_independent: case mp_cmykcolor_type:
16968     mp_recycle_value(mp, mp->cur_exp); 
16969     mp_free_node(mp, mp->cur_exp,value_node_size);
16970     break;
16971   case mp_string_type:
16972     delete_str_ref(mp->cur_exp); break;
16973   case mp_pen_type: case mp_path_type: 
16974     mp_toss_knot_list(mp, mp->cur_exp); break;
16975   case mp_picture_type:
16976     delete_edge_ref(mp->cur_exp); break;
16977   default: 
16978     break;
16979   }
16980   mp->cur_type=mp_known; mp->cur_exp=v;
16981 }
16982
16983 @ There's a much more general procedure that is capable of releasing
16984 the storage associated with any two-word value packet.
16985
16986 @<Declarations@>=
16987 static void mp_recycle_value (MP mp,pointer p) ;
16988
16989 @ @c 
16990 static void mp_recycle_value (MP mp,pointer p) {
16991   quarterword t; /* a type code */
16992   integer vv; /* another value */
16993   pointer q,r,s,pp; /* link manipulation registers */
16994   integer v=0; /* a value */
16995   t=mp_type(p);
16996   if ( t<mp_dependent ) v=value(p);
16997   switch (t) {
16998   case undefined: case mp_vacuous: case mp_boolean_type: case mp_known:
16999   case mp_numeric_type:
17000     break;
17001   case unknown_types:
17002     mp_ring_delete(mp, p); break;
17003   case mp_string_type:
17004     delete_str_ref(v); break;
17005   case mp_path_type: case mp_pen_type:
17006     mp_toss_knot_list(mp, v); break;
17007   case mp_picture_type:
17008     delete_edge_ref(v); break;
17009   case mp_cmykcolor_type: case mp_pair_type: case mp_color_type:
17010   case mp_transform_type:
17011     @<Recycle a big node@>; break; 
17012   case mp_dependent: case mp_proto_dependent:
17013     @<Recycle a dependency list@>; break;
17014   case mp_independent:
17015     @<Recycle an independent variable@>; break;
17016   case mp_token_list: case mp_structured:
17017     mp_confusion(mp, "recycle"); break;
17018 @:this can't happen recycle}{\quad recycle@>
17019   case mp_unsuffixed_macro: case mp_suffixed_macro:
17020     mp_delete_mac_ref(mp, value(p)); break;
17021   } /* there are no other cases */
17022   mp_type(p)=undefined;
17023 }
17024
17025 @ @<Recycle a big node@>=
17026 if ( v!=null ){ 
17027   q=v+mp->big_node_size[t];
17028   do {  
17029     q=q-2; mp_recycle_value(mp, q);
17030   } while (q!=v);
17031   mp_free_node(mp, v,mp->big_node_size[t]);
17032 }
17033
17034 @ @<Recycle a dependency list@>=
17035
17036   q=dep_list(p);
17037   while ( mp_info(q)!=null ) q=mp_link(q);
17038   mp_link(prev_dep(p))=mp_link(q);
17039   prev_dep(mp_link(q))=prev_dep(p);
17040   mp_link(q)=null; mp_flush_node_list(mp, dep_list(p));
17041 }
17042
17043 @ When an independent variable disappears, it simply fades away, unless
17044 something depends on it. In the latter case, a dependent variable whose
17045 coefficient of dependence is maximal will take its place.
17046 The relevant algorithm is due to Ignacio~A. Zabala, who implemented it
17047 as part of his Ph.D. thesis (Stanford University, December 1982).
17048 @^Zabala Salelles, Ignacio Andr\'es@>
17049
17050 For example, suppose that variable $x$ is being recycled, and that the
17051 only variables depending on~$x$ are $y=2x+a$ and $z=x+b$. In this case
17052 we want to make $y$ independent and $z=.5y-.5a+b$; no other variables
17053 will depend on~$y$. If $\\{tracingequations}>0$ in this situation,
17054 we will print `\.{\#\#\# -2x=-y+a}'.
17055
17056 There's a slight complication, however: An independent variable $x$
17057 can occur both in dependency lists and in proto-dependency lists.
17058 This makes it necessary to be careful when deciding which coefficient
17059 is maximal.
17060
17061 Furthermore, this complication is not so slight when
17062 a proto-dependent variable is chosen to become independent. For example,
17063 suppose that $y=2x+100a$ is proto-dependent while $z=x+b$ is dependent;
17064 then we must change $z=.5y-50a+b$ to a proto-dependency, because of the
17065 large coefficient `50'.
17066
17067 In order to deal with these complications without wasting too much time,
17068 we shall link together the occurrences of~$x$ among all the linear
17069 dependencies, maintaining separate lists for the dependent and
17070 proto-dependent cases.
17071
17072 @<Recycle an independent variable@>=
17073
17074   mp->max_c[mp_dependent]=0; mp->max_c[mp_proto_dependent]=0;
17075   mp->max_link[mp_dependent]=null; mp->max_link[mp_proto_dependent]=null;
17076   q=mp_link(dep_head);
17077   while ( q!=dep_head ) { 
17078     s=value_loc(q); /* now |mp_link(s)=dep_list(q)| */
17079     while (1) { 
17080       r=mp_link(s);
17081       if ( mp_info(r)==null ) break;
17082       if ( mp_info(r)!=p ) { 
17083         s=r;
17084       } else  { 
17085         t=mp_type(q); mp_link(s)=mp_link(r); mp_info(r)=q;
17086         if ( abs(value(r))>mp->max_c[t] ) {
17087           @<Record a new maximum coefficient of type |t|@>;
17088         } else { 
17089           mp_link(r)=mp->max_link[t]; mp->max_link[t]=r;
17090         }
17091       }
17092     } 
17093     q=mp_link(r);
17094   }
17095   if ( (mp->max_c[mp_dependent]>0)||(mp->max_c[mp_proto_dependent]>0) ) {
17096     @<Choose a dependent variable to take the place of the disappearing
17097     independent variable, and change all remaining dependencies
17098     accordingly@>;
17099   }
17100 }
17101
17102 @ The code for independency removal makes use of three two-word arrays.
17103
17104 @<Glob...@>=
17105 integer max_c[mp_proto_dependent+1];  /* max coefficient magnitude */
17106 pointer max_ptr[mp_proto_dependent+1]; /* where |p| occurs with |max_c| */
17107 pointer max_link[mp_proto_dependent+1]; /* other occurrences of |p| */
17108
17109 @ @<Record a new maximum coefficient...@>=
17110
17111   if ( mp->max_c[t]>0 ) {
17112     mp_link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17113   }
17114   mp->max_c[t]=abs(value(r)); mp->max_ptr[t]=r;
17115 }
17116
17117 @ @<Choose a dependent...@>=
17118
17119   if ( (mp->max_c[mp_dependent] / 010000) >= mp->max_c[mp_proto_dependent] )
17120     t=mp_dependent;
17121   else 
17122     t=mp_proto_dependent;
17123   @<Determine the dependency list |s| to substitute for the independent
17124     variable~|p|@>;
17125   t=mp_dependent+mp_proto_dependent-t; /* complement |t| */
17126   if ( mp->max_c[t]>0 ) { /* we need to pick up an unchosen dependency */ 
17127     mp_link(mp->max_ptr[t])=mp->max_link[t]; mp->max_link[t]=mp->max_ptr[t];
17128   }
17129   if ( t!=mp_dependent ) { @<Substitute new dependencies in place of |p|@>; }
17130   else { @<Substitute new proto-dependencies in place of |p|@>;}
17131   mp_flush_node_list(mp, s);
17132   if ( mp->fix_needed ) mp_fix_dependencies(mp);
17133   check_arith;
17134 }
17135
17136 @ Let |s=max_ptr[t]|. At this point we have $|value|(s)=\pm|max_c|[t]$,
17137 and |mp_info(s)| points to the dependent variable~|pp| of type~|t| from
17138 whose dependency list we have removed node~|s|. We must reinsert
17139 node~|s| into the dependency list, with coefficient $-1.0$, and with
17140 |pp| as the new independent variable. Since |pp| will have a larger serial
17141 number than any other variable, we can put node |s| at the head of the
17142 list.
17143
17144 @<Determine the dep...@>=
17145 s=mp->max_ptr[t]; pp=mp_info(s); v=value(s);
17146 if ( t==mp_dependent ) value(s)=-fraction_one; else value(s)=-unity;
17147 r=dep_list(pp); mp_link(s)=r;
17148 while ( mp_info(r)!=null ) r=mp_link(r);
17149 q=mp_link(r); mp_link(r)=null;
17150 prev_dep(q)=prev_dep(pp); mp_link(prev_dep(pp))=q;
17151 new_indep(pp);
17152 if ( mp->cur_exp==pp ) if ( mp->cur_type==t ) mp->cur_type=mp_independent;
17153 if ( mp->internal[mp_tracing_equations]>0 ) { 
17154   @<Show the transformed dependency@>; 
17155 }
17156
17157 @ Now $(-v)$ times the formerly independent variable~|p| is being replaced
17158 by the dependency list~|s|.
17159
17160 @<Show the transformed...@>=
17161 if ( mp_interesting(mp, p) ) {
17162   mp_begin_diagnostic(mp); mp_print_nl(mp, "### ");
17163 @:]]]\#\#\#_}{\.{\#\#\#}@>
17164   if ( v>0 ) mp_print_char(mp, xord('-'));
17165   if ( t==mp_dependent ) vv=mp_round_fraction(mp, mp->max_c[mp_dependent]);
17166   else vv=mp->max_c[mp_proto_dependent];
17167   if ( vv!=unity ) mp_print_scaled(mp, vv);
17168   mp_print_variable_name(mp, p);
17169   while ( value(p) % s_scale>0 ) {
17170     mp_print(mp, "*4"); value(p)=value(p)-2;
17171   }
17172   if ( t==mp_dependent ) mp_print_char(mp, xord('=')); else mp_print(mp, " = ");
17173   mp_print_dependency(mp, s,t);
17174   mp_end_diagnostic(mp, false);
17175 }
17176
17177 @ Finally, there are dependent and proto-dependent variables whose
17178 dependency lists must be brought up to date.
17179
17180 @<Substitute new dependencies...@>=
17181 for (t=mp_dependent;t<=mp_proto_dependent;t++){ 
17182   r=mp->max_link[t];
17183   while ( r!=null ) {
17184     q=mp_info(r);
17185     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17186      mp_make_fraction(mp, value(r),-v),s,t,mp_dependent);
17187     if ( dep_list(q)==mp->dep_final ) mp_make_known(mp, q,mp->dep_final);
17188     q=r; r=mp_link(r); mp_free_node(mp, q,dep_node_size);
17189   }
17190 }
17191
17192 @ @<Substitute new proto...@>=
17193 for (t=mp_dependent;t<=mp_proto_dependent;t++) {
17194   r=mp->max_link[t];
17195   while ( r!=null ) {
17196     q=mp_info(r);
17197     if ( t==mp_dependent ) { /* for safety's sake, we change |q| to |mp_proto_dependent| */
17198       if ( mp->cur_exp==q ) if ( mp->cur_type==mp_dependent )
17199         mp->cur_type=mp_proto_dependent;
17200       dep_list(q)=mp_p_over_v(mp, dep_list(q),unity,
17201          mp_dependent,mp_proto_dependent);
17202       mp_type(q)=mp_proto_dependent; 
17203       value(r)=mp_round_fraction(mp, value(r));
17204     }
17205     dep_list(q)=mp_p_plus_fq(mp, dep_list(q),
17206        mp_make_scaled(mp, value(r),-v),s,
17207        mp_proto_dependent,mp_proto_dependent);
17208     if ( dep_list(q)==mp->dep_final ) 
17209        mp_make_known(mp, q,mp->dep_final);
17210     q=r; r=mp_link(r); mp_free_node(mp, q,dep_node_size);
17211   }
17212 }
17213
17214 @ Here are some routines that provide handy combinations of actions
17215 that are often needed during error recovery. For example,
17216 `|flush_error|' flushes the current expression, replaces it by
17217 a given value, and calls |error|.
17218
17219 Errors often are detected after an extra token has already been scanned.
17220 The `\\{put\_get}' routines put that token back before calling |error|;
17221 then they get it back again. (Or perhaps they get another token, if
17222 the user has changed things.)
17223
17224 @<Declarations@>=
17225 static void mp_flush_error (MP mp,scaled v);
17226 static void mp_put_get_error (MP mp);
17227 static void mp_put_get_flush_error (MP mp,scaled v) ;
17228
17229 @ @c
17230 void mp_flush_error (MP mp,scaled v) { 
17231   mp_error(mp); mp_flush_cur_exp(mp, v); 
17232 }
17233 void mp_put_get_error (MP mp) { 
17234   mp_back_error(mp); mp_get_x_next(mp); 
17235 }
17236 void mp_put_get_flush_error (MP mp,scaled v) { 
17237   mp_put_get_error(mp);
17238   mp_flush_cur_exp(mp, v); 
17239 }
17240
17241 @ A global variable |var_flag| is set to a special command code
17242 just before \MP\ calls |scan_expression|, if the expression should be
17243 treated as a variable when this command code immediately follows. For
17244 example, |var_flag| is set to |assignment| at the beginning of a
17245 statement, because we want to know the {\sl location\/} of a variable at
17246 the left of `\.{:=}', not the {\sl value\/} of that variable.
17247
17248 The |scan_expression| subroutine calls |scan_tertiary|,
17249 which calls |scan_secondary|, which calls |scan_primary|, which sets
17250 |var_flag:=0|. In this way each of the scanning routines ``knows''
17251 when it has been called with a special |var_flag|, but |var_flag| is
17252 usually zero.
17253
17254 A variable preceding a command that equals |var_flag| is converted to a
17255 token list rather than a value. Furthermore, an `\.{=}' sign following an
17256 expression with |var_flag=assignment| is not considered to be a relation
17257 that produces boolean expressions.
17258
17259
17260 @<Glob...@>=
17261 int var_flag; /* command that wants a variable */
17262
17263 @ @<Set init...@>=
17264 mp->var_flag=0;
17265
17266 @* \[37] Parsing primary expressions.
17267 The first parsing routine, |scan_primary|, is also the most complicated one,
17268 since it involves so many different cases. But each case---with one
17269 exception---is fairly simple by itself.
17270
17271 When |scan_primary| begins, the first token of the primary to be scanned
17272 should already appear in |cur_cmd|, |cur_mod|, and |cur_sym|. The values
17273 of |cur_type| and |cur_exp| should be either dead or dormant, as explained
17274 earlier. If |cur_cmd| is not between |min_primary_command| and
17275 |max_primary_command|, inclusive, a syntax error will be signaled.
17276
17277 @<Declare the basic parsing subroutines@>=
17278 void mp_scan_primary (MP mp) {
17279   pointer p,q,r; /* for list manipulation */
17280   quarterword c; /* a primitive operation code */
17281   int my_var_flag; /* initial value of |my_var_flag| */
17282   pointer l_delim,r_delim; /* hash addresses of a delimiter pair */
17283   @<Other local variables for |scan_primary|@>;
17284   my_var_flag=mp->var_flag; mp->var_flag=0;
17285 RESTART:
17286   check_arith;
17287   @<Supply diagnostic information, if requested@>;
17288   switch (mp->cur_cmd) {
17289   case left_delimiter:
17290     @<Scan a delimited primary@>; break;
17291   case begin_group:
17292     @<Scan a grouped primary@>; break;
17293   case string_token:
17294     @<Scan a string constant@>; break;
17295   case numeric_token:
17296     @<Scan a primary that starts with a numeric token@>; break;
17297   case nullary:
17298     @<Scan a nullary operation@>; break;
17299   case unary: case type_name: case cycle: case plus_or_minus:
17300     @<Scan a unary operation@>; break;
17301   case primary_binary:
17302     @<Scan a binary operation with `\&{of}' between its operands@>; break;
17303   case str_op:
17304     @<Convert a suffix to a string@>; break;
17305   case internal_quantity:
17306     @<Scan an internal numeric quantity@>; break;
17307   case capsule_token:
17308     mp_make_exp_copy(mp, mp->cur_mod); break;
17309   case tag_token:
17310     @<Scan a variable primary; |goto restart| if it turns out to be a macro@>; break;
17311   default: 
17312     mp_bad_exp(mp, "A primary"); goto RESTART; break;
17313 @.A primary expression...@>
17314   }
17315   mp_get_x_next(mp); /* the routines |goto done| if they don't want this */
17316 DONE: 
17317   if ( mp->cur_cmd==left_bracket ) {
17318     if ( mp->cur_type>=mp_known ) {
17319       @<Scan a mediation construction@>;
17320     }
17321   }
17322 }
17323
17324
17325
17326 @ Errors at the beginning of expressions are flagged by |bad_exp|.
17327
17328 @c 
17329 static void mp_bad_exp (MP mp, const char * s) {
17330   int save_flag;
17331   print_err(s); mp_print(mp, " expression can't begin with `");
17332   mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); 
17333   mp_print_char(mp, xord('\''));
17334   help4("I'm afraid I need some sort of value in order to continue,",
17335     "so I've tentatively inserted `0'. You may want to",
17336     "delete this zero and insert something else;",
17337     "see Chapter 27 of The METAFONTbook for an example.");
17338 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
17339   mp_back_input(mp); mp->cur_sym=0; mp->cur_cmd=numeric_token; 
17340   mp->cur_mod=0; mp_ins_error(mp);
17341   save_flag=mp->var_flag; mp->var_flag=0; mp_get_x_next(mp);
17342   mp->var_flag=save_flag;
17343 }
17344
17345 @ @<Supply diagnostic information, if requested@>=
17346 #ifdef DEBUG
17347 if ( mp->panicking ) mp_check_mem(mp, false);
17348 #endif
17349 if ( mp->interrupt!=0 ) if ( mp->OK_to_interrupt ) {
17350   mp_back_input(mp); check_interrupt; mp_get_x_next(mp);
17351 }
17352
17353 @ @<Scan a delimited primary@>=
17354
17355   l_delim=mp->cur_sym; r_delim=mp->cur_mod; 
17356   mp_get_x_next(mp); mp_scan_expression(mp);
17357   if ( (mp->cur_cmd==comma) && (mp->cur_type>=mp_known) ) {
17358     @<Scan the rest of a delimited set of numerics@>;
17359   } else {
17360     mp_check_delimiter(mp, l_delim,r_delim);
17361   }
17362 }
17363
17364 @ The |stash_in| subroutine puts the current (numeric) expression into a field
17365 within a ``big node.''
17366
17367 @c 
17368 static void mp_stash_in (MP mp,pointer p) {
17369   pointer q; /* temporary register */
17370   mp_type(p)=mp->cur_type;
17371   if ( mp->cur_type==mp_known ) {
17372     value(p)=mp->cur_exp;
17373   } else { 
17374     if ( mp->cur_type==mp_independent ) {
17375       @<Stash an independent |cur_exp| into a big node@>;
17376     } else { 
17377       mp->mem[value_loc(p)]=mp->mem[value_loc(mp->cur_exp)];
17378       /* |dep_list(p):=dep_list(cur_exp)| and |prev_dep(p):=prev_dep(cur_exp)| */
17379       mp_link(prev_dep(p))=p;
17380     }
17381     mp_free_node(mp, mp->cur_exp,value_node_size);
17382   }
17383   mp->cur_type=mp_vacuous;
17384 }
17385
17386 @ In rare cases the current expression can become |independent|. There
17387 may be many dependency lists pointing to such an independent capsule,
17388 so we can't simply move it into place within a big node. Instead,
17389 we copy it, then recycle it.
17390
17391 @ @<Stash an independent |cur_exp|...@>=
17392
17393   q=mp_single_dependency(mp, mp->cur_exp);
17394   if ( q==mp->dep_final ){ 
17395     mp_type(p)=mp_known; value(p)=0; mp_free_node(mp, q,dep_node_size);
17396   } else { 
17397     mp_type(p)=mp_dependent; mp_new_dep(mp, p,q);
17398   }
17399   mp_recycle_value(mp, mp->cur_exp);
17400 }
17401
17402 @ This code uses the fact that |red_part_loc| and |green_part_loc|
17403 are synonymous with |x_part_loc| and |y_part_loc|.
17404
17405 @<Scan the rest of a delimited set of numerics@>=
17406
17407 p=mp_stash_cur_exp(mp);
17408 mp_get_x_next(mp); mp_scan_expression(mp);
17409 @<Make sure the second part of a pair or color has a numeric type@>;
17410 q=mp_get_node(mp, value_node_size); mp_name_type(q)=mp_capsule;
17411 if ( mp->cur_cmd==comma ) mp_type(q)=mp_color_type;
17412 else mp_type(q)=mp_pair_type;
17413 mp_init_big_node(mp, q); r=value(q);
17414 mp_stash_in(mp, y_part_loc(r));
17415 mp_unstash_cur_exp(mp, p);
17416 mp_stash_in(mp, x_part_loc(r));
17417 if ( mp->cur_cmd==comma ) {
17418   @<Scan the last of a triplet of numerics@>;
17419 }
17420 if ( mp->cur_cmd==comma ) {
17421   mp_type(q)=mp_cmykcolor_type;
17422   mp_init_big_node(mp, q); t=value(q);
17423   mp->mem[cyan_part_loc(t)]=mp->mem[red_part_loc(r)];
17424   value(cyan_part_loc(t))=value(red_part_loc(r));
17425   mp->mem[magenta_part_loc(t)]=mp->mem[green_part_loc(r)];
17426   value(magenta_part_loc(t))=value(green_part_loc(r));
17427   mp->mem[yellow_part_loc(t)]=mp->mem[blue_part_loc(r)];
17428   value(yellow_part_loc(t))=value(blue_part_loc(r));
17429   mp_recycle_value(mp, r);
17430   r=t;
17431   @<Scan the last of a quartet of numerics@>;
17432 }
17433 mp_check_delimiter(mp, l_delim,r_delim);
17434 mp->cur_type=mp_type(q);
17435 mp->cur_exp=q;
17436 }
17437
17438 @ @<Make sure the second part of a pair or color has a numeric type@>=
17439 if ( mp->cur_type<mp_known ) {
17440   exp_err("Nonnumeric ypart has been replaced by 0");
17441 @.Nonnumeric...replaced by 0@>
17442   help4("I've started to scan a pair `(a,b)' or a color `(a,b,c)';",
17443     "but after finding a nice `a' I found a `b' that isn't",
17444     "of numeric type. So I've changed that part to zero.",
17445     "(The b that I didn't like appears above the error message.)");
17446   mp_put_get_flush_error(mp, 0);
17447 }
17448
17449 @ @<Scan the last of a triplet of numerics@>=
17450
17451   mp_get_x_next(mp); mp_scan_expression(mp);
17452   if ( mp->cur_type<mp_known ) {
17453     exp_err("Nonnumeric third part has been replaced by 0");
17454 @.Nonnumeric...replaced by 0@>
17455     help3("I've just scanned a color `(a,b,c)' or cmykcolor(a,b,c,d); but the `c'",
17456       "isn't of numeric type. So I've changed that part to zero.",
17457       "(The c that I didn't like appears above the error message.)");
17458     mp_put_get_flush_error(mp, 0);
17459   }
17460   mp_stash_in(mp, blue_part_loc(r));
17461 }
17462
17463 @ @<Scan the last of a quartet of numerics@>=
17464
17465   mp_get_x_next(mp); mp_scan_expression(mp);
17466   if ( mp->cur_type<mp_known ) {
17467     exp_err("Nonnumeric blackpart has been replaced by 0");
17468 @.Nonnumeric...replaced by 0@>
17469     help3("I've just scanned a cmykcolor `(c,m,y,k)'; but the `k' isn't",
17470       "of numeric type. So I've changed that part to zero.",
17471       "(The k that I didn't like appears above the error message.)");
17472     mp_put_get_flush_error(mp, 0);
17473   }
17474   mp_stash_in(mp, black_part_loc(r));
17475 }
17476
17477 @ The local variable |group_line| keeps track of the line
17478 where a \&{begingroup} command occurred; this will be useful
17479 in an error message if the group doesn't actually end.
17480
17481 @<Other local variables for |scan_primary|@>=
17482 integer group_line; /* where a group began */
17483
17484 @ @<Scan a grouped primary@>=
17485
17486   group_line=mp_true_line(mp);
17487   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17488   save_boundary_item(p);
17489   do {  
17490     mp_do_statement(mp); /* ends with |cur_cmd>=semicolon| */
17491   } while (mp->cur_cmd==semicolon);
17492   if ( mp->cur_cmd!=end_group ) {
17493     print_err("A group begun on line ");
17494 @.A group...never ended@>
17495     mp_print_int(mp, group_line);
17496     mp_print(mp, " never ended");
17497     help2("I saw a `begingroup' back there that hasn't been matched",
17498           "by `endgroup'. So I've inserted `endgroup' now.");
17499     mp_back_error(mp); mp->cur_cmd=end_group;
17500   }
17501   mp_unsave(mp); 
17502     /* this might change |cur_type|, if independent variables are recycled */
17503   if ( mp->internal[mp_tracing_commands]>0 ) show_cur_cmd_mod;
17504 }
17505
17506 @ @<Scan a string constant@>=
17507
17508   mp->cur_type=mp_string_type; mp->cur_exp=mp->cur_mod;
17509 }
17510
17511 @ Later we'll come to procedures that perform actual operations like
17512 addition, square root, and so on; our purpose now is to do the parsing.
17513 But we might as well mention those future procedures now, so that the
17514 suspense won't be too bad:
17515
17516 \smallskip
17517 |do_nullary(c)| does primitive operations that have no operands (e.g.,
17518 `\&{true}' or `\&{pencircle}');
17519
17520 \smallskip
17521 |do_unary(c)| applies a primitive operation to the current expression;
17522
17523 \smallskip
17524 |do_binary(p,c)| applies a primitive operation to the capsule~|p|
17525 and the current expression.
17526
17527 @<Scan a nullary operation@>=mp_do_nullary(mp, mp->cur_mod)
17528
17529 @ @<Scan a unary operation@>=
17530
17531   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_primary(mp); 
17532   mp_do_unary(mp, c); goto DONE;
17533 }
17534
17535 @ A numeric token might be a primary by itself, or it might be the
17536 numerator of a fraction composed solely of numeric tokens, or it might
17537 multiply the primary that follows (provided that the primary doesn't begin
17538 with a plus sign or a minus sign). The code here uses the facts that
17539 |max_primary_command=plus_or_minus| and
17540 |max_primary_command-1=numeric_token|. If a fraction is found that is less
17541 than unity, we try to retain higher precision when we use it in scalar
17542 multiplication.
17543
17544 @<Other local variables for |scan_primary|@>=
17545 scaled num,denom; /* for primaries that are fractions, like `1/2' */
17546
17547 @ @<Scan a primary that starts with a numeric token@>=
17548
17549   mp->cur_exp=mp->cur_mod; mp->cur_type=mp_known; mp_get_x_next(mp);
17550   if ( mp->cur_cmd!=slash ) { 
17551     num=0; denom=0;
17552   } else { 
17553     mp_get_x_next(mp);
17554     if ( mp->cur_cmd!=numeric_token ) { 
17555       mp_back_input(mp);
17556       mp->cur_cmd=slash; mp->cur_mod=over; mp->cur_sym=frozen_slash;
17557       goto DONE;
17558     }
17559     num=mp->cur_exp; denom=mp->cur_mod;
17560     if ( denom==0 ) { @<Protest division by zero@>; }
17561     else { mp->cur_exp=mp_make_scaled(mp, num,denom); }
17562     check_arith; mp_get_x_next(mp);
17563   }
17564   if ( mp->cur_cmd>=min_primary_command ) {
17565    if ( mp->cur_cmd<numeric_token ) { /* in particular, |cur_cmd<>plus_or_minus| */
17566      p=mp_stash_cur_exp(mp); mp_scan_primary(mp);
17567      if ( (abs(num)>=abs(denom))||(mp->cur_type<mp_color_type) ) {
17568        mp_do_binary(mp, p,times);
17569      } else {
17570        mp_frac_mult(mp, num,denom);
17571        mp_free_node(mp, p,value_node_size);
17572      }
17573     }
17574   }
17575   goto DONE;
17576 }
17577
17578 @ @<Protest division...@>=
17579
17580   print_err("Division by zero");
17581 @.Division by zero@>
17582   help1("I'll pretend that you meant to divide by 1."); mp_error(mp);
17583 }
17584
17585 @ @<Scan a binary operation with `\&{of}' between its operands@>=
17586
17587   c=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
17588   if ( mp->cur_cmd!=of_token ) {
17589     mp_missing_err(mp, "of"); mp_print(mp, " for "); 
17590     mp_print_cmd_mod(mp, primary_binary,c);
17591 @.Missing `of'@>
17592     help1("I've got the first argument; will look now for the other.");
17593     mp_back_error(mp);
17594   }
17595   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_primary(mp); 
17596   mp_do_binary(mp, p,c); goto DONE;
17597 }
17598
17599 @ @<Convert a suffix to a string@>=
17600
17601   mp_get_x_next(mp); mp_scan_suffix(mp); 
17602   mp->old_setting=mp->selector; mp->selector=new_string;
17603   mp_show_token_list(mp, mp->cur_exp,null,100000,0); 
17604   mp_flush_token_list(mp, mp->cur_exp);
17605   mp->cur_exp=mp_make_string(mp); mp->selector=mp->old_setting; 
17606   mp->cur_type=mp_string_type;
17607   goto DONE;
17608 }
17609
17610 @ If an internal quantity appears all by itself on the left of an
17611 assignment, we return a token list of length one, containing the address
17612 of the internal quantity plus |hash_end|. (This accords with the conventions
17613 of the save stack, as described earlier.)
17614
17615 @<Scan an internal...@>=
17616
17617   q=mp->cur_mod;
17618   if ( my_var_flag==assignment ) {
17619     mp_get_x_next(mp);
17620     if ( mp->cur_cmd==assignment ) {
17621       mp->cur_exp=mp_get_avail(mp);
17622       mp_info(mp->cur_exp)=q+hash_end; mp->cur_type=mp_token_list; 
17623       goto DONE;
17624     }
17625     mp_back_input(mp);
17626   }
17627   mp->cur_type=mp_known; mp->cur_exp=mp->internal[q];
17628 }
17629
17630 @ The most difficult part of |scan_primary| has been saved for last, since
17631 it was necessary to build up some confidence first. We can now face the task
17632 of scanning a variable.
17633
17634 As we scan a variable, we build a token list containing the relevant
17635 names and subscript values, simultaneously following along in the
17636 ``collective'' structure to see if we are actually dealing with a macro
17637 instead of a value.
17638
17639 The local variables |pre_head| and |post_head| will point to the beginning
17640 of the prefix and suffix lists; |tail| will point to the end of the list
17641 that is currently growing.
17642
17643 Another local variable, |tt|, contains partial information about the
17644 declared type of the variable-so-far. If |tt>=mp_unsuffixed_macro|, the
17645 relation |tt=mp_type(q)| will always hold. If |tt=undefined|, the routine
17646 doesn't bother to update its information about type. And if
17647 |undefined<tt<mp_unsuffixed_macro|, the precise value of |tt| isn't critical.
17648
17649 @ @<Other local variables for |scan_primary|@>=
17650 pointer pre_head,post_head,tail;
17651   /* prefix and suffix list variables */
17652 quarterword tt; /* approximation to the type of the variable-so-far */
17653 pointer t; /* a token */
17654 pointer macro_ref = 0; /* reference count for a suffixed macro */
17655
17656 @ @<Scan a variable primary...@>=
17657
17658   fast_get_avail(pre_head); tail=pre_head; post_head=null; tt=mp_vacuous;
17659   while (1) { 
17660     t=mp_cur_tok(mp); mp_link(tail)=t;
17661     if ( tt!=undefined ) {
17662        @<Find the approximate type |tt| and corresponding~|q|@>;
17663       if ( tt>=mp_unsuffixed_macro ) {
17664         @<Either begin an unsuffixed macro call or
17665           prepare for a suffixed one@>;
17666       }
17667     }
17668     mp_get_x_next(mp); tail=t;
17669     if ( mp->cur_cmd==left_bracket ) {
17670       @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>;
17671     }
17672     if ( mp->cur_cmd>max_suffix_token ) break;
17673     if ( mp->cur_cmd<min_suffix_token ) break;
17674   } /* now |cur_cmd| is |internal_quantity|, |tag_token|, or |numeric_token| */
17675   @<Handle unusual cases that masquerade as variables, and |goto restart|
17676     or |goto done| if appropriate;
17677     otherwise make a copy of the variable and |goto done|@>;
17678 }
17679
17680 @ @<Either begin an unsuffixed macro call or...@>=
17681
17682   mp_link(tail)=null;
17683   if ( tt>mp_unsuffixed_macro ) { /* |tt=mp_suffixed_macro| */
17684     post_head=mp_get_avail(mp); tail=post_head; mp_link(tail)=t;
17685     tt=undefined; macro_ref=value(q); add_mac_ref(macro_ref);
17686   } else {
17687     @<Set up unsuffixed macro call and |goto restart|@>;
17688   }
17689 }
17690
17691 @ @<Scan for a subscript; replace |cur_cmd| by |numeric_token| if found@>=
17692
17693   mp_get_x_next(mp); mp_scan_expression(mp);
17694   if ( mp->cur_cmd!=right_bracket ) {
17695     @<Put the left bracket and the expression back to be rescanned@>;
17696   } else { 
17697     if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17698     mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp; mp->cur_sym=0;
17699   }
17700 }
17701
17702 @ The left bracket that we thought was introducing a subscript might have
17703 actually been the left bracket in a mediation construction like `\.{x[a,b]}'.
17704 So we don't issue an error message at this point; but we do want to back up
17705 so as to avoid any embarrassment about our incorrect assumption.
17706
17707 @<Put the left bracket and the expression back to be rescanned@>=
17708
17709   mp_back_input(mp); /* that was the token following the current expression */
17710   mp_back_expr(mp); mp->cur_cmd=left_bracket; 
17711   mp->cur_mod=0; mp->cur_sym=frozen_left_bracket;
17712 }
17713
17714 @ Here's a routine that puts the current expression back to be read again.
17715
17716 @c 
17717 static void mp_back_expr (MP mp) {
17718   pointer p; /* capsule token */
17719   p=mp_stash_cur_exp(mp); mp_link(p)=null; back_list(p);
17720 }
17721
17722 @ Unknown subscripts lead to the following error message.
17723
17724 @c 
17725 static void mp_bad_subscript (MP mp) { 
17726   exp_err("Improper subscript has been replaced by zero");
17727 @.Improper subscript...@>
17728   help3("A bracketed subscript must have a known numeric value;",
17729     "unfortunately, what I found was the value that appears just",
17730     "above this error message. So I'll try a zero subscript.");
17731   mp_flush_error(mp, 0);
17732 }
17733
17734 @ Every time we call |get_x_next|, there's a chance that the variable we've
17735 been looking at will disappear. Thus, we cannot safely keep |q| pointing
17736 into the variable structure; we need to start searching from the root each time.
17737
17738 @<Find the approximate type |tt| and corresponding~|q|@>=
17739 @^inner loop@>
17740
17741   p=mp_link(pre_head); q=mp_info(p); tt=undefined;
17742   if ( eq_type(q) % outer_tag==tag_token ) {
17743     q=equiv(q);
17744     if ( q==null ) goto DONE2;
17745     while (1) { 
17746       p=mp_link(p);
17747       if ( p==null ) {
17748         tt=mp_type(q); goto DONE2;
17749       };
17750       if ( mp_type(q)!=mp_structured ) goto DONE2;
17751       q=mp_link(attr_head(q)); /* the |collective_subscript| attribute */
17752       if ( p>=mp->hi_mem_min ) { /* it's not a subscript */
17753         do {  q=mp_link(q); } while (! (attr_loc(q)>=mp_info(p)));
17754         if ( attr_loc(q)>mp_info(p) ) goto DONE2;
17755       }
17756     }
17757   }
17758 DONE2:
17759   ;
17760 }
17761
17762 @ How do things stand now? Well, we have scanned an entire variable name,
17763 including possible subscripts and/or attributes; |cur_cmd|, |cur_mod|, and
17764 |cur_sym| represent the token that follows. If |post_head=null|, a
17765 token list for this variable name starts at |mp_link(pre_head)|, with all
17766 subscripts evaluated. But if |post_head<>null|, the variable turned out
17767 to be a suffixed macro; |pre_head| is the head of the prefix list, while
17768 |post_head| is the head of a token list containing both `\.{\AT!}' and
17769 the suffix.
17770
17771 Our immediate problem is to see if this variable still exists. (Variable
17772 structures can change drastically whenever we call |get_x_next|; users
17773 aren't supposed to do this, but the fact that it is possible means that
17774 we must be cautious.)
17775
17776 The following procedure prints an error message when a variable
17777 unexpectedly disappears. Its help message isn't quite right for
17778 our present purposes, but we'll be able to fix that up.
17779
17780 @c 
17781 static void mp_obliterated (MP mp,pointer q) { 
17782   print_err("Variable "); mp_show_token_list(mp, q,null,1000,0);
17783   mp_print(mp, " has been obliterated");
17784 @.Variable...obliterated@>
17785   help5("It seems you did a nasty thing---probably by accident,",
17786      "but nevertheless you nearly hornswoggled me...",
17787      "While I was evaluating the right-hand side of this",
17788      "command, something happened, and the left-hand side",
17789      "is no longer a variable! So I won't change anything.");
17790 }
17791
17792 @ If the variable does exist, we also need to check
17793 for a few other special cases before deciding that a plain old ordinary
17794 variable has, indeed, been scanned.
17795
17796 @<Handle unusual cases that masquerade as variables...@>=
17797 if ( post_head!=null ) {
17798   @<Set up suffixed macro call and |goto restart|@>;
17799 }
17800 q=mp_link(pre_head); free_avail(pre_head);
17801 if ( mp->cur_cmd==my_var_flag ) { 
17802   mp->cur_type=mp_token_list; mp->cur_exp=q; goto DONE;
17803 }
17804 p=mp_find_variable(mp, q);
17805 if ( p!=null ) {
17806   mp_make_exp_copy(mp, p);
17807 } else { 
17808   mp_obliterated(mp, q);
17809   mp->help_line[2]="While I was evaluating the suffix of this variable,";
17810   mp->help_line[1]="something was redefined, and it's no longer a variable!";
17811   mp->help_line[0]="In order to get back on my feet, I've inserted `0' instead.";
17812   mp_put_get_flush_error(mp, 0);
17813 }
17814 mp_flush_node_list(mp, q); 
17815 goto DONE
17816
17817 @ The only complication associated with macro calling is that the prefix
17818 and ``at'' parameters must be packaged in an appropriate list of lists.
17819
17820 @<Set up unsuffixed macro call and |goto restart|@>=
17821
17822   p=mp_get_avail(mp); mp_info(pre_head)=mp_link(pre_head); mp_link(pre_head)=p;
17823   mp_info(p)=t; mp_macro_call(mp, value(q),pre_head,null);
17824   mp_get_x_next(mp); 
17825   goto RESTART;
17826 }
17827
17828 @ If the ``variable'' that turned out to be a suffixed macro no longer exists,
17829 we don't care, because we have reserved a pointer (|macro_ref|) to its
17830 token list.
17831
17832 @<Set up suffixed macro call and |goto restart|@>=
17833
17834   mp_back_input(mp); p=mp_get_avail(mp); q=mp_link(post_head);
17835   mp_info(pre_head)=mp_link(pre_head); mp_link(pre_head)=post_head;
17836   mp_info(post_head)=q; mp_link(post_head)=p; mp_info(p)=mp_link(q); mp_link(q)=null;
17837   mp_macro_call(mp, macro_ref,pre_head,null); decr(ref_count(macro_ref));
17838   mp_get_x_next(mp); goto RESTART;
17839 }
17840
17841 @ Our remaining job is simply to make a copy of the value that has been
17842 found. Some cases are harder than others, but complexity arises solely
17843 because of the multiplicity of possible cases.
17844
17845 @<Declare the procedure called |make_exp_copy|@>=
17846 @<Declare subroutines needed by |make_exp_copy|@>
17847 static void mp_make_exp_copy (MP mp,pointer p) {
17848   pointer q,r,t; /* registers for list manipulation */
17849 RESTART: 
17850   mp->cur_type=mp_type(p);
17851   switch (mp->cur_type) {
17852   case mp_vacuous: case mp_boolean_type: case mp_known:
17853     mp->cur_exp=value(p); break;
17854   case unknown_types:
17855     mp->cur_exp=mp_new_ring_entry(mp, p);
17856     break;
17857   case mp_string_type: 
17858     mp->cur_exp=value(p); add_str_ref(mp->cur_exp);
17859     break;
17860   case mp_picture_type:
17861     mp->cur_exp=value(p);add_edge_ref(mp->cur_exp);
17862     break;
17863   case mp_pen_type:
17864     mp->cur_exp=copy_pen(value(p));
17865     break; 
17866   case mp_path_type:
17867     mp->cur_exp=mp_copy_path(mp, value(p));
17868     break;
17869   case mp_transform_type: case mp_color_type: 
17870   case mp_cmykcolor_type: case mp_pair_type:
17871     @<Copy the big node |p|@>;
17872     break;
17873   case mp_dependent: case mp_proto_dependent:
17874     mp_encapsulate(mp, mp_copy_dep_list(mp, dep_list(p)));
17875     break;
17876   case mp_numeric_type: 
17877     new_indep(p); goto RESTART;
17878     break;
17879   case mp_independent: 
17880     q=mp_single_dependency(mp, p);
17881     if ( q==mp->dep_final ){ 
17882       mp->cur_type=mp_known; mp->cur_exp=0; mp_free_node(mp, q,dep_node_size);
17883     } else { 
17884       mp->cur_type=mp_dependent; mp_encapsulate(mp, q);
17885     }
17886     break;
17887   default: 
17888     mp_confusion(mp, "copy");
17889 @:this can't happen copy}{\quad copy@>
17890     break;
17891   }
17892 }
17893
17894 @ The |encapsulate| subroutine assumes that |dep_final| is the
17895 tail of dependency list~|p|.
17896
17897 @<Declare subroutines needed by |make_exp_copy|@>=
17898 static void mp_encapsulate (MP mp,pointer p) { 
17899   mp->cur_exp=mp_get_node(mp, value_node_size); mp_type(mp->cur_exp)=mp->cur_type;
17900   mp_name_type(mp->cur_exp)=mp_capsule; mp_new_dep(mp, mp->cur_exp,p);
17901 }
17902
17903 @ The most tedious case arises when the user refers to a
17904 \&{pair}, \&{color}, or \&{transform} variable; we must copy several fields,
17905 each of which can be |independent|, |dependent|, |mp_proto_dependent|,
17906 or |known|.
17907
17908 @<Copy the big node |p|@>=
17909
17910   if ( value(p)==null ) 
17911     mp_init_big_node(mp, p);
17912   t=mp_get_node(mp, value_node_size); mp_name_type(t)=mp_capsule; mp_type(t)=mp->cur_type;
17913   mp_init_big_node(mp, t);
17914   q=value(p)+mp->big_node_size[mp->cur_type]; 
17915   r=value(t)+mp->big_node_size[mp->cur_type];
17916   do {  
17917     q=q-2; r=r-2; mp_install(mp, r,q);
17918   } while (q!=value(p));
17919   mp->cur_exp=t;
17920 }
17921
17922 @ The |install| procedure copies a numeric field~|q| into field~|r| of
17923 a big node that will be part of a capsule.
17924
17925 @<Declare subroutines needed by |make_exp_copy|@>=
17926 static void mp_install (MP mp,pointer r, pointer q) {
17927   pointer p; /* temporary register */
17928   if ( mp_type(q)==mp_known ){ 
17929     value(r)=value(q); mp_type(r)=mp_known;
17930   } else  if ( mp_type(q)==mp_independent ) {
17931     p=mp_single_dependency(mp, q);
17932     if ( p==mp->dep_final ) {
17933       mp_type(r)=mp_known; value(r)=0; mp_free_node(mp, p,dep_node_size);
17934     } else  { 
17935       mp_type(r)=mp_dependent; mp_new_dep(mp, r,p);
17936     }
17937   } else {
17938     mp_type(r)=mp_type(q); mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(q)));
17939   }
17940 }
17941
17942 @ Expressions of the form `\.{a[b,c]}' are converted into
17943 `\.{b+a*(c-b)}', without checking the types of \.b~or~\.c,
17944 provided that \.a is numeric.
17945
17946 @<Scan a mediation...@>=
17947
17948   p=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17949   if ( mp->cur_cmd!=comma ) {
17950     @<Put the left bracket and the expression back...@>;
17951     mp_unstash_cur_exp(mp, p);
17952   } else { 
17953     q=mp_stash_cur_exp(mp); mp_get_x_next(mp); mp_scan_expression(mp);
17954     if ( mp->cur_cmd!=right_bracket ) {
17955       mp_missing_err(mp, "]");
17956 @.Missing `]'@>
17957       help3("I've scanned an expression of the form `a[b,c',",
17958       "so a right bracket should have come next.",
17959       "I shall pretend that one was there.");
17960       mp_back_error(mp);
17961     }
17962     r=mp_stash_cur_exp(mp); mp_make_exp_copy(mp, q);
17963     mp_do_binary(mp, r,minus); mp_do_binary(mp, p,times); 
17964     mp_do_binary(mp, q,plus); mp_get_x_next(mp);
17965   }
17966 }
17967
17968 @ Here is a comparatively simple routine that is used to scan the
17969 \&{suffix} parameters of a macro.
17970
17971 @<Declare the basic parsing subroutines@>=
17972 static void mp_scan_suffix (MP mp) {
17973   pointer h,t; /* head and tail of the list being built */
17974   pointer p; /* temporary register */
17975   h=mp_get_avail(mp); t=h;
17976   while (1) { 
17977     if ( mp->cur_cmd==left_bracket ) {
17978       @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>;
17979     }
17980     if ( mp->cur_cmd==numeric_token ) {
17981       p=mp_new_num_tok(mp, mp->cur_mod);
17982     } else if ((mp->cur_cmd==tag_token)||(mp->cur_cmd==internal_quantity) ) {
17983        p=mp_get_avail(mp); mp_info(p)=mp->cur_sym;
17984     } else {
17985       break;
17986     }
17987     mp_link(t)=p; t=p; mp_get_x_next(mp);
17988   }
17989   mp->cur_exp=mp_link(h); free_avail(h); mp->cur_type=mp_token_list;
17990 }
17991
17992 @ @<Scan a bracketed subscript and set |cur_cmd:=numeric_token|@>=
17993
17994   mp_get_x_next(mp); mp_scan_expression(mp);
17995   if ( mp->cur_type!=mp_known ) mp_bad_subscript(mp);
17996   if ( mp->cur_cmd!=right_bracket ) {
17997      mp_missing_err(mp, "]");
17998 @.Missing `]'@>
17999     help3("I've seen a `[' and a subscript value, in a suffix,",
18000       "so a right bracket should have come next.",
18001       "I shall pretend that one was there.");
18002     mp_back_error(mp);
18003   }
18004   mp->cur_cmd=numeric_token; mp->cur_mod=mp->cur_exp;
18005 }
18006
18007 @* \[38] Parsing secondary and higher expressions.
18008
18009 After the intricacies of |scan_primary|\kern-1pt,
18010 the |scan_secondary| routine is
18011 refreshingly simple. It's not trivial, but the operations are relatively
18012 straightforward; the main difficulty is, again, that expressions and data
18013 structures might change drastically every time we call |get_x_next|, so a
18014 cautious approach is mandatory. For example, a macro defined by
18015 \&{primarydef} might have disappeared by the time its second argument has
18016 been scanned; we solve this by increasing the reference count of its token
18017 list, so that the macro can be called even after it has been clobbered.
18018
18019 @<Declare the basic parsing subroutines@>=
18020 static void mp_scan_secondary (MP mp) {
18021   pointer p; /* for list manipulation */
18022   halfword c,d; /* operation codes or modifiers */
18023   pointer mac_name; /* token defined with \&{primarydef} */
18024 RESTART:
18025   if ((mp->cur_cmd<min_primary_command)||
18026       (mp->cur_cmd>max_primary_command) )
18027     mp_bad_exp(mp, "A secondary");
18028 @.A secondary expression...@>
18029   mp_scan_primary(mp);
18030 CONTINUE: 
18031   if ( mp->cur_cmd<=max_secondary_command &&
18032        mp->cur_cmd>=min_secondary_command ) {
18033     p=mp_stash_cur_exp(mp); 
18034     c=mp->cur_mod; d=mp->cur_cmd;
18035     if ( d==secondary_primary_macro ) { 
18036       mac_name=mp->cur_sym; 
18037       add_mac_ref(c);
18038     }
18039     mp_get_x_next(mp); 
18040     mp_scan_primary(mp);
18041     if ( d!=secondary_primary_macro ) {
18042       mp_do_binary(mp, p,c);
18043     } else { 
18044       mp_back_input(mp); 
18045       mp_binary_mac(mp, p,c,mac_name);
18046       decr(ref_count(c)); 
18047       mp_get_x_next(mp); 
18048       goto RESTART;
18049     }
18050     goto CONTINUE;
18051   }
18052 }
18053
18054 @ The following procedure calls a macro that has two parameters,
18055 |p| and |cur_exp|.
18056
18057 @c 
18058 static void mp_binary_mac (MP mp,pointer p, pointer c, pointer n) {
18059   pointer q,r; /* nodes in the parameter list */
18060   q=mp_get_avail(mp); r=mp_get_avail(mp); mp_link(q)=r;
18061   mp_info(q)=p; mp_info(r)=mp_stash_cur_exp(mp);
18062   mp_macro_call(mp, c,q,n);
18063 }
18064
18065 @ The next procedure, |scan_tertiary|, is pretty much the same deal.
18066
18067 @<Declare the basic parsing subroutines@>=
18068 static void mp_scan_tertiary (MP mp) {
18069   pointer p; /* for list manipulation */
18070   halfword c,d; /* operation codes or modifiers */
18071   pointer mac_name; /* token defined with \&{secondarydef} */
18072 RESTART:
18073   if ((mp->cur_cmd<min_primary_command)||
18074       (mp->cur_cmd>max_primary_command) )
18075     mp_bad_exp(mp, "A tertiary");
18076 @.A tertiary expression...@>
18077   mp_scan_secondary(mp);
18078 CONTINUE: 
18079   if ( mp->cur_cmd<=max_tertiary_command ) {
18080     if ( mp->cur_cmd>=min_tertiary_command ) {
18081       p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18082       if ( d==tertiary_secondary_macro ) { 
18083         mac_name=mp->cur_sym; add_mac_ref(c);
18084       };
18085       mp_get_x_next(mp); mp_scan_secondary(mp);
18086       if ( d!=tertiary_secondary_macro ) {
18087         mp_do_binary(mp, p,c);
18088       } else { 
18089         mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18090         decr(ref_count(c)); mp_get_x_next(mp); 
18091         goto RESTART;
18092       }
18093       goto CONTINUE;
18094     }
18095   }
18096 }
18097
18098 @ Finally we reach the deepest level in our quartet of parsing routines.
18099 This one is much like the others; but it has an extra complication from
18100 paths, which materialize here.
18101
18102 @d continue_path 25 /* a label inside of |scan_expression| */
18103 @d finish_path 26 /* another */
18104
18105 @<Declare the basic parsing subroutines@>=
18106 static void mp_scan_expression (MP mp) {
18107   pointer p,q,r,pp,qq; /* for list manipulation */
18108   halfword c,d; /* operation codes or modifiers */
18109   int my_var_flag; /* initial value of |var_flag| */
18110   pointer mac_name; /* token defined with \&{tertiarydef} */
18111   boolean cycle_hit; /* did a path expression just end with `\&{cycle}'? */
18112   scaled x,y; /* explicit coordinates or tension at a path join */
18113   int t; /* knot type following a path join */
18114   t=0; y=0; x=0;
18115   my_var_flag=mp->var_flag; mac_name=null;
18116 RESTART:
18117   if ((mp->cur_cmd<min_primary_command)||
18118       (mp->cur_cmd>max_primary_command) )
18119     mp_bad_exp(mp, "An");
18120 @.An expression...@>
18121   mp_scan_tertiary(mp);
18122 CONTINUE: 
18123   if ( mp->cur_cmd<=max_expression_command )
18124     if ( mp->cur_cmd>=min_expression_command ) {
18125       if ( (mp->cur_cmd!=equals)||(my_var_flag!=assignment) ) {
18126         p=mp_stash_cur_exp(mp); c=mp->cur_mod; d=mp->cur_cmd;
18127         if ( d==expression_tertiary_macro ) {
18128           mac_name=mp->cur_sym; add_mac_ref(c);
18129         }
18130         if ( (d<ampersand)||((d==ampersand)&&
18131              ((mp_type(p)==mp_pair_type)||(mp_type(p)==mp_path_type))) ) {
18132           @<Scan a path construction operation;
18133             but |return| if |p| has the wrong type@>;
18134         } else { 
18135           mp_get_x_next(mp); mp_scan_tertiary(mp);
18136           if ( d!=expression_tertiary_macro ) {
18137             mp_do_binary(mp, p,c);
18138           } else  { 
18139             mp_back_input(mp); mp_binary_mac(mp, p,c,mac_name);
18140             decr(ref_count(c)); mp_get_x_next(mp); 
18141             goto RESTART;
18142           }
18143         }
18144         goto CONTINUE;
18145      }
18146   }
18147 }
18148
18149 @ The reader should review the data structure conventions for paths before
18150 hoping to understand the next part of this code.
18151
18152 @<Scan a path construction operation...@>=
18153
18154   cycle_hit=false;
18155   @<Convert the left operand, |p|, into a partial path ending at~|q|;
18156     but |return| if |p| doesn't have a suitable type@>;
18157 CONTINUE_PATH: 
18158   @<Determine the path join parameters;
18159     but |goto finish_path| if there's only a direction specifier@>;
18160   if ( mp->cur_cmd==cycle ) {
18161     @<Get ready to close a cycle@>;
18162   } else { 
18163     mp_scan_tertiary(mp);
18164     @<Convert the right operand, |cur_exp|,
18165       into a partial path from |pp| to~|qq|@>;
18166   }
18167   @<Join the partial paths and reset |p| and |q| to the head and tail
18168     of the result@>;
18169   if ( mp->cur_cmd>=min_expression_command )
18170     if ( mp->cur_cmd<=ampersand ) if ( ! cycle_hit ) goto CONTINUE_PATH;
18171 FINISH_PATH:
18172   @<Choose control points for the path and put the result into |cur_exp|@>;
18173 }
18174
18175 @ @<Convert the left operand, |p|, into a partial path ending at~|q|...@>=
18176
18177   mp_unstash_cur_exp(mp, p);
18178   if ( mp->cur_type==mp_pair_type ) p=mp_new_knot(mp);
18179   else if ( mp->cur_type==mp_path_type ) p=mp->cur_exp;
18180   else return;
18181   q=p;
18182   while ( mp_link(q)!=p ) q=mp_link(q);
18183   if ( mp_left_type(p)!=mp_endpoint ) { /* open up a cycle */
18184     r=mp_copy_knot(mp, p); mp_link(q)=r; q=r;
18185   }
18186   mp_left_type(p)=mp_open; mp_right_type(q)=mp_open;
18187 }
18188
18189 @ A pair of numeric values is changed into a knot node for a one-point path
18190 when \MP\ discovers that the pair is part of a path.
18191
18192 @c 
18193 static pointer mp_new_knot (MP mp) { /* convert a pair to a knot with two endpoints */
18194   pointer q; /* the new node */
18195   q=mp_get_node(mp, knot_node_size); mp_left_type(q)=mp_endpoint;
18196   mp_right_type(q)=mp_endpoint; mp_originator(q)=mp_metapost_user; mp_link(q)=q;
18197   mp_known_pair(mp); mp_x_coord(q)=mp->cur_x; mp_y_coord(q)=mp->cur_y;
18198   return q;
18199 }
18200
18201 @ The |known_pair| subroutine sets |cur_x| and |cur_y| to the components
18202 of the current expression, assuming that the current expression is a
18203 pair of known numerics. Unknown components are zeroed, and the
18204 current expression is flushed.
18205
18206 @<Declarations@>=
18207 static void mp_known_pair (MP mp);
18208
18209 @ @c
18210 void mp_known_pair (MP mp) {
18211   pointer p; /* the pair node */
18212   if ( mp->cur_type!=mp_pair_type ) {
18213     exp_err("Undefined coordinates have been replaced by (0,0)");
18214 @.Undefined coordinates...@>
18215     help5("I need x and y numbers for this part of the path.",
18216        "The value I found (see above) was no good;",
18217        "so I'll try to keep going by using zero instead.",
18218        "(Chapter 27 of The METAFONTbook explains that",
18219 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18220        "you might want to type `I ??" "?' now.)");
18221     mp_put_get_flush_error(mp, 0); mp->cur_x=0; mp->cur_y=0;
18222   } else { 
18223     p=value(mp->cur_exp);
18224      @<Make sure that both |x| and |y| parts of |p| are known;
18225        copy them into |cur_x| and |cur_y|@>;
18226     mp_flush_cur_exp(mp, 0);
18227   }
18228 }
18229
18230 @ @<Make sure that both |x| and |y| parts of |p| are known...@>=
18231 if ( mp_type(x_part_loc(p))==mp_known ) {
18232   mp->cur_x=value(x_part_loc(p));
18233 } else { 
18234   mp_disp_err(mp, x_part_loc(p),
18235     "Undefined x coordinate has been replaced by 0");
18236 @.Undefined coordinates...@>
18237   help5("I need a `known' x value for this part of the path.",
18238     "The value I found (see above) was no good;",
18239     "so I'll try to keep going by using zero instead.",
18240     "(Chapter 27 of The METAFONTbook explains that",
18241 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18242     "you might want to type `I ??" "?' now.)");
18243   mp_put_get_error(mp); mp_recycle_value(mp, x_part_loc(p)); mp->cur_x=0;
18244 }
18245 if ( mp_type(y_part_loc(p))==mp_known ) {
18246   mp->cur_y=value(y_part_loc(p));
18247 } else { 
18248   mp_disp_err(mp, y_part_loc(p),
18249     "Undefined y coordinate has been replaced by 0");
18250   help5("I need a `known' y value for this part of the path.",
18251     "The value I found (see above) was no good;",
18252     "so I'll try to keep going by using zero instead.",
18253     "(Chapter 27 of The METAFONTbook explains that",
18254     "you might want to type `I ??" "?' now.)");
18255   mp_put_get_error(mp); mp_recycle_value(mp, y_part_loc(p)); mp->cur_y=0;
18256 }
18257
18258 @ At this point |cur_cmd| is either |ampersand|, |left_brace|, or |path_join|.
18259
18260 @<Determine the path join parameters...@>=
18261 if ( mp->cur_cmd==left_brace ) {
18262   @<Put the pre-join direction information into node |q|@>;
18263 }
18264 d=mp->cur_cmd;
18265 if ( d==path_join ) {
18266   @<Determine the tension and/or control points@>;
18267 } else if ( d!=ampersand ) {
18268   goto FINISH_PATH;
18269 }
18270 mp_get_x_next(mp);
18271 if ( mp->cur_cmd==left_brace ) {
18272   @<Put the post-join direction information into |x| and |t|@>;
18273 } else if ( mp_right_type(q)!=mp_explicit ) {
18274   t=mp_open; x=0;
18275 }
18276
18277 @ The |scan_direction| subroutine looks at the directional information
18278 that is enclosed in braces, and also scans ahead to the following character.
18279 A type code is returned, either |open| (if the direction was $(0,0)$),
18280 or |curl| (if the direction was a curl of known value |cur_exp|), or
18281 |given| (if the direction is given by the |angle| value that now
18282 appears in |cur_exp|).
18283
18284 There's nothing difficult about this subroutine, but the program is rather
18285 lengthy because a variety of potential errors need to be nipped in the bud.
18286
18287 @c 
18288 static quarterword mp_scan_direction (MP mp) {
18289   int t; /* the type of information found */
18290   scaled x; /* an |x| coordinate */
18291   mp_get_x_next(mp);
18292   if ( mp->cur_cmd==curl_command ) {
18293      @<Scan a curl specification@>;
18294   } else {
18295     @<Scan a given direction@>;
18296   }
18297   if ( mp->cur_cmd!=right_brace ) {
18298     mp_missing_err(mp, "}");
18299 @.Missing `\char`\}'@>
18300     help3("I've scanned a direction spec for part of a path,",
18301       "so a right brace should have come next.",
18302       "I shall pretend that one was there.");
18303     mp_back_error(mp);
18304   }
18305   mp_get_x_next(mp); 
18306   return t;
18307 }
18308
18309 @ @<Scan a curl specification@>=
18310 { mp_get_x_next(mp); mp_scan_expression(mp);
18311 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<0) ){ 
18312   exp_err("Improper curl has been replaced by 1");
18313 @.Improper curl@>
18314   help1("A curl must be a known, nonnegative number.");
18315   mp_put_get_flush_error(mp, unity);
18316 }
18317 t=mp_curl;
18318 }
18319
18320 @ @<Scan a given direction@>=
18321 { mp_scan_expression(mp);
18322   if ( mp->cur_type>mp_pair_type ) {
18323     @<Get given directions separated by commas@>;
18324   } else {
18325     mp_known_pair(mp);
18326   }
18327   if ( (mp->cur_x==0)&&(mp->cur_y==0) )  t=mp_open;
18328   else  { t=mp_given; mp->cur_exp=mp_n_arg(mp, mp->cur_x,mp->cur_y);}
18329 }
18330
18331 @ @<Get given directions separated by commas@>=
18332
18333   if ( mp->cur_type!=mp_known ) {
18334     exp_err("Undefined x coordinate has been replaced by 0");
18335 @.Undefined coordinates...@>
18336     help5("I need a `known' x value for this part of the path.",
18337       "The value I found (see above) was no good;",
18338       "so I'll try to keep going by using zero instead.",
18339       "(Chapter 27 of The METAFONTbook explains that",
18340 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
18341       "you might want to type `I ??" "?' now.)");
18342     mp_put_get_flush_error(mp, 0);
18343   }
18344   x=mp->cur_exp;
18345   if ( mp->cur_cmd!=comma ) {
18346     mp_missing_err(mp, ",");
18347 @.Missing `,'@>
18348     help2("I've got the x coordinate of a path direction;",
18349           "will look for the y coordinate next.");
18350     mp_back_error(mp);
18351   }
18352   mp_get_x_next(mp); mp_scan_expression(mp);
18353   if ( mp->cur_type!=mp_known ) {
18354      exp_err("Undefined y coordinate has been replaced by 0");
18355     help5("I need a `known' y value for this part of the path.",
18356       "The value I found (see above) was no good;",
18357       "so I'll try to keep going by using zero instead.",
18358       "(Chapter 27 of The METAFONTbook explains that",
18359       "you might want to type `I ??" "?' now.)");
18360     mp_put_get_flush_error(mp, 0);
18361   }
18362   mp->cur_y=mp->cur_exp; mp->cur_x=x;
18363 }
18364
18365 @ At this point |mp_right_type(q)| is usually |open|, but it may have been
18366 set to some other value by a previous operation. We must maintain
18367 the value of |mp_right_type(q)| in cases such as
18368 `\.{..\{curl2\}z\{0,0\}..}'.
18369
18370 @<Put the pre-join...@>=
18371
18372   t=mp_scan_direction(mp);
18373   if ( t!=mp_open ) {
18374     mp_right_type(q)=t; right_given(q)=mp->cur_exp;
18375     if ( mp_left_type(q)==mp_open ) {
18376       mp_left_type(q)=t; left_given(q)=mp->cur_exp;
18377     } /* note that |left_given(q)=left_curl(q)| */
18378   }
18379 }
18380
18381 @ Since |left_tension| and |mp_left_y| share the same position in knot nodes,
18382 and since |left_given| is similarly equivalent to |mp_left_x|, we use
18383 |x| and |y| to hold the given direction and tension information when
18384 there are no explicit control points.
18385
18386 @<Put the post-join...@>=
18387
18388   t=mp_scan_direction(mp);
18389   if ( mp_right_type(q)!=mp_explicit ) x=mp->cur_exp;
18390   else t=mp_explicit; /* the direction information is superfluous */
18391 }
18392
18393 @ @<Determine the tension and/or...@>=
18394
18395   mp_get_x_next(mp);
18396   if ( mp->cur_cmd==tension ) {
18397     @<Set explicit tensions@>;
18398   } else if ( mp->cur_cmd==controls ) {
18399     @<Set explicit control points@>;
18400   } else  { 
18401     right_tension(q)=unity; y=unity; mp_back_input(mp); /* default tension */
18402     goto DONE;
18403   };
18404   if ( mp->cur_cmd!=path_join ) {
18405      mp_missing_err(mp, "..");
18406 @.Missing `..'@>
18407     help1("A path join command should end with two dots.");
18408     mp_back_error(mp);
18409   }
18410 DONE:
18411   ;
18412 }
18413
18414 @ @<Set explicit tensions@>=
18415
18416   mp_get_x_next(mp); y=mp->cur_cmd;
18417   if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18418   mp_scan_primary(mp);
18419   @<Make sure that the current expression is a valid tension setting@>;
18420   if ( y==at_least ) negate(mp->cur_exp);
18421   right_tension(q)=mp->cur_exp;
18422   if ( mp->cur_cmd==and_command ) {
18423     mp_get_x_next(mp); y=mp->cur_cmd;
18424     if ( mp->cur_cmd==at_least ) mp_get_x_next(mp);
18425     mp_scan_primary(mp);
18426     @<Make sure that the current expression is a valid tension setting@>;
18427     if ( y==at_least ) negate(mp->cur_exp);
18428   }
18429   y=mp->cur_exp;
18430 }
18431
18432 @ @d min_tension three_quarter_unit
18433
18434 @<Make sure that the current expression is a valid tension setting@>=
18435 if ( (mp->cur_type!=mp_known)||(mp->cur_exp<min_tension) ) {
18436   exp_err("Improper tension has been set to 1");
18437 @.Improper tension@>
18438   help1("The expression above should have been a number >=3/4.");
18439   mp_put_get_flush_error(mp, unity);
18440 }
18441
18442 @ @<Set explicit control points@>=
18443
18444   mp_right_type(q)=mp_explicit; t=mp_explicit; mp_get_x_next(mp); mp_scan_primary(mp);
18445   mp_known_pair(mp); mp_right_x(q)=mp->cur_x; mp_right_y(q)=mp->cur_y;
18446   if ( mp->cur_cmd!=and_command ) {
18447     x=mp_right_x(q); y=mp_right_y(q);
18448   } else { 
18449     mp_get_x_next(mp); mp_scan_primary(mp);
18450     mp_known_pair(mp); x=mp->cur_x; y=mp->cur_y;
18451   }
18452 }
18453
18454 @ @<Convert the right operand, |cur_exp|, into a partial path...@>=
18455
18456   if ( mp->cur_type!=mp_path_type ) pp=mp_new_knot(mp);
18457   else pp=mp->cur_exp;
18458   qq=pp;
18459   while ( mp_link(qq)!=pp ) qq=mp_link(qq);
18460   if ( mp_left_type(pp)!=mp_endpoint ) { /* open up a cycle */
18461     r=mp_copy_knot(mp, pp); mp_link(qq)=r; qq=r;
18462   }
18463   mp_left_type(pp)=mp_open; mp_right_type(qq)=mp_open;
18464 }
18465
18466 @ If a person tries to define an entire path by saying `\.{(x,y)\&cycle}',
18467 we silently change the specification to `\.{(x,y)..cycle}', since a cycle
18468 shouldn't have length zero.
18469
18470 @<Get ready to close a cycle@>=
18471
18472   cycle_hit=true; mp_get_x_next(mp); pp=p; qq=p;
18473   if ( d==ampersand ) if ( p==q ) {
18474     d=path_join; right_tension(q)=unity; y=unity;
18475   }
18476 }
18477
18478 @ @<Join the partial paths and reset |p| and |q|...@>=
18479
18480 if ( d==ampersand ) {
18481   if ( (mp_x_coord(q)!=mp_x_coord(pp))||(mp_y_coord(q)!=mp_y_coord(pp)) ) {
18482     print_err("Paths don't touch; `&' will be changed to `..'");
18483 @.Paths don't touch@>
18484     help3("When you join paths `p&q', the ending point of p",
18485       "must be exactly equal to the starting point of q.",
18486       "So I'm going to pretend that you said `p..q' instead.");
18487     mp_put_get_error(mp); d=path_join; right_tension(q)=unity; y=unity;
18488   }
18489 }
18490 @<Plug an opening in |mp_right_type(pp)|, if possible@>;
18491 if ( d==ampersand ) {
18492   @<Splice independent paths together@>;
18493 } else  { 
18494   @<Plug an opening in |mp_right_type(q)|, if possible@>;
18495   mp_link(q)=pp; mp_left_y(pp)=y;
18496   if ( t!=mp_open ) { mp_left_x(pp)=x; mp_left_type(pp)=t;  };
18497 }
18498 q=qq;
18499 }
18500
18501 @ @<Plug an opening in |mp_right_type(q)|...@>=
18502 if ( mp_right_type(q)==mp_open ) {
18503   if ( (mp_left_type(q)==mp_curl)||(mp_left_type(q)==mp_given) ) {
18504     mp_right_type(q)=mp_left_type(q); right_given(q)=left_given(q);
18505   }
18506 }
18507
18508 @ @<Plug an opening in |mp_right_type(pp)|...@>=
18509 if ( mp_right_type(pp)==mp_open ) {
18510   if ( (t==mp_curl)||(t==mp_given) ) {
18511     mp_right_type(pp)=t; right_given(pp)=x;
18512   }
18513 }
18514
18515 @ @<Splice independent paths together@>=
18516
18517   if ( mp_left_type(q)==mp_open ) if ( mp_right_type(q)==mp_open ) {
18518     mp_left_type(q)=mp_curl; left_curl(q)=unity;
18519   }
18520   if ( mp_right_type(pp)==mp_open ) if ( t==mp_open ) {
18521     mp_right_type(pp)=mp_curl; right_curl(pp)=unity;
18522   }
18523   mp_right_type(q)=mp_right_type(pp); mp_link(q)=mp_link(pp);
18524   mp_right_x(q)=mp_right_x(pp); mp_right_y(q)=mp_right_y(pp);
18525   mp_free_node(mp, pp,knot_node_size);
18526   if ( qq==pp ) qq=q;
18527 }
18528
18529 @ @<Choose control points for the path...@>=
18530 if ( cycle_hit ) { 
18531   if ( d==ampersand ) p=q;
18532 } else  { 
18533   mp_left_type(p)=mp_endpoint;
18534   if ( mp_right_type(p)==mp_open ) { 
18535     mp_right_type(p)=mp_curl; right_curl(p)=unity;
18536   }
18537   mp_right_type(q)=mp_endpoint;
18538   if ( mp_left_type(q)==mp_open ) { 
18539     mp_left_type(q)=mp_curl; left_curl(q)=unity;
18540   }
18541   mp_link(q)=p;
18542 }
18543 mp_make_choices(mp, p);
18544 mp->cur_type=mp_path_type; mp->cur_exp=p
18545
18546 @ Finally, we sometimes need to scan an expression whose value is
18547 supposed to be either |true_code| or |false_code|.
18548
18549 @<Declare the basic parsing subroutines@>=
18550 static void mp_get_boolean (MP mp) { 
18551   mp_get_x_next(mp); mp_scan_expression(mp);
18552   if ( mp->cur_type!=mp_boolean_type ) {
18553     exp_err("Undefined condition will be treated as `false'");
18554 @.Undefined condition...@>
18555     help2("The expression shown above should have had a definite",
18556           "true-or-false value. I'm changing it to `false'.");
18557     mp_put_get_flush_error(mp, false_code); mp->cur_type=mp_boolean_type;
18558   }
18559 }
18560
18561 @* \[39] Doing the operations.
18562 The purpose of parsing is primarily to permit people to avoid piles of
18563 parentheses. But the real work is done after the structure of an expression
18564 has been recognized; that's when new expressions are generated. We
18565 turn now to the guts of \MP, which handles individual operators that
18566 have come through the parsing mechanism.
18567
18568 We'll start with the easy ones that take no operands, then work our way
18569 up to operators with one and ultimately two arguments. In other words,
18570 we will write the three procedures |do_nullary|, |do_unary|, and |do_binary|
18571 that are invoked periodically by the expression scanners.
18572
18573 First let's make sure that all of the primitive operators are in the
18574 hash table. Although |scan_primary| and its relatives made use of the
18575 \\{cmd} code for these operators, the \\{do} routines base everything
18576 on the \\{mod} code. For example, |do_binary| doesn't care whether the
18577 operation it performs is a |primary_binary| or |secondary_binary|, etc.
18578
18579 @<Put each...@>=
18580 mp_primitive(mp, "true",nullary,true_code);
18581 @:true_}{\&{true} primitive@>
18582 mp_primitive(mp, "false",nullary,false_code);
18583 @:false_}{\&{false} primitive@>
18584 mp_primitive(mp, "nullpicture",nullary,null_picture_code);
18585 @:null_picture_}{\&{nullpicture} primitive@>
18586 mp_primitive(mp, "nullpen",nullary,null_pen_code);
18587 @:null_pen_}{\&{nullpen} primitive@>
18588 mp_primitive(mp, "jobname",nullary,job_name_op);
18589 @:job_name_}{\&{jobname} primitive@>
18590 mp_primitive(mp, "readstring",nullary,read_string_op);
18591 @:read_string_}{\&{readstring} primitive@>
18592 mp_primitive(mp, "pencircle",nullary,pen_circle);
18593 @:pen_circle_}{\&{pencircle} primitive@>
18594 mp_primitive(mp, "normaldeviate",nullary,normal_deviate);
18595 @:normal_deviate_}{\&{normaldeviate} primitive@>
18596 mp_primitive(mp, "readfrom",unary,read_from_op);
18597 @:read_from_}{\&{readfrom} primitive@>
18598 mp_primitive(mp, "closefrom",unary,close_from_op);
18599 @:close_from_}{\&{closefrom} primitive@>
18600 mp_primitive(mp, "odd",unary,odd_op);
18601 @:odd_}{\&{odd} primitive@>
18602 mp_primitive(mp, "known",unary,known_op);
18603 @:known_}{\&{known} primitive@>
18604 mp_primitive(mp, "unknown",unary,unknown_op);
18605 @:unknown_}{\&{unknown} primitive@>
18606 mp_primitive(mp, "not",unary,not_op);
18607 @:not_}{\&{not} primitive@>
18608 mp_primitive(mp, "decimal",unary,decimal);
18609 @:decimal_}{\&{decimal} primitive@>
18610 mp_primitive(mp, "reverse",unary,reverse);
18611 @:reverse_}{\&{reverse} primitive@>
18612 mp_primitive(mp, "makepath",unary,make_path_op);
18613 @:make_path_}{\&{makepath} primitive@>
18614 mp_primitive(mp, "makepen",unary,make_pen_op);
18615 @:make_pen_}{\&{makepen} primitive@>
18616 mp_primitive(mp, "oct",unary,oct_op);
18617 @:oct_}{\&{oct} primitive@>
18618 mp_primitive(mp, "hex",unary,hex_op);
18619 @:hex_}{\&{hex} primitive@>
18620 mp_primitive(mp, "ASCII",unary,ASCII_op);
18621 @:ASCII_}{\&{ASCII} primitive@>
18622 mp_primitive(mp, "char",unary,char_op);
18623 @:char_}{\&{char} primitive@>
18624 mp_primitive(mp, "length",unary,length_op);
18625 @:length_}{\&{length} primitive@>
18626 mp_primitive(mp, "turningnumber",unary,turning_op);
18627 @:turning_number_}{\&{turningnumber} primitive@>
18628 mp_primitive(mp, "xpart",unary,x_part);
18629 @:x_part_}{\&{xpart} primitive@>
18630 mp_primitive(mp, "ypart",unary,y_part);
18631 @:y_part_}{\&{ypart} primitive@>
18632 mp_primitive(mp, "xxpart",unary,xx_part);
18633 @:xx_part_}{\&{xxpart} primitive@>
18634 mp_primitive(mp, "xypart",unary,xy_part);
18635 @:xy_part_}{\&{xypart} primitive@>
18636 mp_primitive(mp, "yxpart",unary,yx_part);
18637 @:yx_part_}{\&{yxpart} primitive@>
18638 mp_primitive(mp, "yypart",unary,yy_part);
18639 @:yy_part_}{\&{yypart} primitive@>
18640 mp_primitive(mp, "redpart",unary,red_part);
18641 @:red_part_}{\&{redpart} primitive@>
18642 mp_primitive(mp, "greenpart",unary,green_part);
18643 @:green_part_}{\&{greenpart} primitive@>
18644 mp_primitive(mp, "bluepart",unary,blue_part);
18645 @:blue_part_}{\&{bluepart} primitive@>
18646 mp_primitive(mp, "cyanpart",unary,cyan_part);
18647 @:cyan_part_}{\&{cyanpart} primitive@>
18648 mp_primitive(mp, "magentapart",unary,magenta_part);
18649 @:magenta_part_}{\&{magentapart} primitive@>
18650 mp_primitive(mp, "yellowpart",unary,yellow_part);
18651 @:yellow_part_}{\&{yellowpart} primitive@>
18652 mp_primitive(mp, "blackpart",unary,black_part);
18653 @:black_part_}{\&{blackpart} primitive@>
18654 mp_primitive(mp, "greypart",unary,grey_part);
18655 @:grey_part_}{\&{greypart} primitive@>
18656 mp_primitive(mp, "colormodel",unary,color_model_part);
18657 @:color_model_part_}{\&{colormodel} primitive@>
18658 mp_primitive(mp, "fontpart",unary,font_part);
18659 @:font_part_}{\&{fontpart} primitive@>
18660 mp_primitive(mp, "textpart",unary,text_part);
18661 @:text_part_}{\&{textpart} primitive@>
18662 mp_primitive(mp, "pathpart",unary,path_part);
18663 @:path_part_}{\&{pathpart} primitive@>
18664 mp_primitive(mp, "penpart",unary,pen_part);
18665 @:pen_part_}{\&{penpart} primitive@>
18666 mp_primitive(mp, "dashpart",unary,dash_part);
18667 @:dash_part_}{\&{dashpart} primitive@>
18668 mp_primitive(mp, "sqrt",unary,sqrt_op);
18669 @:sqrt_}{\&{sqrt} primitive@>
18670 mp_primitive(mp, "mexp",unary,mp_m_exp_op);
18671 @:m_exp_}{\&{mexp} primitive@>
18672 mp_primitive(mp, "mlog",unary,mp_m_log_op);
18673 @:m_log_}{\&{mlog} primitive@>
18674 mp_primitive(mp, "sind",unary,sin_d_op);
18675 @:sin_d_}{\&{sind} primitive@>
18676 mp_primitive(mp, "cosd",unary,cos_d_op);
18677 @:cos_d_}{\&{cosd} primitive@>
18678 mp_primitive(mp, "floor",unary,floor_op);
18679 @:floor_}{\&{floor} primitive@>
18680 mp_primitive(mp, "uniformdeviate",unary,uniform_deviate);
18681 @:uniform_deviate_}{\&{uniformdeviate} primitive@>
18682 mp_primitive(mp, "charexists",unary,char_exists_op);
18683 @:char_exists_}{\&{charexists} primitive@>
18684 mp_primitive(mp, "fontsize",unary,font_size);
18685 @:font_size_}{\&{fontsize} primitive@>
18686 mp_primitive(mp, "llcorner",unary,ll_corner_op);
18687 @:ll_corner_}{\&{llcorner} primitive@>
18688 mp_primitive(mp, "lrcorner",unary,lr_corner_op);
18689 @:lr_corner_}{\&{lrcorner} primitive@>
18690 mp_primitive(mp, "ulcorner",unary,ul_corner_op);
18691 @:ul_corner_}{\&{ulcorner} primitive@>
18692 mp_primitive(mp, "urcorner",unary,ur_corner_op);
18693 @:ur_corner_}{\&{urcorner} primitive@>
18694 mp_primitive(mp, "arclength",unary,arc_length);
18695 @:arc_length_}{\&{arclength} primitive@>
18696 mp_primitive(mp, "angle",unary,angle_op);
18697 @:angle_}{\&{angle} primitive@>
18698 mp_primitive(mp, "cycle",cycle,cycle_op);
18699 @:cycle_}{\&{cycle} primitive@>
18700 mp_primitive(mp, "stroked",unary,stroked_op);
18701 @:stroked_}{\&{stroked} primitive@>
18702 mp_primitive(mp, "filled",unary,filled_op);
18703 @:filled_}{\&{filled} primitive@>
18704 mp_primitive(mp, "textual",unary,textual_op);
18705 @:textual_}{\&{textual} primitive@>
18706 mp_primitive(mp, "clipped",unary,clipped_op);
18707 @:clipped_}{\&{clipped} primitive@>
18708 mp_primitive(mp, "bounded",unary,bounded_op);
18709 @:bounded_}{\&{bounded} primitive@>
18710 mp_primitive(mp, "+",plus_or_minus,plus);
18711 @:+ }{\.{+} primitive@>
18712 mp_primitive(mp, "-",plus_or_minus,minus);
18713 @:- }{\.{-} primitive@>
18714 mp_primitive(mp, "*",secondary_binary,times);
18715 @:* }{\.{*} primitive@>
18716 mp_primitive(mp, "/",slash,over); mp->eqtb[frozen_slash]=mp->eqtb[mp->cur_sym];
18717 @:/ }{\.{/} primitive@>
18718 mp_primitive(mp, "++",tertiary_binary,pythag_add);
18719 @:++_}{\.{++} primitive@>
18720 mp_primitive(mp, "+-+",tertiary_binary,pythag_sub);
18721 @:+-+_}{\.{+-+} primitive@>
18722 mp_primitive(mp, "or",tertiary_binary,or_op);
18723 @:or_}{\&{or} primitive@>
18724 mp_primitive(mp, "and",and_command,and_op);
18725 @:and_}{\&{and} primitive@>
18726 mp_primitive(mp, "<",expression_binary,less_than);
18727 @:< }{\.{<} primitive@>
18728 mp_primitive(mp, "<=",expression_binary,less_or_equal);
18729 @:<=_}{\.{<=} primitive@>
18730 mp_primitive(mp, ">",expression_binary,greater_than);
18731 @:> }{\.{>} primitive@>
18732 mp_primitive(mp, ">=",expression_binary,greater_or_equal);
18733 @:>=_}{\.{>=} primitive@>
18734 mp_primitive(mp, "=",equals,equal_to);
18735 @:= }{\.{=} primitive@>
18736 mp_primitive(mp, "<>",expression_binary,unequal_to);
18737 @:<>_}{\.{<>} primitive@>
18738 mp_primitive(mp, "substring",primary_binary,substring_of);
18739 @:substring_}{\&{substring} primitive@>
18740 mp_primitive(mp, "subpath",primary_binary,subpath_of);
18741 @:subpath_}{\&{subpath} primitive@>
18742 mp_primitive(mp, "directiontime",primary_binary,direction_time_of);
18743 @:direction_time_}{\&{directiontime} primitive@>
18744 mp_primitive(mp, "point",primary_binary,point_of);
18745 @:point_}{\&{point} primitive@>
18746 mp_primitive(mp, "precontrol",primary_binary,precontrol_of);
18747 @:precontrol_}{\&{precontrol} primitive@>
18748 mp_primitive(mp, "postcontrol",primary_binary,postcontrol_of);
18749 @:postcontrol_}{\&{postcontrol} primitive@>
18750 mp_primitive(mp, "penoffset",primary_binary,pen_offset_of);
18751 @:pen_offset_}{\&{penoffset} primitive@>
18752 mp_primitive(mp, "arctime",primary_binary,arc_time_of);
18753 @:arc_time_of_}{\&{arctime} primitive@>
18754 mp_primitive(mp, "mpversion",nullary,mp_version);
18755 @:mp_verison_}{\&{mpversion} primitive@>
18756 mp_primitive(mp, "&",ampersand,concatenate);
18757 @:!!!}{\.{\&} primitive@>
18758 mp_primitive(mp, "rotated",secondary_binary,rotated_by);
18759 @:rotated_}{\&{rotated} primitive@>
18760 mp_primitive(mp, "slanted",secondary_binary,slanted_by);
18761 @:slanted_}{\&{slanted} primitive@>
18762 mp_primitive(mp, "scaled",secondary_binary,scaled_by);
18763 @:scaled_}{\&{scaled} primitive@>
18764 mp_primitive(mp, "shifted",secondary_binary,shifted_by);
18765 @:shifted_}{\&{shifted} primitive@>
18766 mp_primitive(mp, "transformed",secondary_binary,transformed_by);
18767 @:transformed_}{\&{transformed} primitive@>
18768 mp_primitive(mp, "xscaled",secondary_binary,x_scaled);
18769 @:x_scaled_}{\&{xscaled} primitive@>
18770 mp_primitive(mp, "yscaled",secondary_binary,y_scaled);
18771 @:y_scaled_}{\&{yscaled} primitive@>
18772 mp_primitive(mp, "zscaled",secondary_binary,z_scaled);
18773 @:z_scaled_}{\&{zscaled} primitive@>
18774 mp_primitive(mp, "infont",secondary_binary,in_font);
18775 @:in_font_}{\&{infont} primitive@>
18776 mp_primitive(mp, "intersectiontimes",tertiary_binary,intersect);
18777 @:intersection_times_}{\&{intersectiontimes} primitive@>
18778 mp_primitive(mp, "envelope",primary_binary,envelope_of);
18779 @:envelope_}{\&{envelope} primitive@>
18780
18781 @ @<Cases of |print_cmd...@>=
18782 case nullary:
18783 case unary:
18784 case primary_binary:
18785 case secondary_binary:
18786 case tertiary_binary:
18787 case expression_binary:
18788 case cycle:
18789 case plus_or_minus:
18790 case slash:
18791 case ampersand:
18792 case equals:
18793 case and_command:
18794   mp_print_op(mp, m);
18795   break;
18796
18797 @ OK, let's look at the simplest \\{do} procedure first.
18798
18799 @c @<Declare nullary action procedure@>
18800 static void mp_do_nullary (MP mp,quarterword c) { 
18801   check_arith;
18802   if ( mp->internal[mp_tracing_commands]>two )
18803     mp_show_cmd_mod(mp, nullary,c);
18804   switch (c) {
18805   case true_code: case false_code: 
18806     mp->cur_type=mp_boolean_type; mp->cur_exp=c;
18807     break;
18808   case null_picture_code: 
18809     mp->cur_type=mp_picture_type;
18810     mp->cur_exp=mp_get_node(mp, edge_header_size); 
18811     mp_init_edges(mp, mp->cur_exp);
18812     break;
18813   case null_pen_code: 
18814     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, 0);
18815     break;
18816   case normal_deviate: 
18817     mp->cur_type=mp_known; mp->cur_exp=mp_norm_rand(mp);
18818     break;
18819   case pen_circle: 
18820     mp->cur_type=mp_pen_type; mp->cur_exp=mp_get_pen_circle(mp, unity);
18821     break;
18822   case job_name_op:  
18823     if ( mp->job_name==NULL ) mp_open_log_file(mp);
18824     mp->cur_type=mp_string_type; mp->cur_exp=rts(mp->job_name);
18825     break;
18826   case mp_version: 
18827     mp->cur_type=mp_string_type; 
18828     mp->cur_exp=intern(metapost_version) ;
18829     break;
18830   case read_string_op:
18831     @<Read a string from the terminal@>;
18832     break;
18833   } /* there are no other cases */
18834   check_arith;
18835 }
18836
18837 @ @<Read a string...@>=
18838
18839   if (mp->noninteractive || mp->interaction<=mp_nonstop_mode )
18840     mp_fatal_error(mp, "*** (cannot readstring in nonstop modes)");
18841   mp_begin_file_reading(mp); name=is_read;
18842   limit=start; prompt_input("");
18843   mp_finish_read(mp);
18844 }
18845
18846 @ @<Declare nullary action procedure@>=
18847 static void mp_finish_read (MP mp) { /* copy |buffer| line to |cur_exp| */
18848   size_t k;
18849   str_room((int)mp->last-start);
18850   for (k=(size_t)start;k<=mp->last-1;k++) {
18851    append_char(mp->buffer[k]);
18852   }
18853   mp_end_file_reading(mp); mp->cur_type=mp_string_type; 
18854   mp->cur_exp=mp_make_string(mp);
18855 }
18856
18857 @ Things get a bit more interesting when there's an operand. The
18858 operand to |do_unary| appears in |cur_type| and |cur_exp|.
18859
18860 @c @<Declare unary action procedures@>
18861 static void mp_do_unary (MP mp,quarterword c) {
18862   pointer p,q,r; /* for list manipulation */
18863   integer x; /* a temporary register */
18864   check_arith;
18865   if ( mp->internal[mp_tracing_commands]>two )
18866     @<Trace the current unary operation@>;
18867   switch (c) {
18868   case plus:
18869     if ( mp->cur_type<mp_color_type ) mp_bad_unary(mp, plus);
18870     break;
18871   case minus:
18872     @<Negate the current expression@>;
18873     break;
18874   @<Additional cases of unary operators@>;
18875   } /* there are no other cases */
18876   check_arith;
18877 }
18878
18879 @ The |nice_pair| function returns |true| if both components of a pair
18880 are known.
18881
18882 @<Declare unary action procedures@>=
18883 static boolean mp_nice_pair (MP mp,integer p, quarterword t) { 
18884   if ( t==mp_pair_type ) {
18885     p=value(p);
18886     if ( mp_type(x_part_loc(p))==mp_known )
18887       if ( mp_type(y_part_loc(p))==mp_known )
18888         return true;
18889   }
18890   return false;
18891 }
18892
18893 @ The |nice_color_or_pair| function is analogous except that it also accepts
18894 fully known colors.
18895
18896 @<Declare unary action procedures@>=
18897 static boolean mp_nice_color_or_pair (MP mp,integer p, quarterword t) {
18898   pointer q,r; /* for scanning the big node */
18899   if ( (t!=mp_pair_type)&&(t!=mp_color_type)&&(t!=mp_cmykcolor_type) ) {
18900     return false;
18901   } else { 
18902     q=value(p);
18903     r=q+mp->big_node_size[mp_type(p)];
18904     do {  
18905       r=r-2;
18906       if ( mp_type(r)!=mp_known )
18907         return false;
18908     } while (r!=q);
18909     return true;
18910   }
18911 }
18912
18913 @ @<Declare unary action...@>=
18914 static void mp_print_known_or_unknown_type (MP mp,quarterword t, integer v) { 
18915   mp_print_char(mp, xord('('));
18916   if ( t>mp_known ) mp_print(mp, "unknown numeric");
18917   else { if ( (t==mp_pair_type)||(t==mp_color_type)||(t==mp_cmykcolor_type) )
18918     if ( ! mp_nice_color_or_pair(mp, v,t) ) mp_print(mp, "unknown ");
18919     mp_print_type(mp, t);
18920   }
18921   mp_print_char(mp, xord(')'));
18922 }
18923
18924 @ @<Declare unary action...@>=
18925 static void mp_bad_unary (MP mp,quarterword c) { 
18926   exp_err("Not implemented: "); mp_print_op(mp, c);
18927 @.Not implemented...@>
18928   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
18929   help3("I'm afraid I don't know how to apply that operation to that",
18930     "particular type. Continue, and I'll simply return the",
18931     "argument (shown above) as the result of the operation.");
18932   mp_put_get_error(mp);
18933 }
18934
18935 @ @<Trace the current unary operation@>=
18936
18937   mp_begin_diagnostic(mp); mp_print_nl(mp, "{"); 
18938   mp_print_op(mp, c); mp_print_char(mp, xord('('));
18939   mp_print_exp(mp, null,0); /* show the operand, but not verbosely */
18940   mp_print(mp, ")}"); mp_end_diagnostic(mp, false);
18941 }
18942
18943 @ Negation is easy except when the current expression
18944 is of type |independent|, or when it is a pair with one or more
18945 |independent| components.
18946
18947 It is tempting to argue that the negative of an independent variable
18948 is an independent variable, hence we don't have to do anything when
18949 negating it. The fallacy is that other dependent variables pointing
18950 to the current expression must change the sign of their
18951 coefficients if we make no change to the current expression.
18952
18953 Instead, we work around the problem by copying the current expression
18954 and recycling it afterwards (cf.~the |stash_in| routine).
18955
18956 @<Negate the current expression@>=
18957 switch (mp->cur_type) {
18958 case mp_color_type:
18959 case mp_cmykcolor_type:
18960 case mp_pair_type:
18961 case mp_independent: 
18962   q=mp->cur_exp; mp_make_exp_copy(mp, q);
18963   if ( mp->cur_type==mp_dependent ) {
18964     mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18965   } else if ( mp->cur_type<=mp_pair_type ) { /* |mp_color_type| or |mp_pair_type| */
18966     p=value(mp->cur_exp);
18967     r=p+mp->big_node_size[mp->cur_type];
18968     do {  
18969       r=r-2;
18970       if ( mp_type(r)==mp_known ) negate(value(r));
18971       else mp_negate_dep_list(mp, dep_list(r));
18972     } while (r!=p);
18973   } /* if |cur_type=mp_known| then |cur_exp=0| */
18974   mp_recycle_value(mp, q); mp_free_node(mp, q,value_node_size);
18975   break;
18976 case mp_dependent:
18977 case mp_proto_dependent:
18978   mp_negate_dep_list(mp, dep_list(mp->cur_exp));
18979   break;
18980 case mp_known:
18981   negate(mp->cur_exp);
18982   break;
18983 default:
18984   mp_bad_unary(mp, minus);
18985   break;
18986 }
18987
18988 @ @<Declare unary action...@>=
18989 static void mp_negate_dep_list (MP mp,pointer p) { 
18990   while (1) { 
18991     negate(value(p));
18992     if ( mp_info(p)==null ) return;
18993     p=mp_link(p);
18994   }
18995 }
18996
18997 @ @<Additional cases of unary operators@>=
18998 case not_op: 
18999   if ( mp->cur_type!=mp_boolean_type ) mp_bad_unary(mp, not_op);
19000   else mp->cur_exp=true_code+false_code-mp->cur_exp;
19001   break;
19002
19003 @ @d three_sixty_units 23592960 /* that's |360*unity| */
19004 @d boolean_reset(A) if ( (A) ) mp->cur_exp=true_code; else mp->cur_exp=false_code
19005
19006 @<Additional cases of unary operators@>=
19007 case sqrt_op:
19008 case mp_m_exp_op:
19009 case mp_m_log_op:
19010 case sin_d_op:
19011 case cos_d_op:
19012 case floor_op:
19013 case  uniform_deviate:
19014 case odd_op:
19015 case char_exists_op:
19016   if ( mp->cur_type!=mp_known ) {
19017     mp_bad_unary(mp, c);
19018   } else {
19019     switch (c) {
19020     case sqrt_op:mp->cur_exp=mp_square_rt(mp, mp->cur_exp);break;
19021     case mp_m_exp_op:mp->cur_exp=mp_m_exp(mp, mp->cur_exp);break;
19022     case mp_m_log_op:mp->cur_exp=mp_m_log(mp, mp->cur_exp);break;
19023     case sin_d_op:
19024     case cos_d_op:
19025       mp_n_sin_cos(mp, (mp->cur_exp % three_sixty_units)*16);
19026       if ( c==sin_d_op ) mp->cur_exp=mp_round_fraction(mp, mp->n_sin);
19027       else mp->cur_exp=mp_round_fraction(mp, mp->n_cos);
19028       break;
19029     case floor_op:mp->cur_exp=mp_floor_scaled(mp, mp->cur_exp);break;
19030     case uniform_deviate:mp->cur_exp=mp_unif_rand(mp, mp->cur_exp);break;
19031     case odd_op: 
19032       boolean_reset(odd(mp_round_unscaled(mp, mp->cur_exp)));
19033       mp->cur_type=mp_boolean_type;
19034       break;
19035     case char_exists_op:
19036       @<Determine if a character has been shipped out@>;
19037       break;
19038     } /* there are no other cases */
19039   }
19040   break;
19041
19042 @ @<Additional cases of unary operators@>=
19043 case angle_op:
19044   if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) ) {
19045     p=value(mp->cur_exp);
19046     x=mp_n_arg(mp, value(x_part_loc(p)),value(y_part_loc(p)));
19047     if ( x>=0 ) mp_flush_cur_exp(mp, (x+8)/ 16);
19048     else mp_flush_cur_exp(mp, -((-x+8)/ 16));
19049   } else {
19050     mp_bad_unary(mp, angle_op);
19051   }
19052   break;
19053
19054 @ If the current expression is a pair, but the context wants it to
19055 be a path, we call |pair_to_path|.
19056
19057 @<Declare unary action...@>=
19058 static void mp_pair_to_path (MP mp) { 
19059   mp->cur_exp=mp_new_knot(mp); 
19060   mp->cur_type=mp_path_type;
19061 }
19062
19063
19064 @d pict_color_type(A) ((mp_link(dummy_loc(mp->cur_exp))!=null) &&
19065          (has_color(mp_link(dummy_loc(mp->cur_exp)))) &&
19066          ((mp_color_model(mp_link(dummy_loc(mp->cur_exp)))==A)
19067          ||
19068          ((mp_color_model(mp_link(dummy_loc(mp->cur_exp)))==mp_uninitialized_model) &&
19069          (mp->internal[mp_default_color_model]/unity)==(A))))
19070
19071 @<Additional cases of unary operators@>=
19072 case x_part:
19073 case y_part:
19074   if ( (mp->cur_type==mp_pair_type)||(mp->cur_type==mp_transform_type) )
19075     mp_take_part(mp, c);
19076   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19077   else mp_bad_unary(mp, c);
19078   break;
19079 case xx_part:
19080 case xy_part:
19081 case yx_part:
19082 case yy_part: 
19083   if ( mp->cur_type==mp_transform_type ) mp_take_part(mp, c);
19084   else if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19085   else mp_bad_unary(mp, c);
19086   break;
19087 case red_part:
19088 case green_part:
19089 case blue_part: 
19090   if ( mp->cur_type==mp_color_type ) mp_take_part(mp, c);
19091   else if ( mp->cur_type==mp_picture_type ) {
19092     if pict_color_type(mp_rgb_model) mp_take_pict_part(mp, c);
19093     else mp_bad_color_part(mp, c);
19094   }
19095   else mp_bad_unary(mp, c);
19096   break;
19097 case cyan_part:
19098 case magenta_part:
19099 case yellow_part:
19100 case black_part: 
19101   if ( mp->cur_type==mp_cmykcolor_type) mp_take_part(mp, c); 
19102   else if ( mp->cur_type==mp_picture_type ) {
19103     if pict_color_type(mp_cmyk_model) mp_take_pict_part(mp, c);
19104     else mp_bad_color_part(mp, c);
19105   }
19106   else mp_bad_unary(mp, c);
19107   break;
19108 case grey_part: 
19109   if ( mp->cur_type==mp_known ) mp->cur_exp=value(c);
19110   else if ( mp->cur_type==mp_picture_type ) {
19111     if pict_color_type(mp_grey_model) mp_take_pict_part(mp, c);
19112     else mp_bad_color_part(mp, c);
19113   }
19114   else mp_bad_unary(mp, c);
19115   break;
19116 case color_model_part: 
19117   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19118   else mp_bad_unary(mp, c);
19119   break;
19120
19121 @ @<Declarations@>=
19122 static void mp_bad_color_part(MP mp, quarterword c);
19123
19124 @ @c
19125 static void mp_bad_color_part(MP mp, quarterword c) {
19126   pointer p; /* the big node */
19127   p=mp_link(dummy_loc(mp->cur_exp));
19128   exp_err("Wrong picture color model: "); mp_print_op(mp, c);
19129 @.Wrong picture color model...@>
19130   if (mp_color_model(p)==mp_grey_model)
19131     mp_print(mp, " of grey object");
19132   else if (mp_color_model(p)==mp_cmyk_model)
19133     mp_print(mp, " of cmyk object");
19134   else if (mp_color_model(p)==mp_rgb_model)
19135     mp_print(mp, " of rgb object");
19136   else if (mp_color_model(p)==mp_no_model) 
19137     mp_print(mp, " of marking object");
19138   else 
19139     mp_print(mp," of defaulted object");
19140   help3("You can only ask for the redpart, greenpart, bluepart of a rgb object,",
19141     "the cyanpart, magentapart, yellowpart or blackpart of a cmyk object, ",
19142     "or the greypart of a grey object. No mixing and matching, please.");
19143   mp_error(mp);
19144   if (c==black_part)
19145     mp_flush_cur_exp(mp,unity);
19146   else
19147     mp_flush_cur_exp(mp,0);
19148 }
19149
19150 @ In the following procedure, |cur_exp| points to a capsule, which points to
19151 a big node. We want to delete all but one part of the big node.
19152
19153 @<Declare unary action...@>=
19154 static void mp_take_part (MP mp,quarterword c) {
19155   pointer p; /* the big node */
19156   p=value(mp->cur_exp); value(temp_val)=p; mp_type(temp_val)=mp->cur_type;
19157   mp_link(p)=temp_val; mp_free_node(mp, mp->cur_exp,value_node_size);
19158   mp_make_exp_copy(mp, p+mp->sector_offset[c+mp_x_part_sector-x_part]);
19159   mp_recycle_value(mp, temp_val);
19160 }
19161
19162 @ @<Initialize table entries...@>=
19163 mp_name_type(temp_val)=mp_capsule;
19164
19165 @ @<Additional cases of unary operators@>=
19166 case font_part:
19167 case text_part:
19168 case path_part:
19169 case pen_part:
19170 case dash_part:
19171   if ( mp->cur_type==mp_picture_type ) mp_take_pict_part(mp, c);
19172   else mp_bad_unary(mp, c);
19173   break;
19174
19175 @ @<Declarations@>=
19176 static void mp_scale_edges (MP mp);
19177
19178 @ @<Declare unary action...@>=
19179 static void mp_take_pict_part (MP mp,quarterword c) {
19180   pointer p; /* first graphical object in |cur_exp| */
19181   p=mp_link(dummy_loc(mp->cur_exp));
19182   if ( p!=null ) {
19183     switch (c) {
19184     case x_part: case y_part: case xx_part:
19185     case xy_part: case yx_part: case yy_part:
19186       if ( mp_type(p)==mp_text_code ) mp_flush_cur_exp(mp, text_trans_part(p+c));
19187       else goto NOT_FOUND;
19188       break;
19189     case red_part: case green_part: case blue_part:
19190       if ( has_color(p) ) mp_flush_cur_exp(mp, obj_color_part(p+c));
19191       else goto NOT_FOUND;
19192       break;
19193     case cyan_part: case magenta_part: case yellow_part:
19194     case black_part:
19195       if ( has_color(p) ) {
19196         if ( mp_color_model(p)==mp_uninitialized_model && c==black_part)
19197           mp_flush_cur_exp(mp, unity);
19198         else
19199           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-cyan_part)));
19200       } else goto NOT_FOUND;
19201       break;
19202     case grey_part:
19203       if ( has_color(p) )
19204           mp_flush_cur_exp(mp, obj_color_part(p+c+(red_part-grey_part)));
19205       else goto NOT_FOUND;
19206       break;
19207     case color_model_part:
19208       if ( has_color(p) ) {
19209         if ( mp_color_model(p)==mp_uninitialized_model )
19210           mp_flush_cur_exp(mp, mp->internal[mp_default_color_model]);
19211         else
19212           mp_flush_cur_exp(mp, mp_color_model(p)*unity);
19213       } else goto NOT_FOUND;
19214       break;
19215     @<Handle other cases in |take_pict_part| or |goto not_found|@>;
19216     } /* all cases have been enumerated */
19217     return;
19218   };
19219 NOT_FOUND:
19220   @<Convert the current expression to a null value appropriate
19221     for |c|@>;
19222 }
19223
19224 @ @<Handle other cases in |take_pict_part| or |goto not_found|@>=
19225 case text_part: 
19226   if ( mp_type(p)!=mp_text_code ) goto NOT_FOUND;
19227   else { 
19228     mp_flush_cur_exp(mp, mp_text_p(p));
19229     add_str_ref(mp->cur_exp);
19230     mp->cur_type=mp_string_type;
19231     };
19232   break;
19233 case font_part: 
19234   if ( mp_type(p)!=mp_text_code ) goto NOT_FOUND;
19235   else { 
19236     mp_flush_cur_exp(mp, rts(mp->font_name[mp_font_n(p)])); 
19237     add_str_ref(mp->cur_exp);
19238     mp->cur_type=mp_string_type;
19239   };
19240   break;
19241 case path_part:
19242   if ( mp_type(p)==mp_text_code ) goto NOT_FOUND;
19243   else if ( is_stop(p) ) mp_confusion(mp, "pict");
19244 @:this can't happen pict}{\quad pict@>
19245   else { 
19246     mp_flush_cur_exp(mp, mp_copy_path(mp, mp_path_p(p)));
19247     mp->cur_type=mp_path_type;
19248   }
19249   break;
19250 case pen_part: 
19251   if ( ! has_pen(p) ) goto NOT_FOUND;
19252   else {
19253     if ( mp_pen_p(p)==null ) goto NOT_FOUND;
19254     else { mp_flush_cur_exp(mp, copy_pen(mp_pen_p(p)));
19255       mp->cur_type=mp_pen_type;
19256     };
19257   }
19258   break;
19259 case dash_part: 
19260   if ( mp_type(p)!=mp_stroked_code ) goto NOT_FOUND;
19261   else { if ( mp_dash_p(p)==null ) goto NOT_FOUND;
19262     else { add_edge_ref(mp_dash_p(p));
19263     mp->se_sf=dash_scale(p);
19264     mp->se_pic=mp_dash_p(p);
19265     mp_scale_edges(mp);
19266     mp_flush_cur_exp(mp, mp->se_pic);
19267     mp->cur_type=mp_picture_type;
19268     };
19269   }
19270   break;
19271
19272 @ Since |scale_edges| had to be declared |forward|, it had to be declared as a
19273 parameterless procedure even though it really takes two arguments and updates
19274 one of them.  Hence the following globals are needed.
19275
19276 @<Global...@>=
19277 pointer se_pic;  /* edge header used and updated by |scale_edges| */
19278 scaled se_sf;  /* the scale factor argument to |scale_edges| */
19279
19280 @ @<Convert the current expression to a null value appropriate...@>=
19281 switch (c) {
19282 case text_part: case font_part: 
19283   mp_flush_cur_exp(mp, null_str);
19284   mp->cur_type=mp_string_type;
19285   break;
19286 case path_part: 
19287   mp_flush_cur_exp(mp, mp_get_node(mp, knot_node_size));
19288   mp_left_type(mp->cur_exp)=mp_endpoint;
19289   mp_right_type(mp->cur_exp)=mp_endpoint;
19290   mp_link(mp->cur_exp)=mp->cur_exp;
19291   mp_x_coord(mp->cur_exp)=0;
19292   mp_y_coord(mp->cur_exp)=0;
19293   mp_originator(mp->cur_exp)=mp_metapost_user;
19294   mp->cur_type=mp_path_type;
19295   break;
19296 case pen_part: 
19297   mp_flush_cur_exp(mp, mp_get_pen_circle(mp, 0));
19298   mp->cur_type=mp_pen_type;
19299   break;
19300 case dash_part: 
19301   mp_flush_cur_exp(mp, mp_get_node(mp, edge_header_size));
19302   mp_init_edges(mp, mp->cur_exp);
19303   mp->cur_type=mp_picture_type;
19304   break;
19305 default: 
19306    mp_flush_cur_exp(mp, 0);
19307   break;
19308 }
19309
19310 @ @<Additional cases of unary...@>=
19311 case char_op: 
19312   if ( mp->cur_type!=mp_known ) { 
19313     mp_bad_unary(mp, char_op);
19314   } else { 
19315     mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256; 
19316     mp->cur_type=mp_string_type;
19317     if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
19318   }
19319   break;
19320 case decimal: 
19321   if ( mp->cur_type!=mp_known ) {
19322      mp_bad_unary(mp, decimal);
19323   } else { 
19324     mp->old_setting=mp->selector; mp->selector=new_string;
19325     mp_print_scaled(mp, mp->cur_exp); mp->cur_exp=mp_make_string(mp);
19326     mp->selector=mp->old_setting; mp->cur_type=mp_string_type;
19327   }
19328   break;
19329 case oct_op:
19330 case hex_op:
19331 case ASCII_op: 
19332   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19333   else mp_str_to_num(mp, c);
19334   break;
19335 case font_size: 
19336   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, font_size);
19337   else @<Find the design size of the font whose name is |cur_exp|@>;
19338   break;
19339
19340 @ @<Declare unary action...@>=
19341 static void mp_str_to_num (MP mp,quarterword c) { /* converts a string to a number */
19342   integer n; /* accumulator */
19343   ASCII_code m; /* current character */
19344   pool_pointer k; /* index into |str_pool| */
19345   int b; /* radix of conversion */
19346   boolean bad_char; /* did the string contain an invalid digit? */
19347   if ( c==ASCII_op ) {
19348     if ( length(mp->cur_exp)==0 ) n=-1;
19349     else n=mp->str_pool[mp->str_start[mp->cur_exp]];
19350   } else { 
19351     if ( c==oct_op ) b=8; else b=16;
19352     n=0; bad_char=false;
19353     for (k=mp->str_start[mp->cur_exp];k<=str_stop(mp->cur_exp)-1;k++) {
19354       m=mp->str_pool[k];
19355       if ( (m>='0')&&(m<='9') ) m=m-'0';
19356       else if ( (m>='A')&&(m<='F') ) m=m-'A'+10;
19357       else if ( (m>='a')&&(m<='f') ) m=m-'a'+10;
19358       else  { bad_char=true; m=0; };
19359       if ( (int)m>=b ) { bad_char=true; m=0; };
19360       if ( n<32768 / b ) n=n*b+m; else n=32767;
19361     }
19362     @<Give error messages if |bad_char| or |n>=4096|@>;
19363   }
19364   mp_flush_cur_exp(mp, n*unity);
19365 }
19366
19367 @ @<Give error messages if |bad_char|...@>=
19368 if ( bad_char ) { 
19369   exp_err("String contains illegal digits");
19370 @.String contains illegal digits@>
19371   if ( c==oct_op ) {
19372     help1("I zeroed out characters that weren't in the range 0..7.");
19373   } else  {
19374     help1("I zeroed out characters that weren't hex digits.");
19375   }
19376   mp_put_get_error(mp);
19377 }
19378 if ( (n>4095) ) {
19379   if ( mp->internal[mp_warning_check]>0 ) {
19380     print_err("Number too large ("); 
19381     mp_print_int(mp, n); mp_print_char(mp, xord(')'));
19382 @.Number too large@>
19383     help2("I have trouble with numbers greater than 4095; watch out.",
19384            "(Set warningcheck:=0 to suppress this message.)");
19385     mp_put_get_error(mp);
19386   }
19387 }
19388
19389 @ The length operation is somewhat unusual in that it applies to a variety
19390 of different types of operands.
19391
19392 @<Additional cases of unary...@>=
19393 case length_op: 
19394   switch (mp->cur_type) {
19395   case mp_string_type: mp_flush_cur_exp(mp, length(mp->cur_exp)*unity); break;
19396   case mp_path_type: mp_flush_cur_exp(mp, mp_path_length(mp)); break;
19397   case mp_known: mp->cur_exp=abs(mp->cur_exp); break;
19398   case mp_picture_type: mp_flush_cur_exp(mp, mp_pict_length(mp)); break;
19399   default: 
19400     if ( mp_nice_pair(mp, mp->cur_exp,mp->cur_type) )
19401       mp_flush_cur_exp(mp, mp_pyth_add(mp, 
19402         value(x_part_loc(value(mp->cur_exp))),
19403         value(y_part_loc(value(mp->cur_exp)))));
19404     else mp_bad_unary(mp, c);
19405     break;
19406   }
19407   break;
19408
19409 @ @<Declare unary action...@>=
19410 static scaled mp_path_length (MP mp) { /* computes the length of the current path */
19411   scaled n; /* the path length so far */
19412   pointer p; /* traverser */
19413   p=mp->cur_exp;
19414   if ( mp_left_type(p)==mp_endpoint ) n=-unity; else n=0;
19415   do {  p=mp_link(p); n=n+unity; } while (p!=mp->cur_exp);
19416   return n;
19417 }
19418
19419 @ @<Declare unary action...@>=
19420 static scaled mp_pict_length (MP mp) { 
19421   /* counts interior components in picture |cur_exp| */
19422   scaled n; /* the count so far */
19423   pointer p; /* traverser */
19424   n=0;
19425   p=mp_link(dummy_loc(mp->cur_exp));
19426   if ( p!=null ) {
19427     if ( is_start_or_stop(p) )
19428       if ( mp_skip_1component(mp, p)==null ) p=mp_link(p);
19429     while ( p!=null )  { 
19430       skip_component(p) return n; 
19431       n=n+unity;   
19432     }
19433   }
19434   return n;
19435 }
19436
19437 @ Implement |turningnumber|
19438
19439 @<Additional cases of unary...@>=
19440 case turning_op:
19441   if ( mp->cur_type==mp_pair_type ) mp_flush_cur_exp(mp, 0);
19442   else if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, turning_op);
19443   else if ( mp_left_type(mp->cur_exp)==mp_endpoint )
19444      mp_flush_cur_exp(mp, 0); /* not a cyclic path */
19445   else
19446     mp_flush_cur_exp(mp, mp_turn_cycles_wrapper(mp, mp->cur_exp));
19447   break;
19448
19449 @ The function |an_angle| returns the value of the |angle| primitive, or $0$ if the
19450 argument is |origin|.
19451
19452 @<Declare unary action...@>=
19453 static angle mp_an_angle (MP mp,scaled xpar, scaled ypar) {
19454   if ( (! ((xpar==0) && (ypar==0))) )
19455     return mp_n_arg(mp, xpar,ypar);
19456   return 0;
19457 }
19458
19459
19460 @ The actual turning number is (for the moment) computed in a C function
19461 that receives eight integers corresponding to the four controlling points,
19462 and returns a single angle.  Besides those, we have to account for discrete
19463 moves at the actual points.
19464
19465 @d mp_floor(a) ((a)>=0 ? (int)(a) : -(int)(-(a)))
19466 @d bezier_error (720*(256*256*16))+1
19467 @d mp_sign(v) ((v)>0 ? 1 : ((v)<0 ? -1 : 0 ))
19468 @d mp_out(A) (double)((A)/(256*256*16))
19469 @d divisor (256*256)
19470 @d double2angle(a) (int)mp_floor(a*256.0*256.0*16.0)
19471
19472 @<Declare unary action...@>=
19473 static angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19474             integer CX,integer CY,integer DX,integer DY);
19475
19476 @ @c 
19477 static angle mp_bezier_slope(MP mp, integer AX,integer AY,integer BX,integer BY,
19478             integer CX,integer CY,integer DX,integer DY) {
19479   double a, b, c;
19480   integer deltax,deltay;
19481   double ax,ay,bx,by,cx,cy,dx,dy;
19482   angle xi = 0, xo = 0, xm = 0;
19483   double res = 0;
19484   ax=(double)(AX/divisor);  ay=(double)(AY/divisor);
19485   bx=(double)(BX/divisor);  by=(double)(BY/divisor);
19486   cx=(double)(CX/divisor);  cy=(double)(CY/divisor);
19487   dx=(double)(DX/divisor);  dy=(double)(DY/divisor);
19488
19489   deltax = (BX-AX); deltay = (BY-AY);
19490   if (deltax==0 && deltay == 0) { deltax=(CX-AX); deltay=(CY-AY); }
19491   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19492   xi = mp_an_angle(mp,deltax,deltay);
19493
19494   deltax = (CX-BX); deltay = (CY-BY);
19495   xm = mp_an_angle(mp,deltax,deltay);
19496
19497   deltax = (DX-CX); deltay = (DY-CY);
19498   if (deltax==0 && deltay == 0) { deltax=(DX-BX); deltay=(DY-BY); }
19499   if (deltax==0 && deltay == 0) { deltax=(DX-AX); deltay=(DY-AY); }
19500   xo = mp_an_angle(mp,deltax,deltay);
19501
19502   a = (bx-ax)*(cy-by) - (cx-bx)*(by-ay); /* a = (bp-ap)x(cp-bp); */
19503   b = (bx-ax)*(dy-cy) - (by-ay)*(dx-cx);; /* b = (bp-ap)x(dp-cp);*/
19504   c = (cx-bx)*(dy-cy) - (dx-cx)*(cy-by); /* c = (cp-bp)x(dp-cp);*/
19505
19506   if ((a==0)&&(c==0)) {
19507     res = (b==0 ?  0 :  (mp_out(xo)-mp_out(xi))); 
19508   } else if ((a==0)||(c==0)) {
19509     if ((mp_sign(b) == mp_sign(a)) || (mp_sign(b) == mp_sign(c))) {
19510       res = mp_out(xo)-mp_out(xi); /* ? */
19511       if (res<-180.0) 
19512         res += 360.0;
19513       else if (res>180.0)
19514         res -= 360.0;
19515     } else {
19516       res = mp_out(xo)-mp_out(xi); /* ? */
19517     }
19518   } else if ((mp_sign(a)*mp_sign(c))<0) {
19519     res = mp_out(xo)-mp_out(xi); /* ? */
19520       if (res<-180.0) 
19521         res += 360.0;
19522       else if (res>180.0)
19523         res -= 360.0;
19524   } else {
19525     if (mp_sign(a) == mp_sign(b)) {
19526       res = mp_out(xo)-mp_out(xi); /* ? */
19527       if (res<-180.0) 
19528         res += 360.0;
19529       else if (res>180.0)
19530         res -= 360.0;
19531     } else {
19532       if ((b*b) == (4*a*c)) {
19533         res = (double)bezier_error;
19534       } else if ((b*b) < (4*a*c)) {
19535         res = mp_out(xo)-mp_out(xi); /* ? */
19536         if (res<=0.0 &&res>-180.0) 
19537           res += 360.0;
19538         else if (res>=0.0 && res<180.0)
19539           res -= 360.0;
19540       } else {
19541         res = mp_out(xo)-mp_out(xi);
19542         if (res<-180.0) 
19543           res += 360.0;
19544         else if (res>180.0)
19545           res -= 360.0;
19546       }
19547     }
19548   }
19549   return double2angle(res);
19550 }
19551
19552 @
19553 @d p_nextnext mp_link(mp_link(p))
19554 @d p_next mp_link(p)
19555 @d seven_twenty_deg 05500000000 /* $720\cdot2^{20}$, represents $720^\circ$ */
19556
19557 @<Declare unary action...@>=
19558 static scaled mp_new_turn_cycles (MP mp,pointer c) {
19559   angle res,ang; /*  the angles of intermediate results  */
19560   scaled turns;  /*  the turn counter  */
19561   pointer p;     /*  for running around the path  */
19562   integer xp,yp;   /*  coordinates of next point  */
19563   integer x,y;   /*  helper coordinates  */
19564   angle in_angle,out_angle;     /*  helper angles */
19565   unsigned old_setting; /* saved |selector| setting */
19566   res=0;
19567   turns= 0;
19568   p=c;
19569   old_setting = mp->selector; mp->selector=term_only;
19570   if ( mp->internal[mp_tracing_commands]>unity ) {
19571     mp_begin_diagnostic(mp);
19572     mp_print_nl(mp, "");
19573     mp_end_diagnostic(mp, false);
19574   }
19575   do { 
19576     xp = mp_x_coord(p_next); yp = mp_y_coord(p_next);
19577     ang  = mp_bezier_slope(mp,mp_x_coord(p), mp_y_coord(p), mp_right_x(p), mp_right_y(p),
19578              mp_left_x(p_next), mp_left_y(p_next), xp, yp);
19579     if ( ang>seven_twenty_deg ) {
19580       print_err("Strange path");
19581       mp_error(mp);
19582       mp->selector=old_setting;
19583       return 0;
19584     }
19585     res  = res + ang;
19586     if ( res > one_eighty_deg ) {
19587       res = res - three_sixty_deg;
19588       turns = turns + unity;
19589     }
19590     if ( res <= -one_eighty_deg ) {
19591       res = res + three_sixty_deg;
19592       turns = turns - unity;
19593     }
19594     /*  incoming angle at next point  */
19595     x = mp_left_x(p_next);  y = mp_left_y(p_next);
19596     if ( (xp==x)&&(yp==y) ) { x = mp_right_x(p);  y = mp_right_y(p);  };
19597     if ( (xp==x)&&(yp==y) ) { x = mp_x_coord(p);  y = mp_y_coord(p);  };
19598     in_angle = mp_an_angle(mp, xp - x, yp - y);
19599     /*  outgoing angle at next point  */
19600     x = mp_right_x(p_next);  y = mp_right_y(p_next);
19601     if ( (xp==x)&&(yp==y) ) { x = mp_left_x(p_nextnext);  y = mp_left_y(p_nextnext);  };
19602     if ( (xp==x)&&(yp==y) ) { x = mp_x_coord(p_nextnext); y = mp_y_coord(p_nextnext); };
19603     out_angle = mp_an_angle(mp, x - xp, y- yp);
19604     ang  = (out_angle - in_angle);
19605     reduce_angle(ang);
19606     if ( ang!=0 ) {
19607       res  = res + ang;
19608       if ( res >= one_eighty_deg ) {
19609         res = res - three_sixty_deg;
19610         turns = turns + unity;
19611       };
19612       if ( res <= -one_eighty_deg ) {
19613         res = res + three_sixty_deg;
19614         turns = turns - unity;
19615       };
19616     };
19617     p = mp_link(p);
19618   } while (p!=c);
19619   mp->selector=old_setting;
19620   return turns;
19621 }
19622
19623
19624 @ This code is based on Bogus\l{}av Jackowski's
19625 |emergency_turningnumber| macro, with some minor changes by Taco
19626 Hoekwater. The macro code looked more like this:
19627 {\obeylines
19628 vardef turning\_number primary p =
19629 ~~save res, ang, turns;
19630 ~~res := 0;
19631 ~~if length p <= 2:
19632 ~~~~if Angle ((point 0 of p) - (postcontrol 0 of p)) >= 0:  1  else: -1 fi
19633 ~~else:
19634 ~~~~for t = 0 upto length p-1 :
19635 ~~~~~~angc := Angle ((point t+1 of p)  - (point t of p))
19636 ~~~~~~~~- Angle ((point t of p) - (point t-1 of p));
19637 ~~~~~~if angc > 180: angc := angc - 360; fi;
19638 ~~~~~~if angc < -180: angc := angc + 360; fi;
19639 ~~~~~~res  := res + angc;
19640 ~~~~endfor;
19641 ~~res/360
19642 ~~fi
19643 enddef;}
19644 The general idea is to calculate only the sum of the angles of
19645 straight lines between the points, of a path, not worrying about cusps
19646 or self-intersections in the segments at all. If the segment is not
19647 well-behaved, the result is not necesarily correct. But the old code
19648 was not always correct either, and worse, it sometimes failed for
19649 well-behaved paths as well. All known bugs that were triggered by the
19650 original code no longer occur with this code, and it runs roughly 3
19651 times as fast because the algorithm is much simpler.
19652
19653 @ It is possible to overflow the return value of the |turn_cycles|
19654 function when the path is sufficiently long and winding, but I am not
19655 going to bother testing for that. In any case, it would only return
19656 the looped result value, which is not a big problem.
19657
19658 The macro code for the repeat loop was a bit nicer to look
19659 at than the pascal code, because it could use |point -1 of p|. In
19660 pascal, the fastest way to loop around the path is not to look
19661 backward once, but forward twice. These defines help hide the trick.
19662
19663 @d p_to mp_link(mp_link(p))
19664 @d p_here mp_link(p)
19665 @d p_from p
19666
19667 @<Declare unary action...@>=
19668 static scaled mp_turn_cycles (MP mp,pointer c) {
19669   angle res,ang; /*  the angles of intermediate results  */
19670   scaled turns;  /*  the turn counter  */
19671   pointer p;     /*  for running around the path  */
19672   res=0;  turns= 0; p=c;
19673   do { 
19674     ang  = mp_an_angle (mp, mp_x_coord(p_to) - mp_x_coord(p_here), 
19675                             mp_y_coord(p_to) - mp_y_coord(p_here))
19676         - mp_an_angle (mp, mp_x_coord(p_here) - mp_x_coord(p_from), 
19677                            mp_y_coord(p_here) - mp_y_coord(p_from));
19678     reduce_angle(ang);
19679     res  = res + ang;
19680     if ( res >= three_sixty_deg )  {
19681       res = res - three_sixty_deg;
19682       turns = turns + unity;
19683     };
19684     if ( res <= -three_sixty_deg ) {
19685       res = res + three_sixty_deg;
19686       turns = turns - unity;
19687     };
19688     p = mp_link(p);
19689   } while (p!=c);
19690   return turns;
19691 }
19692
19693 @ @<Declare unary action...@>=
19694 static scaled mp_turn_cycles_wrapper (MP mp,pointer c) {
19695   scaled nval,oval;
19696   scaled saved_t_o; /* tracing\_online saved  */
19697   if ( (mp_link(c)==c)||(mp_link(mp_link(c))==c) ) {
19698     if ( mp_an_angle (mp, mp_x_coord(c) - mp_right_x(c),  mp_y_coord(c) - mp_right_y(c)) > 0 )
19699       return unity;
19700     else
19701       return -unity;
19702   } else {
19703     nval = mp_new_turn_cycles(mp, c);
19704     oval = mp_turn_cycles(mp, c);
19705     if ( nval!=oval ) {
19706       saved_t_o=mp->internal[mp_tracing_online];
19707       mp->internal[mp_tracing_online]=unity;
19708       mp_begin_diagnostic(mp);
19709       mp_print_nl (mp, "Warning: the turningnumber algorithms do not agree."
19710                        " The current computed value is ");
19711       mp_print_scaled(mp, nval);
19712       mp_print(mp, ", but the 'connect-the-dots' algorithm returned ");
19713       mp_print_scaled(mp, oval);
19714       mp_end_diagnostic(mp, false);
19715       mp->internal[mp_tracing_online]=saved_t_o;
19716     }
19717     return nval;
19718   }
19719 }
19720
19721 @ @d type_range(A,B) { 
19722   if ( (mp->cur_type>=(A)) && (mp->cur_type<=(B)) ) 
19723     mp_flush_cur_exp(mp, true_code);
19724   else mp_flush_cur_exp(mp, false_code);
19725   mp->cur_type=mp_boolean_type;
19726   }
19727 @d type_test(A) { 
19728   if ( mp->cur_type==(A) ) 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
19733 @<Additional cases of unary operators@>=
19734 case mp_boolean_type: 
19735   type_range(mp_boolean_type,mp_unknown_boolean); break;
19736 case mp_string_type: 
19737   type_range(mp_string_type,mp_unknown_string); break;
19738 case mp_pen_type: 
19739   type_range(mp_pen_type,mp_unknown_pen); break;
19740 case mp_path_type: 
19741   type_range(mp_path_type,mp_unknown_path); break;
19742 case mp_picture_type: 
19743   type_range(mp_picture_type,mp_unknown_picture); break;
19744 case mp_transform_type: case mp_color_type: case mp_cmykcolor_type:
19745 case mp_pair_type: 
19746   type_test(c); break;
19747 case mp_numeric_type: 
19748   type_range(mp_known,mp_independent); break;
19749 case known_op: case unknown_op: 
19750   mp_test_known(mp, c); break;
19751
19752 @ @<Declare unary action procedures@>=
19753 static void mp_test_known (MP mp,quarterword c) {
19754   int b; /* is the current expression known? */
19755   pointer p,q; /* locations in a big node */
19756   b=false_code;
19757   switch (mp->cur_type) {
19758   case mp_vacuous: case mp_boolean_type: case mp_string_type:
19759   case mp_pen_type: case mp_path_type: case mp_picture_type:
19760   case mp_known: 
19761     b=true_code;
19762     break;
19763   case mp_transform_type:
19764   case mp_color_type: case mp_cmykcolor_type: case mp_pair_type: 
19765     p=value(mp->cur_exp);
19766     q=p+mp->big_node_size[mp->cur_type];
19767     do {  
19768       q=q-2;
19769       if ( mp_type(q)!=mp_known ) 
19770        goto DONE;
19771     } while (q!=p);
19772     b=true_code;
19773   DONE:  
19774     break;
19775   default: 
19776     break;
19777   }
19778   if ( c==known_op ) mp_flush_cur_exp(mp, b);
19779   else mp_flush_cur_exp(mp, true_code+false_code-b);
19780   mp->cur_type=mp_boolean_type;
19781 }
19782
19783 @ @<Additional cases of unary operators@>=
19784 case cycle_op: 
19785   if ( mp->cur_type!=mp_path_type ) mp_flush_cur_exp(mp, false_code);
19786   else if ( mp_left_type(mp->cur_exp)!=mp_endpoint ) mp_flush_cur_exp(mp, true_code);
19787   else mp_flush_cur_exp(mp, false_code);
19788   mp->cur_type=mp_boolean_type;
19789   break;
19790
19791 @ @<Additional cases of unary operators@>=
19792 case arc_length: 
19793   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19794   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, arc_length);
19795   else mp_flush_cur_exp(mp, mp_get_arc_length(mp, mp->cur_exp));
19796   break;
19797
19798 @ Here we use the fact that |c-filled_op+fill_code| is the desired graphical
19799 object |type|.
19800 @^data structure assumptions@>
19801
19802 @<Additional cases of unary operators@>=
19803 case filled_op:
19804 case stroked_op:
19805 case textual_op:
19806 case clipped_op:
19807 case bounded_op:
19808   if ( mp->cur_type!=mp_picture_type ) mp_flush_cur_exp(mp, false_code);
19809   else if ( mp_link(dummy_loc(mp->cur_exp))==null ) mp_flush_cur_exp(mp, false_code);
19810   else if ( mp_type(mp_link(dummy_loc(mp->cur_exp)))==c+mp_fill_code-filled_op )
19811     mp_flush_cur_exp(mp, true_code);
19812   else mp_flush_cur_exp(mp, false_code);
19813   mp->cur_type=mp_boolean_type;
19814   break;
19815
19816 @ @<Additional cases of unary operators@>=
19817 case make_pen_op: 
19818   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19819   if ( mp->cur_type!=mp_path_type ) mp_bad_unary(mp, make_pen_op);
19820   else { 
19821     mp->cur_type=mp_pen_type;
19822     mp->cur_exp=mp_make_pen(mp, mp->cur_exp,true);
19823   };
19824   break;
19825 case make_path_op: 
19826   if ( mp->cur_type!=mp_pen_type ) mp_bad_unary(mp, make_path_op);
19827   else  { 
19828     mp->cur_type=mp_path_type;
19829     mp_make_path(mp, mp->cur_exp);
19830   };
19831   break;
19832 case reverse: 
19833   if ( mp->cur_type==mp_path_type ) {
19834     p=mp_htap_ypoc(mp, mp->cur_exp);
19835     if ( mp_right_type(p)==mp_endpoint ) p=mp_link(p);
19836     mp_toss_knot_list(mp, mp->cur_exp); mp->cur_exp=p;
19837   } else if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
19838   else mp_bad_unary(mp, reverse);
19839   break;
19840
19841 @ The |pair_value| routine changes the current expression to a
19842 given ordered pair of values.
19843
19844 @<Declare unary action procedures@>=
19845 static void mp_pair_value (MP mp,scaled x, scaled y) {
19846   pointer p; /* a pair node */
19847   p=mp_get_node(mp, value_node_size); 
19848   mp_flush_cur_exp(mp, p); mp->cur_type=mp_pair_type;
19849   mp_type(p)=mp_pair_type; mp_name_type(p)=mp_capsule; mp_init_big_node(mp, p);
19850   p=value(p);
19851   mp_type(x_part_loc(p))=mp_known; value(x_part_loc(p))=x;
19852   mp_type(y_part_loc(p))=mp_known; value(y_part_loc(p))=y;
19853 }
19854
19855 @ @<Additional cases of unary operators@>=
19856 case ll_corner_op: 
19857   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ll_corner_op);
19858   else mp_pair_value(mp, mp_minx, mp_miny);
19859   break;
19860 case lr_corner_op: 
19861   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, lr_corner_op);
19862   else mp_pair_value(mp, mp_maxx, mp_miny);
19863   break;
19864 case ul_corner_op: 
19865   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ul_corner_op);
19866   else mp_pair_value(mp, mp_minx, mp_maxy);
19867   break;
19868 case ur_corner_op: 
19869   if ( ! mp_get_cur_bbox(mp) ) mp_bad_unary(mp, ur_corner_op);
19870   else mp_pair_value(mp, mp_maxx, mp_maxy);
19871   break;
19872
19873 @ Here is a function that sets |minx|, |maxx|, |miny|, |maxy| to the bounding
19874 box of the current expression.  The boolean result is |false| if the expression
19875 has the wrong type.
19876
19877 @<Declare unary action procedures@>=
19878 static boolean mp_get_cur_bbox (MP mp) { 
19879   switch (mp->cur_type) {
19880   case mp_picture_type: 
19881     mp_set_bbox(mp, mp->cur_exp,true);
19882     if ( minx_val(mp->cur_exp)>maxx_val(mp->cur_exp) ) {
19883       mp_minx=0; mp_maxx=0; mp_miny=0; mp_maxy=0;
19884     } else { 
19885       mp_minx=minx_val(mp->cur_exp);
19886       mp_maxx=maxx_val(mp->cur_exp);
19887       mp_miny=miny_val(mp->cur_exp);
19888       mp_maxy=maxy_val(mp->cur_exp);
19889     }
19890     break;
19891   case mp_path_type: 
19892     mp_path_bbox(mp, mp->cur_exp);
19893     break;
19894   case mp_pen_type: 
19895     mp_pen_bbox(mp, mp->cur_exp);
19896     break;
19897   default: 
19898     return false;
19899   }
19900   return true;
19901 }
19902
19903 @ @<Additional cases of unary operators@>=
19904 case read_from_op:
19905 case close_from_op: 
19906   if ( mp->cur_type!=mp_string_type ) mp_bad_unary(mp, c);
19907   else mp_do_read_or_close(mp,c);
19908   break;
19909
19910 @ Here is a routine that interprets |cur_exp| as a file name and tries to read
19911 a line from the file or to close the file.
19912
19913 @<Declare unary action procedures@>=
19914 static void mp_do_read_or_close (MP mp,quarterword c) {
19915   readf_index n,n0; /* indices for searching |rd_fname| */
19916   @<Find the |n| where |rd_fname[n]=cur_exp|; if |cur_exp| must be inserted,
19917     call |start_read_input| and |goto found| or |not_found|@>;
19918   mp_begin_file_reading(mp);
19919   name=is_read;
19920   if ( mp_input_ln(mp, mp->rd_file[n] ) ) 
19921     goto FOUND;
19922   mp_end_file_reading(mp);
19923 NOT_FOUND:
19924   @<Record the end of file and set |cur_exp| to a dummy value@>;
19925   return;
19926 CLOSE_FILE:
19927   mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous; 
19928   return;
19929 FOUND:
19930   mp_flush_cur_exp(mp, 0);
19931   mp_finish_read(mp);
19932 }
19933
19934 @ Free slots in the |rd_file| and |rd_fname| arrays are marked with NULL's in
19935 |rd_fname|.
19936
19937 @<Find the |n| where |rd_fname[n]=cur_exp|...@>=
19938 {   
19939   char *fn;
19940   n=mp->read_files;
19941   n0=mp->read_files;
19942   fn = str(mp->cur_exp);
19943   while (mp_xstrcmp(fn,mp->rd_fname[n])!=0) { 
19944     if ( n>0 ) {
19945       decr(n);
19946     } else if ( c==close_from_op ) {
19947       goto CLOSE_FILE;
19948     } else {
19949       if ( n0==mp->read_files ) {
19950         if ( mp->read_files<mp->max_read_files ) {
19951           incr(mp->read_files);
19952         } else {
19953           void **rd_file;
19954           char **rd_fname;
19955               readf_index l,k;
19956           l = mp->max_read_files + (mp->max_read_files/4);
19957           rd_file = xmalloc((l+1), sizeof(void *));
19958           rd_fname = xmalloc((l+1), sizeof(char *));
19959               for (k=0;k<=l;k++) {
19960             if (k<=mp->max_read_files) {
19961                   rd_file[k]=mp->rd_file[k]; 
19962               rd_fname[k]=mp->rd_fname[k];
19963             } else {
19964               rd_file[k]=0; 
19965               rd_fname[k]=NULL;
19966             }
19967           }
19968               xfree(mp->rd_file); xfree(mp->rd_fname);
19969           mp->max_read_files = l;
19970           mp->rd_file = rd_file;
19971           mp->rd_fname = rd_fname;
19972         }
19973       }
19974       n=n0;
19975       if ( mp_start_read_input(mp,fn,n) ) 
19976         goto FOUND;
19977       else 
19978         goto NOT_FOUND;
19979     }
19980     if ( mp->rd_fname[n]==NULL ) { n0=n; }
19981   } 
19982   if ( c==close_from_op ) { 
19983     (mp->close_file)(mp,mp->rd_file[n]); 
19984     goto NOT_FOUND; 
19985   }
19986 }
19987
19988 @ @<Record the end of file and set |cur_exp| to a dummy value@>=
19989 xfree(mp->rd_fname[n]);
19990 mp->rd_fname[n]=NULL;
19991 if ( n==mp->read_files-1 ) mp->read_files=n;
19992 if ( c==close_from_op ) 
19993   goto CLOSE_FILE;
19994 mp_flush_cur_exp(mp, mp->eof_line);
19995 mp->cur_type=mp_string_type
19996
19997 @ The string denoting end-of-file is a one-byte string at position zero, by definition
19998
19999 @<Glob...@>=
20000 str_number eof_line;
20001
20002 @ @<Set init...@>=
20003 mp->eof_line=0;
20004
20005 @ Finally, we have the operations that combine a capsule~|p|
20006 with the current expression.
20007
20008 @d binary_return  { mp_finish_binary(mp, old_p, old_exp); return; }
20009
20010 @c @<Declare binary action procedures@>
20011 static void mp_finish_binary (MP mp, pointer old_p, pointer old_exp ){
20012   check_arith; 
20013   @<Recycle any sidestepped |independent| capsules@>;
20014 }
20015 static void mp_do_binary (MP mp,pointer p, quarterword c) {
20016   pointer q,r,rr; /* for list manipulation */
20017   pointer old_p,old_exp; /* capsules to recycle */
20018   integer v; /* for numeric manipulation */
20019   check_arith;
20020   if ( mp->internal[mp_tracing_commands]>two ) {
20021     @<Trace the current binary operation@>;
20022   }
20023   @<Sidestep |independent| cases in capsule |p|@>;
20024   @<Sidestep |independent| cases in the current expression@>;
20025   switch (c) {
20026   case plus: case minus:
20027     @<Add or subtract the current expression from |p|@>;
20028     break;
20029   @<Additional cases of binary operators@>;
20030   }; /* there are no other cases */
20031   mp_recycle_value(mp, p); 
20032   mp_free_node(mp, p,value_node_size); /* |return| to avoid this */
20033   mp_finish_binary(mp, old_p, old_exp);
20034 }
20035
20036 @ @<Declare binary action...@>=
20037 static void mp_bad_binary (MP mp,pointer p, quarterword c) { 
20038   mp_disp_err(mp, p,"");
20039   exp_err("Not implemented: ");
20040 @.Not implemented...@>
20041   if ( c>=min_of ) mp_print_op(mp, c);
20042   mp_print_known_or_unknown_type(mp, mp_type(p),p);
20043   if ( c>=min_of ) mp_print(mp, "of"); else mp_print_op(mp, c);
20044   mp_print_known_or_unknown_type(mp, mp->cur_type,mp->cur_exp);
20045   help3("I'm afraid I don't know how to apply that operation to that",
20046        "combination of types. Continue, and I'll return the second",
20047        "argument (see above) as the result of the operation.");
20048   mp_put_get_error(mp);
20049 }
20050 static void mp_bad_envelope_pen (MP mp) {
20051   mp_disp_err(mp, null,"");
20052   exp_err("Not implemented: envelope(elliptical pen)of(path)");
20053 @.Not implemented...@>
20054   help3("I'm afraid I don't know how to apply that operation to that",
20055        "combination of types. Continue, and I'll return the second",
20056        "argument (see above) as the result of the operation.");
20057   mp_put_get_error(mp);
20058 }
20059
20060 @ @<Trace the current binary operation@>=
20061
20062   mp_begin_diagnostic(mp); mp_print_nl(mp, "{(");
20063   mp_print_exp(mp,p,0); /* show the operand, but not verbosely */
20064   mp_print_char(mp,xord(')')); mp_print_op(mp,c); mp_print_char(mp,xord('('));
20065   mp_print_exp(mp,null,0); mp_print(mp,")}"); 
20066   mp_end_diagnostic(mp, false);
20067 }
20068
20069 @ Several of the binary operations are potentially complicated by the
20070 fact that |independent| values can sneak into capsules. For example,
20071 we've seen an instance of this difficulty in the unary operation
20072 of negation. In order to reduce the number of cases that need to be
20073 handled, we first change the two operands (if necessary)
20074 to rid them of |independent| components. The original operands are
20075 put into capsules called |old_p| and |old_exp|, which will be
20076 recycled after the binary operation has been safely carried out.
20077
20078 @<Recycle any sidestepped |independent| capsules@>=
20079 if ( old_p!=null ) { 
20080   mp_recycle_value(mp, old_p); mp_free_node(mp, old_p,value_node_size);
20081 }
20082 if ( old_exp!=null ) {
20083   mp_recycle_value(mp, old_exp); mp_free_node(mp, old_exp,value_node_size);
20084 }
20085
20086 @ A big node is considered to be ``tarnished'' if it contains at least one
20087 independent component. We will define a simple function called `|tarnished|'
20088 that returns |null| if and only if its argument is not tarnished.
20089
20090 @<Sidestep |independent| cases in capsule |p|@>=
20091 switch (mp_type(p)) {
20092 case mp_transform_type:
20093 case mp_color_type:
20094 case mp_cmykcolor_type:
20095 case mp_pair_type: 
20096   old_p=mp_tarnished(mp, p);
20097   break;
20098 case mp_independent: old_p=mp_void; break;
20099 default: old_p=null; break;
20100 }
20101 if ( old_p!=null ) {
20102   q=mp_stash_cur_exp(mp); old_p=p; mp_make_exp_copy(mp, old_p);
20103   p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
20104 }
20105
20106 @ @<Sidestep |independent| cases in the current expression@>=
20107 switch (mp->cur_type) {
20108 case mp_transform_type:
20109 case mp_color_type:
20110 case mp_cmykcolor_type:
20111 case mp_pair_type: 
20112   old_exp=mp_tarnished(mp, mp->cur_exp);
20113   break;
20114 case mp_independent:old_exp=mp_void; break;
20115 default: old_exp=null; break;
20116 }
20117 if ( old_exp!=null ) {
20118   old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20119 }
20120
20121 @ @<Declare binary action...@>=
20122 static pointer mp_tarnished (MP mp,pointer p) {
20123   pointer q; /* beginning of the big node */
20124   pointer r; /* current position in the big node */
20125   q=value(p); r=q+mp->big_node_size[mp_type(p)];
20126   do {  
20127    r=r-2;
20128    if ( mp_type(r)==mp_independent ) return mp_void; 
20129   } while (r!=q);
20130   return null;
20131 }
20132
20133 @ @<Add or subtract the current expression from |p|@>=
20134 if ( (mp->cur_type<mp_color_type)||(mp_type(p)<mp_color_type) ) {
20135   mp_bad_binary(mp, p,c);
20136 } else  {
20137   if ((mp->cur_type>mp_pair_type)&&(mp_type(p)>mp_pair_type) ) {
20138     mp_add_or_subtract(mp, p,null,c);
20139   } else {
20140     if ( mp->cur_type!=mp_type(p) )  {
20141       mp_bad_binary(mp, p,c);
20142     } else { 
20143       q=value(p); r=value(mp->cur_exp);
20144       rr=r+mp->big_node_size[mp->cur_type];
20145       while ( r<rr ) { 
20146         mp_add_or_subtract(mp, q,r,c);
20147         q=q+2; r=r+2;
20148       }
20149     }
20150   }
20151 }
20152
20153 @ The first argument to |add_or_subtract| is the location of a value node
20154 in a capsule or pair node that will soon be recycled. The second argument
20155 is either a location within a pair or transform node of |cur_exp|,
20156 or it is null (which means that |cur_exp| itself should be the second
20157 argument).  The third argument is either |plus| or |minus|.
20158
20159 The sum or difference of the numeric quantities will replace the second
20160 operand.  Arithmetic overflow may go undetected; users aren't supposed to
20161 be monkeying around with really big values.
20162 @^overflow in arithmetic@>
20163
20164 @<Declare binary action...@>=
20165 @<Declare the procedure called |dep_finish|@>
20166 static void mp_add_or_subtract (MP mp,pointer p, pointer q, quarterword c) {
20167   quarterword s,t; /* operand types */
20168   pointer r; /* list traverser */
20169   integer v; /* second operand value */
20170   if ( q==null ) { 
20171     t=mp->cur_type;
20172     if ( t<mp_dependent ) v=mp->cur_exp; else v=dep_list(mp->cur_exp);
20173   } else { 
20174     t=mp_type(q);
20175     if ( t<mp_dependent ) v=value(q); else v=dep_list(q);
20176   }
20177   if ( t==mp_known ) {
20178     if ( c==minus ) negate(v);
20179     if ( mp_type(p)==mp_known ) {
20180       v=mp_slow_add(mp, value(p),v);
20181       if ( q==null ) mp->cur_exp=v; else value(q)=v;
20182       return;
20183     }
20184     @<Add a known value to the constant term of |dep_list(p)|@>;
20185   } else  { 
20186     if ( c==minus ) mp_negate_dep_list(mp, v);
20187     @<Add operand |p| to the dependency list |v|@>;
20188   }
20189 }
20190
20191 @ @<Add a known value to the constant term of |dep_list(p)|@>=
20192 r=dep_list(p);
20193 while ( mp_info(r)!=null ) r=mp_link(r);
20194 value(r)=mp_slow_add(mp, value(r),v);
20195 if ( q==null ) {
20196   q=mp_get_node(mp, value_node_size); mp->cur_exp=q; mp->cur_type=mp_type(p);
20197   mp_name_type(q)=mp_capsule;
20198 }
20199 dep_list(q)=dep_list(p); mp_type(q)=mp_type(p);
20200 prev_dep(q)=prev_dep(p); mp_link(prev_dep(p))=q;
20201 mp_type(p)=mp_known; /* this will keep the recycler from collecting non-garbage */
20202
20203 @ We prefer |dependent| lists to |mp_proto_dependent| ones, because it is
20204 nice to retain the extra accuracy of |fraction| coefficients.
20205 But we have to handle both kinds, and mixtures too.
20206
20207 @<Add operand |p| to the dependency list |v|@>=
20208 if ( mp_type(p)==mp_known ) {
20209   @<Add the known |value(p)| to the constant term of |v|@>;
20210 } else { 
20211   s=mp_type(p); r=dep_list(p);
20212   if ( t==mp_dependent ) {
20213     if ( s==mp_dependent ) {
20214       if ( mp_max_coef(mp, r)+mp_max_coef(mp, v)<coef_bound )
20215         v=mp_p_plus_q(mp, v,r,mp_dependent); goto DONE;
20216       } /* |fix_needed| will necessarily be false */
20217       t=mp_proto_dependent; 
20218       v=mp_p_over_v(mp, v,unity,mp_dependent,mp_proto_dependent);
20219     }
20220     if ( s==mp_proto_dependent ) v=mp_p_plus_q(mp, v,r,mp_proto_dependent);
20221     else v=mp_p_plus_fq(mp, v,unity,r,mp_proto_dependent,mp_dependent);
20222  DONE:  
20223     @<Output the answer, |v| (which might have become |known|)@>;
20224   }
20225
20226 @ @<Add the known |value(p)| to the constant term of |v|@>=
20227
20228   while ( mp_info(v)!=null ) v=mp_link(v);
20229   value(v)=mp_slow_add(mp, value(p),value(v));
20230 }
20231
20232 @ @<Output the answer, |v| (which might have become |known|)@>=
20233 if ( q!=null ) mp_dep_finish(mp, v,q,t);
20234 else  { mp->cur_type=t; mp_dep_finish(mp, v,null,t); }
20235
20236 @ Here's the current situation: The dependency list |v| of type |t|
20237 should either be put into the current expression (if |q=null|) or
20238 into location |q| within a pair node (otherwise). The destination (|cur_exp|
20239 or |q|) formerly held a dependency list with the same
20240 final pointer as the list |v|.
20241
20242 @<Declare the procedure called |dep_finish|@>=
20243 static void mp_dep_finish (MP mp, pointer v, pointer q, quarterword t) {
20244   pointer p; /* the destination */
20245   scaled vv; /* the value, if it is |known| */
20246   if ( q==null ) p=mp->cur_exp; else p=q;
20247   dep_list(p)=v; mp_type(p)=t;
20248   if ( mp_info(v)==null ) { 
20249     vv=value(v);
20250     if ( q==null ) { 
20251       mp_flush_cur_exp(mp, vv);
20252     } else  { 
20253       mp_recycle_value(mp, p); mp_type(q)=mp_known; value(q)=vv; 
20254     }
20255   } else if ( q==null ) {
20256     mp->cur_type=t;
20257   }
20258   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20259 }
20260
20261 @ Let's turn now to the six basic relations of comparison.
20262
20263 @<Additional cases of binary operators@>=
20264 case less_than: case less_or_equal: case greater_than:
20265 case greater_or_equal: case equal_to: case unequal_to:
20266   check_arith; /* at this point |arith_error| should be |false|? */
20267   if ( (mp->cur_type>mp_pair_type)&&(mp_type(p)>mp_pair_type) ) {
20268     mp_add_or_subtract(mp, p,null,minus); /* |cur_exp:=(p)-cur_exp| */
20269   } else if ( mp->cur_type!=mp_type(p) ) {
20270     mp_bad_binary(mp, p,c); goto DONE; 
20271   } else if ( mp->cur_type==mp_string_type ) {
20272     mp_flush_cur_exp(mp, mp_str_vs_str(mp, value(p),mp->cur_exp));
20273   } else if ((mp->cur_type==mp_unknown_string)||
20274            (mp->cur_type==mp_unknown_boolean) ) {
20275     @<Check if unknowns have been equated@>;
20276   } else if ( (mp->cur_type<=mp_pair_type)&&(mp->cur_type>=mp_transform_type)) {
20277     @<Reduce comparison of big nodes to comparison of scalars@>;
20278   } else if ( mp->cur_type==mp_boolean_type ) {
20279     mp_flush_cur_exp(mp, mp->cur_exp-value(p));
20280   } else { 
20281     mp_bad_binary(mp, p,c); goto DONE;
20282   }
20283   @<Compare the current expression with zero@>;
20284 DONE:  
20285   mp->arith_error=false; /* ignore overflow in comparisons */
20286   break;
20287
20288 @ @<Compare the current expression with zero@>=
20289 if ( mp->cur_type!=mp_known ) {
20290   if ( mp->cur_type<mp_known ) {
20291     mp_disp_err(mp, p,"");
20292     help1("The quantities shown above have not been equated.")
20293   } else  {
20294     help2("Oh dear. I can\'t decide if the expression above is positive,",
20295           "negative, or zero. So this comparison test won't be `true'.");
20296   }
20297   exp_err("Unknown relation will be considered false");
20298 @.Unknown relation...@>
20299   mp_put_get_flush_error(mp, false_code);
20300 } else {
20301   switch (c) {
20302   case less_than: boolean_reset(mp->cur_exp<0); break;
20303   case less_or_equal: boolean_reset(mp->cur_exp<=0); break;
20304   case greater_than: boolean_reset(mp->cur_exp>0); break;
20305   case greater_or_equal: boolean_reset(mp->cur_exp>=0); break;
20306   case equal_to: boolean_reset(mp->cur_exp==0); break;
20307   case unequal_to: boolean_reset(mp->cur_exp!=0); break;
20308   }; /* there are no other cases */
20309 }
20310 mp->cur_type=mp_boolean_type
20311
20312 @ When two unknown strings are in the same ring, we know that they are
20313 equal. Otherwise, we don't know whether they are equal or not, so we
20314 make no change.
20315
20316 @<Check if unknowns have been equated@>=
20317
20318   q=value(mp->cur_exp);
20319   while ( (q!=mp->cur_exp)&&(q!=p) ) q=value(q);
20320   if ( q==p ) mp_flush_cur_exp(mp, 0);
20321 }
20322
20323 @ @<Reduce comparison of big nodes to comparison of scalars@>=
20324
20325   q=value(p); r=value(mp->cur_exp);
20326   rr=r+mp->big_node_size[mp->cur_type]-2;
20327   while (1) { mp_add_or_subtract(mp, q,r,minus);
20328     if ( mp_type(r)!=mp_known ) break;
20329     if ( value(r)!=0 ) break;
20330     if ( r==rr ) break;
20331     q=q+2; r=r+2;
20332   }
20333   mp_take_part(mp, mp_name_type(r)+x_part-mp_x_part_sector);
20334 }
20335
20336 @ Here we use the sneaky fact that |and_op-false_code=or_op-true_code|.
20337
20338 @<Additional cases of binary operators@>=
20339 case and_op:
20340 case or_op: 
20341   if ( (mp_type(p)!=mp_boolean_type)||(mp->cur_type!=mp_boolean_type) )
20342     mp_bad_binary(mp, p,c);
20343   else if ( value(p)==c+false_code-and_op ) mp->cur_exp=value(p);
20344   break;
20345
20346 @ @<Additional cases of binary operators@>=
20347 case times: 
20348   if ( (mp->cur_type<mp_color_type)||(mp_type(p)<mp_color_type) ) {
20349    mp_bad_binary(mp, p,times);
20350   } else if ( (mp->cur_type==mp_known)||(mp_type(p)==mp_known) ) {
20351     @<Multiply when at least one operand is known@>;
20352   } else if ( (mp_nice_color_or_pair(mp, p,mp_type(p))&&(mp->cur_type>mp_pair_type))
20353       ||(mp_nice_color_or_pair(mp, mp->cur_exp,mp->cur_type)&&
20354           (mp_type(p)>mp_pair_type)) ) {
20355     mp_hard_times(mp, p); 
20356     binary_return;
20357   } else {
20358     mp_bad_binary(mp, p,times);
20359   }
20360   break;
20361
20362 @ @<Multiply when at least one operand is known@>=
20363
20364   if ( mp_type(p)==mp_known ) {
20365     v=value(p); mp_free_node(mp, p,value_node_size); 
20366   } else {
20367     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20368   }
20369   if ( mp->cur_type==mp_known ) {
20370     mp->cur_exp=mp_take_scaled(mp, mp->cur_exp,v);
20371   } else if ( (mp->cur_type==mp_pair_type)||
20372               (mp->cur_type==mp_color_type)||
20373               (mp->cur_type==mp_cmykcolor_type) ) {
20374     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20375     do {  
20376        p=p-2; mp_dep_mult(mp, p,v,true);
20377     } while (p!=value(mp->cur_exp));
20378   } else {
20379     mp_dep_mult(mp, null,v,true);
20380   }
20381   binary_return;
20382 }
20383
20384 @ @<Declare binary action...@>=
20385 static void mp_dep_mult (MP mp,pointer p, integer v, boolean v_is_scaled) {
20386   pointer q; /* the dependency list being multiplied by |v| */
20387   quarterword s,t; /* its type, before and after */
20388   if ( p==null ) {
20389     q=mp->cur_exp;
20390   } else if ( mp_type(p)!=mp_known ) {
20391     q=p;
20392   } else { 
20393     if ( v_is_scaled ) value(p)=mp_take_scaled(mp, value(p),v);
20394     else value(p)=mp_take_fraction(mp, value(p),v);
20395     return;
20396   };
20397   t=mp_type(q); q=dep_list(q); s=t;
20398   if ( t==mp_dependent ) if ( v_is_scaled )
20399     if (mp_ab_vs_cd(mp, mp_max_coef(mp,q),abs(v),coef_bound-1,unity)>=0 ) 
20400       t=mp_proto_dependent;
20401   q=mp_p_times_v(mp, q,v,s,t,v_is_scaled); 
20402   mp_dep_finish(mp, q,p,t);
20403 }
20404
20405 @ Here is a routine that is similar to |times|; but it is invoked only
20406 internally, when |v| is a |fraction| whose magnitude is at most~1,
20407 and when |cur_type>=mp_color_type|.
20408
20409 @c 
20410 static void mp_frac_mult (MP mp,scaled n, scaled d) {
20411   /* multiplies |cur_exp| by |n/d| */
20412   pointer p; /* a pair node */
20413   pointer old_exp; /* a capsule to recycle */
20414   fraction v; /* |n/d| */
20415   if ( mp->internal[mp_tracing_commands]>two ) {
20416     @<Trace the fraction multiplication@>;
20417   }
20418   switch (mp->cur_type) {
20419   case mp_transform_type:
20420   case mp_color_type:
20421   case mp_cmykcolor_type:
20422   case mp_pair_type:
20423    old_exp=mp_tarnished(mp, mp->cur_exp);
20424    break;
20425   case mp_independent: old_exp=mp_void; break;
20426   default: old_exp=null; break;
20427   }
20428   if ( old_exp!=null ) { 
20429      old_exp=mp->cur_exp; mp_make_exp_copy(mp, old_exp);
20430   }
20431   v=mp_make_fraction(mp, n,d);
20432   if ( mp->cur_type==mp_known ) {
20433     mp->cur_exp=mp_take_fraction(mp, mp->cur_exp,v);
20434   } else if ( mp->cur_type<=mp_pair_type ) { 
20435     p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20436     do {  
20437       p=p-2;
20438       mp_dep_mult(mp, p,v,false);
20439     } while (p!=value(mp->cur_exp));
20440   } else {
20441     mp_dep_mult(mp, null,v,false);
20442   }
20443   if ( old_exp!=null ) {
20444     mp_recycle_value(mp, old_exp); 
20445     mp_free_node(mp, old_exp,value_node_size);
20446   }
20447 }
20448
20449 @ @<Trace the fraction multiplication@>=
20450
20451   mp_begin_diagnostic(mp); 
20452   mp_print_nl(mp, "{("); mp_print_scaled(mp,n); mp_print_char(mp,xord('/'));
20453   mp_print_scaled(mp,d); mp_print(mp,")*("); mp_print_exp(mp,null,0); 
20454   mp_print(mp,")}");
20455   mp_end_diagnostic(mp, false);
20456 }
20457
20458 @ The |hard_times| routine multiplies a nice color or pair by a dependency list.
20459
20460 @<Declare binary action procedures@>=
20461 static void mp_hard_times (MP mp,pointer p) {
20462   pointer q; /* a copy of the dependent variable |p| */
20463   pointer r; /* a component of the big node for the nice color or pair */
20464   scaled v; /* the known value for |r| */
20465   if ( mp_type(p)<=mp_pair_type ) { 
20466      q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p); p=q;
20467   }; /* now |cur_type=mp_pair_type| or |cur_type=mp_color_type| */
20468   r=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20469   while (1) { 
20470     r=r-2;
20471     v=value(r);
20472     mp_type(r)=mp_type(p);
20473     if ( r==value(mp->cur_exp) ) 
20474       break;
20475     mp_new_dep(mp, r,mp_copy_dep_list(mp, dep_list(p)));
20476     mp_dep_mult(mp, r,v,true);
20477   }
20478   mp->mem[value_loc(r)]=mp->mem[value_loc(p)];
20479   mp_link(prev_dep(p))=r;
20480   mp_free_node(mp, p,value_node_size);
20481   mp_dep_mult(mp, r,v,true);
20482 }
20483
20484 @ @<Additional cases of binary operators@>=
20485 case over: 
20486   if ( (mp->cur_type!=mp_known)||(mp_type(p)<mp_color_type) ) {
20487     mp_bad_binary(mp, p,over);
20488   } else { 
20489     v=mp->cur_exp; mp_unstash_cur_exp(mp, p);
20490     if ( v==0 ) {
20491       @<Squeal about division by zero@>;
20492     } else { 
20493       if ( mp->cur_type==mp_known ) {
20494         mp->cur_exp=mp_make_scaled(mp, mp->cur_exp,v);
20495       } else if ( mp->cur_type<=mp_pair_type ) { 
20496         p=value(mp->cur_exp)+mp->big_node_size[mp->cur_type];
20497         do {  
20498           p=p-2;  mp_dep_div(mp, p,v);
20499         } while (p!=value(mp->cur_exp));
20500       } else {
20501         mp_dep_div(mp, null,v);
20502       }
20503     }
20504     binary_return;
20505   }
20506   break;
20507
20508 @ @<Declare binary action...@>=
20509 static void mp_dep_div (MP mp,pointer p, scaled v) {
20510   pointer q; /* the dependency list being divided by |v| */
20511   quarterword s,t; /* its type, before and after */
20512   if ( p==null ) q=mp->cur_exp;
20513   else if ( mp_type(p)!=mp_known ) q=p;
20514   else { value(p)=mp_make_scaled(mp, value(p),v); return; };
20515   t=mp_type(q); q=dep_list(q); s=t;
20516   if ( t==mp_dependent )
20517     if ( mp_ab_vs_cd(mp, mp_max_coef(mp,q),unity,coef_bound-1,abs(v))>=0 ) 
20518       t=mp_proto_dependent;
20519   q=mp_p_over_v(mp, q,v,s,t); 
20520   mp_dep_finish(mp, q,p,t);
20521 }
20522
20523 @ @<Squeal about division by zero@>=
20524
20525   exp_err("Division by zero");
20526 @.Division by zero@>
20527   help2("You're trying to divide the quantity shown above the error",
20528         "message by zero. I'm going to divide it by one instead.");
20529   mp_put_get_error(mp);
20530 }
20531
20532 @ @<Additional cases of binary operators@>=
20533 case pythag_add:
20534 case pythag_sub: 
20535    if ( (mp->cur_type==mp_known)&&(mp_type(p)==mp_known) ) {
20536      if ( c==pythag_add ) mp->cur_exp=mp_pyth_add(mp, value(p),mp->cur_exp);
20537      else mp->cur_exp=mp_pyth_sub(mp, value(p),mp->cur_exp);
20538    } else mp_bad_binary(mp, p,c);
20539    break;
20540
20541 @ The next few sections of the program deal with affine transformations
20542 of coordinate data.
20543
20544 @<Additional cases of binary operators@>=
20545 case rotated_by: case slanted_by:
20546 case scaled_by: case shifted_by: case transformed_by:
20547 case x_scaled: case y_scaled: case z_scaled:
20548   if ( mp_type(p)==mp_path_type ) { 
20549     path_trans(c,p); binary_return;
20550   } else if ( mp_type(p)==mp_pen_type ) { 
20551     pen_trans(c,p);
20552     mp->cur_exp=mp_convex_hull(mp, mp->cur_exp); 
20553       /* rounding error could destroy convexity */
20554     binary_return;
20555   } else if ( (mp_type(p)==mp_pair_type)||(mp_type(p)==mp_transform_type) ) {
20556     mp_big_trans(mp, p,c);
20557   } else if ( mp_type(p)==mp_picture_type ) {
20558     mp_do_edges_trans(mp, p,c); binary_return;
20559   } else {
20560     mp_bad_binary(mp, p,c);
20561   }
20562   break;
20563
20564 @ Let |c| be one of the eight transform operators. The procedure call
20565 |set_up_trans(c)| first changes |cur_exp| to a transform that corresponds to
20566 |c| and the original value of |cur_exp|. (In particular, |cur_exp| doesn't
20567 change at all if |c=transformed_by|.)
20568
20569 Then, if all components of the resulting transform are |known|, they are
20570 moved to the global variables |txx|, |txy|, |tyx|, |tyy|, |tx|, |ty|;
20571 and |cur_exp| is changed to the known value zero.
20572
20573 @<Declare binary action...@>=
20574 static void mp_set_up_trans (MP mp,quarterword c) {
20575   pointer p,q,r; /* list manipulation registers */
20576   if ( (c!=transformed_by)||(mp->cur_type!=mp_transform_type) ) {
20577     @<Put the current transform into |cur_exp|@>;
20578   }
20579   @<If the current transform is entirely known, stash it in global variables;
20580     otherwise |return|@>;
20581 }
20582
20583 @ @<Glob...@>=
20584 scaled txx;
20585 scaled txy;
20586 scaled tyx;
20587 scaled tyy;
20588 scaled tx;
20589 scaled ty; /* current transform coefficients */
20590
20591 @ @<Put the current transform...@>=
20592
20593   p=mp_stash_cur_exp(mp); 
20594   mp->cur_exp=mp_id_transform(mp); 
20595   mp->cur_type=mp_transform_type;
20596   q=value(mp->cur_exp);
20597   switch (c) {
20598   @<For each of the eight cases, change the relevant fields of |cur_exp|
20599     and |goto done|;
20600     but do nothing if capsule |p| doesn't have the appropriate type@>;
20601   }; /* there are no other cases */
20602   mp_disp_err(mp, p,"Improper transformation argument");
20603 @.Improper transformation argument@>
20604   help3("The expression shown above has the wrong type,",
20605        "so I can\'t transform anything using it.",
20606        "Proceed, and I'll omit the transformation.");
20607   mp_put_get_error(mp);
20608 DONE: 
20609   mp_recycle_value(mp, p); 
20610   mp_free_node(mp, p,value_node_size);
20611 }
20612
20613 @ @<If the current transform is entirely known, ...@>=
20614 q=value(mp->cur_exp); r=q+transform_node_size;
20615 do {  
20616   r=r-2;
20617   if ( mp_type(r)!=mp_known ) return;
20618 } while (r!=q);
20619 mp->txx=value(xx_part_loc(q));
20620 mp->txy=value(xy_part_loc(q));
20621 mp->tyx=value(yx_part_loc(q));
20622 mp->tyy=value(yy_part_loc(q));
20623 mp->tx=value(x_part_loc(q));
20624 mp->ty=value(y_part_loc(q));
20625 mp_flush_cur_exp(mp, 0)
20626
20627 @ @<For each of the eight cases...@>=
20628 case rotated_by:
20629   if ( mp_type(p)==mp_known )
20630     @<Install sines and cosines, then |goto done|@>;
20631   break;
20632 case slanted_by:
20633   if ( mp_type(p)>mp_pair_type ) { 
20634    mp_install(mp, xy_part_loc(q),p); goto DONE;
20635   };
20636   break;
20637 case scaled_by:
20638   if ( mp_type(p)>mp_pair_type ) { 
20639     mp_install(mp, xx_part_loc(q),p); mp_install(mp, yy_part_loc(q),p); 
20640     goto DONE;
20641   };
20642   break;
20643 case shifted_by:
20644   if ( mp_type(p)==mp_pair_type ) {
20645     r=value(p); mp_install(mp, x_part_loc(q),x_part_loc(r));
20646     mp_install(mp, y_part_loc(q),y_part_loc(r)); goto DONE;
20647   };
20648   break;
20649 case x_scaled:
20650   if ( mp_type(p)>mp_pair_type ) {
20651     mp_install(mp, xx_part_loc(q),p); goto DONE;
20652   };
20653   break;
20654 case y_scaled:
20655   if ( mp_type(p)>mp_pair_type ) {
20656     mp_install(mp, yy_part_loc(q),p); goto DONE;
20657   };
20658   break;
20659 case z_scaled:
20660   if ( mp_type(p)==mp_pair_type )
20661     @<Install a complex multiplier, then |goto done|@>;
20662   break;
20663 case transformed_by:
20664   break;
20665   
20666
20667 @ @<Install sines and cosines, then |goto done|@>=
20668 { mp_n_sin_cos(mp, (value(p) % three_sixty_units)*16);
20669   value(xx_part_loc(q))=mp_round_fraction(mp, mp->n_cos);
20670   value(yx_part_loc(q))=mp_round_fraction(mp, mp->n_sin);
20671   value(xy_part_loc(q))=-value(yx_part_loc(q));
20672   value(yy_part_loc(q))=value(xx_part_loc(q));
20673   goto DONE;
20674 }
20675
20676 @ @<Install a complex multiplier, then |goto done|@>=
20677
20678   r=value(p);
20679   mp_install(mp, xx_part_loc(q),x_part_loc(r));
20680   mp_install(mp, yy_part_loc(q),x_part_loc(r));
20681   mp_install(mp, yx_part_loc(q),y_part_loc(r));
20682   if ( mp_type(y_part_loc(r))==mp_known ) negate(value(y_part_loc(r)));
20683   else mp_negate_dep_list(mp, dep_list(y_part_loc(r)));
20684   mp_install(mp, xy_part_loc(q),y_part_loc(r));
20685   goto DONE;
20686 }
20687
20688 @ Procedure |set_up_known_trans| is like |set_up_trans|, but it
20689 insists that the transformation be entirely known.
20690
20691 @<Declare binary action...@>=
20692 static void mp_set_up_known_trans (MP mp,quarterword c) { 
20693   mp_set_up_trans(mp, c);
20694   if ( mp->cur_type!=mp_known ) {
20695     exp_err("Transform components aren't all known");
20696 @.Transform components...@>
20697     help3("I'm unable to apply a partially specified transformation",
20698       "except to a fully known pair or transform.",
20699       "Proceed, and I'll omit the transformation.");
20700     mp_put_get_flush_error(mp, 0);
20701     mp->txx=unity; mp->txy=0; mp->tyx=0; mp->tyy=unity; 
20702     mp->tx=0; mp->ty=0;
20703   }
20704 }
20705
20706 @ Here's a procedure that applies the transform |txx..ty| to a pair of
20707 coordinates in locations |p| and~|q|.
20708
20709 @<Declare binary action...@>= 
20710 static void mp_trans (MP mp,pointer p, pointer q) {
20711   scaled v; /* the new |x| value */
20712   v=mp_take_scaled(mp, mp->mem[p].sc,mp->txx)+
20713   mp_take_scaled(mp, mp->mem[q].sc,mp->txy)+mp->tx;
20714   mp->mem[q].sc=mp_take_scaled(mp, mp->mem[p].sc,mp->tyx)+
20715   mp_take_scaled(mp, mp->mem[q].sc,mp->tyy)+mp->ty;
20716   mp->mem[p].sc=v;
20717 }
20718
20719 @ The simplest transformation procedure applies a transform to all
20720 coordinates of a path.  The |path_trans(c)(p)| macro applies
20721 a transformation defined by |cur_exp| and the transform operator |c|
20722 to the path~|p|.
20723
20724 @d path_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20725                      mp_unstash_cur_exp(mp, (B)); 
20726                      mp_do_path_trans(mp, mp->cur_exp); }
20727
20728 @<Declare binary action...@>=
20729 static void mp_do_path_trans (MP mp,pointer p) {
20730   pointer q; /* list traverser */
20731   q=p;
20732   do { 
20733     if ( mp_left_type(q)!=mp_endpoint ) 
20734       mp_trans(mp, q+3,q+4); /* that's |mp_left_x| and |mp_left_y| */
20735     mp_trans(mp, q+1,q+2); /* that's |mp_x_coord| and |mp_y_coord| */
20736     if ( mp_right_type(q)!=mp_endpoint ) 
20737       mp_trans(mp, q+5,q+6); /* that's |mp_right_x| and |mp_right_y| */
20738 @^data structure assumptions@>
20739     q=mp_link(q);
20740   } while (q!=p);
20741 }
20742
20743 @ Transforming a pen is very similar, except that there are no |mp_left_type|
20744 and |mp_right_type| fields.
20745
20746 @d pen_trans(A,B) { mp_set_up_known_trans(mp, (A)); 
20747                     mp_unstash_cur_exp(mp, (B)); 
20748                     mp_do_pen_trans(mp, mp->cur_exp); }
20749
20750 @<Declare binary action...@>=
20751 static void mp_do_pen_trans (MP mp,pointer p) {
20752   pointer q; /* list traverser */
20753   if ( pen_is_elliptical(p) ) {
20754     mp_trans(mp, p+3,p+4); /* that's |mp_left_x| and |mp_left_y| */
20755     mp_trans(mp, p+5,p+6); /* that's |mp_right_x| and |mp_right_y| */
20756   };
20757   q=p;
20758   do { 
20759     mp_trans(mp, q+1,q+2); /* that's |mp_x_coord| and |mp_y_coord| */
20760 @^data structure assumptions@>
20761     q=mp_link(q);
20762   } while (q!=p);
20763 }
20764
20765 @ The next transformation procedure applies to edge structures. It will do
20766 any transformation, but the results may be substandard if the picture contains
20767 text that uses downloaded bitmap fonts.  The binary action procedure is
20768 |do_edges_trans|, but we also need a function that just scales a picture.
20769 That routine is |scale_edges|.  Both it and the underlying routine |edges_trans|
20770 should be thought of as procedures that update an edge structure |h|, except
20771 that they have to return a (possibly new) structure because of the need to call
20772 |private_edges|.
20773
20774 @<Declare binary action...@>=
20775 static pointer mp_edges_trans (MP mp, pointer h) {
20776   pointer q; /* the object being transformed */
20777   pointer r,s; /* for list manipulation */
20778   scaled sx,sy; /* saved transformation parameters */
20779   scaled sqdet; /* square root of determinant for |dash_scale| */
20780   integer sgndet; /* sign of the determinant */
20781   scaled v; /* a temporary value */
20782   h=mp_private_edges(mp, h);
20783   sqdet=mp_sqrt_det(mp, mp->txx,mp->txy,mp->tyx,mp->tyy);
20784   sgndet=mp_ab_vs_cd(mp, mp->txx,mp->tyy,mp->txy,mp->tyx);
20785   if ( dash_list(h)!=null_dash ) {
20786     @<Try to transform the dash list of |h|@>;
20787   }
20788   @<Make the bounding box of |h| unknown if it can't be updated properly
20789     without scanning the whole structure@>;  
20790   q=mp_link(dummy_loc(h));
20791   while ( q!=null ) { 
20792     @<Transform graphical object |q|@>;
20793     q=mp_link(q);
20794   }
20795   return h;
20796 }
20797 static void mp_do_edges_trans (MP mp,pointer p, quarterword c) { 
20798   mp_set_up_known_trans(mp, c);
20799   value(p)=mp_edges_trans(mp, value(p));
20800   mp_unstash_cur_exp(mp, p);
20801 }
20802 static void mp_scale_edges (MP mp) { 
20803   mp->txx=mp->se_sf; mp->tyy=mp->se_sf;
20804   mp->txy=0; mp->tyx=0; mp->tx=0; mp->ty=0;
20805   mp->se_pic=mp_edges_trans(mp, mp->se_pic);
20806 }
20807
20808 @ @<Try to transform the dash list of |h|@>=
20809 if ( (mp->txy!=0)||(mp->tyx!=0)||
20810      (mp->ty!=0)||(abs(mp->txx)!=abs(mp->tyy))) {
20811   mp_flush_dash_list(mp, h);
20812 } else { 
20813   if ( mp->txx<0 ) { @<Reverse the dash list of |h|@>; } 
20814   @<Scale the dash list by |txx| and shift it by |tx|@>;
20815   dash_y(h)=mp_take_scaled(mp, dash_y(h),abs(mp->tyy));
20816 }
20817
20818 @ @<Reverse the dash list of |h|@>=
20819
20820   r=dash_list(h);
20821   dash_list(h)=null_dash;
20822   while ( r!=null_dash ) {
20823     s=r; r=mp_link(r);
20824     v=start_x(s); start_x(s)=stop_x(s); stop_x(s)=v;
20825     mp_link(s)=dash_list(h);
20826     dash_list(h)=s;
20827   }
20828 }
20829
20830 @ @<Scale the dash list by |txx| and shift it by |tx|@>=
20831 r=dash_list(h);
20832 while ( r!=null_dash ) {
20833   start_x(r)=mp_take_scaled(mp, start_x(r),mp->txx)+mp->tx;
20834   stop_x(r)=mp_take_scaled(mp, stop_x(r),mp->txx)+mp->tx;
20835   r=mp_link(r);
20836 }
20837
20838 @ @<Make the bounding box of |h| unknown if it can't be updated properly...@>=
20839 if ( (mp->txx==0)&&(mp->tyy==0) ) {
20840   @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>;
20841 } else if ( (mp->txy!=0)||(mp->tyx!=0) ) {
20842   mp_init_bbox(mp, h);
20843   goto DONE1;
20844 }
20845 if ( minx_val(h)<=maxx_val(h) ) {
20846   @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift by
20847    |(tx,ty)|@>;
20848 }
20849 DONE1:
20850
20851
20852
20853 @ @<Swap the $x$ and $y$ parameters in the bounding box of |h|@>=
20854
20855   v=minx_val(h); minx_val(h)=miny_val(h); miny_val(h)=v;
20856   v=maxx_val(h); maxx_val(h)=maxy_val(h); maxy_val(h)=v;
20857 }
20858
20859 @ The sum ``|txx+txy|'' is whichever of |txx| or |txy| is nonzero.  The other
20860 sum is similar.
20861
20862 @<Scale the bounding box by |txx+txy| and |tyx+tyy|; then shift...@>=
20863
20864   minx_val(h)=mp_take_scaled(mp, minx_val(h),mp->txx+mp->txy)+mp->tx;
20865   maxx_val(h)=mp_take_scaled(mp, maxx_val(h),mp->txx+mp->txy)+mp->tx;
20866   miny_val(h)=mp_take_scaled(mp, miny_val(h),mp->tyx+mp->tyy)+mp->ty;
20867   maxy_val(h)=mp_take_scaled(mp, maxy_val(h),mp->tyx+mp->tyy)+mp->ty;
20868   if ( mp->txx+mp->txy<0 ) {
20869     v=minx_val(h); minx_val(h)=maxx_val(h); maxx_val(h)=v;
20870   }
20871   if ( mp->tyx+mp->tyy<0 ) {
20872     v=miny_val(h); miny_val(h)=maxy_val(h); maxy_val(h)=v;
20873   }
20874 }
20875
20876 @ Now we ready for the main task of transforming the graphical objects in edge
20877 structure~|h|.
20878
20879 @<Transform graphical object |q|@>=
20880 switch (mp_type(q)) {
20881 case mp_fill_code: case mp_stroked_code: 
20882   mp_do_path_trans(mp, mp_path_p(q));
20883   @<Transform |mp_pen_p(q)|, making sure polygonal pens stay counter-clockwise@>;
20884   break;
20885 case mp_start_clip_code: case mp_start_bounds_code: 
20886   mp_do_path_trans(mp, mp_path_p(q));
20887   break;
20888 case mp_text_code: 
20889   r=text_tx_loc(q);
20890   @<Transform the compact transformation starting at |r|@>;
20891   break;
20892 case mp_stop_clip_code: case mp_stop_bounds_code: 
20893   break;
20894 } /* there are no other cases */
20895
20896 @ Note that the shift parameters |(tx,ty)| apply only to the path being stroked.
20897 The |dash_scale| has to be adjusted  to scale the dash lengths in |mp_dash_p(q)|
20898 since the \ps\ output procedures will try to compensate for the transformation
20899 we are applying to |mp_pen_p(q)|.  Since this compensation is based on the square
20900 root of the determinant, |sqdet| is the appropriate factor.
20901
20902 @<Transform |mp_pen_p(q)|, making sure...@>=
20903 if ( mp_pen_p(q)!=null ) {
20904   sx=mp->tx; sy=mp->ty;
20905   mp->tx=0; mp->ty=0;
20906   mp_do_pen_trans(mp, mp_pen_p(q));
20907   if ( ((mp_type(q)==mp_stroked_code)&&(mp_dash_p(q)!=null)) )
20908     dash_scale(q)=mp_take_scaled(mp, dash_scale(q),sqdet);
20909   if ( ! pen_is_elliptical(mp_pen_p(q)) )
20910     if ( sgndet<0 )
20911       mp_pen_p(q)=mp_make_pen(mp, mp_copy_path(mp, mp_pen_p(q)),true); 
20912          /* this unreverses the pen */
20913   mp->tx=sx; mp->ty=sy;
20914 }
20915
20916 @ This uses the fact that transformations are stored in the order
20917 |(tx,ty,txx,txy,tyx,tyy)|.
20918 @^data structure assumptions@>
20919
20920 @<Transform the compact transformation starting at |r|@>=
20921 mp_trans(mp, r,r+1);
20922 sx=mp->tx; sy=mp->ty;
20923 mp->tx=0; mp->ty=0;
20924 mp_trans(mp, r+2,r+4);
20925 mp_trans(mp, r+3,r+5);
20926 mp->tx=sx; mp->ty=sy
20927
20928 @ The hard cases of transformation occur when big nodes are involved,
20929 and when some of their components are unknown.
20930
20931 @<Declare binary action...@>=
20932 @<Declare subroutines needed by |big_trans|@>
20933 static void mp_big_trans (MP mp,pointer p, quarterword c) {
20934   pointer q,r,pp,qq; /* list manipulation registers */
20935   quarterword s; /* size of a big node */
20936   s=mp->big_node_size[mp_type(p)]; q=value(p); r=q+s;
20937   do {  
20938     r=r-2;
20939     if ( mp_type(r)!=mp_known ) {
20940       @<Transform an unknown big node and |return|@>;
20941     }
20942   } while (r!=q);
20943   @<Transform a known big node@>;
20944 } /* node |p| will now be recycled by |do_binary| */
20945
20946 @ @<Transform an unknown big node and |return|@>=
20947
20948   mp_set_up_known_trans(mp, c); mp_make_exp_copy(mp, p); 
20949   r=value(mp->cur_exp);
20950   if ( mp->cur_type==mp_transform_type ) {
20951     mp_bilin1(mp, yy_part_loc(r),mp->tyy,xy_part_loc(q),mp->tyx,0);
20952     mp_bilin1(mp, yx_part_loc(r),mp->tyy,xx_part_loc(q),mp->tyx,0);
20953     mp_bilin1(mp, xy_part_loc(r),mp->txx,yy_part_loc(q),mp->txy,0);
20954     mp_bilin1(mp, xx_part_loc(r),mp->txx,yx_part_loc(q),mp->txy,0);
20955   }
20956   mp_bilin1(mp, y_part_loc(r),mp->tyy,x_part_loc(q),mp->tyx,mp->ty);
20957   mp_bilin1(mp, x_part_loc(r),mp->txx,y_part_loc(q),mp->txy,mp->tx);
20958   return;
20959 }
20960
20961 @ Let |p| point to a two-word value field inside a big node of |cur_exp|,
20962 and let |q| point to a another value field. The |bilin1| procedure
20963 replaces |p| by $p\cdot t+q\cdot u+\delta$.
20964
20965 @<Declare subroutines needed by |big_trans|@>=
20966 static void mp_bilin1 (MP mp, pointer p, scaled t, pointer q, 
20967                 scaled u, scaled delta) {
20968   pointer r; /* list traverser */
20969   if ( t!=unity ) mp_dep_mult(mp, p,t,true);
20970   if ( u!=0 ) {
20971     if ( mp_type(q)==mp_known ) {
20972       delta+=mp_take_scaled(mp, value(q),u);
20973     } else { 
20974       @<Ensure that |type(p)=mp_proto_dependent|@>;
20975       dep_list(p)=mp_p_plus_fq(mp, dep_list(p),u,dep_list(q),
20976                                mp_proto_dependent,mp_type(q));
20977     }
20978   }
20979   if ( mp_type(p)==mp_known ) {
20980     value(p)+=delta;
20981   } else {
20982     r=dep_list(p);
20983     while ( mp_info(r)!=null ) r=mp_link(r);
20984     delta+=value(r);
20985     if ( r!=dep_list(p) ) value(r)=delta;
20986     else { mp_recycle_value(mp, p); mp_type(p)=mp_known; value(p)=delta; };
20987   }
20988   if ( mp->fix_needed ) mp_fix_dependencies(mp);
20989 }
20990
20991 @ @<Ensure that |type(p)=mp_proto_dependent|@>=
20992 if ( mp_type(p)!=mp_proto_dependent ) {
20993   if ( mp_type(p)==mp_known ) 
20994     mp_new_dep(mp, p,mp_const_dependency(mp, value(p)));
20995   else 
20996     dep_list(p)=mp_p_times_v(mp, dep_list(p),unity,mp_dependent,
20997                              mp_proto_dependent,true);
20998   mp_type(p)=mp_proto_dependent;
20999 }
21000
21001 @ @<Transform a known big node@>=
21002 mp_set_up_trans(mp, c);
21003 if ( mp->cur_type==mp_known ) {
21004   @<Transform known by known@>;
21005 } else { 
21006   pp=mp_stash_cur_exp(mp); qq=value(pp);
21007   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
21008   if ( mp->cur_type==mp_transform_type ) {
21009     mp_bilin2(mp, yy_part_loc(r),yy_part_loc(qq),
21010       value(xy_part_loc(q)),yx_part_loc(qq),null);
21011     mp_bilin2(mp, yx_part_loc(r),yy_part_loc(qq),
21012       value(xx_part_loc(q)),yx_part_loc(qq),null);
21013     mp_bilin2(mp, xy_part_loc(r),xx_part_loc(qq),
21014       value(yy_part_loc(q)),xy_part_loc(qq),null);
21015     mp_bilin2(mp, xx_part_loc(r),xx_part_loc(qq),
21016       value(yx_part_loc(q)),xy_part_loc(qq),null);
21017   };
21018   mp_bilin2(mp, y_part_loc(r),yy_part_loc(qq),
21019     value(x_part_loc(q)),yx_part_loc(qq),y_part_loc(qq));
21020   mp_bilin2(mp, x_part_loc(r),xx_part_loc(qq),
21021     value(y_part_loc(q)),xy_part_loc(qq),x_part_loc(qq));
21022   mp_recycle_value(mp, pp); mp_free_node(mp, pp,value_node_size);
21023 }
21024
21025 @ Let |p| be a |mp_proto_dependent| value whose dependency list ends
21026 at |dep_final|. The following procedure adds |v| times another
21027 numeric quantity to~|p|.
21028
21029 @<Declare subroutines needed by |big_trans|@>=
21030 static void mp_add_mult_dep (MP mp,pointer p, scaled v, pointer r) { 
21031   if ( mp_type(r)==mp_known ) {
21032     value(mp->dep_final)+=mp_take_scaled(mp, value(r),v);
21033   } else  { 
21034     dep_list(p)=mp_p_plus_fq(mp, dep_list(p),v,dep_list(r),
21035                                                          mp_proto_dependent,mp_type(r));
21036     if ( mp->fix_needed ) mp_fix_dependencies(mp);
21037   }
21038 }
21039
21040 @ The |bilin2| procedure is something like |bilin1|, but with known
21041 and unknown quantities reversed. Parameter |p| points to a value field
21042 within the big node for |cur_exp|; and |type(p)=mp_known|. Parameters
21043 |t| and~|u| point to value fields elsewhere; so does parameter~|q|,
21044 unless it is |null| (which stands for zero). Location~|p| will be
21045 replaced by $p\cdot t+v\cdot u+q$.
21046
21047 @<Declare subroutines needed by |big_trans|@>=
21048 static void mp_bilin2 (MP mp,pointer p, pointer t, scaled v, 
21049                 pointer u, pointer q) {
21050   scaled vv; /* temporary storage for |value(p)| */
21051   vv=value(p); mp_type(p)=mp_proto_dependent;
21052   mp_new_dep(mp, p,mp_const_dependency(mp, 0)); /* this sets |dep_final| */
21053   if ( vv!=0 ) 
21054     mp_add_mult_dep(mp, p,vv,t); /* |dep_final| doesn't change */
21055   if ( v!=0 ) mp_add_mult_dep(mp, p,v,u);
21056   if ( q!=null ) mp_add_mult_dep(mp, p,unity,q);
21057   if ( dep_list(p)==mp->dep_final ) {
21058     vv=value(mp->dep_final); mp_recycle_value(mp, p);
21059     mp_type(p)=mp_known; value(p)=vv;
21060   }
21061 }
21062
21063 @ @<Transform known by known@>=
21064
21065   mp_make_exp_copy(mp, p); r=value(mp->cur_exp);
21066   if ( mp->cur_type==mp_transform_type ) {
21067     mp_bilin3(mp, yy_part_loc(r),mp->tyy,value(xy_part_loc(q)),mp->tyx,0);
21068     mp_bilin3(mp, yx_part_loc(r),mp->tyy,value(xx_part_loc(q)),mp->tyx,0);
21069     mp_bilin3(mp, xy_part_loc(r),mp->txx,value(yy_part_loc(q)),mp->txy,0);
21070     mp_bilin3(mp, xx_part_loc(r),mp->txx,value(yx_part_loc(q)),mp->txy,0);
21071   }
21072   mp_bilin3(mp, y_part_loc(r),mp->tyy,value(x_part_loc(q)),mp->tyx,mp->ty);
21073   mp_bilin3(mp, x_part_loc(r),mp->txx,value(y_part_loc(q)),mp->txy,mp->tx);
21074 }
21075
21076 @ Finally, in |bilin3| everything is |known|.
21077
21078 @<Declare subroutines needed by |big_trans|@>=
21079 static void mp_bilin3 (MP mp,pointer p, scaled t, 
21080                scaled v, scaled u, scaled delta) { 
21081   if ( t!=unity )
21082     delta+=mp_take_scaled(mp, value(p),t);
21083   else 
21084     delta+=value(p);
21085   if ( u!=0 ) value(p)=delta+mp_take_scaled(mp, v,u);
21086   else value(p)=delta;
21087 }
21088
21089 @ @<Additional cases of binary operators@>=
21090 case concatenate: 
21091   if ( (mp->cur_type==mp_string_type)&&(mp_type(p)==mp_string_type) ) mp_cat(mp, p);
21092   else mp_bad_binary(mp, p,concatenate);
21093   break;
21094 case substring_of: 
21095   if ( mp_nice_pair(mp, p,mp_type(p))&&(mp->cur_type==mp_string_type) )
21096     mp_chop_string(mp, value(p));
21097   else mp_bad_binary(mp, p,substring_of);
21098   break;
21099 case subpath_of: 
21100   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21101   if ( mp_nice_pair(mp, p,mp_type(p))&&(mp->cur_type==mp_path_type) )
21102     mp_chop_path(mp, value(p));
21103   else mp_bad_binary(mp, p,subpath_of);
21104   break;
21105
21106 @ @<Declare binary action...@>=
21107 static void mp_cat (MP mp,pointer p) {
21108   str_number a,b; /* the strings being concatenated */
21109   pool_pointer k; /* index into |str_pool| */
21110   a=value(p); b=mp->cur_exp; str_room(length(a)+length(b));
21111   for (k=mp->str_start[a];k<=str_stop(a)-1;k++) {
21112     append_char(mp->str_pool[k]);
21113   }
21114   for (k=mp->str_start[b];k<=str_stop(b)-1;k++) {
21115     append_char(mp->str_pool[k]);
21116   }
21117   mp->cur_exp=mp_make_string(mp); delete_str_ref(b);
21118 }
21119
21120 @ @<Declare binary action...@>=
21121 static void mp_chop_string (MP mp,pointer p) {
21122   integer a, b; /* start and stop points */
21123   integer l; /* length of the original string */
21124   integer k; /* runs from |a| to |b| */
21125   str_number s; /* the original string */
21126   boolean reversed; /* was |a>b|? */
21127   a=mp_round_unscaled(mp, value(x_part_loc(p)));
21128   b=mp_round_unscaled(mp, value(y_part_loc(p)));
21129   if ( a<=b ) reversed=false;
21130   else  { reversed=true; k=a; a=b; b=k; };
21131   s=mp->cur_exp; l=length(s);
21132   if ( a<0 ) { 
21133     a=0;
21134     if ( b<0 ) b=0;
21135   }
21136   if ( b>l ) { 
21137     b=l;
21138     if ( a>l ) a=l;
21139   }
21140   str_room(b-a);
21141   if ( reversed ) {
21142     for (k=mp->str_start[s]+b-1;k>=mp->str_start[s]+a;k--)  {
21143       append_char(mp->str_pool[k]);
21144     }
21145   } else  {
21146     for (k=mp->str_start[s]+a;k<=mp->str_start[s]+b-1;k++)  {
21147       append_char(mp->str_pool[k]);
21148     }
21149   }
21150   mp->cur_exp=mp_make_string(mp); delete_str_ref(s);
21151 }
21152
21153 @ @<Declare binary action...@>=
21154 static void mp_chop_path (MP mp,pointer p) {
21155   pointer q; /* a knot in the original path */
21156   pointer pp,qq,rr,ss; /* link variables for copies of path nodes */
21157   scaled a,b,k,l; /* indices for chopping */
21158   boolean reversed; /* was |a>b|? */
21159   l=mp_path_length(mp); a=value(x_part_loc(p)); b=value(y_part_loc(p));
21160   if ( a<=b ) reversed=false;
21161   else  { reversed=true; k=a; a=b; b=k; };
21162   @<Dispense with the cases |a<0| and/or |b>l|@>;
21163   q=mp->cur_exp;
21164   while ( a>=unity ) {
21165     q=mp_link(q); a=a-unity; b=b-unity;
21166   }
21167   if ( b==a ) {
21168     @<Construct a path from |pp| to |qq| of length zero@>; 
21169   } else { 
21170     @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>; 
21171   }
21172   mp_left_type(pp)=mp_endpoint; mp_right_type(qq)=mp_endpoint; mp_link(qq)=pp;
21173   mp_toss_knot_list(mp, mp->cur_exp);
21174   if ( reversed ) {
21175     mp->cur_exp=mp_link(mp_htap_ypoc(mp, pp)); mp_toss_knot_list(mp, pp);
21176   } else {
21177     mp->cur_exp=pp;
21178   }
21179 }
21180
21181 @ @<Dispense with the cases |a<0| and/or |b>l|@>=
21182 if ( a<0 ) {
21183   if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
21184     a=0; if ( b<0 ) b=0;
21185   } else  {
21186     do {  a=a+l; b=b+l; } while (a<0); /* a cycle always has length |l>0| */
21187   }
21188 }
21189 if ( b>l ) {
21190   if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
21191     b=l; if ( a>l ) a=l;
21192   } else {
21193     while ( a>=l ) { 
21194       a=a-l; b=b-l;
21195     }
21196   }
21197 }
21198
21199 @ @<Construct a path from |pp| to |qq| of length $\lceil b\rceil$@>=
21200
21201   pp=mp_copy_knot(mp, q); qq=pp;
21202   do {  
21203     q=mp_link(q); rr=qq; qq=mp_copy_knot(mp, q); mp_link(rr)=qq; b=b-unity;
21204   } while (b>0);
21205   if ( a>0 ) {
21206     ss=pp; pp=mp_link(pp);
21207     mp_split_cubic(mp, ss,a*010000); pp=mp_link(ss);
21208     mp_free_node(mp, ss,knot_node_size);
21209     if ( rr==ss ) {
21210       b=mp_make_scaled(mp, b,unity-a); rr=pp;
21211     }
21212   }
21213   if ( b<0 ) {
21214     mp_split_cubic(mp, rr,(b+unity)*010000);
21215     mp_free_node(mp, qq,knot_node_size);
21216     qq=mp_link(rr);
21217   }
21218 }
21219
21220 @ @<Construct a path from |pp| to |qq| of length zero@>=
21221
21222   if ( a>0 ) { mp_split_cubic(mp, q,a*010000); q=mp_link(q); };
21223   pp=mp_copy_knot(mp, q); qq=pp;
21224 }
21225
21226 @ @<Additional cases of binary operators@>=
21227 case point_of: case precontrol_of: case postcontrol_of: 
21228   if ( mp->cur_type==mp_pair_type )
21229      mp_pair_to_path(mp);
21230   if ( (mp->cur_type==mp_path_type)&&(mp_type(p)==mp_known) )
21231     mp_find_point(mp, value(p),c);
21232   else 
21233     mp_bad_binary(mp, p,c);
21234   break;
21235 case pen_offset_of: 
21236   if ( (mp->cur_type==mp_pen_type)&& mp_nice_pair(mp, p,mp_type(p)) )
21237     mp_set_up_offset(mp, value(p));
21238   else 
21239     mp_bad_binary(mp, p,pen_offset_of);
21240   break;
21241 case direction_time_of: 
21242   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21243   if ( (mp->cur_type==mp_path_type)&& mp_nice_pair(mp, p,mp_type(p)) )
21244     mp_set_up_direction_time(mp, value(p));
21245   else 
21246     mp_bad_binary(mp, p,direction_time_of);
21247   break;
21248 case envelope_of:
21249   if ( (mp_type(p) != mp_pen_type) || (mp->cur_type != mp_path_type) )
21250     mp_bad_binary(mp, p,envelope_of);
21251   else
21252     mp_set_up_envelope(mp, p);
21253   break;
21254
21255 @ @<Declare binary action...@>=
21256 static void mp_set_up_offset (MP mp,pointer p) { 
21257   mp_find_offset(mp, value(x_part_loc(p)),value(y_part_loc(p)),mp->cur_exp);
21258   mp_pair_value(mp, mp->cur_x,mp->cur_y);
21259 }
21260 static void mp_set_up_direction_time (MP mp,pointer p) { 
21261   mp_flush_cur_exp(mp, mp_find_direction_time(mp, value(x_part_loc(p)),
21262   value(y_part_loc(p)),mp->cur_exp));
21263 }
21264 static void mp_set_up_envelope (MP mp,pointer p) {
21265   quarterword ljoin, lcap;
21266   scaled miterlim;
21267   pointer q = mp_copy_path(mp, mp->cur_exp); /* the original path */
21268   /* TODO: accept elliptical pens for straight paths */
21269   if (pen_is_elliptical(value(p))) {
21270     mp_bad_envelope_pen(mp);
21271     mp->cur_exp = q;
21272     mp->cur_type = mp_path_type;
21273     return;
21274   }
21275   if ( mp->internal[mp_linejoin]>unity ) ljoin=2;
21276   else if ( mp->internal[mp_linejoin]>0 ) ljoin=1;
21277   else ljoin=0;
21278   if ( mp->internal[mp_linecap]>unity ) lcap=2;
21279   else if ( mp->internal[mp_linecap]>0 ) lcap=1;
21280   else lcap=0;
21281   if ( mp->internal[mp_miterlimit]<unity )
21282     miterlim=unity;
21283   else
21284     miterlim=mp->internal[mp_miterlimit];
21285   mp->cur_exp = mp_make_envelope(mp, q, value(p), ljoin,lcap,miterlim);
21286   mp->cur_type = mp_path_type;
21287 }
21288
21289 @ @<Declare binary action...@>=
21290 static void mp_find_point (MP mp,scaled v, quarterword c) {
21291   pointer p; /* the path */
21292   scaled n; /* its length */
21293   p=mp->cur_exp;
21294   if ( mp_left_type(p)==mp_endpoint ) n=-unity; else n=0;
21295   do {  p=mp_link(p); n=n+unity; } while (p!=mp->cur_exp);
21296   if ( n==0 ) { 
21297     v=0; 
21298   } else if ( v<0 ) {
21299     if ( mp_left_type(p)==mp_endpoint ) v=0;
21300     else v=n-1-((-v-1) % n);
21301   } else if ( v>n ) {
21302     if ( mp_left_type(p)==mp_endpoint ) v=n;
21303     else v=v % n;
21304   }
21305   p=mp->cur_exp;
21306   while ( v>=unity ) { p=mp_link(p); v=v-unity;  };
21307   if ( v!=0 ) {
21308      @<Insert a fractional node by splitting the cubic@>;
21309   }
21310   @<Set the current expression to the desired path coordinates@>;
21311 }
21312
21313 @ @<Insert a fractional node...@>=
21314 { mp_split_cubic(mp, p,v*010000); p=mp_link(p); }
21315
21316 @ @<Set the current expression to the desired path coordinates...@>=
21317 switch (c) {
21318 case point_of: 
21319   mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21320   break;
21321 case precontrol_of: 
21322   if ( mp_left_type(p)==mp_endpoint ) mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21323   else mp_pair_value(mp, mp_left_x(p),mp_left_y(p));
21324   break;
21325 case postcontrol_of: 
21326   if ( mp_right_type(p)==mp_endpoint ) mp_pair_value(mp, mp_x_coord(p),mp_y_coord(p));
21327   else mp_pair_value(mp, mp_right_x(p),mp_right_y(p));
21328   break;
21329 } /* there are no other cases */
21330
21331 @ @<Additional cases of binary operators@>=
21332 case arc_time_of: 
21333   if ( mp->cur_type==mp_pair_type )
21334      mp_pair_to_path(mp);
21335   if ( (mp->cur_type==mp_path_type)&&(mp_type(p)==mp_known) )
21336     mp_flush_cur_exp(mp, mp_get_arc_time(mp, mp->cur_exp,value(p)));
21337   else 
21338     mp_bad_binary(mp, p,c);
21339   break;
21340
21341 @ @<Additional cases of bin...@>=
21342 case intersect: 
21343   if ( mp_type(p)==mp_pair_type ) {
21344     q=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, p);
21345     mp_pair_to_path(mp); p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q);
21346   };
21347   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
21348   if ( (mp->cur_type==mp_path_type)&&(mp_type(p)==mp_path_type) ) {
21349     mp_path_intersection(mp, value(p),mp->cur_exp);
21350     mp_pair_value(mp, mp->cur_t,mp->cur_tt);
21351   } else {
21352     mp_bad_binary(mp, p,intersect);
21353   }
21354   break;
21355
21356 @ @<Additional cases of bin...@>=
21357 case in_font:
21358   if ( (mp->cur_type!=mp_string_type)||(mp_type(p)!=mp_string_type)) 
21359     mp_bad_binary(mp, p,in_font);
21360   else { mp_do_infont(mp, p); binary_return; }
21361   break;
21362
21363 @ Function |new_text_node| owns the reference count for its second argument
21364 (the text string) but not its first (the font name).
21365
21366 @<Declare binary action...@>=
21367 static void mp_do_infont (MP mp,pointer p) {
21368   pointer q;
21369   q=mp_get_node(mp, edge_header_size);
21370   mp_init_edges(mp, q);
21371   mp_link(obj_tail(q))=mp_new_text_node(mp,str(mp->cur_exp),value(p));
21372   obj_tail(q)=mp_link(obj_tail(q));
21373   mp_free_node(mp, p,value_node_size);
21374   mp_flush_cur_exp(mp, q);
21375   mp->cur_type=mp_picture_type;
21376 }
21377
21378 @* \[40] Statements and commands.
21379 The chief executive of \MP\ is the |do_statement| routine, which
21380 contains the master switch that causes all the various pieces of \MP\
21381 to do their things, in the right order.
21382
21383 In a sense, this is the grand climax of the program: It applies all the
21384 tools that we have worked so hard to construct. In another sense, this is
21385 the messiest part of the program: It necessarily refers to other pieces
21386 of code all over the place, so that a person can't fully understand what is
21387 going on without paging back and forth to be reminded of conventions that
21388 are defined elsewhere. We are now at the hub of the web.
21389
21390 The structure of |do_statement| itself is quite simple.  The first token
21391 of the statement is fetched using |get_x_next|.  If it can be the first
21392 token of an expression, we look for an equation, an assignment, or a
21393 title. Otherwise we use a \&{case} construction to branch at high speed to
21394 the appropriate routine for various and sundry other types of commands,
21395 each of which has an ``action procedure'' that does the necessary work.
21396
21397 The program uses the fact that
21398 $$\hbox{|min_primary_command=max_statement_command=type_name|}$$
21399 to interpret a statement that starts with, e.g., `\&{string}',
21400 as a type declaration rather than a boolean expression.
21401
21402 @c void mp_do_statement (MP mp) { /* governs \MP's activities */
21403   mp->cur_type=mp_vacuous; mp_get_x_next(mp);
21404   if ( mp->cur_cmd>max_primary_command ) {
21405     @<Worry about bad statement@>;
21406   } else if ( mp->cur_cmd>max_statement_command ) {
21407     @<Do an equation, assignment, title, or
21408      `$\langle\,$expression$\,\rangle\,$\&{endgroup}'@>;
21409   } else {
21410     @<Do a statement that doesn't begin with an expression@>;
21411   }
21412   if ( mp->cur_cmd<semicolon )
21413     @<Flush unparsable junk that was found after the statement@>;
21414   mp->error_count=0;
21415 }
21416
21417 @ @<Declarations@>=
21418 @<Declare action procedures for use by |do_statement|@>
21419
21420 @ The only command codes |>max_primary_command| that can be present
21421 at the beginning of a statement are |semicolon| and higher; these
21422 occur when the statement is null.
21423
21424 @<Worry about bad statement@>=
21425
21426   if ( mp->cur_cmd<semicolon ) {
21427     print_err("A statement can't begin with `");
21428 @.A statement can't begin with x@>
21429     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod); mp_print_char(mp, xord('\''));
21430     help5("I was looking for the beginning of a new statement.",
21431       "If you just proceed without changing anything, I'll ignore",
21432       "everything up to the next `;'. Please insert a semicolon",
21433       "now in front of anything that you don't want me to delete.",
21434       "(See Chapter 27 of The METAFONTbook for an example.)");
21435 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21436     mp_back_error(mp); mp_get_x_next(mp);
21437   }
21438 }
21439
21440 @ The help message printed here says that everything is flushed up to
21441 a semicolon, but actually the commands |end_group| and |stop| will
21442 also terminate a statement.
21443
21444 @<Flush unparsable junk that was found after the statement@>=
21445
21446   print_err("Extra tokens will be flushed");
21447 @.Extra tokens will be flushed@>
21448   help6("I've just read as much of that statement as I could fathom,",
21449         "so a semicolon should have been next. It's very puzzling...",
21450         "but I'll try to get myself back together, by ignoring",
21451         "everything up to the next `;'. Please insert a semicolon",
21452         "now in front of anything that you don't want me to delete.",
21453         "(See Chapter 27 of The METAFONTbook for an example.)");
21454 @:METAFONTbook}{\sl The {\logos METAFONT\/}book@>
21455   mp_back_error(mp); mp->scanner_status=flushing;
21456   do {  
21457     get_t_next;
21458     @<Decrease the string reference count...@>;
21459   } while (! end_of_statement); /* |cur_cmd=semicolon|, |end_group|, or |stop| */
21460   mp->scanner_status=normal;
21461 }
21462
21463 @ If |do_statement| ends with |cur_cmd=end_group|, we should have
21464 |cur_type=mp_vacuous| unless the statement was simply an expression;
21465 in the latter case, |cur_type| and |cur_exp| should represent that
21466 expression.
21467
21468 @<Do a statement that doesn't...@>=
21469
21470   if ( mp->internal[mp_tracing_commands]>0 ) 
21471     show_cur_cmd_mod;
21472   switch (mp->cur_cmd ) {
21473   case type_name:mp_do_type_declaration(mp); break;
21474   case macro_def:
21475     if ( mp->cur_mod>var_def ) mp_make_op_def(mp);
21476     else if ( mp->cur_mod>end_def ) mp_scan_def(mp);
21477      break;
21478   @<Cases of |do_statement| that invoke particular commands@>;
21479   } /* there are no other cases */
21480   mp->cur_type=mp_vacuous;
21481 }
21482
21483 @ The most important statements begin with expressions.
21484
21485 @<Do an equation, assignment, title, or...@>=
21486
21487   mp->var_flag=assignment; mp_scan_expression(mp);
21488   if ( mp->cur_cmd<end_group ) {
21489     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21490     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21491     else if ( mp->cur_type==mp_string_type ) {@<Do a title@> ; }
21492     else if ( mp->cur_type!=mp_vacuous ){ 
21493       exp_err("Isolated expression");
21494 @.Isolated expression@>
21495       help3("I couldn't find an `=' or `:=' after the",
21496         "expression that is shown above this error message,",
21497         "so I guess I'll just ignore it and carry on.");
21498       mp_put_get_error(mp);
21499     }
21500     mp_flush_cur_exp(mp, 0); mp->cur_type=mp_vacuous;
21501   }
21502 }
21503
21504 @ @<Do a title@>=
21505
21506   if ( mp->internal[mp_tracing_titles]>0 ) {
21507     mp_print_nl(mp, "");  mp_print_str(mp, mp->cur_exp); update_terminal;
21508   }
21509 }
21510
21511 @ Equations and assignments are performed by the pair of mutually recursive
21512 @^recursion@>
21513 routines |do_equation| and |do_assignment|. These routines are called when
21514 |cur_cmd=equals| and when |cur_cmd=assignment|, respectively; the left-hand
21515 side is in |cur_type| and |cur_exp|, while the right-hand side is yet
21516 to be scanned. After the routines are finished, |cur_type| and |cur_exp|
21517 will be equal to the right-hand side (which will normally be equal
21518 to the left-hand side).
21519
21520 @<Declarations@>=
21521 @<Declare the procedure called |make_eq|@>
21522 static void mp_do_equation (MP mp) ;
21523
21524 @ @c
21525 void mp_do_equation (MP mp) {
21526   pointer lhs; /* capsule for the left-hand side */
21527   pointer p; /* temporary register */
21528   lhs=mp_stash_cur_exp(mp); mp_get_x_next(mp); 
21529   mp->var_flag=assignment; mp_scan_expression(mp);
21530   if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21531   else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21532   if ( mp->internal[mp_tracing_commands]>two ) 
21533     @<Trace the current equation@>;
21534   if ( mp->cur_type==mp_unknown_path ) if ( mp_type(lhs)==mp_pair_type ) {
21535     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, lhs); lhs=p;
21536   }; /* in this case |make_eq| will change the pair to a path */
21537   mp_make_eq(mp, lhs); /* equate |lhs| to |(cur_type,cur_exp)| */
21538 }
21539
21540 @ And |do_assignment| is similar to |do_equation|:
21541
21542 @<Declarations@>=
21543 static void mp_do_assignment (MP mp);
21544
21545 @ @c
21546 void mp_do_assignment (MP mp) {
21547   pointer lhs; /* token list for the left-hand side */
21548   pointer p; /* where the left-hand value is stored */
21549   pointer q; /* temporary capsule for the right-hand value */
21550   if ( mp->cur_type!=mp_token_list ) { 
21551     exp_err("Improper `:=' will be changed to `='");
21552 @.Improper `:='@>
21553     help2("I didn't find a variable name at the left of the `:=',",
21554           "so I'm going to pretend that you said `=' instead.");
21555     mp_error(mp); mp_do_equation(mp);
21556   } else { 
21557     lhs=mp->cur_exp; mp->cur_type=mp_vacuous;
21558     mp_get_x_next(mp); mp->var_flag=assignment; mp_scan_expression(mp);
21559     if ( mp->cur_cmd==equals ) mp_do_equation(mp);
21560     else if ( mp->cur_cmd==assignment ) mp_do_assignment(mp);
21561     if ( mp->internal[mp_tracing_commands]>two ) 
21562       @<Trace the current assignment@>;
21563     if ( mp_info(lhs)>hash_end ) {
21564       @<Assign the current expression to an internal variable@>;
21565     } else  {
21566       @<Assign the current expression to the variable |lhs|@>;
21567     }
21568     mp_flush_node_list(mp, lhs);
21569   }
21570 }
21571
21572 @ @<Trace the current equation@>=
21573
21574   mp_begin_diagnostic(mp); mp_print_nl(mp, "{("); mp_print_exp(mp,lhs,0);
21575   mp_print(mp,")=("); mp_print_exp(mp,null,0); 
21576   mp_print(mp,")}"); mp_end_diagnostic(mp, false);
21577 }
21578
21579 @ @<Trace the current assignment@>=
21580
21581   mp_begin_diagnostic(mp); mp_print_nl(mp, "{");
21582   if ( mp_info(lhs)>hash_end ) 
21583      mp_print(mp, mp->int_name[mp_info(lhs)-(hash_end)]);
21584   else 
21585      mp_show_token_list(mp, lhs,null,1000,0);
21586   mp_print(mp, ":="); mp_print_exp(mp, null,0); 
21587   mp_print_char(mp, xord('}')); mp_end_diagnostic(mp, false);
21588 }
21589
21590 @ @<Assign the current expression to an internal variable@>=
21591 if ( mp->cur_type==mp_known )  {
21592   mp->internal[mp_info(lhs)-(hash_end)]=mp->cur_exp;
21593 } else { 
21594   exp_err("Internal quantity `");
21595 @.Internal quantity...@>
21596   mp_print(mp, mp->int_name[mp_info(lhs)-(hash_end)]);
21597   mp_print(mp, "' must receive a known value");
21598   help2("I can\'t set an internal quantity to anything but a known",
21599         "numeric value, so I'll have to ignore this assignment.");
21600   mp_put_get_error(mp);
21601 }
21602
21603 @ @<Assign the current expression to the variable |lhs|@>=
21604
21605   p=mp_find_variable(mp, lhs);
21606   if ( p!=null ) {
21607     q=mp_stash_cur_exp(mp); mp->cur_type=mp_und_type(mp, p); 
21608     mp_recycle_value(mp, p);
21609     mp_type(p)=mp->cur_type; value(p)=null; mp_make_exp_copy(mp, p);
21610     p=mp_stash_cur_exp(mp); mp_unstash_cur_exp(mp, q); mp_make_eq(mp, p);
21611   } else  { 
21612     mp_obliterated(mp, lhs); mp_put_get_error(mp);
21613   }
21614 }
21615
21616
21617 @ And now we get to the nitty-gritty. The |make_eq| procedure is given
21618 a pointer to a capsule that is to be equated to the current expression.
21619
21620 @<Declare the procedure called |make_eq|@>=
21621 static void mp_make_eq (MP mp,pointer lhs) ;
21622
21623
21624
21625 @c void mp_make_eq (MP mp,pointer lhs) {
21626   quarterword t; /* type of the left-hand side */
21627   pointer p,q; /* pointers inside of big nodes */
21628   integer v=0; /* value of the left-hand side */
21629 RESTART: 
21630   t=mp_type(lhs);
21631   if ( t<=mp_pair_type ) v=value(lhs);
21632   switch (t) {
21633   @<For each type |t|, make an equation and |goto done| unless |cur_type|
21634     is incompatible with~|t|@>;
21635   } /* all cases have been listed */
21636   @<Announce that the equation cannot be performed@>;
21637 DONE:
21638   check_arith; mp_recycle_value(mp, lhs); 
21639   mp_free_node(mp, lhs,value_node_size);
21640 }
21641
21642 @ @<Announce that the equation cannot be performed@>=
21643 mp_disp_err(mp, lhs,""); 
21644 exp_err("Equation cannot be performed (");
21645 @.Equation cannot be performed@>
21646 if ( mp_type(lhs)<=mp_pair_type ) mp_print_type(mp, mp_type(lhs));
21647 else mp_print(mp, "numeric");
21648 mp_print_char(mp, xord('='));
21649 if ( mp->cur_type<=mp_pair_type ) mp_print_type(mp, mp->cur_type);
21650 else mp_print(mp, "numeric");
21651 mp_print_char(mp, xord(')'));
21652 help2("I'm sorry, but I don't know how to make such things equal.",
21653       "(See the two expressions just above the error message.)");
21654 mp_put_get_error(mp)
21655
21656 @ @<For each type |t|, make an equation and |goto done| unless...@>=
21657 case mp_boolean_type: case mp_string_type: case mp_pen_type:
21658 case mp_path_type: case mp_picture_type:
21659   if ( mp->cur_type==t+unknown_tag ) { 
21660     mp_nonlinear_eq(mp, v,mp->cur_exp,false); 
21661     mp_unstash_cur_exp(mp, mp->cur_exp); goto DONE;
21662   } else if ( mp->cur_type==t ) {
21663     @<Report redundant or inconsistent equation and |goto done|@>;
21664   }
21665   break;
21666 case unknown_types:
21667   if ( mp->cur_type==t-unknown_tag ) { 
21668     mp_nonlinear_eq(mp, mp->cur_exp,lhs,true); goto DONE;
21669   } else if ( mp->cur_type==t ) { 
21670     mp_ring_merge(mp, lhs,mp->cur_exp); goto DONE;
21671   } else if ( mp->cur_type==mp_pair_type ) {
21672     if ( t==mp_unknown_path ) { 
21673      mp_pair_to_path(mp); goto RESTART;
21674     };
21675   }
21676   break;
21677 case mp_transform_type: case mp_color_type:
21678 case mp_cmykcolor_type: case mp_pair_type:
21679   if ( mp->cur_type==t ) {
21680     @<Do multiple equations and |goto done|@>;
21681   }
21682   break;
21683 case mp_known: case mp_dependent:
21684 case mp_proto_dependent: case mp_independent:
21685   if ( mp->cur_type>=mp_known ) { 
21686     mp_try_eq(mp, lhs,null); goto DONE;
21687   };
21688   break;
21689 case mp_vacuous:
21690   break;
21691
21692 @ @<Report redundant or inconsistent equation and |goto done|@>=
21693
21694   if ( mp->cur_type<=mp_string_type ) {
21695     if ( mp->cur_type==mp_string_type ) {
21696       if ( mp_str_vs_str(mp, v,mp->cur_exp)!=0 ) {
21697         goto NOT_FOUND;
21698       }
21699     } else if ( v!=mp->cur_exp ) {
21700       goto NOT_FOUND;
21701     }
21702     @<Exclaim about a redundant equation@>; goto DONE;
21703   }
21704   print_err("Redundant or inconsistent equation");
21705 @.Redundant or inconsistent equation@>
21706   help2("An equation between already-known quantities can't help.",
21707         "But don't worry; continue and I'll just ignore it.");
21708   mp_put_get_error(mp); goto DONE;
21709 NOT_FOUND: 
21710   print_err("Inconsistent equation");
21711 @.Inconsistent equation@>
21712   help2("The equation I just read contradicts what was said before.",
21713         "But don't worry; continue and I'll just ignore it.");
21714   mp_put_get_error(mp); goto DONE;
21715 }
21716
21717 @ @<Do multiple equations and |goto done|@>=
21718
21719   p=v+mp->big_node_size[t]; 
21720   q=value(mp->cur_exp)+mp->big_node_size[t];
21721   do {  
21722     p=p-2; q=q-2; mp_try_eq(mp, p,q);
21723   } while (p!=v);
21724   goto DONE;
21725 }
21726
21727 @ The first argument to |try_eq| is the location of a value node
21728 in a capsule that will soon be recycled. The second argument is
21729 either a location within a pair or transform node pointed to by
21730 |cur_exp|, or it is |null| (which means that |cur_exp| itself
21731 serves as the second argument). The idea is to leave |cur_exp| unchanged,
21732 but to equate the two operands.
21733
21734 @<Declarations@>=
21735 static void mp_try_eq (MP mp,pointer l, pointer r) ;
21736
21737
21738 @c void mp_try_eq (MP mp,pointer l, pointer r) {
21739   pointer p; /* dependency list for right operand minus left operand */
21740   int t; /* the type of list |p| */
21741   pointer q; /* the constant term of |p| is here */
21742   pointer pp; /* dependency list for right operand */
21743   int tt; /* the type of list |pp| */
21744   boolean copied; /* have we copied a list that ought to be recycled? */
21745   @<Remove the left operand from its container, negate it, and
21746     put it into dependency list~|p| with constant term~|q|@>;
21747   @<Add the right operand to list |p|@>;
21748   if ( mp_info(p)==null ) {
21749     @<Deal with redundant or inconsistent equation@>;
21750   } else { 
21751     mp_linear_eq(mp, p,t);
21752     if ( r==null ) if ( mp->cur_type!=mp_known ) {
21753       if ( mp_type(mp->cur_exp)==mp_known ) {
21754         pp=mp->cur_exp; mp->cur_exp=value(mp->cur_exp); mp->cur_type=mp_known;
21755         mp_free_node(mp, pp,value_node_size);
21756       }
21757     }
21758   }
21759 }
21760
21761 @ @<Remove the left operand from its container, negate it, and...@>=
21762 t=mp_type(l);
21763 if ( t==mp_known ) { 
21764   t=mp_dependent; p=mp_const_dependency(mp, -value(l)); q=p;
21765 } else if ( t==mp_independent ) {
21766   t=mp_dependent; p=mp_single_dependency(mp, l); negate(value(p));
21767   q=mp->dep_final;
21768 } else { 
21769   p=dep_list(l); q=p;
21770   while (1) { 
21771     negate(value(q));
21772     if ( mp_info(q)==null ) break;
21773     q=mp_link(q);
21774   }
21775   mp_link(prev_dep(l))=mp_link(q); prev_dep(mp_link(q))=prev_dep(l);
21776   mp_type(l)=mp_known;
21777 }
21778
21779 @ @<Deal with redundant or inconsistent equation@>=
21780
21781   if ( abs(value(p))>64 ) { /* off by .001 or more */
21782     print_err("Inconsistent equation");
21783 @.Inconsistent equation@>
21784     mp_print(mp, " (off by "); mp_print_scaled(mp, value(p)); 
21785     mp_print_char(mp, xord(')'));
21786     help2("The equation I just read contradicts what was said before.",
21787           "But don't worry; continue and I'll just ignore it.");
21788     mp_put_get_error(mp);
21789   } else if ( r==null ) {
21790     @<Exclaim about a redundant equation@>;
21791   }
21792   mp_free_node(mp, p,dep_node_size);
21793 }
21794
21795 @ @<Add the right operand to list |p|@>=
21796 if ( r==null ) {
21797   if ( mp->cur_type==mp_known ) {
21798     value(q)=value(q)+mp->cur_exp; goto DONE1;
21799   } else { 
21800     tt=mp->cur_type;
21801     if ( tt==mp_independent ) pp=mp_single_dependency(mp, mp->cur_exp);
21802     else pp=dep_list(mp->cur_exp);
21803   } 
21804 } else {
21805   if ( mp_type(r)==mp_known ) {
21806     value(q)=value(q)+value(r); goto DONE1;
21807   } else { 
21808     tt=mp_type(r);
21809     if ( tt==mp_independent ) pp=mp_single_dependency(mp, r);
21810     else pp=dep_list(r);
21811   }
21812 }
21813 if ( tt!=mp_independent ) copied=false;
21814 else  { copied=true; tt=mp_dependent; };
21815 @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>;
21816 if ( copied ) mp_flush_node_list(mp, pp);
21817 DONE1:
21818
21819 @ @<Add dependency list |pp| of type |tt| to dependency list~|p| of type~|t|@>=
21820 mp->watch_coefs=false;
21821 if ( t==tt ) {
21822   p=mp_p_plus_q(mp, p,pp,t);
21823 } else if ( t==mp_proto_dependent ) {
21824   p=mp_p_plus_fq(mp, p,unity,pp,mp_proto_dependent,mp_dependent);
21825 } else { 
21826   q=p;
21827   while ( mp_info(q)!=null ) {
21828     value(q)=mp_round_fraction(mp, value(q)); q=mp_link(q);
21829   }
21830   t=mp_proto_dependent; p=mp_p_plus_q(mp, p,pp,t);
21831 }
21832 mp->watch_coefs=true;
21833
21834 @ Our next goal is to process type declarations. For this purpose it's
21835 convenient to have a procedure that scans a $\langle\,$declared
21836 variable$\,\rangle$ and returns the corresponding token list. After the
21837 following procedure has acted, the token after the declared variable
21838 will have been scanned, so it will appear in |cur_cmd|, |cur_mod|,
21839 and~|cur_sym|.
21840
21841 @<Declarations@>=
21842 static pointer mp_scan_declared_variable (MP mp) ;
21843
21844 @ @c
21845 pointer mp_scan_declared_variable (MP mp) {
21846   pointer x; /* hash address of the variable's root */
21847   pointer h,t; /* head and tail of the token list to be returned */
21848   pointer l; /* hash address of left bracket */
21849   mp_get_symbol(mp); x=mp->cur_sym;
21850   if ( mp->cur_cmd!=tag_token ) mp_clear_symbol(mp, x,false);
21851   h=mp_get_avail(mp); mp_info(h)=x; t=h;
21852   while (1) { 
21853     mp_get_x_next(mp);
21854     if ( mp->cur_sym==0 ) break;
21855     if ( mp->cur_cmd!=tag_token ) if ( mp->cur_cmd!=internal_quantity)  {
21856       if ( mp->cur_cmd==left_bracket ) {
21857         @<Descend past a collective subscript@>;
21858       } else {
21859         break;
21860       }
21861     }
21862     mp_link(t)=mp_get_avail(mp); t=mp_link(t); mp_info(t)=mp->cur_sym;
21863   }
21864   if ( (eq_type(x)%outer_tag)!=tag_token ) mp_clear_symbol(mp, x,false);
21865   if ( equiv(x)==null ) mp_new_root(mp, x);
21866   return h;
21867 }
21868
21869 @ If the subscript isn't collective, we don't accept it as part of the
21870 declared variable.
21871
21872 @<Descend past a collective subscript@>=
21873
21874   l=mp->cur_sym; mp_get_x_next(mp);
21875   if ( mp->cur_cmd!=right_bracket ) {
21876     mp_back_input(mp); mp->cur_sym=l; mp->cur_cmd=left_bracket; break;
21877   } else {
21878     mp->cur_sym=collective_subscript;
21879   }
21880 }
21881
21882 @ Type declarations are introduced by the following primitive operations.
21883
21884 @<Put each...@>=
21885 mp_primitive(mp, "numeric",type_name,mp_numeric_type);
21886 @:numeric_}{\&{numeric} primitive@>
21887 mp_primitive(mp, "string",type_name,mp_string_type);
21888 @:string_}{\&{string} primitive@>
21889 mp_primitive(mp, "boolean",type_name,mp_boolean_type);
21890 @:boolean_}{\&{boolean} primitive@>
21891 mp_primitive(mp, "path",type_name,mp_path_type);
21892 @:path_}{\&{path} primitive@>
21893 mp_primitive(mp, "pen",type_name,mp_pen_type);
21894 @:pen_}{\&{pen} primitive@>
21895 mp_primitive(mp, "picture",type_name,mp_picture_type);
21896 @:picture_}{\&{picture} primitive@>
21897 mp_primitive(mp, "transform",type_name,mp_transform_type);
21898 @:transform_}{\&{transform} primitive@>
21899 mp_primitive(mp, "color",type_name,mp_color_type);
21900 @:color_}{\&{color} primitive@>
21901 mp_primitive(mp, "rgbcolor",type_name,mp_color_type);
21902 @:color_}{\&{rgbcolor} primitive@>
21903 mp_primitive(mp, "cmykcolor",type_name,mp_cmykcolor_type);
21904 @:color_}{\&{cmykcolor} primitive@>
21905 mp_primitive(mp, "pair",type_name,mp_pair_type);
21906 @:pair_}{\&{pair} primitive@>
21907
21908 @ @<Cases of |print_cmd...@>=
21909 case type_name: mp_print_type(mp, m); break;
21910
21911 @ Now we are ready to handle type declarations, assuming that a
21912 |type_name| has just been scanned.
21913
21914 @<Declare action procedures for use by |do_statement|@>=
21915 static void mp_do_type_declaration (MP mp) ;
21916
21917 @ @c
21918 void mp_do_type_declaration (MP mp) {
21919   quarterword t; /* the type being declared */
21920   pointer p; /* token list for a declared variable */
21921   pointer q; /* value node for the variable */
21922   if ( mp->cur_mod>=mp_transform_type ) 
21923     t=mp->cur_mod;
21924   else 
21925     t=mp->cur_mod+unknown_tag;
21926   do {  
21927     p=mp_scan_declared_variable(mp);
21928     mp_flush_variable(mp, equiv(mp_info(p)),mp_link(p),false);
21929     q=mp_find_variable(mp, p);
21930     if ( q!=null ) { 
21931       mp_type(q)=t; value(q)=null; 
21932     } else  { 
21933       print_err("Declared variable conflicts with previous vardef");
21934 @.Declared variable conflicts...@>
21935       help2("You can't use, e.g., `numeric foo[]' after `vardef foo'.",
21936             "Proceed, and I'll ignore the illegal redeclaration.");
21937       mp_put_get_error(mp);
21938     }
21939     mp_flush_list(mp, p);
21940     if ( mp->cur_cmd<comma ) {
21941       @<Flush spurious symbols after the declared variable@>;
21942     }
21943   } while (! end_of_statement);
21944 }
21945
21946 @ @<Flush spurious symbols after the declared variable@>=
21947
21948   print_err("Illegal suffix of declared variable will be flushed");
21949 @.Illegal suffix...flushed@>
21950   help5("Variables in declarations must consist entirely of",
21951     "names and collective subscripts, e.g., `x[]a'.",
21952     "Are you trying to use a reserved word in a variable name?",
21953     "I'm going to discard the junk I found here,",
21954     "up to the next comma or the end of the declaration.");
21955   if ( mp->cur_cmd==numeric_token )
21956     mp->help_line[2]="Explicit subscripts like `x15a' aren't permitted.";
21957   mp_put_get_error(mp); mp->scanner_status=flushing;
21958   do {  
21959     get_t_next;
21960     @<Decrease the string reference count...@>;
21961   } while (mp->cur_cmd<comma); /* either |end_of_statement| or |cur_cmd=comma| */
21962   mp->scanner_status=normal;
21963 }
21964
21965 @ \MP's |main_control| procedure just calls |do_statement| repeatedly
21966 until coming to the end of the user's program.
21967 Each execution of |do_statement| concludes with
21968 |cur_cmd=semicolon|, |end_group|, or |stop|.
21969
21970 @c 
21971 static void mp_main_control (MP mp) { 
21972   do {  
21973     mp_do_statement(mp);
21974     if ( mp->cur_cmd==end_group ) {
21975       print_err("Extra `endgroup'");
21976 @.Extra `endgroup'@>
21977       help2("I'm not currently working on a `begingroup',",
21978             "so I had better not try to end anything.");
21979       mp_flush_error(mp, 0);
21980     }
21981   } while (mp->cur_cmd!=stop);
21982 }
21983 int mp_run (MP mp) {
21984   if (mp->history < mp_fatal_error_stop ) {
21985     xfree(mp->jump_buf);
21986     mp->jump_buf = malloc(sizeof(jmp_buf));
21987     if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) 
21988       return mp->history;
21989     mp_main_control(mp); /* come to life */
21990     mp_final_cleanup(mp); /* prepare for death */
21991     mp_close_files_and_terminate(mp);
21992   }
21993   return mp->history;
21994 }
21995
21996 @ For |mp_execute|, we need to define a structure to store the
21997 redirected input and output. This structure holds the five relevant
21998 streams: the three informational output streams, the PostScript
21999 generation stream, and the input stream. These streams have many
22000 things in common, so it makes sense to give them their own structure
22001 definition. 
22002
22003 \item{fptr} is a virtual file pointer
22004 \item{data} is the data this stream holds
22005 \item{cur}  is a cursor pointing into |data| 
22006 \item{size} is the allocated length of the data stream
22007 \item{used} is the actual length of the data stream
22008
22009 There are small differences between input and output: |term_in| never
22010 uses |used|, whereas the other four never use |cur|.
22011
22012 @<Exported types@>= 
22013 typedef struct {
22014    void * fptr;
22015    char * data;
22016    char * cur;
22017    size_t size;
22018    size_t used;
22019 } mp_stream;
22020
22021 typedef struct {
22022     mp_stream term_out;
22023     mp_stream error_out;
22024     mp_stream log_out;
22025     mp_stream ps_out;
22026     mp_stream term_in;
22027     struct mp_edge_object *edges;
22028 } mp_run_data;
22029
22030 @ We need a function to clear an output stream, this is called at the
22031 beginning of |mp_execute|. We also need one for destroying an output
22032 stream, this is called just before a stream is (re)opened.
22033
22034 @c
22035 static void mp_reset_stream(mp_stream *str) {
22036    xfree(str->data); 
22037    str->cur = NULL;
22038    str->size = 0; 
22039    str->used = 0;
22040 }
22041 static void mp_free_stream(mp_stream *str) {
22042    xfree(str->fptr); 
22043    mp_reset_stream(str);
22044 }
22045
22046 @ @<Declarations@>=
22047 static void mp_reset_stream(mp_stream *str);
22048 static void mp_free_stream(mp_stream *str);
22049
22050 @ The global instance contains a pointer instead of the actual structure
22051 even though it is essentially static, because that makes it is easier to move 
22052 the object around.
22053
22054 @<Global ...@>=
22055 mp_run_data run_data;
22056
22057 @ Another type is needed: the indirection will overload some of the
22058 file pointer objects in the instance (but not all). For clarity, an
22059 indirect object is used that wraps a |FILE *|.
22060
22061 @<Types ... @>=
22062 typedef struct File {
22063     FILE *f;
22064 } File;
22065
22066 @ Here are all of the functions that need to be overloaded for |mp_execute|.
22067
22068 @<Declarations@>=
22069 static void *mplib_open_file(MP mp, const char *fname, const char *fmode, int ftype);
22070 static int mplib_get_char(void *f, mp_run_data * mplib_data);
22071 static void mplib_unget_char(void *f, mp_run_data * mplib_data, int c);
22072 static char *mplib_read_ascii_file(MP mp, void *ff, size_t * size);
22073 static void mplib_write_ascii_file(MP mp, void *ff, const char *s);
22074 static void mplib_read_binary_file(MP mp, void *ff, void **data, size_t * size);
22075 static void mplib_write_binary_file(MP mp, void *ff, void *s, size_t size);
22076 static void mplib_close_file(MP mp, void *ff);
22077 static int mplib_eof_file(MP mp, void *ff);
22078 static void mplib_flush_file(MP mp, void *ff);
22079 static void mplib_shipout_backend(MP mp, int h);
22080
22081 @ The |xmalloc(1,1)| calls make sure the stored indirection values are unique.
22082
22083 @d reset_stream(a)  do { 
22084         mp_reset_stream(&(a));
22085         if (!ff->f) {
22086           ff->f = xmalloc(1,1);
22087           (a).fptr = ff->f;
22088         } } while (0)
22089
22090 @c
22091
22092 static void *mplib_open_file(MP mp, const char *fname, const char *fmode, int ftype)
22093 {
22094     File *ff = xmalloc(1, sizeof(File));
22095     mp_run_data *run = mp_rundata(mp);
22096     ff->f = NULL;
22097     if (ftype == mp_filetype_terminal) {
22098         if (fmode[0] == 'r') {
22099             if (!ff->f) {
22100               ff->f = xmalloc(1,1);
22101               run->term_in.fptr = ff->f;
22102             }
22103         } else {
22104             reset_stream(run->term_out);
22105         }
22106     } else if (ftype == mp_filetype_error) {
22107         reset_stream(run->error_out);
22108     } else if (ftype == mp_filetype_log) {
22109         reset_stream(run->log_out);
22110     } else if (ftype == mp_filetype_postscript) {
22111         mp_free_stream(&(run->ps_out));
22112         ff->f = xmalloc(1,1);
22113         run->ps_out.fptr = ff->f;
22114     } else {
22115         char realmode[3];
22116         char *f = (mp->find_file)(mp, fname, fmode, ftype);
22117         if (f == NULL)
22118             return NULL;
22119         realmode[0] = *fmode;
22120         realmode[1] = 'b';
22121         realmode[2] = 0;
22122         ff->f = fopen(f, realmode);
22123         free(f);
22124         if ((fmode[0] == 'r') && (ff->f == NULL)) {
22125             free(ff);
22126             return NULL;
22127         }
22128     }
22129     return ff;
22130 }
22131
22132 static int mplib_get_char(void *f, mp_run_data * run)
22133 {
22134     int c;
22135     if (f == run->term_in.fptr && run->term_in.data != NULL) {
22136         if (run->term_in.size == 0) {
22137             if (run->term_in.cur  != NULL) {
22138                 run->term_in.cur = NULL;
22139             } else {
22140                 xfree(run->term_in.data);
22141             }
22142             c = EOF;
22143         } else {
22144             run->term_in.size--;
22145             c = *(run->term_in.cur)++;
22146         }
22147     } else {
22148         c = fgetc(f);
22149     }
22150     return c;
22151 }
22152
22153 static void mplib_unget_char(void *f, mp_run_data * run, int c)
22154 {
22155     if (f == run->term_in.fptr && run->term_in.cur != NULL) {
22156         run->term_in.size++;
22157         run->term_in.cur--;
22158     } else {
22159         ungetc(c, f);
22160     }
22161 }
22162
22163
22164 static char *mplib_read_ascii_file(MP mp, void *ff, size_t * size)
22165 {
22166     char *s = NULL;
22167     if (ff != NULL) {
22168         int c;
22169         size_t len = 0, lim = 128;
22170         mp_run_data *run = mp_rundata(mp);
22171         FILE *f = ((File *) ff)->f;
22172         if (f == NULL)
22173             return NULL;
22174         *size = 0;
22175         c = mplib_get_char(f, run);
22176         if (c == EOF)
22177             return NULL;
22178         s = malloc(lim);
22179         if (s == NULL)
22180             return NULL;
22181         while (c != EOF && c != '\n' && c != '\r') {
22182             if (len == lim) {
22183                 s = xrealloc(s, (lim + (lim >> 2)),1);
22184                 if (s == NULL)
22185                     return NULL;
22186                 lim += (lim >> 2);
22187             }
22188             s[len++] = c;
22189             c = mplib_get_char(f, run);
22190         }
22191         if (c == '\r') {
22192             c = mplib_get_char(f, run);
22193             if (c != EOF && c != '\n')
22194                 mplib_unget_char(f, run, c);
22195         }
22196         s[len] = 0;
22197         *size = len;
22198     }
22199     return s;
22200 }
22201
22202 static void mp_append_string (MP mp, mp_stream *a,const char *b) {
22203     size_t l = strlen(b);
22204     if ((a->used+l)>=a->size) {
22205         a->size += 256+(a->size)/5+l;
22206         a->data = xrealloc(a->data,a->size,1);
22207     }
22208     (void)strcpy(a->data+a->used,b);
22209     a->used += l;
22210 }
22211
22212
22213 static void mplib_write_ascii_file(MP mp, void *ff, const char *s)
22214 {
22215     if (ff != NULL) {
22216         void *f = ((File *) ff)->f;
22217         mp_run_data *run = mp_rundata(mp);
22218         if (f != NULL) {
22219             if (f == run->term_out.fptr) {
22220                 mp_append_string(mp,&(run->term_out), s);
22221             } else if (f == run->error_out.fptr) {
22222                 mp_append_string(mp,&(run->error_out), s);
22223             } else if (f == run->log_out.fptr) {
22224                 mp_append_string(mp,&(run->log_out), s);
22225             } else if (f == run->ps_out.fptr) {
22226                 mp_append_string(mp,&(run->ps_out), s);
22227             } else {
22228                 fprintf((FILE *) f, "%s", s);
22229             }
22230         }
22231     }
22232 }
22233
22234 static void mplib_read_binary_file(MP mp, void *ff, void **data, size_t * size)
22235 {
22236     (void) mp;
22237     if (ff != NULL) {
22238         size_t len = 0;
22239         FILE *f = ((File *) ff)->f;
22240         if (f != NULL)
22241             len = fread(*data, 1, *size, f);
22242         *size = len;
22243     }
22244 }
22245
22246 static void mplib_write_binary_file(MP mp, void *ff, void *s, size_t size)
22247 {
22248     (void) mp;
22249     if (ff != NULL) {
22250         FILE *f = ((File *) ff)->f;
22251         if (f != NULL)
22252             (void)fwrite(s, size, 1, f);
22253     }
22254 }
22255
22256 static void mplib_close_file(MP mp, void *ff)
22257 {
22258     if (ff != NULL) {
22259         mp_run_data *run = mp_rundata(mp);
22260         void *f = ((File *) ff)->f;
22261         if (f != NULL) {
22262           if (f != run->term_out.fptr
22263             && f != run->error_out.fptr
22264             && f != run->log_out.fptr
22265             && f != run->ps_out.fptr
22266             && f != run->term_in.fptr) {
22267             fclose(f);
22268           }
22269         }
22270         free(ff);
22271     }
22272 }
22273
22274 static int mplib_eof_file(MP mp, void *ff)
22275 {
22276     if (ff != NULL) {
22277         mp_run_data *run = mp_rundata(mp);
22278         FILE *f = ((File *) ff)->f;
22279         if (f == NULL)
22280             return 1;
22281         if (f == run->term_in.fptr && run->term_in.data != NULL) {
22282             return (run->term_in.size == 0);
22283         }
22284         return feof(f);
22285     }
22286     return 1;
22287 }
22288
22289 static void mplib_flush_file(MP mp, void *ff)
22290 {
22291     (void) mp;
22292     (void) ff;
22293     return;
22294 }
22295
22296 static void mplib_shipout_backend(MP mp, int h)
22297 {
22298     mp_edge_object *hh = mp_gr_export(mp, h);
22299     if (hh) {
22300         mp_run_data *run = mp_rundata(mp);
22301         if (run->edges==NULL) {
22302            run->edges = hh;
22303         } else {
22304            mp_edge_object *p = run->edges; 
22305            while (p->next!=NULL) { p = p->next; }
22306             p->next = hh;
22307         } 
22308     }
22309 }
22310
22311
22312 @ This is where we fill them all in.
22313 @<Prepare function pointers for non-interactive use@>=
22314 {
22315     mp->open_file         = mplib_open_file;
22316     mp->close_file        = mplib_close_file;
22317     mp->eof_file          = mplib_eof_file;
22318     mp->flush_file        = mplib_flush_file;
22319     mp->write_ascii_file  = mplib_write_ascii_file;
22320     mp->read_ascii_file   = mplib_read_ascii_file;
22321     mp->write_binary_file = mplib_write_binary_file;
22322     mp->read_binary_file  = mplib_read_binary_file;
22323     mp->shipout_backend   = mplib_shipout_backend;
22324 }
22325
22326 @ Perhaps this is the most important API function in the library.
22327
22328 @<Exported function ...@>=
22329 extern mp_run_data *mp_rundata (MP mp) ;
22330
22331 @ @c
22332 mp_run_data *mp_rundata (MP mp)  {
22333   return &(mp->run_data);
22334 }
22335
22336 @ @<Dealloc ...@>=
22337 mp_free_stream(&(mp->run_data.term_in));
22338 mp_free_stream(&(mp->run_data.term_out));
22339 mp_free_stream(&(mp->run_data.log_out));
22340 mp_free_stream(&(mp->run_data.error_out));
22341 mp_free_stream(&(mp->run_data.ps_out));
22342
22343 @ @<Finish non-interactive use@>=
22344 xfree(mp->term_out);
22345 xfree(mp->term_in);
22346 xfree(mp->err_out);
22347
22348 @ @<Start non-interactive work@>=
22349 @<Initialize the output routines@>;
22350 mp->input_ptr=0; mp->max_in_stack=0;
22351 mp->in_open=0; mp->open_parens=0; mp->max_buf_stack=0;
22352 mp->param_ptr=0; mp->max_param_stack=0;
22353 start = loc = iindex = 0; mp->first = 0;
22354 line=0; name=is_term;
22355 mp->mpx_name[0]=absent;
22356 mp->force_eof=false;
22357 t_open_in; 
22358 mp->scanner_status=normal;
22359 if (mp->mem_ident==NULL) {
22360   if ( ! mp_load_mem_file(mp) ) {
22361     (mp->close_file)(mp, mp->mem_file); 
22362      mp->history  = mp_fatal_error_stop;
22363      return mp->history;
22364   }
22365   (mp->close_file)(mp, mp->mem_file);
22366 }
22367 mp_fix_date_and_time(mp);
22368 if (mp->random_seed==0)
22369   mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
22370 mp_init_randoms(mp, mp->random_seed);
22371 @<Initialize the print |selector|...@>;
22372 mp_open_log_file(mp);
22373 mp_set_job_id(mp);
22374 mp_init_map_file(mp, mp->troff_mode);
22375 mp->history=mp_spotless; /* ready to go! */
22376 if (mp->troff_mode) {
22377   mp->internal[mp_gtroffmode]=unity; 
22378   mp->internal[mp_prologues]=unity; 
22379 }
22380 if ( mp->start_sym>0 ) { /* insert the `\&{everyjob}' symbol */
22381   mp->cur_sym=mp->start_sym; mp_back_input(mp);
22382 }
22383
22384 @ @c
22385 int mp_execute (MP mp, char *s, size_t l) {
22386   mp_reset_stream(&(mp->run_data.term_out));
22387   mp_reset_stream(&(mp->run_data.log_out));
22388   mp_reset_stream(&(mp->run_data.error_out));
22389   mp_reset_stream(&(mp->run_data.ps_out));
22390   if (mp->finished) {
22391       return mp->history;
22392   } else if (!mp->noninteractive) {
22393       mp->history = mp_fatal_error_stop ;
22394       return mp->history;
22395   }
22396   if (mp->history < mp_fatal_error_stop ) {
22397     xfree(mp->jump_buf);
22398     mp->jump_buf = malloc(sizeof(jmp_buf));
22399     if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) {   
22400        return mp->history; 
22401     }
22402     if (s==NULL) { /* this signals EOF */
22403       mp_final_cleanup(mp); /* prepare for death */
22404       mp_close_files_and_terminate(mp);
22405       return mp->history;
22406     } 
22407     mp->tally=0; 
22408     mp->term_offset=0; mp->file_offset=0; 
22409     /* Perhaps some sort of warning here when |data| is not 
22410      * yet exhausted would be nice ...  this happens after errors
22411      */
22412     if (mp->run_data.term_in.data)
22413       xfree(mp->run_data.term_in.data);
22414     mp->run_data.term_in.data = xstrdup(s);
22415     mp->run_data.term_in.cur = mp->run_data.term_in.data;
22416     mp->run_data.term_in.size = l;
22417     if (mp->run_state == 0) {
22418       mp->selector=term_only; 
22419       @<Start non-interactive work@>; 
22420     }
22421     mp->run_state =1;    
22422     (void)mp_input_ln(mp,mp->term_in);
22423     mp_firm_up_the_line(mp);    
22424     mp->buffer[limit]=xord('%');
22425     mp->first=(size_t)(limit+1); 
22426     loc=start;
22427         do {  
22428       mp_do_statement(mp);
22429     } while (mp->cur_cmd!=stop);
22430     mp_final_cleanup(mp); 
22431     mp_close_files_and_terminate(mp);
22432   }
22433   return mp->history;
22434 }
22435
22436 @ This function cleans up
22437 @c
22438 int mp_finish (MP mp) {
22439   int history = 0;
22440   if (mp->finished || mp->history >= mp_fatal_error_stop) {
22441     history = mp->history;
22442     mp_free(mp);
22443     return history;
22444   }
22445   xfree(mp->jump_buf);
22446   mp->jump_buf = malloc(sizeof(jmp_buf));
22447   if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)) != 0) { 
22448     history = mp->history;
22449   } else {
22450     history = mp->history;
22451     mp_final_cleanup(mp); /* prepare for death */
22452   }
22453   mp_close_files_and_terminate(mp);
22454   mp_free(mp);
22455   return history;
22456 }
22457
22458 @ People may want to know the library version
22459 @c 
22460 char * mp_metapost_version (void) {
22461   return mp_strdup(metapost_version);
22462 }
22463
22464 @ @<Exported function headers@>=
22465 int mp_run (MP mp);
22466 int mp_execute (MP mp, char *s, size_t l);
22467 int mp_finish (MP mp);
22468 char * mp_metapost_version (void);
22469
22470 @ @<Put each...@>=
22471 mp_primitive(mp, "end",stop,0);
22472 @:end_}{\&{end} primitive@>
22473 mp_primitive(mp, "dump",stop,1);
22474 @:dump_}{\&{dump} primitive@>
22475
22476 @ @<Cases of |print_cmd...@>=
22477 case stop:
22478   if ( m==0 ) mp_print(mp, "end");
22479   else mp_print(mp, "dump");
22480   break;
22481
22482 @* \[41] Commands.
22483 Let's turn now to statements that are classified as ``commands'' because
22484 of their imperative nature. We'll begin with simple ones, so that it
22485 will be clear how to hook command processing into the |do_statement| routine;
22486 then we'll tackle the tougher commands.
22487
22488 Here's one of the simplest:
22489
22490 @<Cases of |do_statement|...@>=
22491 case mp_random_seed: mp_do_random_seed(mp);  break;
22492
22493 @ @<Declare action procedures for use by |do_statement|@>=
22494 static void mp_do_random_seed (MP mp) ;
22495
22496 @ @c void mp_do_random_seed (MP mp) { 
22497   mp_get_x_next(mp);
22498   if ( mp->cur_cmd!=assignment ) {
22499     mp_missing_err(mp, ":=");
22500 @.Missing `:='@>
22501     help1("Always say `randomseed:=<numeric expression>'.");
22502     mp_back_error(mp);
22503   };
22504   mp_get_x_next(mp); mp_scan_expression(mp);
22505   if ( mp->cur_type!=mp_known ) {
22506     exp_err("Unknown value will be ignored");
22507 @.Unknown value...ignored@>
22508     help2("Your expression was too random for me to handle,",
22509           "so I won't change the random seed just now.");
22510     mp_put_get_flush_error(mp, 0);
22511   } else {
22512    @<Initialize the random seed to |cur_exp|@>;
22513   }
22514 }
22515
22516 @ @<Initialize the random seed to |cur_exp|@>=
22517
22518   mp_init_randoms(mp, mp->cur_exp);
22519   if ( mp->selector>=log_only && mp->selector<write_file) {
22520     mp->old_setting=mp->selector; mp->selector=log_only;
22521     mp_print_nl(mp, "{randomseed:="); 
22522     mp_print_scaled(mp, mp->cur_exp); 
22523     mp_print_char(mp, xord('}'));
22524     mp_print_nl(mp, ""); mp->selector=mp->old_setting;
22525   }
22526 }
22527
22528 @ And here's another simple one (somewhat different in flavor):
22529
22530 @<Cases of |do_statement|...@>=
22531 case mode_command: 
22532   mp_print_ln(mp); mp->interaction=mp->cur_mod;
22533   @<Initialize the print |selector| based on |interaction|@>;
22534   if ( mp->log_opened ) mp->selector=mp->selector+2;
22535   mp_get_x_next(mp);
22536   break;
22537
22538 @ @<Put each...@>=
22539 mp_primitive(mp, "batchmode",mode_command,mp_batch_mode);
22540 @:mp_batch_mode_}{\&{batchmode} primitive@>
22541 mp_primitive(mp, "nonstopmode",mode_command,mp_nonstop_mode);
22542 @:mp_nonstop_mode_}{\&{nonstopmode} primitive@>
22543 mp_primitive(mp, "scrollmode",mode_command,mp_scroll_mode);
22544 @:mp_scroll_mode_}{\&{scrollmode} primitive@>
22545 mp_primitive(mp, "errorstopmode",mode_command,mp_error_stop_mode);
22546 @:mp_error_stop_mode_}{\&{errorstopmode} primitive@>
22547
22548 @ @<Cases of |print_cmd_mod|...@>=
22549 case mode_command: 
22550   switch (m) {
22551   case mp_batch_mode: mp_print(mp, "batchmode"); break;
22552   case mp_nonstop_mode: mp_print(mp, "nonstopmode"); break;
22553   case mp_scroll_mode: mp_print(mp, "scrollmode"); break;
22554   default: mp_print(mp, "errorstopmode"); break;
22555   }
22556   break;
22557
22558 @ The `\&{inner}' and `\&{outer}' commands are only slightly harder.
22559
22560 @<Cases of |do_statement|...@>=
22561 case protection_command: mp_do_protection(mp); break;
22562
22563 @ @<Put each...@>=
22564 mp_primitive(mp, "inner",protection_command,0);
22565 @:inner_}{\&{inner} primitive@>
22566 mp_primitive(mp, "outer",protection_command,1);
22567 @:outer_}{\&{outer} primitive@>
22568
22569 @ @<Cases of |print_cmd...@>=
22570 case protection_command: 
22571   if ( m==0 ) mp_print(mp, "inner");
22572   else mp_print(mp, "outer");
22573   break;
22574
22575 @ @<Declare action procedures for use by |do_statement|@>=
22576 static void mp_do_protection (MP mp) ;
22577
22578 @ @c void mp_do_protection (MP mp) {
22579   int m; /* 0 to unprotect, 1 to protect */
22580   halfword t; /* the |eq_type| before we change it */
22581   m=mp->cur_mod;
22582   do {  
22583     mp_get_symbol(mp); t=eq_type(mp->cur_sym);
22584     if ( m==0 ) { 
22585       if ( t>=outer_tag ) 
22586         eq_type(mp->cur_sym)=t-outer_tag;
22587     } else if ( t<outer_tag ) {
22588       eq_type(mp->cur_sym)=t+outer_tag;
22589     }
22590     mp_get_x_next(mp);
22591   } while (mp->cur_cmd==comma);
22592 }
22593
22594 @ \MP\ never defines the tokens `\.(' and `\.)' to be primitives, but
22595 plain \MP\ begins with the declaration `\&{delimiters} \.{()}'. Such a
22596 declaration assigns the command code |left_delimiter| to `\.{(}' and
22597 |right_delimiter| to `\.{)}'; the |equiv| of each delimiter is the
22598 hash address of its mate.
22599
22600 @<Cases of |do_statement|...@>=
22601 case delimiters: mp_def_delims(mp); break;
22602
22603 @ @<Declare action procedures for use by |do_statement|@>=
22604 static void mp_def_delims (MP mp) ;
22605
22606 @ @c void mp_def_delims (MP mp) {
22607   pointer l_delim,r_delim; /* the new delimiter pair */
22608   mp_get_clear_symbol(mp); l_delim=mp->cur_sym;
22609   mp_get_clear_symbol(mp); r_delim=mp->cur_sym;
22610   eq_type(l_delim)=left_delimiter; equiv(l_delim)=r_delim;
22611   eq_type(r_delim)=right_delimiter; equiv(r_delim)=l_delim;
22612   mp_get_x_next(mp);
22613 }
22614
22615 @ Here is a procedure that is called when \MP\ has reached a point
22616 where some right delimiter is mandatory.
22617
22618 @<Declarations@>=
22619 static void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim);
22620
22621 @ @c
22622 void mp_check_delimiter (MP mp,pointer l_delim, pointer r_delim) {
22623   if ( mp->cur_cmd==right_delimiter ) 
22624     if ( mp->cur_mod==l_delim ) 
22625       return;
22626   if ( mp->cur_sym!=r_delim ) {
22627      mp_missing_err(mp, str(text(r_delim)));
22628 @.Missing `)'@>
22629     help2("I found no right delimiter to match a left one. So I've",
22630           "put one in, behind the scenes; this may fix the problem.");
22631     mp_back_error(mp);
22632   } else { 
22633     print_err("The token `"); mp_print_text(r_delim);
22634 @.The token...delimiter@>
22635     mp_print(mp, "' is no longer a right delimiter");
22636     help3("Strange: This token has lost its former meaning!",
22637       "I'll read it as a right delimiter this time;",
22638       "but watch out, I'll probably miss it later.");
22639     mp_error(mp);
22640   }
22641 }
22642
22643 @ The next four commands save or change the values associated with tokens.
22644
22645 @<Cases of |do_statement|...@>=
22646 case save_command: 
22647   do {  
22648     mp_get_symbol(mp); mp_save_variable(mp, mp->cur_sym); mp_get_x_next(mp);
22649   } while (mp->cur_cmd==comma);
22650   break;
22651 case interim_command: mp_do_interim(mp); break;
22652 case let_command: mp_do_let(mp); break;
22653 case new_internal: mp_do_new_internal(mp); break;
22654
22655 @ @<Declare action procedures for use by |do_statement|@>=
22656 static void mp_do_statement (MP mp);
22657 static void mp_do_interim (MP mp);
22658
22659 @ @c void mp_do_interim (MP mp) { 
22660   mp_get_x_next(mp);
22661   if ( mp->cur_cmd!=internal_quantity ) {
22662      print_err("The token `");
22663 @.The token...quantity@>
22664     if ( mp->cur_sym==0 ) mp_print(mp, "(%CAPSULE)");
22665     else mp_print_text(mp->cur_sym);
22666     mp_print(mp, "' isn't an internal quantity");
22667     help1("Something like `tracingonline' should follow `interim'.");
22668     mp_back_error(mp);
22669   } else { 
22670     mp_save_internal(mp, mp->cur_mod); mp_back_input(mp);
22671   }
22672   mp_do_statement(mp);
22673 }
22674
22675 @ The following procedure is careful not to undefine the left-hand symbol
22676 too soon, lest commands like `{\tt let x=x}' have a surprising effect.
22677
22678 @<Declare action procedures for use by |do_statement|@>=
22679 static void mp_do_let (MP mp) ;
22680
22681 @ @c void mp_do_let (MP mp) {
22682   pointer l; /* hash location of the left-hand symbol */
22683   mp_get_symbol(mp); l=mp->cur_sym; mp_get_x_next(mp);
22684   if ( mp->cur_cmd!=equals ) if ( mp->cur_cmd!=assignment ) {
22685      mp_missing_err(mp, "=");
22686 @.Missing `='@>
22687     help3("You should have said `let symbol = something'.",
22688       "But don't worry; I'll pretend that an equals sign",
22689       "was present. The next token I read will be `something'.");
22690     mp_back_error(mp);
22691   }
22692   mp_get_symbol(mp);
22693   switch (mp->cur_cmd) {
22694   case defined_macro: case secondary_primary_macro:
22695   case tertiary_secondary_macro: case expression_tertiary_macro: 
22696     add_mac_ref(mp->cur_mod);
22697     break;
22698   default: 
22699     break;
22700   }
22701   mp_clear_symbol(mp, l,false); eq_type(l)=mp->cur_cmd;
22702   if ( mp->cur_cmd==tag_token ) equiv(l)=null;
22703   else equiv(l)=mp->cur_mod;
22704   mp_get_x_next(mp);
22705 }
22706
22707 @ @<Declarations@>=
22708 static void mp_do_new_internal (MP mp) ;
22709
22710 @ @<Internal library ...@>=
22711 void mp_grow_internals (MP mp, int l);
22712
22713 @ @c
22714 void mp_grow_internals (MP mp, int l) {
22715   scaled *internal;
22716   char * *int_name; 
22717   int k;
22718   if ( hash_end+l>max_halfword ) {
22719     mp_confusion(mp, "out of memory space"); /* can't be reached */
22720   }
22721   int_name = xmalloc ((l+1),sizeof(char *));
22722   internal = xmalloc ((l+1),sizeof(scaled));
22723   for (k=0;k<=l; k++ ) { 
22724     if (k<=mp->max_internal) {
22725       internal[k]=mp->internal[k]; 
22726       int_name[k]=mp->int_name[k]; 
22727     } else {
22728       internal[k]=0; 
22729       int_name[k]=NULL; 
22730     }
22731   }
22732   xfree(mp->internal); xfree(mp->int_name);
22733   mp->int_name = int_name;
22734   mp->internal = internal;
22735   mp->max_internal = l;
22736 }
22737
22738 void mp_do_new_internal (MP mp) { 
22739   do {  
22740     if ( mp->int_ptr==mp->max_internal ) {
22741       mp_grow_internals(mp, (mp->max_internal + (mp->max_internal/4)));
22742     }
22743     mp_get_clear_symbol(mp); incr(mp->int_ptr);
22744     eq_type(mp->cur_sym)=internal_quantity; 
22745     equiv(mp->cur_sym)=mp->int_ptr;
22746     if(mp->int_name[mp->int_ptr]!=NULL)
22747       xfree(mp->int_name[mp->int_ptr]);
22748     mp->int_name[mp->int_ptr]=str(text(mp->cur_sym)); 
22749     mp->internal[mp->int_ptr]=0;
22750     mp_get_x_next(mp);
22751   } while (mp->cur_cmd==comma);
22752 }
22753
22754 @ @<Dealloc variables@>=
22755 for (k=0;k<=mp->max_internal;k++) {
22756    xfree(mp->int_name[k]);
22757 }
22758 xfree(mp->internal); 
22759 xfree(mp->int_name); 
22760
22761
22762 @ The various `\&{show}' commands are distinguished by modifier fields
22763 in the usual way.
22764
22765 @d show_token_code 0 /* show the meaning of a single token */
22766 @d show_stats_code 1 /* show current memory and string usage */
22767 @d show_code 2 /* show a list of expressions */
22768 @d show_var_code 3 /* show a variable and its descendents */
22769 @d show_dependencies_code 4 /* show dependent variables in terms of independents */
22770
22771 @<Put each...@>=
22772 mp_primitive(mp, "showtoken",show_command,show_token_code);
22773 @:show_token_}{\&{showtoken} primitive@>
22774 mp_primitive(mp, "showstats",show_command,show_stats_code);
22775 @:show_stats_}{\&{showstats} primitive@>
22776 mp_primitive(mp, "show",show_command,show_code);
22777 @:show_}{\&{show} primitive@>
22778 mp_primitive(mp, "showvariable",show_command,show_var_code);
22779 @:show_var_}{\&{showvariable} primitive@>
22780 mp_primitive(mp, "showdependencies",show_command,show_dependencies_code);
22781 @:show_dependencies_}{\&{showdependencies} primitive@>
22782
22783 @ @<Cases of |print_cmd...@>=
22784 case show_command: 
22785   switch (m) {
22786   case show_token_code:mp_print(mp, "showtoken"); break;
22787   case show_stats_code:mp_print(mp, "showstats"); break;
22788   case show_code:mp_print(mp, "show"); break;
22789   case show_var_code:mp_print(mp, "showvariable"); break;
22790   default: mp_print(mp, "showdependencies"); break;
22791   }
22792   break;
22793
22794 @ @<Cases of |do_statement|...@>=
22795 case show_command:mp_do_show_whatever(mp); break;
22796
22797 @ The value of |cur_mod| controls the |verbosity| in the |print_exp| routine:
22798 if it's |show_code|, complicated structures are abbreviated, otherwise
22799 they aren't.
22800
22801 @<Declare action procedures for use by |do_statement|@>=
22802 static void mp_do_show (MP mp) ;
22803
22804 @ @c void mp_do_show (MP mp) { 
22805   do {  
22806     mp_get_x_next(mp); mp_scan_expression(mp);
22807     mp_print_nl(mp, ">> ");
22808 @.>>@>
22809     mp_print_exp(mp, null,2); mp_flush_cur_exp(mp, 0);
22810   } while (mp->cur_cmd==comma);
22811 }
22812
22813 @ @<Declare action procedures for use by |do_statement|@>=
22814 static void mp_disp_token (MP mp) ;
22815
22816 @ @c void mp_disp_token (MP mp) { 
22817   mp_print_nl(mp, "> ");
22818 @.>\relax@>
22819   if ( mp->cur_sym==0 ) {
22820     @<Show a numeric or string or capsule token@>;
22821   } else { 
22822     mp_print_text(mp->cur_sym); mp_print_char(mp, xord('='));
22823     if ( eq_type(mp->cur_sym)>=outer_tag ) mp_print(mp, "(outer) ");
22824     mp_print_cmd_mod(mp, mp->cur_cmd,mp->cur_mod);
22825     if ( mp->cur_cmd==defined_macro ) {
22826       mp_print_ln(mp); mp_show_macro(mp, mp->cur_mod,null,100000);
22827     } /* this avoids recursion between |show_macro| and |print_cmd_mod| */
22828 @^recursion@>
22829   }
22830 }
22831
22832 @ @<Show a numeric or string or capsule token@>=
22833
22834   if ( mp->cur_cmd==numeric_token ) {
22835     mp_print_scaled(mp, mp->cur_mod);
22836   } else if ( mp->cur_cmd==capsule_token ) {
22837     mp_print_capsule(mp,mp->cur_mod);
22838   } else  { 
22839     mp_print_char(mp, xord('"')); 
22840     mp_print_str(mp, mp->cur_mod); mp_print_char(mp, xord('"'));
22841     delete_str_ref(mp->cur_mod);
22842   }
22843 }
22844
22845 @ The following cases of |print_cmd_mod| might arise in connection
22846 with |disp_token|, although they don't necessarily correspond to
22847 primitive tokens.
22848
22849 @<Cases of |print_cmd_...@>=
22850 case left_delimiter:
22851 case right_delimiter: 
22852   if ( c==left_delimiter ) mp_print(mp, "left");
22853   else mp_print(mp, "right");
22854   mp_print(mp, " delimiter that matches "); 
22855   mp_print_text(m);
22856   break;
22857 case tag_token:
22858   if ( m==null ) mp_print(mp, "tag");
22859    else mp_print(mp, "variable");
22860    break;
22861 case defined_macro: 
22862    mp_print(mp, "macro:");
22863    break;
22864 case secondary_primary_macro:
22865 case tertiary_secondary_macro:
22866 case expression_tertiary_macro:
22867   mp_print_cmd_mod(mp, macro_def,c); 
22868   mp_print(mp, "'d macro:");
22869   mp_print_ln(mp); mp_show_token_list(mp, mp_link(mp_link(m)),null,1000,0);
22870   break;
22871 case repeat_loop:
22872   mp_print(mp, "[repeat the loop]");
22873   break;
22874 case internal_quantity:
22875   mp_print(mp, mp->int_name[m]);
22876   break;
22877
22878 @ @<Declare action procedures for use by |do_statement|@>=
22879 static void mp_do_show_token (MP mp) ;
22880
22881 @ @c void mp_do_show_token (MP mp) { 
22882   do {  
22883     get_t_next; mp_disp_token(mp);
22884     mp_get_x_next(mp);
22885   } while (mp->cur_cmd==comma);
22886 }
22887
22888 @ @<Declare action procedures for use by |do_statement|@>=
22889 static void mp_do_show_stats (MP mp) ;
22890
22891 @ @c void mp_do_show_stats (MP mp) { 
22892   mp_print_nl(mp, "Memory usage ");
22893 @.Memory usage...@>
22894   mp_print_int(mp, mp->var_used); mp_print_char(mp, xord('&')); mp_print_int(mp, mp->dyn_used);
22895   mp_print(mp, " ("); mp_print_int(mp, mp->hi_mem_min-mp->lo_mem_max-1);
22896   mp_print(mp, " still untouched)"); mp_print_ln(mp);
22897   mp_print_nl(mp, "String usage ");
22898   mp_print_int(mp, mp->strs_in_use-mp->init_str_use);
22899   mp_print_char(mp, xord('&')); mp_print_int(mp, mp->pool_in_use-mp->init_pool_ptr);
22900   mp_print(mp, " (");
22901   mp_print_int(mp, mp->max_strings-1-mp->strs_used_up); mp_print_char(mp, xord('&'));
22902   mp_print_int(mp, mp->pool_size-mp->pool_ptr); 
22903   mp_print(mp, " now untouched)"); mp_print_ln(mp);
22904   mp_get_x_next(mp);
22905 }
22906
22907 @ Here's a recursive procedure that gives an abbreviated account
22908 of a variable, for use by |do_show_var|.
22909
22910 @<Declare action procedures for use by |do_statement|@>=
22911 static void mp_disp_var (MP mp,pointer p) ;
22912
22913 @ @c void mp_disp_var (MP mp,pointer p) {
22914   pointer q; /* traverses attributes and subscripts */
22915   int n; /* amount of macro text to show */
22916   if ( mp_type(p)==mp_structured )  {
22917     @<Descend the structure@>;
22918   } else if ( mp_type(p)>=mp_unsuffixed_macro ) {
22919     @<Display a variable macro@>;
22920   } else if ( mp_type(p)!=undefined ){ 
22921     mp_print_nl(mp, ""); mp_print_variable_name(mp, p); 
22922     mp_print_char(mp, xord('='));
22923     mp_print_exp(mp, p,0);
22924   }
22925 }
22926
22927 @ @<Descend the structure@>=
22928
22929   q=attr_head(p);
22930   do {  mp_disp_var(mp, q); q=mp_link(q); } while (q!=end_attr);
22931   q=subscr_head(p);
22932   while ( mp_name_type(q)==mp_subscr ) { 
22933     mp_disp_var(mp, q); q=mp_link(q);
22934   }
22935 }
22936
22937 @ @<Display a variable macro@>=
22938
22939   mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22940   if ( mp_type(p)>mp_unsuffixed_macro ) 
22941     mp_print(mp, "@@#"); /* |suffixed_macro| */
22942   mp_print(mp, "=macro:");
22943   if ( (int)mp->file_offset>=mp->max_print_line-20 ) n=5;
22944   else n=mp->max_print_line-mp->file_offset-15;
22945   mp_show_macro(mp, value(p),null,n);
22946 }
22947
22948 @ @<Declare action procedures for use by |do_statement|@>=
22949 static void mp_do_show_var (MP mp) ;
22950
22951 @ @c void mp_do_show_var (MP mp) { 
22952   do {  
22953     get_t_next;
22954     if ( mp->cur_sym>0 ) if ( mp->cur_sym<=hash_end )
22955       if ( mp->cur_cmd==tag_token ) if ( mp->cur_mod!=null ) {
22956       mp_disp_var(mp, mp->cur_mod); goto DONE;
22957     }
22958    mp_disp_token(mp);
22959   DONE:
22960    mp_get_x_next(mp);
22961   } while (mp->cur_cmd==comma);
22962 }
22963
22964 @ @<Declare action procedures for use by |do_statement|@>=
22965 static void mp_do_show_dependencies (MP mp) ;
22966
22967 @ @c void mp_do_show_dependencies (MP mp) {
22968   pointer p; /* link that runs through all dependencies */
22969   p=mp_link(dep_head);
22970   while ( p!=dep_head ) {
22971     if ( mp_interesting(mp, p) ) {
22972       mp_print_nl(mp, ""); mp_print_variable_name(mp, p);
22973       if ( mp_type(p)==mp_dependent ) mp_print_char(mp, xord('='));
22974       else mp_print(mp, " = "); /* extra spaces imply proto-dependency */
22975       mp_print_dependency(mp, dep_list(p),mp_type(p));
22976     }
22977     p=dep_list(p);
22978     while ( mp_info(p)!=null ) p=mp_link(p);
22979     p=mp_link(p);
22980   }
22981   mp_get_x_next(mp);
22982 }
22983
22984 @ Finally we are ready for the procedure that governs all of the
22985 show commands.
22986
22987 @<Declare action procedures for use by |do_statement|@>=
22988 static void mp_do_show_whatever (MP mp) ;
22989
22990 @ @c void mp_do_show_whatever (MP mp) { 
22991   if ( mp->interaction==mp_error_stop_mode ) wake_up_terminal;
22992   switch (mp->cur_mod) {
22993   case show_token_code:mp_do_show_token(mp); break;
22994   case show_stats_code:mp_do_show_stats(mp); break;
22995   case show_code:mp_do_show(mp); break;
22996   case show_var_code:mp_do_show_var(mp); break;
22997   case show_dependencies_code:mp_do_show_dependencies(mp); break;
22998   } /* there are no other cases */
22999   if ( mp->internal[mp_showstopping]>0 ){ 
23000     print_err("OK");
23001 @.OK@>
23002     if ( mp->interaction<mp_error_stop_mode ) { 
23003       help0; decr(mp->error_count);
23004     } else {
23005       help1("This isn't an error message; I'm just showing something.");
23006     }
23007     if ( mp->cur_cmd==semicolon ) mp_error(mp);
23008      else mp_put_get_error(mp);
23009   }
23010 }
23011
23012 @ The `\&{addto}' command needs the following additional primitives:
23013
23014 @d double_path_code 0 /* command modifier for `\&{doublepath}' */
23015 @d contour_code 1 /* command modifier for `\&{contour}' */
23016 @d also_code 2 /* command modifier for `\&{also}' */
23017
23018 @ Pre and postscripts need two new identifiers:
23019
23020 @d with_mp_pre_script 11
23021 @d with_mp_post_script 13
23022
23023 @<Put each...@>=
23024 mp_primitive(mp, "doublepath",thing_to_add,double_path_code);
23025 @:double_path_}{\&{doublepath} primitive@>
23026 mp_primitive(mp, "contour",thing_to_add,contour_code);
23027 @:contour_}{\&{contour} primitive@>
23028 mp_primitive(mp, "also",thing_to_add,also_code);
23029 @:also_}{\&{also} primitive@>
23030 mp_primitive(mp, "withpen",with_option,mp_pen_type);
23031 @:with_pen_}{\&{withpen} primitive@>
23032 mp_primitive(mp, "dashed",with_option,mp_picture_type);
23033 @:dashed_}{\&{dashed} primitive@>
23034 mp_primitive(mp, "withprescript",with_option,with_mp_pre_script);
23035 @:with_mp_pre_script_}{\&{withprescript} primitive@>
23036 mp_primitive(mp, "withpostscript",with_option,with_mp_post_script);
23037 @:with_mp_post_script_}{\&{withpostscript} primitive@>
23038 mp_primitive(mp, "withoutcolor",with_option,mp_no_model);
23039 @:with_color_}{\&{withoutcolor} primitive@>
23040 mp_primitive(mp, "withgreyscale",with_option,mp_grey_model);
23041 @:with_color_}{\&{withgreyscale} primitive@>
23042 mp_primitive(mp, "withcolor",with_option,mp_uninitialized_model);
23043 @:with_color_}{\&{withcolor} primitive@>
23044 /*  \&{withrgbcolor} is an alias for \&{withcolor} */
23045 mp_primitive(mp, "withrgbcolor",with_option,mp_rgb_model);
23046 @:with_color_}{\&{withrgbcolor} primitive@>
23047 mp_primitive(mp, "withcmykcolor",with_option,mp_cmyk_model);
23048 @:with_color_}{\&{withcmykcolor} primitive@>
23049
23050 @ @<Cases of |print_cmd...@>=
23051 case thing_to_add:
23052   if ( m==contour_code ) mp_print(mp, "contour");
23053   else if ( m==double_path_code ) mp_print(mp, "doublepath");
23054   else mp_print(mp, "also");
23055   break;
23056 case with_option:
23057   if ( m==mp_pen_type ) mp_print(mp, "withpen");
23058   else if ( m==with_mp_pre_script ) mp_print(mp, "withprescript");
23059   else if ( m==with_mp_post_script ) mp_print(mp, "withpostscript");
23060   else if ( m==mp_no_model ) mp_print(mp, "withoutcolor");
23061   else if ( m==mp_rgb_model ) mp_print(mp, "withrgbcolor");
23062   else if ( m==mp_uninitialized_model ) mp_print(mp, "withcolor");
23063   else if ( m==mp_cmyk_model ) mp_print(mp, "withcmykcolor");
23064   else if ( m==mp_grey_model ) mp_print(mp, "withgreyscale");
23065   else mp_print(mp, "dashed");
23066   break;
23067
23068 @ The |scan_with_list| procedure parses a $\langle$with list$\rangle$ and
23069 updates the list of graphical objects starting at |p|.  Each $\langle$with
23070 clause$\rangle$ updates all graphical objects whose |type| is compatible.
23071 Other objects are ignored.
23072
23073 @<Declare action procedures for use by |do_statement|@>=
23074 static void mp_scan_with_list (MP mp,pointer p) ;
23075
23076 @ @c void mp_scan_with_list (MP mp,pointer p) {
23077   quarterword t; /* |cur_mod| of the |with_option| (should match |cur_type|) */
23078   pointer q; /* for list manipulation */
23079   unsigned old_setting; /* saved |selector| setting */
23080   pointer k; /* for finding the near-last item in a list  */
23081   str_number s; /* for string cleanup after combining  */
23082   pointer cp,pp,dp,ap,bp;
23083     /* objects being updated; |void| initially; |null| to suppress update */
23084   cp=mp_void; pp=mp_void; dp=mp_void; ap=mp_void; bp=mp_void;
23085   k=0;
23086   while ( mp->cur_cmd==with_option ){ 
23087     t=mp->cur_mod;
23088     mp_get_x_next(mp);
23089     if ( t!=mp_no_model ) mp_scan_expression(mp);
23090     if (((t==with_mp_pre_script)&&(mp->cur_type!=mp_string_type))||
23091      ((t==with_mp_post_script)&&(mp->cur_type!=mp_string_type))||
23092      ((t==mp_uninitialized_model)&&
23093         ((mp->cur_type!=mp_cmykcolor_type)&&(mp->cur_type!=mp_color_type)
23094           &&(mp->cur_type!=mp_known)&&(mp->cur_type!=mp_boolean_type)))||
23095      ((t==mp_cmyk_model)&&(mp->cur_type!=mp_cmykcolor_type))||
23096      ((t==mp_rgb_model)&&(mp->cur_type!=mp_color_type))||
23097      ((t==mp_grey_model)&&(mp->cur_type!=mp_known))||
23098      ((t==mp_pen_type)&&(mp->cur_type!=t))||
23099      ((t==mp_picture_type)&&(mp->cur_type!=t)) ) {
23100       @<Complain about improper type@>;
23101     } else if ( t==mp_uninitialized_model ) {
23102       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23103       if ( cp!=null )
23104         @<Transfer a color from the current expression to object~|cp|@>;
23105       mp_flush_cur_exp(mp, 0);
23106     } else if ( t==mp_rgb_model ) {
23107       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23108       if ( cp!=null )
23109         @<Transfer a rgbcolor from the current expression to object~|cp|@>;
23110       mp_flush_cur_exp(mp, 0);
23111     } else if ( t==mp_cmyk_model ) {
23112       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23113       if ( cp!=null )
23114         @<Transfer a cmykcolor from the current expression to object~|cp|@>;
23115       mp_flush_cur_exp(mp, 0);
23116     } else if ( t==mp_grey_model ) {
23117       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23118       if ( cp!=null )
23119         @<Transfer a greyscale from the current expression to object~|cp|@>;
23120       mp_flush_cur_exp(mp, 0);
23121     } else if ( t==mp_no_model ) {
23122       if ( cp==mp_void ) @<Make |cp| a colored object in object list~|p|@>;
23123       if ( cp!=null )
23124         @<Transfer a noncolor from the current expression to object~|cp|@>;
23125     } else if ( t==mp_pen_type ) {
23126       if ( pp==mp_void ) @<Make |pp| an object in list~|p| that needs a pen@>;
23127       if ( pp!=null ) {
23128         if ( mp_pen_p(pp)!=null ) mp_toss_knot_list(mp, mp_pen_p(pp));
23129         mp_pen_p(pp)=mp->cur_exp; mp->cur_type=mp_vacuous;
23130       }
23131     } else if ( t==with_mp_pre_script ) {
23132       if ( ap==mp_void )
23133         ap=p;
23134       while ( (ap!=null)&&(! has_color(ap)) )
23135          ap=mp_link(ap);
23136       if ( ap!=null ) {
23137         if ( mp_pre_script(ap)!=null ) { /*  build a new,combined string  */
23138           s=mp_pre_script(ap);
23139           old_setting=mp->selector;
23140               mp->selector=new_string;
23141           str_room(length(mp_pre_script(ap))+length(mp->cur_exp)+2);
23142               mp_print_str(mp, mp->cur_exp);
23143           append_char(13);  /* a forced \ps\ newline  */
23144           mp_print_str(mp, mp_pre_script(ap));
23145           mp_pre_script(ap)=mp_make_string(mp);
23146           delete_str_ref(s);
23147           mp->selector=old_setting;
23148         } else {
23149           mp_pre_script(ap)=mp->cur_exp;
23150         }
23151         mp->cur_type=mp_vacuous;
23152       }
23153     } else if ( t==with_mp_post_script ) {
23154       if ( bp==mp_void )
23155         k=p; 
23156       bp=k;
23157       while ( mp_link(k)!=null ) {
23158         k=mp_link(k);
23159         if ( has_color(k) ) bp=k;
23160       }
23161       if ( bp!=null ) {
23162          if ( mp_post_script(bp)!=null ) {
23163            s=mp_post_script(bp);
23164            old_setting=mp->selector;
23165                mp->selector=new_string;
23166            str_room(length(mp_post_script(bp))+length(mp->cur_exp)+2);
23167            mp_print_str(mp, mp_post_script(bp));
23168            append_char(13); /* a forced \ps\ newline  */
23169            mp_print_str(mp, mp->cur_exp);
23170            mp_post_script(bp)=mp_make_string(mp);
23171            delete_str_ref(s);
23172            mp->selector=old_setting;
23173          } else {
23174            mp_post_script(bp)=mp->cur_exp;
23175          }
23176          mp->cur_type=mp_vacuous;
23177        }
23178     } else { 
23179       if ( dp==mp_void ) {
23180         @<Make |dp| a stroked node in list~|p|@>;
23181       }
23182       if ( dp!=null ) {
23183         if ( mp_dash_p(dp)!=null ) delete_edge_ref(mp_dash_p(dp));
23184         mp_dash_p(dp)=mp_make_dashes(mp, mp->cur_exp);
23185         dash_scale(dp)=unity;
23186         mp->cur_type=mp_vacuous;
23187       }
23188     }
23189   }
23190   @<Copy the information from objects |cp|, |pp|, and |dp| into the rest
23191     of the list@>;
23192 }
23193
23194 @ @<Complain about improper type@>=
23195 { exp_err("Improper type");
23196 @.Improper type@>
23197 help2("Next time say `withpen <known pen expression>';",
23198       "I'll ignore the bad `with' clause and look for another.");
23199 if ( t==with_mp_pre_script )
23200   mp->help_line[1]="Next time say `withprescript <known string expression>';";
23201 else if ( t==with_mp_post_script )
23202   mp->help_line[1]="Next time say `withpostscript <known string expression>';";
23203 else if ( t==mp_picture_type )
23204   mp->help_line[1]="Next time say `dashed <known picture expression>';";
23205 else if ( t==mp_uninitialized_model )
23206   mp->help_line[1]="Next time say `withcolor <known color expression>';";
23207 else if ( t==mp_rgb_model )
23208   mp->help_line[1]="Next time say `withrgbcolor <known color expression>';";
23209 else if ( t==mp_cmyk_model )
23210   mp->help_line[1]="Next time say `withcmykcolor <known cmykcolor expression>';";
23211 else if ( t==mp_grey_model )
23212   mp->help_line[1]="Next time say `withgreyscale <known numeric expression>';";;
23213 mp_put_get_flush_error(mp, 0);
23214 }
23215
23216 @ Forcing the color to be between |0| and |unity| here guarantees that no
23217 picture will ever contain a color outside the legal range for \ps\ graphics.
23218
23219 @<Transfer a color from the current expression to object~|cp|@>=
23220 { if ( mp->cur_type==mp_color_type )
23221    @<Transfer a rgbcolor from the current expression to object~|cp|@>
23222 else if ( mp->cur_type==mp_cmykcolor_type )
23223    @<Transfer a cmykcolor from the current expression to object~|cp|@>
23224 else if ( mp->cur_type==mp_known )
23225    @<Transfer a greyscale from the current expression to object~|cp|@>
23226 else if ( mp->cur_exp==false_code )
23227    @<Transfer a noncolor from the current expression to object~|cp|@>;
23228 }
23229
23230 @ @<Transfer a rgbcolor from the current expression to object~|cp|@>=
23231 { q=value(mp->cur_exp);
23232 cyan_val(cp)=0;
23233 magenta_val(cp)=0;
23234 yellow_val(cp)=0;
23235 black_val(cp)=0;
23236 red_val(cp)=value(red_part_loc(q));
23237 green_val(cp)=value(green_part_loc(q));
23238 blue_val(cp)=value(blue_part_loc(q));
23239 mp_color_model(cp)=mp_rgb_model;
23240 if ( red_val(cp)<0 ) red_val(cp)=0;
23241 if ( green_val(cp)<0 ) green_val(cp)=0;
23242 if ( blue_val(cp)<0 ) blue_val(cp)=0;
23243 if ( red_val(cp)>unity ) red_val(cp)=unity;
23244 if ( green_val(cp)>unity ) green_val(cp)=unity;
23245 if ( blue_val(cp)>unity ) blue_val(cp)=unity;
23246 }
23247
23248 @ @<Transfer a cmykcolor from the current expression to object~|cp|@>=
23249 { q=value(mp->cur_exp);
23250 cyan_val(cp)=value(cyan_part_loc(q));
23251 magenta_val(cp)=value(magenta_part_loc(q));
23252 yellow_val(cp)=value(yellow_part_loc(q));
23253 black_val(cp)=value(black_part_loc(q));
23254 mp_color_model(cp)=mp_cmyk_model;
23255 if ( cyan_val(cp)<0 ) cyan_val(cp)=0;
23256 if ( magenta_val(cp)<0 ) magenta_val(cp)=0;
23257 if ( yellow_val(cp)<0 ) yellow_val(cp)=0;
23258 if ( black_val(cp)<0 ) black_val(cp)=0;
23259 if ( cyan_val(cp)>unity ) cyan_val(cp)=unity;
23260 if ( magenta_val(cp)>unity ) magenta_val(cp)=unity;
23261 if ( yellow_val(cp)>unity ) yellow_val(cp)=unity;
23262 if ( black_val(cp)>unity ) black_val(cp)=unity;
23263 }
23264
23265 @ @<Transfer a greyscale from the current expression to object~|cp|@>=
23266 { q=mp->cur_exp;
23267 cyan_val(cp)=0;
23268 magenta_val(cp)=0;
23269 yellow_val(cp)=0;
23270 black_val(cp)=0;
23271 grey_val(cp)=q;
23272 mp_color_model(cp)=mp_grey_model;
23273 if ( grey_val(cp)<0 ) grey_val(cp)=0;
23274 if ( grey_val(cp)>unity ) grey_val(cp)=unity;
23275 }
23276
23277 @ @<Transfer a noncolor from the current expression to object~|cp|@>=
23278 {
23279 cyan_val(cp)=0;
23280 magenta_val(cp)=0;
23281 yellow_val(cp)=0;
23282 black_val(cp)=0;
23283 grey_val(cp)=0;
23284 mp_color_model(cp)=mp_no_model;
23285 }
23286
23287 @ @<Make |cp| a colored object in object list~|p|@>=
23288 { cp=p;
23289   while ( cp!=null ){ 
23290     if ( has_color(cp) ) break;
23291     cp=mp_link(cp);
23292   }
23293 }
23294
23295 @ @<Make |pp| an object in list~|p| that needs a pen@>=
23296 { pp=p;
23297   while ( pp!=null ) {
23298     if ( has_pen(pp) ) break;
23299     pp=mp_link(pp);
23300   }
23301 }
23302
23303 @ @<Make |dp| a stroked node in list~|p|@>=
23304 { dp=p;
23305   while ( dp!=null ) {
23306     if ( mp_type(dp)==mp_stroked_code ) break;
23307     dp=mp_link(dp);
23308   }
23309 }
23310
23311 @ @<Copy the information from objects |cp|, |pp|, and |dp| into...@>=
23312 @<Copy |cp|'s color into the colored objects linked to~|cp|@>;
23313 if ( pp>mp_void ) {
23314   @<Copy |mp_pen_p(pp)| into stroked and filled nodes linked to |pp|@>;
23315 }
23316 if ( dp>mp_void ) {
23317   @<Make stroked nodes linked to |dp| refer to |mp_dash_p(dp)|@>;
23318 }
23319
23320
23321 @ @<Copy |cp|'s color into the colored objects linked to~|cp|@>=
23322 { q=mp_link(cp);
23323   while ( q!=null ) { 
23324     if ( has_color(q) ) {
23325       red_val(q)=red_val(cp);
23326       green_val(q)=green_val(cp);
23327       blue_val(q)=blue_val(cp);
23328       black_val(q)=black_val(cp);
23329       mp_color_model(q)=mp_color_model(cp);
23330     }
23331     q=mp_link(q);
23332   }
23333 }
23334
23335 @ @<Copy |mp_pen_p(pp)| into stroked and filled nodes linked to |pp|@>=
23336 { q=mp_link(pp);
23337   while ( q!=null ) {
23338     if ( has_pen(q) ) {
23339       if ( mp_pen_p(q)!=null ) mp_toss_knot_list(mp, mp_pen_p(q));
23340       mp_pen_p(q)=copy_pen(mp_pen_p(pp));
23341     }
23342     q=mp_link(q);
23343   }
23344 }
23345
23346 @ @<Make stroked nodes linked to |dp| refer to |mp_dash_p(dp)|@>=
23347 { q=mp_link(dp);
23348   while ( q!=null ) {
23349     if ( mp_type(q)==mp_stroked_code ) {
23350       if ( mp_dash_p(q)!=null ) delete_edge_ref(mp_dash_p(q));
23351       mp_dash_p(q)=mp_dash_p(dp);
23352       dash_scale(q)=unity;
23353       if ( mp_dash_p(q)!=null ) add_edge_ref(mp_dash_p(q));
23354     }
23355     q=mp_link(q);
23356   }
23357 }
23358
23359 @ One of the things we need to do when we've parsed an \&{addto} or
23360 similar command is find the header of a supposed \&{picture} variable, given
23361 a token list for that variable.  Since the edge structure is about to be
23362 updated, we use |private_edges| to make sure that this is possible.
23363
23364 @<Declare action procedures for use by |do_statement|@>=
23365 static pointer mp_find_edges_var (MP mp, pointer t) ;
23366
23367 @ @c pointer mp_find_edges_var (MP mp, pointer t) {
23368   pointer p;
23369   pointer cur_edges; /* the return value */
23370   p=mp_find_variable(mp, t); cur_edges=null;
23371   if ( p==null ) { 
23372     mp_obliterated(mp, t); mp_put_get_error(mp);
23373   } else if ( mp_type(p)!=mp_picture_type )  { 
23374     print_err("Variable "); mp_show_token_list(mp, t,null,1000,0);
23375 @.Variable x is the wrong type@>
23376     mp_print(mp, " is the wrong type ("); 
23377     mp_print_type(mp, mp_type(p)); mp_print_char(mp, xord(')'));
23378     help2("I was looking for a \"known\" picture variable.",
23379           "So I'll not change anything just now."); 
23380     mp_put_get_error(mp);
23381   } else { 
23382     value(p)=mp_private_edges(mp, value(p));
23383     cur_edges=value(p);
23384   }
23385   mp_flush_node_list(mp, t);
23386   return cur_edges;
23387 }
23388
23389 @ @<Cases of |do_statement|...@>=
23390 case add_to_command: mp_do_add_to(mp); break;
23391 case bounds_command:mp_do_bounds(mp); break;
23392
23393 @ @<Put each...@>=
23394 mp_primitive(mp, "clip",bounds_command,mp_start_clip_code);
23395 @:clip_}{\&{clip} primitive@>
23396 mp_primitive(mp, "setbounds",bounds_command,mp_start_bounds_code);
23397 @:set_bounds_}{\&{setbounds} primitive@>
23398
23399 @ @<Cases of |print_cmd...@>=
23400 case bounds_command: 
23401   if ( m==mp_start_clip_code ) mp_print(mp, "clip");
23402   else mp_print(mp, "setbounds");
23403   break;
23404
23405 @ The following function parses the beginning of an \&{addto} or \&{clip}
23406 command: it expects a variable name followed by a token with |cur_cmd=sep|
23407 and then an expression.  The function returns the token list for the variable
23408 and stores the command modifier for the separator token in the global variable
23409 |last_add_type|.  We must be careful because this variable might get overwritten
23410 any time we call |get_x_next|.
23411
23412 @<Glob...@>=
23413 quarterword last_add_type;
23414   /* command modifier that identifies the last \&{addto} command */
23415
23416 @ @<Declare action procedures for use by |do_statement|@>=
23417 static pointer mp_start_draw_cmd (MP mp,quarterword sep) ;
23418
23419 @ @c pointer mp_start_draw_cmd (MP mp,quarterword sep) {
23420   pointer lhv; /* variable to add to left */
23421   quarterword add_type=0; /* value to be returned in |last_add_type| */
23422   lhv=null;
23423   mp_get_x_next(mp); mp->var_flag=sep; mp_scan_primary(mp);
23424   if ( mp->cur_type!=mp_token_list ) {
23425     @<Abandon edges command because there's no variable@>;
23426   } else  { 
23427     lhv=mp->cur_exp; add_type=mp->cur_mod;
23428     mp->cur_type=mp_vacuous; mp_get_x_next(mp); mp_scan_expression(mp);
23429   }
23430   mp->last_add_type=add_type;
23431   return lhv;
23432 }
23433
23434 @ @<Abandon edges command because there's no variable@>=
23435 { exp_err("Not a suitable variable");
23436 @.Not a suitable variable@>
23437   help4("At this point I needed to see the name of a picture variable.",
23438     "(Or perhaps you have indeed presented me with one; I might",
23439     "have missed it, if it wasn't followed by the proper token.)",
23440     "So I'll not change anything just now.");
23441   mp_put_get_flush_error(mp, 0);
23442 }
23443
23444 @ Here is an example of how to use |start_draw_cmd|.
23445
23446 @<Declare action procedures for use by |do_statement|@>=
23447 static void mp_do_bounds (MP mp) ;
23448
23449 @ @c void mp_do_bounds (MP mp) {
23450   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
23451   pointer p; /* for list manipulation */
23452   integer m; /* initial value of |cur_mod| */
23453   m=mp->cur_mod;
23454   lhv=mp_start_draw_cmd(mp, to_token);
23455   if ( lhv!=null ) {
23456     lhe=mp_find_edges_var(mp, lhv);
23457     if ( lhe==null ) {
23458       mp_flush_cur_exp(mp, 0);
23459     } else if ( mp->cur_type!=mp_path_type ) {
23460       exp_err("Improper `clip'");
23461 @.Improper `addto'@>
23462       help2("This expression should have specified a known path.",
23463             "So I'll not change anything just now."); 
23464       mp_put_get_flush_error(mp, 0);
23465     } else if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
23466       @<Complain about a non-cycle@>;
23467     } else {
23468       @<Make |cur_exp| into a \&{setbounds} or clipping path and add it to |lhe|@>;
23469     }
23470   }
23471 }
23472
23473 @ @<Complain about a non-cycle@>=
23474 { print_err("Not a cycle");
23475 @.Not a cycle@>
23476   help2("That contour should have ended with `..cycle' or `&cycle'.",
23477         "So I'll not change anything just now."); mp_put_get_error(mp);
23478 }
23479
23480 @ @<Make |cur_exp| into a \&{setbounds} or clipping path and add...@>=
23481 { p=mp_new_bounds_node(mp, mp->cur_exp,m);
23482   mp_link(p)=mp_link(dummy_loc(lhe));
23483   mp_link(dummy_loc(lhe))=p;
23484   if ( obj_tail(lhe)==dummy_loc(lhe) ) obj_tail(lhe)=p;
23485   p=mp_get_node(mp, mp->gr_object_size[stop_type(m)]);
23486   mp_type(p)=stop_type(m);
23487   mp_link(obj_tail(lhe))=p;
23488   obj_tail(lhe)=p;
23489   mp_init_bbox(mp, lhe);
23490 }
23491
23492 @ The |do_add_to| procedure is a little like |do_clip| but there are a lot more
23493 cases to deal with.
23494
23495 @<Declare action procedures for use by |do_statement|@>=
23496 static void mp_do_add_to (MP mp) ;
23497
23498 @ @c void mp_do_add_to (MP mp) {
23499   pointer lhv,lhe; /* variable on left, the corresponding edge structure */
23500   pointer p; /* the graphical object or list for |scan_with_list| to update */
23501   pointer e; /* an edge structure to be merged */
23502   quarterword add_type; /* |also_code|, |contour_code|, or |double_path_code| */
23503   lhv=mp_start_draw_cmd(mp, thing_to_add); add_type=mp->last_add_type;
23504   if ( lhv!=null ) {
23505     if ( add_type==also_code ) {
23506       @<Make sure the current expression is a suitable picture and set |e| and |p|
23507        appropriately@>;
23508     } else {
23509       @<Create a graphical object |p| based on |add_type| and the current
23510         expression@>;
23511     }
23512     mp_scan_with_list(mp, p);
23513     @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>;
23514   }
23515 }
23516
23517 @ Setting |p:=null| causes the $\langle$with list$\rangle$ to be ignored;
23518 setting |e:=null| prevents anything from being added to |lhe|.
23519
23520 @ @<Make sure the current expression is a suitable picture and set |e|...@>=
23521
23522   p=null; e=null;
23523   if ( mp->cur_type!=mp_picture_type ) {
23524     exp_err("Improper `addto'");
23525 @.Improper `addto'@>
23526     help2("This expression should have specified a known picture.",
23527           "So I'll not change anything just now."); 
23528     mp_put_get_flush_error(mp, 0);
23529   } else { 
23530     e=mp_private_edges(mp, mp->cur_exp); mp->cur_type=mp_vacuous;
23531     p=mp_link(dummy_loc(e));
23532   }
23533 }
23534
23535 @ In this case |add_type<>also_code| so setting |p:=null| suppresses future
23536 attempts to add to the edge structure.
23537
23538 @<Create a graphical object |p| based on |add_type| and the current...@>=
23539 { e=null; p=null;
23540   if ( mp->cur_type==mp_pair_type ) mp_pair_to_path(mp);
23541   if ( mp->cur_type!=mp_path_type ) {
23542     exp_err("Improper `addto'");
23543 @.Improper `addto'@>
23544     help2("This expression should have specified a known path.",
23545           "So I'll not change anything just now."); 
23546     mp_put_get_flush_error(mp, 0);
23547   } else if ( add_type==contour_code ) {
23548     if ( mp_left_type(mp->cur_exp)==mp_endpoint ) {
23549       @<Complain about a non-cycle@>;
23550     } else { 
23551       p=mp_new_fill_node(mp, mp->cur_exp);
23552       mp->cur_type=mp_vacuous;
23553     }
23554   } else { 
23555     p=mp_new_stroked_node(mp, mp->cur_exp);
23556     mp->cur_type=mp_vacuous;
23557   }
23558 }
23559
23560 @ @<Use |p|, |e|, and |add_type| to augment |lhv| as requested@>=
23561 lhe=mp_find_edges_var(mp, lhv);
23562 if ( lhe==null ) {
23563   if ( (e==null)&&(p!=null) ) e=mp_toss_gr_object(mp, p);
23564   if ( e!=null ) delete_edge_ref(e);
23565 } else if ( add_type==also_code ) {
23566   if ( e!=null ) {
23567     @<Merge |e| into |lhe| and delete |e|@>;
23568   } else { 
23569     do_nothing;
23570   }
23571 } else if ( p!=null ) {
23572   mp_link(obj_tail(lhe))=p;
23573   obj_tail(lhe)=p;
23574   if ( add_type==double_path_code )
23575     if ( mp_pen_p(p)==null ) 
23576       mp_pen_p(p)=mp_get_pen_circle(mp, 0);
23577 }
23578
23579 @ @<Merge |e| into |lhe| and delete |e|@>=
23580 { if ( mp_link(dummy_loc(e))!=null ) {
23581     mp_link(obj_tail(lhe))=mp_link(dummy_loc(e));
23582     obj_tail(lhe)=obj_tail(e);
23583     obj_tail(e)=dummy_loc(e);
23584     mp_link(dummy_loc(e))=null;
23585     mp_flush_dash_list(mp, lhe);
23586   }
23587   mp_toss_edges(mp, e);
23588 }
23589
23590 @ @<Cases of |do_statement|...@>=
23591 case ship_out_command: mp_do_ship_out(mp); break;
23592
23593 @ @<Declare action procedures for use by |do_statement|@>=
23594 @<Declare the \ps\ output procedures@>
23595 static void mp_do_ship_out (MP mp) ;
23596
23597 @ @c void mp_do_ship_out (MP mp) {
23598   integer c; /* the character code */
23599   mp_get_x_next(mp); mp_scan_expression(mp);
23600   if ( mp->cur_type!=mp_picture_type ) {
23601     @<Complain that it's not a known picture@>;
23602   } else { 
23603     c=mp_round_unscaled(mp, mp->internal[mp_char_code]) % 256;
23604     if ( c<0 ) c=c+256;
23605     @<Store the width information for character code~|c|@>;
23606     mp_ship_out(mp, mp->cur_exp);
23607     mp_flush_cur_exp(mp, 0);
23608   }
23609 }
23610
23611 @ @<Complain that it's not a known picture@>=
23612
23613   exp_err("Not a known picture");
23614   help1("I can only output known pictures.");
23615   mp_put_get_flush_error(mp, 0);
23616 }
23617
23618 @ The \&{everyjob} command simply assigns a nonzero value to the global variable
23619 |start_sym|.
23620
23621 @<Cases of |do_statement|...@>=
23622 case every_job_command: 
23623   mp_get_symbol(mp); mp->start_sym=mp->cur_sym; mp_get_x_next(mp);
23624   break;
23625
23626 @ @<Glob...@>=
23627 halfword start_sym; /* a symbolic token to insert at beginning of job */
23628
23629 @ @<Set init...@>=
23630 mp->start_sym=0;
23631
23632 @ Finally, we have only the ``message'' commands remaining.
23633
23634 @d message_code 0
23635 @d err_message_code 1
23636 @d err_help_code 2
23637 @d filename_template_code 3
23638 @d print_with_leading_zeroes(A)  g = mp->pool_ptr;
23639               mp_print_int(mp, (A)); g = mp->pool_ptr-g;
23640               if ( f>g ) {
23641                 mp->pool_ptr = mp->pool_ptr - g;
23642                 while ( f>g ) {
23643                   mp_print_char(mp, xord('0'));
23644                   decr(f);
23645                   };
23646                 mp_print_int(mp, (A));
23647               };
23648               f = 0
23649
23650 @<Put each...@>=
23651 mp_primitive(mp, "message",message_command,message_code);
23652 @:message_}{\&{message} primitive@>
23653 mp_primitive(mp, "errmessage",message_command,err_message_code);
23654 @:err_message_}{\&{errmessage} primitive@>
23655 mp_primitive(mp, "errhelp",message_command,err_help_code);
23656 @:err_help_}{\&{errhelp} primitive@>
23657 mp_primitive(mp, "filenametemplate",message_command,filename_template_code);
23658 @:filename_template_}{\&{filenametemplate} primitive@>
23659
23660 @ @<Cases of |print_cmd...@>=
23661 case message_command: 
23662   if ( m<err_message_code ) mp_print(mp, "message");
23663   else if ( m==err_message_code ) mp_print(mp, "errmessage");
23664   else if ( m==filename_template_code ) mp_print(mp, "filenametemplate");
23665   else mp_print(mp, "errhelp");
23666   break;
23667
23668 @ @<Cases of |do_statement|...@>=
23669 case message_command: mp_do_message(mp); break;
23670
23671 @ @<Declare action procedures for use by |do_statement|@>=
23672 @<Declare a procedure called |no_string_err|@>
23673 static void mp_do_message (MP mp) ;
23674
23675
23676 @c void mp_do_message (MP mp) {
23677   int m; /* the type of message */
23678   m=mp->cur_mod; mp_get_x_next(mp); mp_scan_expression(mp);
23679   if ( mp->cur_type!=mp_string_type )
23680     mp_no_string_err(mp, "A message should be a known string expression.");
23681   else {
23682     switch (m) {
23683     case message_code: 
23684       mp_print_nl(mp, ""); mp_print_str(mp, mp->cur_exp);
23685       break;
23686     case err_message_code:
23687       @<Print string |cur_exp| as an error message@>;
23688       break;
23689     case err_help_code:
23690       @<Save string |cur_exp| as the |err_help|@>;
23691       break;
23692     case filename_template_code:
23693       @<Save the filename template@>;
23694       break;
23695     } /* there are no other cases */
23696   }
23697   mp_flush_cur_exp(mp, 0);
23698 }
23699
23700 @ @<Declare a procedure called |no_string_err|@>=
23701 static void mp_no_string_err (MP mp, const char *s) { 
23702    exp_err("Not a string");
23703 @.Not a string@>
23704   help1(s);
23705   mp_put_get_error(mp);
23706 }
23707
23708 @ The global variable |err_help| is zero when the user has most recently
23709 given an empty help string, or if none has ever been given.
23710
23711 @<Save string |cur_exp| as the |err_help|@>=
23712
23713   if ( mp->err_help!=0 ) delete_str_ref(mp->err_help);
23714   if ( length(mp->cur_exp)==0 ) mp->err_help=0;
23715   else  { mp->err_help=mp->cur_exp; add_str_ref(mp->err_help); }
23716 }
23717
23718 @ If \&{errmessage} occurs often in |mp_scroll_mode|, without user-defined
23719 \&{errhelp}, we don't want to give a long help message each time. So we
23720 give a verbose explanation only once.
23721
23722 @<Glob...@>=
23723 boolean long_help_seen; /* has the long \.{\\errmessage} help been used? */
23724
23725 @ @<Set init...@>=mp->long_help_seen=false;
23726
23727 @ @<Print string |cur_exp| as an error message@>=
23728
23729   print_err(""); mp_print_str(mp, mp->cur_exp);
23730   if ( mp->err_help!=0 ) {
23731     mp->use_err_help=true;
23732   } else if ( mp->long_help_seen ) { 
23733     help1("(That was another `errmessage'.)") ; 
23734   } else  { 
23735    if ( mp->interaction<mp_error_stop_mode ) mp->long_help_seen=true;
23736     help4("This error message was generated by an `errmessage'",
23737      "command, so I can\'t give any explicit help.",
23738      "Pretend that you're Miss Marple: Examine all clues,",
23739 @^Marple, Jane@>
23740      "and deduce the truth by inspired guesses.");
23741   }
23742   mp_put_get_error(mp); mp->use_err_help=false;
23743 }
23744
23745 @ @<Cases of |do_statement|...@>=
23746 case write_command: mp_do_write(mp); break;
23747
23748 @ @<Declare action procedures for use by |do_statement|@>=
23749 static void mp_do_write (MP mp) ;
23750
23751 @ @c void mp_do_write (MP mp) {
23752   str_number t; /* the line of text to be written */
23753   write_index n,n0; /* for searching |wr_fname| and |wr_file| arrays */
23754   unsigned old_setting; /* for saving |selector| during output */
23755   mp_get_x_next(mp);
23756   mp_scan_expression(mp);
23757   if ( mp->cur_type!=mp_string_type ) {
23758     mp_no_string_err(mp, "The text to be written should be a known string expression");
23759   } else if ( mp->cur_cmd!=to_token ) { 
23760     print_err("Missing `to' clause");
23761     help1("A write command should end with `to <filename>'");
23762     mp_put_get_error(mp);
23763   } else { 
23764     t=mp->cur_exp; mp->cur_type=mp_vacuous;
23765     mp_get_x_next(mp);
23766     mp_scan_expression(mp);
23767     if ( mp->cur_type!=mp_string_type )
23768       mp_no_string_err(mp, "I can\'t write to that file name.  It isn't a known string");
23769     else {
23770       @<Write |t| to the file named by |cur_exp|@>;
23771     }
23772     delete_str_ref(t);
23773   }
23774   mp_flush_cur_exp(mp, 0);
23775 }
23776
23777 @ @<Write |t| to the file named by |cur_exp|@>=
23778
23779   @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if
23780     |cur_exp| must be inserted@>;
23781   if ( mp_str_vs_str(mp, t,mp->eof_line)==0 ) {
23782     @<Record the end of file on |wr_file[n]|@>;
23783   } else { 
23784     old_setting=mp->selector;
23785     mp->selector=n+write_file;
23786     mp_print_str(mp, t); mp_print_ln(mp);
23787     mp->selector = old_setting;
23788   }
23789 }
23790
23791 @ @<Find |n| where |wr_fname[n]=cur_exp| and call |open_write_file| if...@>=
23792 {
23793   char *fn = str(mp->cur_exp);
23794   n=mp->write_files;
23795   n0=mp->write_files;
23796   while (mp_xstrcmp(fn,mp->wr_fname[n])!=0) { 
23797     if ( n==0 ) { /* bottom reached */
23798           if ( n0==mp->write_files ) {
23799         if ( mp->write_files<mp->max_write_files ) {
23800           incr(mp->write_files);
23801         } else {
23802           void **wr_file;
23803           char **wr_fname;
23804               write_index l,k;
23805           l = mp->max_write_files + (mp->max_write_files/4);
23806           wr_file = xmalloc((l+1),sizeof(void *));
23807           wr_fname = xmalloc((l+1),sizeof(char *));
23808               for (k=0;k<=l;k++) {
23809             if (k<=mp->max_write_files) {
23810                   wr_file[k]=mp->wr_file[k]; 
23811               wr_fname[k]=mp->wr_fname[k];
23812             } else {
23813                   wr_file[k]=0; 
23814               wr_fname[k]=NULL;
23815             }
23816           }
23817               xfree(mp->wr_file); xfree(mp->wr_fname);
23818           mp->max_write_files = l;
23819           mp->wr_file = wr_file;
23820           mp->wr_fname = wr_fname;
23821         }
23822       }
23823       n=n0;
23824       mp_open_write_file(mp, fn ,n);
23825     } else { 
23826       decr(n);
23827           if ( mp->wr_fname[n]==NULL )  n0=n; 
23828     }
23829   }
23830 }
23831
23832 @ @<Record the end of file on |wr_file[n]|@>=
23833 { (mp->close_file)(mp,mp->wr_file[n]);
23834   xfree(mp->wr_fname[n]);
23835   if ( n==mp->write_files-1 ) mp->write_files=n;
23836 }
23837
23838
23839 @* \[42] Writing font metric data.
23840 \TeX\ gets its knowledge about fonts from font metric files, also called
23841 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
23842 but other programs know about them too. One of \MP's duties is to
23843 write \.{TFM} files so that the user's fonts can readily be
23844 applied to typesetting.
23845 @:TFM files}{\.{TFM} files@>
23846 @^font metric files@>
23847
23848 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
23849 Since the number of bytes is always a multiple of~4, we could
23850 also regard the file as a sequence of 32-bit words, but \MP\ uses the
23851 byte interpretation. The format of \.{TFM} files was designed by
23852 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
23853 @^Ramshaw, Lyle Harold@>
23854 of information in a compact but useful form.
23855
23856 @<Glob...@>=
23857 void * tfm_file; /* the font metric output goes here */
23858 char * metric_file_name; /* full name of the font metric file */
23859
23860 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
23861 integers that give the lengths of the various subsequent portions
23862 of the file. These twelve integers are, in order:
23863 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
23864 |lf|&length of the entire file, in words;\cr
23865 |lh|&length of the header data, in words;\cr
23866 |bc|&smallest character code in the font;\cr
23867 |ec|&largest character code in the font;\cr
23868 |nw|&number of words in the width table;\cr
23869 |nh|&number of words in the height table;\cr
23870 |nd|&number of words in the depth table;\cr
23871 |ni|&number of words in the italic correction table;\cr
23872 |nl|&number of words in the lig/kern table;\cr
23873 |nk|&number of words in the kern table;\cr
23874 |ne|&number of words in the extensible character table;\cr
23875 |np|&number of font parameter words.\cr}}$$
23876 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
23877 |ne<=256|, and
23878 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
23879 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
23880 and as few as 0 characters (if |bc=ec+1|).
23881
23882 Incidentally, when two or more 8-bit bytes are combined to form an integer of
23883 16 or more bits, the most significant bytes appear first in the file.
23884 This is called BigEndian order.
23885 @^BigEndian order@>
23886
23887 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
23888 arrays.
23889
23890 The most important data type used here is a |fix_word|, which is
23891 a 32-bit representation of a binary fraction. A |fix_word| is a signed
23892 quantity, with the two's complement of the entire word used to represent
23893 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
23894 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
23895 the smallest is $-2048$. We will see below, however, that all but two of
23896 the |fix_word| values must lie between $-16$ and $+16$.
23897
23898 @ The first data array is a block of header information, which contains
23899 general facts about the font. The header must contain at least two words,
23900 |header[0]| and |header[1]|, whose meaning is explained below.  Additional
23901 header information of use to other software routines might also be
23902 included, and \MP\ will generate it if the \.{headerbyte} command occurs.
23903 For example, 16 more words of header information are in use at the Xerox
23904 Palo Alto Research Center; the first ten specify the character coding
23905 scheme used (e.g., `\.{XEROX TEXT}' or `\.{TEX MATHSY}'), the next five
23906 give the font family name (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
23907 last gives the ``face byte.''
23908
23909 \yskip\hang|header[0]| is a 32-bit check sum that \MP\ will copy into
23910 the \.{GF} output file. This helps ensure consistency between files,
23911 since \TeX\ records the check sums from the \.{TFM}'s it reads, and these
23912 should match the check sums on actual fonts that are used.  The actual
23913 relation between this check sum and the rest of the \.{TFM} file is not
23914 important; the check sum is simply an identification number with the
23915 property that incompatible fonts almost always have distinct check sums.
23916 @^check sum@>
23917
23918 \yskip\hang|header[1]| is a |fix_word| containing the design size of the
23919 font, in units of \TeX\ points. This number must be at least 1.0; it is
23920 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
23921 font, i.e., a font that was designed to look best at a 10-point size,
23922 whatever that really means. When a \TeX\ user asks for a font `\.{at}
23923 $\delta$ \.{pt}', the effect is to override the design size and replace it
23924 by $\delta$, and to multiply the $x$ and~$y$ coordinates of the points in
23925 the font image by a factor of $\delta$ divided by the design size.  {\sl
23926 All other dimensions in the\/ \.{TFM} file are |fix_word|\kern-1pt\
23927 numbers in design-size units.} Thus, for example, the value of |param[6]|,
23928 which defines the \.{em} unit, is often the |fix_word| value $2^{20}=1.0$,
23929 since many fonts have a design size equal to one em.  The other dimensions
23930 must be less than 16 design-size units in absolute value; thus,
23931 |header[1]| and |param[1]| are the only |fix_word| entries in the whole
23932 \.{TFM} file whose first byte might be something besides 0 or 255.
23933 @^design size@>
23934
23935 @ Next comes the |char_info| array, which contains one |char_info_word|
23936 per character. Each word in this part of the file contains six fields
23937 packed into four bytes as follows.
23938
23939 \yskip\hang first byte: |width_index| (8 bits)\par
23940 \hang second byte: |height_index| (4 bits) times 16, plus |depth_index|
23941   (4~bits)\par
23942 \hang third byte: |italic_index| (6 bits) times 4, plus |tag|
23943   (2~bits)\par
23944 \hang fourth byte: |remainder| (8 bits)\par
23945 \yskip\noindent
23946 The actual width of a character is \\{width}|[width_index]|, in design-size
23947 units; this is a device for compressing information, since many characters
23948 have the same width. Since it is quite common for many characters
23949 to have the same height, depth, or italic correction, the \.{TFM} format
23950 imposes a limit of 16 different heights, 16 different depths, and
23951 64 different italic corrections.
23952
23953 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
23954 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
23955 value of zero.  The |width_index| should never be zero unless the
23956 character does not exist in the font, since a character is valid if and
23957 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
23958
23959 @ The |tag| field in a |char_info_word| has four values that explain how to
23960 interpret the |remainder| field.
23961
23962 \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
23963 \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
23964 program starting at location |remainder| in the |lig_kern| array.\par
23965 \hang|tag=2| (|list_tag|) means that this character is part of a chain of
23966 characters of ascending sizes, and not the largest in the chain.  The
23967 |remainder| field gives the character code of the next larger character.\par
23968 \hang|tag=3| (|ext_tag|) means that this character code represents an
23969 extensible character, i.e., a character that is built up of smaller pieces
23970 so that it can be made arbitrarily large. The pieces are specified in
23971 |exten[remainder]|.\par
23972 \yskip\noindent
23973 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
23974 unless they are used in special circumstances in math formulas. For example,
23975 \TeX's \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
23976 operation looks for both |list_tag| and |ext_tag|.
23977
23978 @d no_tag 0 /* vanilla character */
23979 @d lig_tag 1 /* character has a ligature/kerning program */
23980 @d list_tag 2 /* character has a successor in a charlist */
23981 @d ext_tag 3 /* character is extensible */
23982
23983 @ The |lig_kern| array contains instructions in a simple programming language
23984 that explains what to do for special letter pairs. Each word in this array is a
23985 |lig_kern_command| of four bytes.
23986
23987 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
23988   step if the byte is 128 or more, otherwise the next step is obtained by
23989   skipping this number of intervening steps.\par
23990 \hang second byte: |next_char|, ``if |next_char| follows the current character,
23991   then perform the operation and stop, otherwise continue.''\par
23992 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
23993   a kern step otherwise.\par
23994 \hang fourth byte: |remainder|.\par
23995 \yskip\noindent
23996 In a kern step, an
23997 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
23998 between the current character and |next_char|. This amount is
23999 often negative, so that the characters are brought closer together
24000 by kerning; but it might be positive.
24001
24002 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
24003 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
24004 |remainder| is inserted between the current character and |next_char|;
24005 then the current character is deleted if $b=0$, and |next_char| is
24006 deleted if $c=0$; then we pass over $a$~characters to reach the next
24007 current character (which may have a ligature/kerning program of its own).
24008
24009 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
24010 the |next_char| byte is the so-called right boundary character of this font;
24011 the value of |next_char| need not lie between |bc| and~|ec|.
24012 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
24013 there is a special ligature/kerning program for a left boundary character,
24014 beginning at location |256*op_byte+remainder|.
24015 The interpretation is that \TeX\ puts implicit boundary characters
24016 before and after each consecutive string of characters from the same font.
24017 These implicit characters do not appear in the output, but they can affect
24018 ligatures and kerning.
24019
24020 If the very first instruction of a character's |lig_kern| program has
24021 |skip_byte>128|, the program actually begins in location
24022 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
24023 arrays, because the first instruction must otherwise
24024 appear in a location |<=255|.
24025
24026 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
24027 the condition
24028 $$\hbox{|256*op_byte+remainder<nl|.}$$
24029 If such an instruction is encountered during
24030 normal program execution, it denotes an unconditional halt; no ligature
24031 command is performed.
24032
24033 @d stop_flag (128)
24034   /* value indicating `\.{STOP}' in a lig/kern program */
24035 @d kern_flag (128) /* op code for a kern step */
24036 @d skip_byte(A) mp->lig_kern[(A)].b0
24037 @d next_char(A) mp->lig_kern[(A)].b1
24038 @d op_byte(A) mp->lig_kern[(A)].b2
24039 @d rem_byte(A) mp->lig_kern[(A)].b3
24040
24041 @ Extensible characters are specified by an |extensible_recipe|, which
24042 consists of four bytes called |top|, |mid|, |bot|, and |rep| (in this
24043 order). These bytes are the character codes of individual pieces used to
24044 build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
24045 present in the built-up result. For example, an extensible vertical line is
24046 like an extensible bracket, except that the top and bottom pieces are missing.
24047
24048 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
24049 if the piece isn't present. Then the extensible characters have the form
24050 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
24051 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
24052 The width of the extensible character is the width of $R$; and the
24053 height-plus-depth is the sum of the individual height-plus-depths of the
24054 components used, since the pieces are butted together in a vertical list.
24055
24056 @d ext_top(A) mp->exten[(A)].b0 /* |top| piece in a recipe */
24057 @d ext_mid(A) mp->exten[(A)].b1 /* |mid| piece in a recipe */
24058 @d ext_bot(A) mp->exten[(A)].b2 /* |bot| piece in a recipe */
24059 @d ext_rep(A) mp->exten[(A)].b3 /* |rep| piece in a recipe */
24060
24061 @ The final portion of a \.{TFM} file is the |param| array, which is another
24062 sequence of |fix_word| values.
24063
24064 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
24065 to help position accents. For example, |slant=.25| means that when you go
24066 up one unit, you also go .25 units to the right. The |slant| is a pure
24067 number; it is the only |fix_word| other than the design size itself that is
24068 not scaled by the design size.
24069 @^design size@>
24070
24071 \hang|param[2]=space| is the normal spacing between words in text.
24072 Note that character 040 in the font need not have anything to do with
24073 blank spaces.
24074
24075 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
24076
24077 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
24078
24079 \hang|param[5]=x_height| is the size of one ex in the font; it is also
24080 the height of letters for which accents don't have to be raised or lowered.
24081
24082 \hang|param[6]=quad| is the size of one em in the font.
24083
24084 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
24085 ends of sentences.
24086
24087 \yskip\noindent
24088 If fewer than seven parameters are present, \TeX\ sets the missing parameters
24089 to zero.
24090
24091 @d slant_code 1
24092 @d space_code 2
24093 @d space_stretch_code 3
24094 @d space_shrink_code 4
24095 @d x_height_code 5
24096 @d quad_code 6
24097 @d extra_space_code 7
24098
24099 @ So that is what \.{TFM} files hold. One of \MP's duties is to output such
24100 information, and it does this all at once at the end of a job.
24101 In order to prepare for such frenetic activity, it squirrels away the
24102 necessary facts in various arrays as information becomes available.
24103
24104 Character dimensions (\&{charwd}, \&{charht}, \&{chardp}, and \&{charic})
24105 are stored respectively in |tfm_width|, |tfm_height|, |tfm_depth|, and
24106 |tfm_ital_corr|. Other information about a character (e.g., about
24107 its ligatures or successors) is accessible via the |char_tag| and
24108 |char_remainder| arrays. Other information about the font as a whole
24109 is kept in additional arrays called |header_byte|, |lig_kern|,
24110 |kern|, |exten|, and |param|.
24111
24112 @d max_tfm_int 32510
24113 @d undefined_label max_tfm_int /* an undefined local label */
24114
24115 @<Glob...@>=
24116 #define TFM_ITEMS 257
24117 eight_bits bc;
24118 eight_bits ec; /* smallest and largest character codes shipped out */
24119 scaled tfm_width[TFM_ITEMS]; /* \&{charwd} values */
24120 scaled tfm_height[TFM_ITEMS]; /* \&{charht} values */
24121 scaled tfm_depth[TFM_ITEMS]; /* \&{chardp} values */
24122 scaled tfm_ital_corr[TFM_ITEMS]; /* \&{charic} values */
24123 boolean char_exists[TFM_ITEMS]; /* has this code been shipped out? */
24124 int char_tag[TFM_ITEMS]; /* |remainder| category */
24125 int char_remainder[TFM_ITEMS]; /* the |remainder| byte */
24126 char *header_byte; /* bytes of the \.{TFM} header */
24127 int header_last; /* last initialized \.{TFM} header byte */
24128 int header_size; /* size of the \.{TFM} header */
24129 four_quarters *lig_kern; /* the ligature/kern table */
24130 short nl; /* the number of ligature/kern steps so far */
24131 scaled *kern; /* distinct kerning amounts */
24132 short nk; /* the number of distinct kerns so far */
24133 four_quarters exten[TFM_ITEMS]; /* extensible character recipes */
24134 short ne; /* the number of extensible characters so far */
24135 scaled *param; /* \&{fontinfo} parameters */
24136 short np; /* the largest \&{fontinfo} parameter specified so far */
24137 short nw;short nh;short nd;short ni; /* sizes of \.{TFM} subtables */
24138 short skip_table[TFM_ITEMS]; /* local label status */
24139 boolean lk_started; /* has there been a lig/kern step in this command yet? */
24140 integer bchar; /* right boundary character */
24141 short bch_label; /* left boundary starting location */
24142 short ll;short lll; /* registers used for lig/kern processing */
24143 short label_loc[257]; /* lig/kern starting addresses */
24144 eight_bits label_char[257]; /* characters for |label_loc| */
24145 short label_ptr; /* highest position occupied in |label_loc| */
24146
24147 @ @<Allocate or initialize ...@>=
24148 mp->header_size = 128; /* just for init */
24149 mp->header_byte = xmalloc(mp->header_size, sizeof(char));
24150
24151 @ @<Dealloc variables@>=
24152 xfree(mp->header_byte);
24153 xfree(mp->lig_kern);
24154 xfree(mp->kern);
24155 xfree(mp->param);
24156
24157 @ @<Set init...@>=
24158 for (k=0;k<= 255;k++ ) {
24159   mp->tfm_width[k]=0; mp->tfm_height[k]=0; mp->tfm_depth[k]=0; mp->tfm_ital_corr[k]=0;
24160   mp->char_exists[k]=false; mp->char_tag[k]=no_tag; mp->char_remainder[k]=0;
24161   mp->skip_table[k]=undefined_label;
24162 }
24163 memset(mp->header_byte,0,(size_t)mp->header_size);
24164 mp->bc=255; mp->ec=0; mp->nl=0; mp->nk=0; mp->ne=0; mp->np=0;
24165 mp->internal[mp_boundary_char]=-unity;
24166 mp->bch_label=undefined_label;
24167 mp->label_loc[0]=-1; mp->label_ptr=0;
24168
24169 @ @<Declarations@>=
24170 static scaled mp_tfm_check (MP mp,quarterword m) ;
24171
24172 @ @c
24173 static scaled mp_tfm_check (MP mp,quarterword m) {
24174   if ( abs(mp->internal[m])>=fraction_half ) {
24175     print_err("Enormous "); mp_print(mp, mp->int_name[m]);
24176 @.Enormous charwd...@>
24177 @.Enormous chardp...@>
24178 @.Enormous charht...@>
24179 @.Enormous charic...@>
24180 @.Enormous designsize...@>
24181     mp_print(mp, " has been reduced");
24182     help1("Font metric dimensions must be less than 2048pt.");
24183     mp_put_get_error(mp);
24184     if ( mp->internal[m]>0 ) return (fraction_half-1);
24185     else return (1-fraction_half);
24186   } else {
24187     return mp->internal[m];
24188   }
24189 }
24190
24191 @ @<Store the width information for character code~|c|@>=
24192 if ( c<mp->bc ) mp->bc=(eight_bits)c;
24193 if ( c>mp->ec ) mp->ec=(eight_bits)c;
24194 mp->char_exists[c]=true;
24195 mp->tfm_width[c]=mp_tfm_check(mp,mp_char_wd);
24196 mp->tfm_height[c]=mp_tfm_check(mp, mp_char_ht);
24197 mp->tfm_depth[c]=mp_tfm_check(mp, mp_char_dp);
24198 mp->tfm_ital_corr[c]=mp_tfm_check(mp, mp_char_ic)
24199
24200 @ Now let's consider \MP's special \.{TFM}-oriented commands.
24201
24202 @<Cases of |do_statement|...@>=
24203 case tfm_command: mp_do_tfm_command(mp); break;
24204
24205 @ @d char_list_code 0
24206 @d lig_table_code 1
24207 @d extensible_code 2
24208 @d header_byte_code 3
24209 @d font_dimen_code 4
24210
24211 @<Put each...@>=
24212 mp_primitive(mp, "charlist",tfm_command,char_list_code);
24213 @:char_list_}{\&{charlist} primitive@>
24214 mp_primitive(mp, "ligtable",tfm_command,lig_table_code);
24215 @:lig_table_}{\&{ligtable} primitive@>
24216 mp_primitive(mp, "extensible",tfm_command,extensible_code);
24217 @:extensible_}{\&{extensible} primitive@>
24218 mp_primitive(mp, "headerbyte",tfm_command,header_byte_code);
24219 @:header_byte_}{\&{headerbyte} primitive@>
24220 mp_primitive(mp, "fontdimen",tfm_command,font_dimen_code);
24221 @:font_dimen_}{\&{fontdimen} primitive@>
24222
24223 @ @<Cases of |print_cmd...@>=
24224 case tfm_command: 
24225   switch (m) {
24226   case char_list_code:mp_print(mp, "charlist"); break;
24227   case lig_table_code:mp_print(mp, "ligtable"); break;
24228   case extensible_code:mp_print(mp, "extensible"); break;
24229   case header_byte_code:mp_print(mp, "headerbyte"); break;
24230   default: mp_print(mp, "fontdimen"); break;
24231   }
24232   break;
24233
24234 @ @<Declare action procedures for use by |do_statement|@>=
24235 static eight_bits mp_get_code (MP mp) ;
24236
24237 @ @c eight_bits mp_get_code (MP mp) { /* scans a character code value */
24238   integer c; /* the code value found */
24239   mp_get_x_next(mp); mp_scan_expression(mp);
24240   if ( mp->cur_type==mp_known ) { 
24241     c=mp_round_unscaled(mp, mp->cur_exp);
24242     if ( c>=0 ) if ( c<256 ) return (eight_bits)c;
24243   } else if ( mp->cur_type==mp_string_type ) {
24244     if ( length(mp->cur_exp)==1 )  { 
24245       c=mp->str_pool[mp->str_start[mp->cur_exp]];
24246       return (eight_bits)c;
24247     }
24248   }
24249   exp_err("Invalid code has been replaced by 0");
24250 @.Invalid code...@>
24251   help2("I was looking for a number between 0 and 255, or for a",
24252         "string of length 1. Didn't find it; will use 0 instead.");
24253   mp_put_get_flush_error(mp, 0); c=0;
24254   return (eight_bits)c;
24255 }
24256
24257 @ @<Declare action procedures for use by |do_statement|@>=
24258 static void mp_set_tag (MP mp,halfword c, quarterword t, halfword r) ;
24259
24260 @ @c void mp_set_tag (MP mp,halfword c, quarterword t, halfword r) { 
24261   if ( mp->char_tag[c]==no_tag ) {
24262     mp->char_tag[c]=t; mp->char_remainder[c]=r;
24263     if ( t==lig_tag ){ 
24264       incr(mp->label_ptr); mp->label_loc[mp->label_ptr]=r; 
24265       mp->label_char[mp->label_ptr]=(eight_bits)c;
24266     }
24267   } else {
24268     @<Complain about a character tag conflict@>;
24269   }
24270 }
24271
24272 @ @<Complain about a character tag conflict@>=
24273
24274   print_err("Character ");
24275   if ( (c>' ')&&(c<127) ) mp_print_char(mp,xord(c));
24276   else if ( c==256 ) mp_print(mp, "||");
24277   else  { mp_print(mp, "code "); mp_print_int(mp, c); };
24278   mp_print(mp, " is already ");
24279 @.Character c is already...@>
24280   switch (mp->char_tag[c]) {
24281   case lig_tag: mp_print(mp, "in a ligtable"); break;
24282   case list_tag: mp_print(mp, "in a charlist"); break;
24283   case ext_tag: mp_print(mp, "extensible"); break;
24284   } /* there are no other cases */
24285   help2("It's not legal to label a character more than once.",
24286         "So I'll not change anything just now.");
24287   mp_put_get_error(mp); 
24288 }
24289
24290 @ @<Declare action procedures for use by |do_statement|@>=
24291 static void mp_do_tfm_command (MP mp) ;
24292
24293 @ @c void mp_do_tfm_command (MP mp) {
24294   int c,cc; /* character codes */
24295   int k; /* index into the |kern| array */
24296   int j; /* index into |header_byte| or |param| */
24297   switch (mp->cur_mod) {
24298   case char_list_code: 
24299     c=mp_get_code(mp);
24300      /* we will store a list of character successors */
24301     while ( mp->cur_cmd==colon )   { 
24302       cc=mp_get_code(mp); mp_set_tag(mp, c,list_tag,cc); c=cc;
24303     };
24304     break;
24305   case lig_table_code: 
24306     if (mp->lig_kern==NULL) 
24307        mp->lig_kern = xmalloc((max_tfm_int+1),sizeof(four_quarters));
24308     if (mp->kern==NULL) 
24309        mp->kern = xmalloc((max_tfm_int+1),sizeof(scaled));
24310     @<Store a list of ligature/kern steps@>;
24311     break;
24312   case extensible_code: 
24313     @<Define an extensible recipe@>;
24314     break;
24315   case header_byte_code: 
24316   case font_dimen_code: 
24317     c=mp->cur_mod; mp_get_x_next(mp);
24318     mp_scan_expression(mp);
24319     if ( (mp->cur_type!=mp_known)||(mp->cur_exp<half_unit) ) {
24320       exp_err("Improper location");
24321 @.Improper location@>
24322       help2("I was looking for a known, positive number.",
24323             "For safety's sake I'll ignore the present command.");
24324       mp_put_get_error(mp);
24325     } else  { 
24326       j=mp_round_unscaled(mp, mp->cur_exp);
24327       if ( mp->cur_cmd!=colon ) {
24328         mp_missing_err(mp, ":");
24329 @.Missing `:'@>
24330         help1("A colon should follow a headerbyte or fontinfo location.");
24331         mp_back_error(mp);
24332       }
24333       if ( c==header_byte_code ) { 
24334         @<Store a list of header bytes@>;
24335       } else {     
24336         if (mp->param==NULL) 
24337           mp->param = xmalloc((max_tfm_int+1),sizeof(scaled));
24338         @<Store a list of font dimensions@>;
24339       }
24340     }
24341     break;
24342   } /* there are no other cases */
24343 }
24344
24345 @ @<Store a list of ligature/kern steps@>=
24346
24347   mp->lk_started=false;
24348 CONTINUE: 
24349   mp_get_x_next(mp);
24350   if ((mp->cur_cmd==skip_to)&& mp->lk_started )
24351     @<Process a |skip_to| command and |goto done|@>;
24352   if ( mp->cur_cmd==bchar_label ) { c=256; mp->cur_cmd=colon; }
24353   else { mp_back_input(mp); c=mp_get_code(mp); };
24354   if ((mp->cur_cmd==colon)||(mp->cur_cmd==double_colon)) {
24355     @<Record a label in a lig/kern subprogram and |goto continue|@>;
24356   }
24357   if ( mp->cur_cmd==lig_kern_token ) { 
24358     @<Compile a ligature/kern command@>; 
24359   } else  { 
24360     print_err("Illegal ligtable step");
24361 @.Illegal ligtable step@>
24362     help1("I was looking for `=:' or `kern' here.");
24363     mp_back_error(mp); next_char(mp->nl)=qi(0); 
24364     op_byte(mp->nl)=qi(0); rem_byte(mp->nl)=qi(0);
24365     skip_byte(mp->nl)=stop_flag+1; /* this specifies an unconditional stop */
24366   }
24367   if ( mp->nl==max_tfm_int) mp_fatal_error(mp, "ligtable too large");
24368   incr(mp->nl);
24369   if ( mp->cur_cmd==comma ) goto CONTINUE;
24370   if ( skip_byte(mp->nl-1)<stop_flag ) skip_byte(mp->nl-1)=stop_flag;
24371 }
24372 DONE:
24373
24374 @ @<Put each...@>=
24375 mp_primitive(mp, "=:",lig_kern_token,0);
24376 @:=:_}{\.{=:} primitive@>
24377 mp_primitive(mp, "=:|",lig_kern_token,1);
24378 @:=:/_}{\.{=:\char'174} primitive@>
24379 mp_primitive(mp, "=:|>",lig_kern_token,5);
24380 @:=:/>_}{\.{=:\char'174>} primitive@>
24381 mp_primitive(mp, "|=:",lig_kern_token,2);
24382 @:=:/_}{\.{\char'174=:} primitive@>
24383 mp_primitive(mp, "|=:>",lig_kern_token,6);
24384 @:=:/>_}{\.{\char'174=:>} primitive@>
24385 mp_primitive(mp, "|=:|",lig_kern_token,3);
24386 @:=:/_}{\.{\char'174=:\char'174} primitive@>
24387 mp_primitive(mp, "|=:|>",lig_kern_token,7);
24388 @:=:/>_}{\.{\char'174=:\char'174>} primitive@>
24389 mp_primitive(mp, "|=:|>>",lig_kern_token,11);
24390 @:=:/>_}{\.{\char'174=:\char'174>>} primitive@>
24391 mp_primitive(mp, "kern",lig_kern_token,128);
24392 @:kern_}{\&{kern} primitive@>
24393
24394 @ @<Cases of |print_cmd...@>=
24395 case lig_kern_token: 
24396   switch (m) {
24397   case 0:mp_print(mp, "=:"); break;
24398   case 1:mp_print(mp, "=:|"); break;
24399   case 2:mp_print(mp, "|=:"); break;
24400   case 3:mp_print(mp, "|=:|"); break;
24401   case 5:mp_print(mp, "=:|>"); break;
24402   case 6:mp_print(mp, "|=:>"); break;
24403   case 7:mp_print(mp, "|=:|>"); break;
24404   case 11:mp_print(mp, "|=:|>>"); break;
24405   default: mp_print(mp, "kern"); break;
24406   }
24407   break;
24408
24409 @ Local labels are implemented by maintaining the |skip_table| array,
24410 where |skip_table[c]| is either |undefined_label| or the address of the
24411 most recent lig/kern instruction that skips to local label~|c|. In the
24412 latter case, the |skip_byte| in that instruction will (temporarily)
24413 be zero if there were no prior skips to this label, or it will be the
24414 distance to the prior skip.
24415
24416 We may need to cancel skips that span more than 127 lig/kern steps.
24417
24418 @d cancel_skips(A) mp->ll=(A);
24419   do {  
24420     mp->lll=qo(skip_byte(mp->ll)); 
24421     skip_byte(mp->ll)=stop_flag; mp->ll=mp->ll-mp->lll;
24422   } while (mp->lll!=0)
24423 @d skip_error(A) { print_err("Too far to skip");
24424 @.Too far to skip@>
24425   help1("At most 127 lig/kern steps can separate skipto1 from 1::.");
24426   mp_error(mp); cancel_skips((A));
24427   }
24428
24429 @<Process a |skip_to| command and |goto done|@>=
24430
24431   c=mp_get_code(mp);
24432   if ( mp->nl-mp->skip_table[c]>128 ) {
24433     skip_error(mp->skip_table[c]); mp->skip_table[c]=undefined_label;
24434   }
24435   if ( mp->skip_table[c]==undefined_label ) skip_byte(mp->nl-1)=qi(0);
24436   else skip_byte(mp->nl-1)=qi(mp->nl-mp->skip_table[c]-1);
24437   mp->skip_table[c]=mp->nl-1; goto DONE;
24438 }
24439
24440 @ @<Record a label in a lig/kern subprogram and |goto continue|@>=
24441
24442   if ( mp->cur_cmd==colon ) {
24443     if ( c==256 ) mp->bch_label=mp->nl;
24444     else mp_set_tag(mp, c,lig_tag,mp->nl);
24445   } else if ( mp->skip_table[c]<undefined_label ) {
24446     mp->ll=mp->skip_table[c]; mp->skip_table[c]=undefined_label;
24447     do {  
24448       mp->lll=qo(skip_byte(mp->ll));
24449       if ( mp->nl-mp->ll>128 ) {
24450         skip_error(mp->ll); goto CONTINUE;
24451       }
24452       skip_byte(mp->ll)=qi(mp->nl-mp->ll-1); mp->ll=mp->ll-mp->lll;
24453     } while (mp->lll!=0);
24454   }
24455   goto CONTINUE;
24456 }
24457
24458 @ @<Compile a ligature/kern...@>=
24459
24460   next_char(mp->nl)=qi(c); skip_byte(mp->nl)=qi(0);
24461   if ( mp->cur_mod<128 ) { /* ligature op */
24462     op_byte(mp->nl)=qi(mp->cur_mod); rem_byte(mp->nl)=qi(mp_get_code(mp));
24463   } else { 
24464     mp_get_x_next(mp); mp_scan_expression(mp);
24465     if ( mp->cur_type!=mp_known ) {
24466       exp_err("Improper kern");
24467 @.Improper kern@>
24468       help2("The amount of kern should be a known numeric value.",
24469             "I'm zeroing this one. Proceed, with fingers crossed.");
24470       mp_put_get_flush_error(mp, 0);
24471     }
24472     mp->kern[mp->nk]=mp->cur_exp;
24473     k=0; 
24474     while ( mp->kern[k]!=mp->cur_exp ) incr(k);
24475     if ( k==mp->nk ) {
24476       if ( mp->nk==max_tfm_int ) mp_fatal_error(mp, "too many TFM kerns");
24477       incr(mp->nk);
24478     }
24479     op_byte(mp->nl)=kern_flag+(k / 256);
24480     rem_byte(mp->nl)=qi((k % 256));
24481   }
24482   mp->lk_started=true;
24483 }
24484
24485 @ @d missing_extensible_punctuation(A) 
24486   { mp_missing_err(mp, (A));
24487 @.Missing `\char`\#'@>
24488   help1("I'm processing `extensible c: t,m,b,r'."); mp_back_error(mp);
24489   }
24490
24491 @<Define an extensible recipe@>=
24492
24493   if ( mp->ne==256 ) mp_fatal_error(mp, "too many extensible recipies");
24494   c=mp_get_code(mp); mp_set_tag(mp, c,ext_tag,mp->ne);
24495   if ( mp->cur_cmd!=colon ) missing_extensible_punctuation(":");
24496   ext_top(mp->ne)=qi(mp_get_code(mp));
24497   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24498   ext_mid(mp->ne)=qi(mp_get_code(mp));
24499   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24500   ext_bot(mp->ne)=qi(mp_get_code(mp));
24501   if ( mp->cur_cmd!=comma ) missing_extensible_punctuation(",");
24502   ext_rep(mp->ne)=qi(mp_get_code(mp));
24503   incr(mp->ne);
24504 }
24505
24506 @ The header could contain ASCII zeroes, so can't use |strdup|.
24507
24508 @<Store a list of header bytes@>=
24509 do {  
24510   if ( j>=mp->header_size ) {
24511     size_t l = (size_t)(mp->header_size + (mp->header_size/4));
24512     char *t = xmalloc(l,1);
24513     memset(t,0,l); 
24514     memcpy(t,mp->header_byte,(size_t)mp->header_size);
24515     xfree (mp->header_byte);
24516     mp->header_byte = t;
24517     mp->header_size = (int)l;
24518   }
24519   mp->header_byte[j]=(char)mp_get_code(mp); 
24520   incr(j); incr(mp->header_last);
24521 } while (mp->cur_cmd==comma)
24522
24523 @ @<Store a list of font dimensions@>=
24524 do {  
24525   if ( j>max_tfm_int ) mp_fatal_error(mp, "too many fontdimens");
24526   while ( j>mp->np ) { incr(mp->np); mp->param[mp->np]=0; };
24527   mp_get_x_next(mp); mp_scan_expression(mp);
24528   if ( mp->cur_type!=mp_known ){ 
24529     exp_err("Improper font parameter");
24530 @.Improper font parameter@>
24531     help1("I'm zeroing this one. Proceed, with fingers crossed.");
24532     mp_put_get_flush_error(mp, 0);
24533   }
24534   mp->param[j]=mp->cur_exp; incr(j);
24535 } while (mp->cur_cmd==comma)
24536
24537 @ OK: We've stored all the data that is needed for the \.{TFM} file.
24538 All that remains is to output it in the correct format.
24539
24540 An interesting problem needs to be solved in this connection, because
24541 the \.{TFM} format allows at most 256~widths, 16~heights, 16~depths,
24542 and 64~italic corrections. If the data has more distinct values than
24543 this, we want to meet the necessary restrictions by perturbing the
24544 given values as little as possible.
24545
24546 \MP\ solves this problem in two steps. First the values of a given
24547 kind (widths, heights, depths, or italic corrections) are sorted;
24548 then the list of sorted values is perturbed, if necessary.
24549
24550 The sorting operation is facilitated by having a special node of
24551 essentially infinite |value| at the end of the current list.
24552
24553 @<Initialize table entries...@>=
24554 value(inf_val)=fraction_four;
24555
24556 @ Straight linear insertion is good enough for sorting, since the lists
24557 are usually not terribly long. As we work on the data, the current list
24558 will start at |mp_link(temp_head)| and end at |inf_val|; the nodes in this
24559 list will be in increasing order of their |value| fields.
24560
24561 Given such a list, the |sort_in| function takes a value and returns a pointer
24562 to where that value can be found in the list. The value is inserted in
24563 the proper place, if necessary.
24564
24565 At the time we need to do these operations, most of \MP's work has been
24566 completed, so we will have plenty of memory to play with. The value nodes
24567 that are allocated for sorting will never be returned to free storage.
24568
24569 @d clear_the_list mp_link(temp_head)=inf_val
24570
24571 @c 
24572 static pointer mp_sort_in (MP mp,scaled v) {
24573   pointer p,q,r; /* list manipulation registers */
24574   p=temp_head;
24575   while (1) { 
24576     q=mp_link(p);
24577     if ( v<=value(q) ) break;
24578     p=q;
24579   }
24580   if ( v<value(q) ) {
24581     r=mp_get_node(mp, value_node_size); value(r)=v; mp_link(r)=q; mp_link(p)=r;
24582   }
24583   return mp_link(p);
24584 }
24585
24586 @ Now we come to the interesting part, where we reduce the list if necessary
24587 until it has the required size. The |min_cover| routine is basic to this
24588 process; it computes the minimum number~|m| such that the values of the
24589 current sorted list can be covered by |m|~intervals of width~|d|. It
24590 also sets the global value |perturbation| to the smallest value $d'>d$
24591 such that the covering found by this algorithm would be different.
24592
24593 In particular, |min_cover(0)| returns the number of distinct values in the
24594 current list and sets |perturbation| to the minimum distance between
24595 adjacent values.
24596
24597 @c 
24598 static integer mp_min_cover (MP mp,scaled d) {
24599   pointer p; /* runs through the current list */
24600   scaled l; /* the least element covered by the current interval */
24601   integer m; /* lower bound on the size of the minimum cover */
24602   m=0; p=mp_link(temp_head); mp->perturbation=el_gordo;
24603   while ( p!=inf_val ){ 
24604     incr(m); l=value(p);
24605     do {  p=mp_link(p); } while (value(p)<=l+d);
24606     if ( value(p)-l<mp->perturbation ) 
24607       mp->perturbation=value(p)-l;
24608   }
24609   return m;
24610 }
24611
24612 @ @<Glob...@>=
24613 scaled perturbation; /* quantity related to \.{TFM} rounding */
24614 integer excess; /* the list is this much too long */
24615
24616 @ The smallest |d| such that a given list can be covered with |m| intervals
24617 is determined by the |threshold| routine, which is sort of an inverse
24618 to |min_cover|. The idea is to increase the interval size rapidly until
24619 finding the range, then to go sequentially until the exact borderline has
24620 been discovered.
24621
24622 @c 
24623 static scaled mp_threshold (MP mp,integer m) {
24624   scaled d; /* lower bound on the smallest interval size */
24625   mp->excess=mp_min_cover(mp, 0)-m;
24626   if ( mp->excess<=0 ) {
24627     return 0;
24628   } else  { 
24629     do {  
24630       d=mp->perturbation;
24631     } while (mp_min_cover(mp, d+d)>m);
24632     while ( mp_min_cover(mp, d)>m ) 
24633       d=mp->perturbation;
24634     return d;
24635   }
24636 }
24637
24638 @ The |skimp| procedure reduces the current list to at most |m| entries,
24639 by changing values if necessary. It also sets |mp_info(p):=k| if |value(p)|
24640 is the |k|th distinct value on the resulting list, and it sets
24641 |perturbation| to the maximum amount by which a |value| field has
24642 been changed. The size of the resulting list is returned as the
24643 value of |skimp|.
24644
24645 @c 
24646 static integer mp_skimp (MP mp,integer m) {
24647   scaled d; /* the size of intervals being coalesced */
24648   pointer p,q,r; /* list manipulation registers */
24649   scaled l; /* the least value in the current interval */
24650   scaled v; /* a compromise value */
24651   d=mp_threshold(mp, m); mp->perturbation=0;
24652   q=temp_head; m=0; p=mp_link(temp_head);
24653   while ( p!=inf_val ) {
24654     incr(m); l=value(p); mp_info(p)=m;
24655     if ( value(mp_link(p))<=l+d ) {
24656       @<Replace an interval of values by its midpoint@>;
24657     }
24658     q=p; p=mp_link(p);
24659   }
24660   return m;
24661 }
24662
24663 @ @<Replace an interval...@>=
24664
24665   do {  
24666     p=mp_link(p); mp_info(p)=m;
24667     decr(mp->excess); if ( mp->excess==0 ) d=0;
24668   } while (value(mp_link(p))<=l+d);
24669   v=l+halfp(value(p)-l);
24670   if ( value(p)-v>mp->perturbation ) 
24671     mp->perturbation=value(p)-v;
24672   r=q;
24673   do {  
24674     r=mp_link(r); value(r)=v;
24675   } while (r!=p);
24676   mp_link(q)=p; /* remove duplicate values from the current list */
24677 }
24678
24679 @ A warning message is issued whenever something is perturbed by
24680 more than 1/16\thinspace pt.
24681
24682 @c 
24683 static void mp_tfm_warning (MP mp,quarterword m) { 
24684   mp_print_nl(mp, "(some "); 
24685   mp_print(mp, mp->int_name[m]);
24686 @.some charwds...@>
24687 @.some chardps...@>
24688 @.some charhts...@>
24689 @.some charics...@>
24690   mp_print(mp, " values had to be adjusted by as much as ");
24691   mp_print_scaled(mp, mp->perturbation); mp_print(mp, "pt)");
24692 }
24693
24694 @ Here's an example of how we use these routines.
24695 The width data needs to be perturbed only if there are 256 distinct
24696 widths, but \MP\ must check for this case even though it is
24697 highly unusual.
24698
24699 An integer variable |k| will be defined when we use this code.
24700 The |dimen_head| array will contain pointers to the sorted
24701 lists of dimensions.
24702
24703 @<Massage the \.{TFM} widths@>=
24704 clear_the_list;
24705 for (k=mp->bc;k<=mp->ec;k++)  {
24706   if ( mp->char_exists[k] )
24707     mp->tfm_width[k]=mp_sort_in(mp, mp->tfm_width[k]);
24708 }
24709 mp->nw=mp_skimp(mp, 255)+1; mp->dimen_head[1]=mp_link(temp_head);
24710 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_wd)
24711
24712 @ @<Glob...@>=
24713 pointer dimen_head[5]; /* lists of \.{TFM} dimensions */
24714
24715 @ Heights, depths, and italic corrections are different from widths
24716 not only because their list length is more severely restricted, but
24717 also because zero values do not need to be put into the lists.
24718
24719 @<Massage the \.{TFM} heights, depths, and italic corrections@>=
24720 clear_the_list;
24721 for (k=mp->bc;k<=mp->ec;k++) {
24722   if ( mp->char_exists[k] ) {
24723     if ( mp->tfm_height[k]==0 ) mp->tfm_height[k]=zero_val;
24724     else mp->tfm_height[k]=mp_sort_in(mp, mp->tfm_height[k]);
24725   }
24726 }
24727 mp->nh=mp_skimp(mp, 15)+1; mp->dimen_head[2]=mp_link(temp_head);
24728 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ht);
24729 clear_the_list;
24730 for (k=mp->bc;k<=mp->ec;k++) {
24731   if ( mp->char_exists[k] ) {
24732     if ( mp->tfm_depth[k]==0 ) mp->tfm_depth[k]=zero_val;
24733     else mp->tfm_depth[k]=mp_sort_in(mp, mp->tfm_depth[k]);
24734   }
24735 }
24736 mp->nd=mp_skimp(mp, 15)+1; mp->dimen_head[3]=mp_link(temp_head);
24737 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_dp);
24738 clear_the_list;
24739 for (k=mp->bc;k<=mp->ec;k++) {
24740   if ( mp->char_exists[k] ) {
24741     if ( mp->tfm_ital_corr[k]==0 ) mp->tfm_ital_corr[k]=zero_val;
24742     else mp->tfm_ital_corr[k]=mp_sort_in(mp, mp->tfm_ital_corr[k]);
24743   }
24744 }
24745 mp->ni=mp_skimp(mp, 63)+1; mp->dimen_head[4]=mp_link(temp_head);
24746 if ( mp->perturbation>=010000 ) mp_tfm_warning(mp, mp_char_ic)
24747
24748 @ @<Initialize table entries...@>=
24749 value(zero_val)=0; mp_info(zero_val)=0;
24750
24751 @ Bytes 5--8 of the header are set to the design size, unless the user has
24752 some crazy reason for specifying them differently.
24753 @^design size@>
24754
24755 Error messages are not allowed at the time this procedure is called,
24756 so a warning is printed instead.
24757
24758 The value of |max_tfm_dimen| is calculated so that
24759 $$\hbox{|make_scaled(16*max_tfm_dimen,internal[mp_design_size])|}
24760  < \\{three\_bytes}.$$
24761
24762 @d three_bytes 0100000000 /* $2^{24}$ */
24763
24764 @c 
24765 static void mp_fix_design_size (MP mp) {
24766   scaled d; /* the design size */
24767   d=mp->internal[mp_design_size];
24768   if ( (d<unity)||(d>=fraction_half) ) {
24769     if ( d!=0 )
24770       mp_print_nl(mp, "(illegal design size has been changed to 128pt)");
24771 @.illegal design size...@>
24772     d=040000000; mp->internal[mp_design_size]=d;
24773   }
24774   if ( mp->header_byte[4]<0 ) if ( mp->header_byte[5]<0 )
24775     if ( mp->header_byte[6]<0 ) if ( mp->header_byte[7]<0 ) {
24776      mp->header_byte[4]=d / 04000000;
24777      mp->header_byte[5]=(d / 4096) % 256;
24778      mp->header_byte[6]=(d / 16) % 256;
24779      mp->header_byte[7]=(d % 16)*16;
24780   };
24781   mp->max_tfm_dimen=16*mp->internal[mp_design_size]-1-mp->internal[mp_design_size] / 010000000;
24782   if ( mp->max_tfm_dimen>=fraction_half ) mp->max_tfm_dimen=fraction_half-1;
24783 }
24784
24785 @ The |dimen_out| procedure computes a |fix_word| relative to the
24786 design size. If the data was out of range, it is corrected and the
24787 global variable |tfm_changed| is increased by~one.
24788
24789 @c 
24790 static integer mp_dimen_out (MP mp,scaled x) { 
24791   if ( abs(x)>mp->max_tfm_dimen ) {
24792     incr(mp->tfm_changed);
24793     if ( x>0 ) x=mp->max_tfm_dimen; else x=-mp->max_tfm_dimen;
24794   }
24795   x=mp_make_scaled(mp, x*16,mp->internal[mp_design_size]);
24796   return x;
24797 }
24798
24799 @ @<Glob...@>=
24800 scaled max_tfm_dimen; /* bound on widths, heights, kerns, etc. */
24801 integer tfm_changed; /* the number of data entries that were out of bounds */
24802
24803 @ If the user has not specified any of the first four header bytes,
24804 the |fix_check_sum| procedure replaces them by a ``check sum'' computed
24805 from the |tfm_width| data relative to the design size.
24806 @^check sum@>
24807
24808 @c 
24809 static void mp_fix_check_sum (MP mp) {
24810   eight_bits k; /* runs through character codes */
24811   eight_bits B1,B2,B3,B4; /* bytes of the check sum */
24812   integer x;  /* hash value used in check sum computation */
24813   if ( mp->header_byte[0]==0 && mp->header_byte[1]==0 &&
24814        mp->header_byte[2]==0 && mp->header_byte[3]==0 ) {
24815     @<Compute a check sum in |(b1,b2,b3,b4)|@>;
24816     mp->header_byte[0]=(char)B1; mp->header_byte[1]=(char)B2;
24817     mp->header_byte[2]=(char)B3; mp->header_byte[3]=(char)B4; 
24818     return;
24819   }
24820 }
24821
24822 @ @<Compute a check sum in |(b1,b2,b3,b4)|@>=
24823 B1=mp->bc; B2=mp->ec; B3=mp->bc; B4=mp->ec; mp->tfm_changed=0;
24824 for (k=mp->bc;k<=mp->ec;k++) { 
24825   if ( mp->char_exists[k] ) {
24826     x=mp_dimen_out(mp, value(mp->tfm_width[k]))+(k+4)*020000000; /* this is positive */
24827     B1=(eight_bits)((B1+B1+x) % 255);
24828     B2=(eight_bits)((B2+B2+x) % 253);
24829     B3=(eight_bits)((B3+B3+x) % 251);
24830     B4=(eight_bits)((B4+B4+x) % 247);
24831   }
24832 }
24833
24834 @ Finally we're ready to actually write the \.{TFM} information.
24835 Here are some utility routines for this purpose.
24836
24837 @d tfm_out(A) do { /* output one byte to |tfm_file| */
24838   unsigned char s=(unsigned char)(A); 
24839   (mp->write_binary_file)(mp,mp->tfm_file,(void *)&s,1); 
24840   } while (0)
24841
24842 @c 
24843 static void mp_tfm_two (MP mp,integer x) { /* output two bytes to |tfm_file| */
24844   tfm_out(x / 256); tfm_out(x % 256);
24845 }
24846 static void mp_tfm_four (MP mp,integer x) { /* output four bytes to |tfm_file| */
24847   if ( x>=0 ) tfm_out(x / three_bytes);
24848   else { 
24849     x=x+010000000000; /* use two's complement for negative values */
24850     x=x+010000000000;
24851     tfm_out((x / three_bytes) + 128);
24852   };
24853   x=x % three_bytes; tfm_out(x / unity);
24854   x=x % unity; tfm_out(x / 0400);
24855   tfm_out(x % 0400);
24856 }
24857 static void mp_tfm_qqqq (MP mp,four_quarters x) { /* output four quarterwords to |tfm_file| */
24858   tfm_out(qo(x.b0)); tfm_out(qo(x.b1)); 
24859   tfm_out(qo(x.b2)); tfm_out(qo(x.b3));
24860 }
24861
24862 @ @<Finish the \.{TFM} file@>=
24863 if ( mp->job_name==NULL ) mp_open_log_file(mp);
24864 mp_pack_job_name(mp, ".tfm");
24865 while ( ! mp_b_open_out(mp, &mp->tfm_file, mp_filetype_metrics) )
24866   mp_prompt_file_name(mp, "file name for font metrics",".tfm");
24867 mp->metric_file_name=xstrdup(mp->name_of_file);
24868 @<Output the subfile sizes and header bytes@>;
24869 @<Output the character information bytes, then
24870   output the dimensions themselves@>;
24871 @<Output the ligature/kern program@>;
24872 @<Output the extensible character recipes and the font metric parameters@>;
24873   if ( mp->internal[mp_tracing_stats]>0 )
24874   @<Log the subfile sizes of the \.{TFM} file@>;
24875 mp_print_nl(mp, "Font metrics written on "); 
24876 mp_print(mp, mp->metric_file_name); mp_print_char(mp, xord('.'));
24877 @.Font metrics written...@>
24878 (mp->close_file)(mp,mp->tfm_file)
24879
24880 @ Integer variables |lh|, |k|, and |lk_offset| will be defined when we use
24881 this code.
24882
24883 @<Output the subfile sizes and header bytes@>=
24884 k=mp->header_last;
24885 LH=(k+3) / 4; /* this is the number of header words */
24886 if ( mp->bc>mp->ec ) mp->bc=1; /* if there are no characters, |ec=0| and |bc=1| */
24887 @<Compute the ligature/kern program offset and implant the
24888   left boundary label@>;
24889 mp_tfm_two(mp,6+LH+(mp->ec-mp->bc+1)+mp->nw+mp->nh+mp->nd+mp->ni+mp->nl
24890      +lk_offset+mp->nk+mp->ne+mp->np);
24891   /* this is the total number of file words that will be output */
24892 mp_tfm_two(mp, LH); mp_tfm_two(mp, mp->bc); mp_tfm_two(mp, mp->ec); 
24893 mp_tfm_two(mp, mp->nw); mp_tfm_two(mp, mp->nh);
24894 mp_tfm_two(mp, mp->nd); mp_tfm_two(mp, mp->ni); mp_tfm_two(mp, mp->nl+lk_offset); 
24895 mp_tfm_two(mp, mp->nk); mp_tfm_two(mp, mp->ne);
24896 mp_tfm_two(mp, mp->np);
24897 for (k=0;k< 4*LH;k++)   { 
24898   tfm_out(mp->header_byte[k]);
24899 }
24900
24901 @ @<Output the character information bytes...@>=
24902 for (k=mp->bc;k<=mp->ec;k++) {
24903   if ( ! mp->char_exists[k] ) {
24904     mp_tfm_four(mp, 0);
24905   } else { 
24906     tfm_out(mp_info(mp->tfm_width[k])); /* the width index */
24907     tfm_out((mp_info(mp->tfm_height[k]))*16+mp_info(mp->tfm_depth[k]));
24908     tfm_out((mp_info(mp->tfm_ital_corr[k]))*4+mp->char_tag[k]);
24909     tfm_out(mp->char_remainder[k]);
24910   };
24911 }
24912 mp->tfm_changed=0;
24913 for (k=1;k<=4;k++) { 
24914   mp_tfm_four(mp, 0); p=mp->dimen_head[k];
24915   while ( p!=inf_val ) {
24916     mp_tfm_four(mp, mp_dimen_out(mp, value(p))); p=mp_link(p);
24917   }
24918 }
24919
24920
24921 @ We need to output special instructions at the beginning of the
24922 |lig_kern| array in order to specify the right boundary character
24923 and/or to handle starting addresses that exceed 255. The |label_loc|
24924 and |label_char| arrays have been set up to record all the
24925 starting addresses; we have $-1=|label_loc|[0]<|label_loc|[1]\le\cdots
24926 \le|label_loc|[|label_ptr]|$.
24927
24928 @<Compute the ligature/kern program offset...@>=
24929 mp->bchar=mp_round_unscaled(mp, mp->internal[mp_boundary_char]);
24930 if ((mp->bchar<0)||(mp->bchar>255))
24931   { mp->bchar=-1; mp->lk_started=false; lk_offset=0; }
24932 else { mp->lk_started=true; lk_offset=1; };
24933 @<Find the minimum |lk_offset| and adjust all remainders@>;
24934 if ( mp->bch_label<undefined_label )
24935   { skip_byte(mp->nl)=qi(255); next_char(mp->nl)=qi(0);
24936   op_byte(mp->nl)=qi(((mp->bch_label+lk_offset)/ 256));
24937   rem_byte(mp->nl)=qi(((mp->bch_label+lk_offset)% 256));
24938   incr(mp->nl); /* possibly |nl=lig_table_size+1| */
24939   }
24940
24941 @ @<Find the minimum |lk_offset|...@>=
24942 k=mp->label_ptr; /* pointer to the largest unallocated label */
24943 if ( mp->label_loc[k]+lk_offset>255 ) {
24944   lk_offset=0; mp->lk_started=false; /* location 0 can do double duty */
24945   do {  
24946     mp->char_remainder[mp->label_char[k]]=lk_offset;
24947     while ( mp->label_loc[k-1]==mp->label_loc[k] ) {
24948        decr(k); mp->char_remainder[mp->label_char[k]]=lk_offset;
24949     }
24950     incr(lk_offset); decr(k);
24951   } while (! (lk_offset+mp->label_loc[k]<256));
24952     /* N.B.: |lk_offset=256| satisfies this when |k=0| */
24953 }
24954 if ( lk_offset>0 ) {
24955   while ( k>0 ) {
24956     mp->char_remainder[mp->label_char[k]]
24957      =mp->char_remainder[mp->label_char[k]]+lk_offset;
24958     decr(k);
24959   }
24960 }
24961
24962 @ @<Output the ligature/kern program@>=
24963 for (k=0;k<= 255;k++ ) {
24964   if ( mp->skip_table[k]<undefined_label ) {
24965      mp_print_nl(mp, "(local label "); mp_print_int(mp, k); mp_print(mp, ":: was missing)");
24966 @.local label l:: was missing@>
24967     cancel_skips(mp->skip_table[k]);
24968   }
24969 }
24970 if ( mp->lk_started ) { /* |lk_offset=1| for the special |bchar| */
24971   tfm_out(255); tfm_out(mp->bchar); mp_tfm_two(mp, 0);
24972 } else {
24973   for (k=1;k<=lk_offset;k++) {/* output the redirection specs */
24974     mp->ll=mp->label_loc[mp->label_ptr];
24975     if ( mp->bchar<0 ) { tfm_out(254); tfm_out(0);   }
24976     else { tfm_out(255); tfm_out(mp->bchar);   };
24977     mp_tfm_two(mp, mp->ll+lk_offset);
24978     do {  
24979       decr(mp->label_ptr);
24980     } while (! (mp->label_loc[mp->label_ptr]<mp->ll));
24981   }
24982 }
24983 for (k=0;k<=mp->nl-1;k++) mp_tfm_qqqq(mp, mp->lig_kern[k]);
24984 for (k=0;k<=mp->nk-1;k++) mp_tfm_four(mp, mp_dimen_out(mp, mp->kern[k]))
24985
24986 @ @<Output the extensible character recipes...@>=
24987 for (k=0;k<=mp->ne-1;k++) 
24988   mp_tfm_qqqq(mp, mp->exten[k]);
24989 for (k=1;k<=mp->np;k++) {
24990   if ( k==1 ) {
24991     if ( abs(mp->param[1])<fraction_half ) {
24992       mp_tfm_four(mp, mp->param[1]*16);
24993     } else  { 
24994       incr(mp->tfm_changed);
24995       if ( mp->param[1]>0 ) mp_tfm_four(mp, el_gordo);
24996       else mp_tfm_four(mp, -el_gordo);
24997     }
24998   } else {
24999     mp_tfm_four(mp, mp_dimen_out(mp, mp->param[k]));
25000   }
25001 }
25002 if ( mp->tfm_changed>0 )  { 
25003   if ( mp->tfm_changed==1 ) mp_print_nl(mp, "(a font metric dimension");
25004 @.a font metric dimension...@>
25005   else  { 
25006     mp_print_nl(mp, "("); mp_print_int(mp, mp->tfm_changed);
25007 @.font metric dimensions...@>
25008     mp_print(mp, " font metric dimensions");
25009   }
25010   mp_print(mp, " had to be decreased)");
25011 }
25012
25013 @ @<Log the subfile sizes of the \.{TFM} file@>=
25014
25015   char s[200];
25016   wlog_ln(" ");
25017   if ( mp->bch_label<undefined_label ) decr(mp->nl);
25018   mp_snprintf(s,128,"(You used %iw,%ih,%id,%ii,%il,%ik,%ie,%ip metric file positions)",
25019                  mp->nw, mp->nh, mp->nd, mp->ni, mp->nl, mp->nk, mp->ne,mp->np);
25020   wlog_ln(s);
25021 }
25022
25023 @* \[43] Reading font metric data.
25024
25025 \MP\ isn't a typesetting program but it does need to find the bounding box
25026 of a sequence of typeset characters.  Thus it needs to read \.{TFM} files as
25027 well as write them.
25028
25029 @<Glob...@>=
25030 void * tfm_infile;
25031
25032 @ All the width, height, and depth information is stored in an array called
25033 |font_info|.  This array is allocated sequentially and each font is stored
25034 as a series of |char_info| words followed by the width, height, and depth
25035 tables.  Since |font_name| entries are permanent, their |str_ref| values are
25036 set to |max_str_ref|.
25037
25038 @<Types...@>=
25039 typedef unsigned int font_number; /* |0..font_max| */
25040
25041 @ The |font_info| array is indexed via a group directory arrays.
25042 For example, the |char_info| data for character~|c| in font~|f| will be
25043 in |font_info[char_base[f]+c].qqqq|.
25044
25045 @<Glob...@>=
25046 font_number font_max; /* maximum font number for included text fonts */
25047 size_t      font_mem_size; /* number of words for \.{TFM} information for text fonts */
25048 memory_word *font_info; /* height, width, and depth data */
25049 char        **font_enc_name; /* encoding names, if any */
25050 boolean     *font_ps_name_fixed; /* are the postscript names fixed already?  */
25051 size_t      next_fmem; /* next unused entry in |font_info| */
25052 font_number last_fnum; /* last font number used so far */
25053 scaled      *font_dsize;  /* 16 times the ``design'' size in \ps\ points */
25054 char        **font_name;  /* name as specified in the \&{infont} command */
25055 char        **font_ps_name;  /* PostScript name for use when |internal[mp_prologues]>0| */
25056 font_number last_ps_fnum; /* last valid |font_ps_name| index */
25057 eight_bits  *font_bc;
25058 eight_bits  *font_ec;  /* first and last character code */
25059 int         *char_base;  /* base address for |char_info| */
25060 int         *width_base; /* index for zeroth character width */
25061 int         *height_base; /* index for zeroth character height */
25062 int         *depth_base; /* index for zeroth character depth */
25063 pointer     *font_sizes;
25064
25065 @ @<Allocate or initialize ...@>=
25066 mp->font_mem_size = 10000; 
25067 mp->font_info = xmalloc ((mp->font_mem_size+1),sizeof(memory_word));
25068 memset (mp->font_info,0,sizeof(memory_word)*(mp->font_mem_size+1));
25069 mp->last_fnum = null_font;
25070
25071 @ @<Dealloc variables@>=
25072 for (k=1;k<=(int)mp->last_fnum;k++) {
25073   xfree(mp->font_enc_name[k]);
25074   xfree(mp->font_name[k]);
25075   xfree(mp->font_ps_name[k]);
25076 }
25077 xfree(mp->font_info);
25078 xfree(mp->font_enc_name);
25079 xfree(mp->font_ps_name_fixed);
25080 xfree(mp->font_dsize);
25081 xfree(mp->font_name);
25082 xfree(mp->font_ps_name);
25083 xfree(mp->font_bc);
25084 xfree(mp->font_ec);
25085 xfree(mp->char_base);
25086 xfree(mp->width_base);
25087 xfree(mp->height_base);
25088 xfree(mp->depth_base);
25089 xfree(mp->font_sizes);
25090
25091
25092 @c 
25093 void mp_reallocate_fonts (MP mp, font_number l) {
25094   font_number f;
25095   XREALLOC(mp->font_enc_name,      l, char *);
25096   XREALLOC(mp->font_ps_name_fixed, l, boolean);
25097   XREALLOC(mp->font_dsize,         l, scaled);
25098   XREALLOC(mp->font_name,          l, char *);
25099   XREALLOC(mp->font_ps_name,       l, char *);
25100   XREALLOC(mp->font_bc,            l, eight_bits);
25101   XREALLOC(mp->font_ec,            l, eight_bits);
25102   XREALLOC(mp->char_base,          l, int);
25103   XREALLOC(mp->width_base,         l, int);
25104   XREALLOC(mp->height_base,        l, int);
25105   XREALLOC(mp->depth_base,         l, int);
25106   XREALLOC(mp->font_sizes,         l, pointer);
25107   for (f=(mp->last_fnum+1);f<=l;f++) {
25108     mp->font_enc_name[f]=NULL;
25109     mp->font_ps_name_fixed[f] = false;
25110     mp->font_name[f]=NULL;
25111     mp->font_ps_name[f]=NULL;
25112     mp->font_sizes[f]=null;
25113   }
25114   mp->font_max = l;
25115 }
25116
25117 @ @<Internal library declarations@>=
25118 void mp_reallocate_fonts (MP mp, font_number l);
25119
25120
25121 @ A |null_font| containing no characters is useful for error recovery.  Its
25122 |font_name| entry starts out empty but is reset each time an erroneous font is
25123 found.  This helps to cut down on the number of duplicate error messages without
25124 wasting a lot of space.
25125
25126 @d null_font 0 /* the |font_number| for an empty font */
25127
25128 @<Set initial...@>=
25129 mp->font_dsize[null_font]=0;
25130 mp->font_bc[null_font]=1;
25131 mp->font_ec[null_font]=0;
25132 mp->char_base[null_font]=0;
25133 mp->width_base[null_font]=0;
25134 mp->height_base[null_font]=0;
25135 mp->depth_base[null_font]=0;
25136 mp->next_fmem=0;
25137 mp->last_fnum=null_font;
25138 mp->last_ps_fnum=null_font;
25139 mp->font_name[null_font]=(char *)"nullfont";
25140 mp->font_ps_name[null_font]=(char *)"";
25141 mp->font_ps_name_fixed[null_font] = false;
25142 mp->font_enc_name[null_font]=NULL;
25143 mp->font_sizes[null_font]=null;
25144
25145 @ Each |char_info| word is of type |four_quarters|.  The |b0| field contains
25146 the |width index|; the |b1| field contains the height
25147 index; the |b2| fields contains the depth index, and the |b3| field used only
25148 for temporary storage. (It is used to keep track of which characters occur in
25149 an edge structure that is being shipped out.)
25150 The corresponding words in the width, height, and depth tables are stored as
25151 |scaled| values in units of \ps\ points.
25152
25153 With the macros below, the |char_info| word for character~|c| in font~|f| is
25154 |char_mp_info(f,c)| and the width is
25155 $$\hbox{|char_width(f,char_mp_info(f,c)).sc|.}$$
25156
25157 @d char_mp_info(A,B) mp->font_info[mp->char_base[(A)]+(B)].qqqq
25158 @d char_width(A,B) mp->font_info[mp->width_base[(A)]+(B).b0].sc
25159 @d char_height(A,B) mp->font_info[mp->height_base[(A)]+(B).b1].sc
25160 @d char_depth(A,B) mp->font_info[mp->depth_base[(A)]+(B).b2].sc
25161 @d ichar_exists(A) ((A).b0>0)
25162
25163 @ When we have a font name and we don't know whether it has been loaded yet,
25164 we scan the |font_name| array before calling |read_font_info|.
25165
25166 @<Declarations@>=
25167 static font_number mp_find_font (MP mp, char *f) ;
25168
25169 @ @c
25170 font_number mp_find_font (MP mp, char *f) {
25171   font_number n;
25172   for (n=0;n<=mp->last_fnum;n++) {
25173     if (mp_xstrcmp(f,mp->font_name[n])==0 ) {
25174       mp_xfree(f);
25175       return n;
25176     }
25177   }
25178   n = mp_read_font_info(mp, f);
25179   mp_xfree(f);
25180   return n;
25181 }
25182
25183 @ This is an interface function for getting the width of character,
25184 as a double in ps units
25185
25186 @c double mp_get_char_dimension (MP mp, char *fname, int c, int t) {
25187   unsigned n;
25188   four_quarters cc;
25189   font_number f = 0;
25190   double w = -1.0;
25191   for (n=0;n<=mp->last_fnum;n++) {
25192     if (mp_xstrcmp(fname,mp->font_name[n])==0 ) {
25193       f = n;
25194       break;
25195     }
25196   }
25197   if (f==0)
25198     return 0.0;
25199   cc = char_mp_info(f,c);
25200   if (! ichar_exists(cc) )
25201     return 0.0;
25202   if (t=='w')
25203     w = (double)char_width(f,cc);
25204   else if (t=='h')
25205     w = (double)char_height(f,cc);
25206   else if (t=='d')
25207     w = (double)char_depth(f,cc);
25208   return w/655.35*(72.27/72);
25209 }
25210
25211 @ @<Exported function ...@>=
25212 double mp_get_char_dimension (MP mp, char *fname, int n, int t);
25213
25214
25215 @ One simple application of |find_font| is the implementation of the |font_size|
25216 operator that gets the design size for a given font name.
25217
25218 @<Find the design size of the font whose name is |cur_exp|@>=
25219 mp_flush_cur_exp(mp, (mp->font_dsize[mp_find_font(mp, str(mp->cur_exp))]+8) / 16)
25220
25221 @ If we discover that the font doesn't have a requested character, we omit it
25222 from the bounding box computation and expect the \ps\ interpreter to drop it.
25223 This routine issues a warning message if the user has asked for it.
25224
25225 @<Declarations@>=
25226 static void mp_lost_warning (MP mp,font_number f, pool_pointer k);
25227
25228 @ @c 
25229 void mp_lost_warning (MP mp,font_number f, pool_pointer k) { 
25230   if ( mp->internal[mp_tracing_lost_chars]>0 ) { 
25231     mp_begin_diagnostic(mp);
25232     if ( mp->selector==log_only ) incr(mp->selector);
25233     mp_print_nl(mp, "Missing character: There is no ");
25234 @.Missing character@>
25235     mp_print_str(mp, mp->str_pool[k]); 
25236     mp_print(mp, " in font ");
25237     mp_print(mp, mp->font_name[f]); mp_print_char(mp, xord('!')); 
25238     mp_end_diagnostic(mp, false);
25239   }
25240 }
25241
25242 @ The whole purpose of saving the height, width, and depth information is to be
25243 able to find the bounding box of an item of text in an edge structure.  The
25244 |set_text_box| procedure takes a text node and adds this information.
25245
25246 @<Declarations@>=
25247 static void mp_set_text_box (MP mp,pointer p); 
25248
25249 @ @c 
25250 void mp_set_text_box (MP mp,pointer p) {
25251   font_number f; /* |mp_font_n(p)| */
25252   ASCII_code bc,ec; /* range of valid characters for font |f| */
25253   pool_pointer k,kk; /* current character and character to stop at */
25254   four_quarters cc; /* the |char_info| for the current character */
25255   scaled h,d; /* dimensions of the current character */
25256   width_val(p)=0;
25257   height_val(p)=-el_gordo;
25258   depth_val(p)=-el_gordo;
25259   f=(font_number)mp_font_n(p);
25260   bc=mp->font_bc[f];
25261   ec=mp->font_ec[f];
25262   kk=str_stop(mp_text_p(p));
25263   k=mp->str_start[mp_text_p(p)];
25264   while ( k<kk ) {
25265     @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>;
25266   }
25267   @<Set the height and depth to zero if the bounding box is empty@>;
25268 }
25269
25270 @ @<Adjust |p|'s bounding box to contain |str_pool[k]|; advance |k|@>=
25271
25272   if ( (mp->str_pool[k]<bc)||(mp->str_pool[k]>ec) ) {
25273     mp_lost_warning(mp, f,k);
25274   } else { 
25275     cc=char_mp_info(f,mp->str_pool[k]);
25276     if ( ! ichar_exists(cc) ) {
25277       mp_lost_warning(mp, f,k);
25278     } else { 
25279       width_val(p)=width_val(p)+char_width(f,cc);
25280       h=char_height(f,cc);
25281       d=char_depth(f,cc);
25282       if ( h>height_val(p) ) height_val(p)=h;
25283       if ( d>depth_val(p) ) depth_val(p)=d;
25284     }
25285   }
25286   incr(k);
25287 }
25288
25289 @ Let's hope modern compilers do comparisons correctly when the difference would
25290 overflow.
25291
25292 @<Set the height and depth to zero if the bounding box is empty@>=
25293 if ( height_val(p)<-depth_val(p) ) { 
25294   height_val(p)=0;
25295   depth_val(p)=0;
25296 }
25297
25298 @ The new primitives fontmapfile and fontmapline.
25299
25300 @<Declare action procedures for use by |do_statement|@>=
25301 static void mp_do_mapfile (MP mp) ;
25302 static void mp_do_mapline (MP mp) ;
25303
25304 @ @c 
25305 static void mp_do_mapfile (MP mp) { 
25306   mp_get_x_next(mp); mp_scan_expression(mp);
25307   if ( mp->cur_type!=mp_string_type ) {
25308     @<Complain about improper map operation@>;
25309   } else {
25310     mp_map_file(mp,mp->cur_exp);
25311   }
25312 }
25313 static void mp_do_mapline (MP mp) { 
25314   mp_get_x_next(mp); mp_scan_expression(mp);
25315   if ( mp->cur_type!=mp_string_type ) {
25316      @<Complain about improper map operation@>;
25317   } else { 
25318      mp_map_line(mp,mp->cur_exp);
25319   }
25320 }
25321
25322 @ @<Complain about improper map operation@>=
25323
25324   exp_err("Unsuitable expression");
25325   help1("Only known strings can be map files or map lines.");
25326   mp_put_get_error(mp);
25327 }
25328
25329 @ To print |scaled| value to PDF output we need some subroutines to ensure
25330 accurary.
25331
25332 @d max_integer   0x7FFFFFFF /* $2^{31}-1$ */
25333
25334 @<Glob...@>=
25335 scaled one_bp; /* scaled value corresponds to 1bp */
25336 scaled one_hundred_bp; /* scaled value corresponds to 100bp */
25337 scaled one_hundred_inch; /* scaled value corresponds to 100in */
25338 integer ten_pow[10]; /* $10^0..10^9$ */
25339 integer scaled_out; /* amount of |scaled| that was taken out in |divide_scaled| */
25340
25341 @ @<Set init...@>=
25342 mp->one_bp = 65782; /* 65781.76 */
25343 mp->one_hundred_bp = 6578176;
25344 mp->one_hundred_inch = 473628672;
25345 mp->ten_pow[0] = 1;
25346 for (i = 1;i<= 9; i++ ) {
25347   mp->ten_pow[i] = 10*mp->ten_pow[i - 1];
25348 }
25349
25350 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
25351
25352 @c scaled mp_divide_scaled (MP mp,scaled s, scaled m, integer  dd) {
25353   scaled q,r;
25354   integer sign,i;
25355   sign = 1;
25356   if ( s < 0 ) { sign = -sign; s = -s; }
25357   if ( m < 0 ) { sign = -sign; m = -m; }
25358   if ( m == 0 )
25359     mp_confusion(mp, "arithmetic: divided by zero");
25360   else if ( m >= (max_integer / 10) )
25361     mp_confusion(mp, "arithmetic: number too big");
25362   q = s / m;
25363   r = s % m;
25364   for (i = 1;i<=dd;i++) {
25365     q = 10*q + (10*r) / m;
25366     r = (10*r) % m;
25367   }
25368   if ( 2*r >= m ) { incr(q); r = r - m; }
25369   mp->scaled_out = sign*(s - (r / mp->ten_pow[dd]));
25370   return (sign*q);
25371 }
25372
25373 @* \[44] Shipping pictures out.
25374 The |ship_out| procedure, to be described below, is given a pointer to
25375 an edge structure. Its mission is to output a file containing the \ps\
25376 description of an edge structure.
25377
25378 @ Each time an edge structure is shipped out we write a new \ps\ output
25379 file named according to the current \&{charcode}.
25380 @:char_code_}{\&{charcode} primitive@>
25381
25382 This is the only backend function that remains in the main |mpost.w| file. 
25383 There are just too many variable accesses needed for status reporting 
25384 etcetera to make it worthwile to move the code to |psout.w|.
25385
25386 @<Internal library declarations@>=
25387 void mp_open_output_file (MP mp) ;
25388
25389 @ @c 
25390 static char *mp_set_output_file_name (MP mp, integer c) {
25391   char *ss = NULL; /* filename extension proposal */  
25392   char *nn = NULL; /* temp string  for str() */
25393   unsigned old_setting; /* previous |selector| setting */
25394   pool_pointer i; /*  indexes into |filename_template|  */
25395   integer cc; /* a temporary integer for template building  */
25396   integer f,g=0; /* field widths */
25397   if ( mp->job_name==NULL ) mp_open_log_file(mp);
25398   if ( mp->filename_template==0 ) {
25399     char *s; /* a file extension derived from |c| */
25400     if ( c<0 ) 
25401       s=xstrdup(".ps");
25402     else 
25403       @<Use |c| to compute the file extension |s|@>;
25404     mp_pack_job_name(mp, s);
25405     free(s);
25406     ss = xstrdup(mp->name_of_file);
25407   } else { /* initializations */
25408     str_number s, n; /* a file extension derived from |c| */
25409     old_setting=mp->selector; 
25410     mp->selector=new_string;
25411     f = 0;
25412     i = mp->str_start[mp->filename_template];
25413     n = null_str; /* initialize */
25414     while ( i<str_stop(mp->filename_template) ) {
25415        if ( mp->str_pool[i]=='%' ) {
25416       CONTINUE:
25417         incr(i);
25418         if ( i<str_stop(mp->filename_template) ) {
25419           if ( mp->str_pool[i]=='j' ) {
25420             mp_print(mp, mp->job_name);
25421           } else if ( mp->str_pool[i]=='d' ) {
25422              cc= mp_round_unscaled(mp, mp->internal[mp_day]);
25423              print_with_leading_zeroes(cc);
25424           } else if ( mp->str_pool[i]=='m' ) {
25425              cc= mp_round_unscaled(mp, mp->internal[mp_month]);
25426              print_with_leading_zeroes(cc);
25427           } else if ( mp->str_pool[i]=='y' ) {
25428              cc= mp_round_unscaled(mp, mp->internal[mp_year]);
25429              print_with_leading_zeroes(cc);
25430           } else if ( mp->str_pool[i]=='H' ) {
25431              cc= mp_round_unscaled(mp, mp->internal[mp_time]) / 60;
25432              print_with_leading_zeroes(cc);
25433           }  else if ( mp->str_pool[i]=='M' ) {
25434              cc= mp_round_unscaled(mp, mp->internal[mp_time]) % 60;
25435              print_with_leading_zeroes(cc);
25436           } else if ( mp->str_pool[i]=='c' ) {
25437             if ( c<0 ) mp_print(mp, "ps");
25438             else print_with_leading_zeroes(c);
25439           } else if ( (mp->str_pool[i]>='0') && 
25440                       (mp->str_pool[i]<='9') ) {
25441             if ( (f<10)  )
25442               f = (f*10) + mp->str_pool[i]-'0';
25443             goto CONTINUE;
25444           } else {
25445             mp_print_str(mp, mp->str_pool[i]);
25446           }
25447         }
25448       } else {
25449         if ( mp->str_pool[i]=='.' )
25450           if (length(n)==0)
25451             n = mp_make_string(mp);
25452         mp_print_str(mp, mp->str_pool[i]);
25453       };
25454       incr(i);
25455     }
25456     s = mp_make_string(mp);
25457     mp->selector= old_setting;
25458     if (length(n)==0) {
25459        n=s;
25460        s=null_str;
25461     }
25462     ss = str(s);
25463     nn = str(n);
25464     mp_pack_file_name(mp, nn,"",ss);
25465     free(nn);
25466     delete_str_ref(n);
25467     delete_str_ref(s);
25468   }
25469   return ss;
25470 }
25471
25472 static char * mp_get_output_file_name (MP mp) {
25473   char *f;
25474   char *saved_name;  /* saved |name_of_file| */
25475   saved_name = xstrdup(mp->name_of_file);
25476   f = xstrdup(mp_set_output_file_name(mp, mp_round_unscaled(mp, mp->internal[mp_char_code])));
25477   mp_pack_file_name(mp, saved_name,NULL,NULL);
25478   free(saved_name);
25479   return f;
25480 }
25481
25482 void mp_open_output_file (MP mp) {
25483   char *ss; /* filename extension proposal */
25484   integer c; /* \&{charcode} rounded to the nearest integer */
25485   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25486   ss = mp_set_output_file_name(mp, c);
25487   while ( ! mp_a_open_out(mp, (void *)&mp->ps_file, mp_filetype_postscript) )
25488     mp_prompt_file_name(mp, "file name for output",ss);
25489   xfree(ss);
25490   @<Store the true output file name if appropriate@>;
25491 }
25492
25493 @ The file extension created here could be up to five characters long in
25494 extreme cases so it may have to be shortened on some systems.
25495 @^system dependencies@>
25496
25497 @<Use |c| to compute the file extension |s|@>=
25498
25499   s = xmalloc(7,1);
25500   mp_snprintf(s,7,".%i",(int)c);
25501 }
25502
25503 @ The user won't want to see all the output file names so we only save the
25504 first and last ones and a count of how many there were.  For this purpose
25505 files are ordered primarily by \&{charcode} and secondarily by order of
25506 creation.
25507 @:char_code_}{\&{charcode} primitive@>
25508
25509 @<Store the true output file name if appropriate@>=
25510 if ((c<mp->first_output_code)&&(mp->first_output_code>=0)) {
25511   mp->first_output_code=c;
25512   xfree(mp->first_file_name);
25513   mp->first_file_name=xstrdup(mp->name_of_file);
25514 }
25515 if ( c>=mp->last_output_code ) {
25516   mp->last_output_code=c;
25517   xfree(mp->last_file_name);
25518   mp->last_file_name=xstrdup(mp->name_of_file);
25519 }
25520
25521 @ @<Glob...@>=
25522 char * first_file_name;
25523 char * last_file_name; /* full file names */
25524 integer first_output_code;integer last_output_code; /* rounded \&{charcode} values */
25525 @:char_code_}{\&{charcode} primitive@>
25526 integer total_shipped; /* total number of |ship_out| operations completed */
25527
25528 @ @<Set init...@>=
25529 mp->first_file_name=xstrdup("");
25530 mp->last_file_name=xstrdup("");
25531 mp->first_output_code=32768;
25532 mp->last_output_code=-32768;
25533 mp->total_shipped=0;
25534
25535 @ @<Dealloc variables@>=
25536 xfree(mp->first_file_name);
25537 xfree(mp->last_file_name);
25538
25539 @ @<Begin the progress report for the output of picture~|c|@>=
25540 if ( (int)mp->term_offset>mp->max_print_line-6 ) mp_print_ln(mp);
25541 else if ( (mp->term_offset>0)||(mp->file_offset>0) ) mp_print_char(mp, xord(' '));
25542 mp_print_char(mp, xord('['));
25543 if ( c>=0 ) mp_print_int(mp, c)
25544
25545 @ @<End progress report@>=
25546 mp_print_char(mp, xord(']'));
25547 update_terminal;
25548 incr(mp->total_shipped)
25549
25550 @ @<Explain what output files were written@>=
25551 if ( mp->total_shipped>0 ) { 
25552   mp_print_nl(mp, "");
25553   mp_print_int(mp, mp->total_shipped);
25554   if (mp->noninteractive) {
25555     mp_print(mp, " figure");
25556     if ( mp->total_shipped>1 ) mp_print_char(mp, xord('s'));
25557     mp_print(mp, " created.");
25558   } else {
25559     mp_print(mp, " output file");
25560     if ( mp->total_shipped>1 ) mp_print_char(mp, xord('s'));
25561     mp_print(mp, " written: ");
25562     mp_print(mp, mp->first_file_name);
25563     if ( mp->total_shipped>1 ) {
25564       if ( 31+strlen(mp->first_file_name)+
25565          strlen(mp->last_file_name)> (unsigned)mp->max_print_line) 
25566         mp_print_ln(mp);
25567       mp_print(mp, " .. ");
25568       mp_print(mp, mp->last_file_name);
25569     }
25570   }
25571 }
25572
25573 @ @<Internal library declarations@>=
25574 boolean mp_has_font_size(MP mp, font_number f );
25575
25576 @ @c 
25577 boolean mp_has_font_size(MP mp, font_number f ) {
25578   return (mp->font_sizes[f]!=null);
25579 }
25580
25581 @ The \&{special} command saves up lines of text to be printed during the next
25582 |ship_out| operation.  The saved items are stored as a list of capsule tokens.
25583
25584 @<Glob...@>=
25585 pointer last_pending; /* the last token in a list of pending specials */
25586
25587 @ @<Set init...@>=
25588 mp->last_pending=spec_head;
25589
25590 @ @<Cases of |do_statement|...@>=
25591 case special_command: 
25592   if ( mp->cur_mod==0 ) mp_do_special(mp); else 
25593   if ( mp->cur_mod==1 ) mp_do_mapfile(mp); else 
25594   mp_do_mapline(mp);
25595   break;
25596
25597 @ @<Declare action procedures for use by |do_statement|@>=
25598 static void mp_do_special (MP mp) ;
25599
25600 @ @c void mp_do_special (MP mp) { 
25601   mp_get_x_next(mp); mp_scan_expression(mp);
25602   if ( mp->cur_type!=mp_string_type ) {
25603     @<Complain about improper special operation@>;
25604   } else { 
25605     mp_link(mp->last_pending)=mp_stash_cur_exp(mp);
25606     mp->last_pending=mp_link(mp->last_pending);
25607     mp_link(mp->last_pending)=null;
25608   }
25609 }
25610
25611 @ @<Complain about improper special operation@>=
25612
25613   exp_err("Unsuitable expression");
25614   help1("Only known strings are allowed for output as specials.");
25615   mp_put_get_error(mp);
25616 }
25617
25618 @ On the export side, we need an extra object type for special strings.
25619
25620 @<Graphical object codes@>=
25621 mp_special_code=8, 
25622
25623 @ @<Export pending specials@>=
25624 p=mp_link(spec_head);
25625 while ( p!=null ) {
25626   mp_special_object *tp;
25627   tp = (mp_special_object *)mp_new_graphic_object(mp,mp_special_code);  
25628   gr_pre_script(tp)  = str(value(p));
25629   if (hh->body==NULL) hh->body = (mp_graphic_object *)tp; 
25630   else gr_link(hp) = (mp_graphic_object *)tp;
25631   hp = (mp_graphic_object *)tp;
25632   p=mp_link(p);
25633 }
25634 mp_flush_token_list(mp, mp_link(spec_head));
25635 mp_link(spec_head)=null;
25636 mp->last_pending=spec_head
25637
25638 @ We are now ready for the main output procedure.  Note that the |selector|
25639 setting is saved in a global variable so that |begin_diagnostic| can access it.
25640
25641 @<Declare the \ps\ output procedures@>=
25642 static void mp_ship_out (MP mp, pointer h) ;
25643
25644 @ Once again, the |gr_XXXX| macros are defined in |mppsout.h|
25645
25646 @d export_color(q,p) 
25647   if ( mp_color_model(p)==mp_uninitialized_model ) {
25648     gr_color_model(q)  = (unsigned char)(mp->internal[mp_default_color_model]/65536);
25649     gr_cyan_val(q)     = 0;
25650         gr_magenta_val(q)  = 0;
25651         gr_yellow_val(q)   = 0;
25652         gr_black_val(q)    = (gr_color_model(q)==mp_cmyk_model ? unity : 0);
25653   } else {
25654     gr_color_model(q)  = (unsigned char)mp_color_model(p);
25655     gr_cyan_val(q)     = cyan_val(p);
25656     gr_magenta_val(q)  = magenta_val(p);
25657     gr_yellow_val(q)   = yellow_val(p);
25658     gr_black_val(q)    = black_val(p);
25659   }
25660
25661 @d export_scripts(q,p)
25662   if (mp_pre_script(p)!=null)  gr_pre_script(q)   = str(mp_pre_script(p));
25663   if (mp_post_script(p)!=null) gr_post_script(q)  = str(mp_post_script(p));
25664
25665 @c
25666 struct mp_edge_object *mp_gr_export(MP mp, pointer h) {
25667   pointer p; /* the current graphical object */
25668   integer t; /* a temporary value */
25669   integer c; /* a rounded charcode */
25670   scaled d_width; /* the current pen width */
25671   mp_edge_object *hh; /* the first graphical object */
25672   mp_graphic_object *hq; /* something |hp| points to  */
25673   mp_text_object    *tt;
25674   mp_fill_object    *tf;
25675   mp_stroked_object *ts;
25676   mp_clip_object    *tc;
25677   mp_bounds_object  *tb;
25678   mp_graphic_object *hp = NULL; /* the current graphical object */
25679   mp_set_bbox(mp, h, true);
25680   hh = xmalloc(1,sizeof(mp_edge_object));
25681   hh->body = NULL;
25682   hh->next = NULL;
25683   hh->parent = mp;
25684   hh->minx = minx_val(h);
25685   hh->miny = miny_val(h);
25686   hh->maxx = maxx_val(h);
25687   hh->maxy = maxy_val(h);
25688   hh->filename = mp_get_output_file_name(mp);
25689   c = mp_round_unscaled(mp,mp->internal[mp_char_code]);
25690   hh->charcode = c;
25691   hh->width = mp->internal[mp_char_wd];
25692   hh->height = mp->internal[mp_char_ht];
25693   hh->depth = mp->internal[mp_char_dp];
25694   hh->ital_corr = mp->internal[mp_char_ic];
25695   @<Export pending specials@>;
25696   p=mp_link(dummy_loc(h));
25697   while ( p!=null ) { 
25698     hq = mp_new_graphic_object(mp,mp_type(p));
25699     switch (mp_type(p)) {
25700     case mp_fill_code:
25701       tf = (mp_fill_object *)hq;
25702       gr_pen_p(tf)        = mp_export_knot_list(mp,mp_pen_p(p));
25703       d_width = mp_get_pen_scale(mp, mp_pen_p(p));
25704       if ((mp_pen_p(p)==null) || pen_is_elliptical(mp_pen_p(p)))  {
25705             gr_path_p(tf)       = mp_export_knot_list(mp,mp_path_p(p));
25706       } else {
25707         pointer pc, pp;
25708         pc = mp_copy_path(mp, mp_path_p(p));
25709         pp = mp_make_envelope(mp, pc, mp_pen_p(p),ljoin_val(p),0,miterlim_val(p));
25710         gr_path_p(tf)       = mp_export_knot_list(mp,pp);
25711         mp_toss_knot_list(mp, pp);
25712         pc = mp_htap_ypoc(mp, mp_path_p(p));
25713         pp = mp_make_envelope(mp, pc, mp_pen_p(p),ljoin_val(p),0,miterlim_val(p));
25714         gr_htap_p(tf)       = mp_export_knot_list(mp,pp);
25715         mp_toss_knot_list(mp, pp);
25716       }
25717       export_color(tf,p) ;
25718       export_scripts(tf,p);
25719       gr_ljoin_val(tf)    = (unsigned char)ljoin_val(p);
25720       gr_miterlim_val(tf) = miterlim_val(p);
25721       break;
25722     case mp_stroked_code:
25723       ts = (mp_stroked_object *)hq;
25724       gr_pen_p(ts)        = mp_export_knot_list(mp,mp_pen_p(p));
25725       d_width = mp_get_pen_scale(mp, mp_pen_p(p));
25726       if (pen_is_elliptical(mp_pen_p(p)))  {
25727               gr_path_p(ts)       = mp_export_knot_list(mp,mp_path_p(p));
25728       } else {
25729         pointer pc;
25730         pc=mp_copy_path(mp, mp_path_p(p));
25731         t=lcap_val(p);
25732         if ( mp_left_type(pc)!=mp_endpoint ) { 
25733           mp_left_type(mp_insert_knot(mp, pc,mp_x_coord(pc),mp_y_coord(pc)))=mp_endpoint;
25734           mp_right_type(pc)=mp_endpoint;
25735           pc=mp_link(pc);
25736           t=1;
25737         }
25738         pc=mp_make_envelope(mp,pc,mp_pen_p(p),ljoin_val(p),t,miterlim_val(p));
25739         gr_path_p(ts)       = mp_export_knot_list(mp,pc);
25740         mp_toss_knot_list(mp, pc);
25741       }
25742       export_color(ts,p) ;
25743       export_scripts(ts,p);
25744       gr_ljoin_val(ts)    = (unsigned char)ljoin_val(p);
25745       gr_miterlim_val(ts) = miterlim_val(p);
25746       gr_lcap_val(ts)     = (unsigned char)lcap_val(p);
25747       gr_dash_p(ts)       = mp_export_dashes(mp,p,&d_width);
25748       break;
25749     case mp_text_code:
25750       tt = (mp_text_object *)hq;
25751       gr_text_p(tt)       = str(mp_text_p(p));
25752       gr_font_n(tt)       = (unsigned int)mp_font_n(p);
25753       gr_font_name(tt)    = mp_xstrdup(mp,mp->font_name[mp_font_n(p)]);
25754       gr_font_dsize(tt)   = (unsigned int)mp->font_dsize[mp_font_n(p)];
25755       export_color(tt,p) ;
25756       export_scripts(tt,p);
25757       gr_width_val(tt)    = width_val(p);
25758       gr_height_val(tt)   = height_val(p);
25759       gr_depth_val(tt)    = depth_val(p);
25760       gr_tx_val(tt)       = tx_val(p);
25761       gr_ty_val(tt)       = ty_val(p);
25762       gr_txx_val(tt)      = txx_val(p);
25763       gr_txy_val(tt)      = txy_val(p);
25764       gr_tyx_val(tt)      = tyx_val(p);
25765       gr_tyy_val(tt)      = tyy_val(p);
25766       break;
25767     case mp_start_clip_code: 
25768       tc = (mp_clip_object *)hq;
25769       gr_path_p(tc) = mp_export_knot_list(mp,mp_path_p(p));
25770       break;
25771     case mp_start_bounds_code:
25772       tb = (mp_bounds_object *)hq;
25773       gr_path_p(tb) = mp_export_knot_list(mp,mp_path_p(p));
25774       break;
25775     case mp_stop_clip_code: 
25776     case mp_stop_bounds_code:
25777       /* nothing to do here */
25778       break;
25779     } 
25780     if (hh->body==NULL) hh->body=hq; else  gr_link(hp) = hq;
25781     hp = hq;
25782     p=mp_link(p);
25783   }
25784   return hh;
25785 }
25786
25787 @ @<Declarations@>=
25788 static struct mp_edge_object *mp_gr_export(MP mp, int h);
25789
25790 @ This function is now nearly trivial.
25791
25792 @c
25793 void mp_ship_out (MP mp, pointer h) { /* output edge structure |h| */
25794   integer c; /* \&{charcode} rounded to the nearest integer */
25795   c=mp_round_unscaled(mp, mp->internal[mp_char_code]);
25796   @<Begin the progress report for the output of picture~|c|@>;
25797   (mp->shipout_backend) (mp, h);
25798   @<End progress report@>;
25799   if ( mp->internal[mp_tracing_output]>0 ) 
25800    mp_print_edges(mp, h," (just shipped out)",true);
25801 }
25802
25803 @ @<Declarations@>=
25804 static void mp_shipout_backend (MP mp, pointer h);
25805
25806 @ @c
25807 void mp_shipout_backend (MP mp, pointer h) {
25808   mp_edge_object *hh; /* the first graphical object */
25809   hh = mp_gr_export(mp,h);
25810   (void)mp_gr_ship_out (hh,
25811                  (mp->internal[mp_prologues]/65536),
25812                  (mp->internal[mp_procset]/65536), 
25813                  false);
25814   mp_gr_toss_objects(hh);
25815 }
25816
25817 @ @<Exported types@>=
25818 typedef void (*mp_backend_writer)(MP, int);
25819
25820 @ @<Option variables@>=
25821 mp_backend_writer shipout_backend;
25822
25823 @ Now that we've finished |ship_out|, let's look at the other commands
25824 by which a user can send things to the \.{GF} file.
25825
25826 @ @<Determine if a character has been shipped out@>=
25827
25828   mp->cur_exp=mp_round_unscaled(mp, mp->cur_exp) % 256;
25829   if ( mp->cur_exp<0 ) mp->cur_exp=mp->cur_exp+256;
25830   boolean_reset(mp->char_exists[mp->cur_exp]);
25831   mp->cur_type=mp_boolean_type;
25832 }
25833
25834 @ @<Glob...@>=
25835 psout_data ps;
25836
25837 @ @<Allocate or initialize ...@>=
25838 mp_backend_initialize(mp);
25839
25840 @ @<Dealloc...@>=
25841 mp_backend_free(mp);
25842
25843
25844 @* \[45] Dumping and undumping the tables.
25845 After \.{INIMP} has seen a collection of macros, it
25846 can write all the necessary information on an auxiliary file so
25847 that production versions of \MP\ are able to initialize their
25848 memory at high speed. The present section of the program takes
25849 care of such output and input. We shall consider simultaneously
25850 the processes of storing and restoring,
25851 so that the inverse relation between them is clear.
25852 @.INIMP@>
25853
25854 The global variable |mem_ident| is a string that is printed right
25855 after the |banner| line when \MP\ is ready to start. For \.{INIMP} this
25856 string says simply `\.{(INIMP)}'; for other versions of \MP\ it says,
25857 for example, `\.{(mem=plain 1990.4.14)}', showing the year,
25858 month, and day that the mem file was created. We have |mem_ident=0|
25859 before \MP's tables are loaded.
25860
25861 @<Glob...@>=
25862 char * mem_ident;
25863 void * mem_file; /* for input or output of mem information */
25864
25865 @ @<Set init...@>=
25866 mp->mem_ident=NULL;
25867
25868 @ @<Initialize table entries...@>=
25869 mp->mem_ident=xstrdup(" (INIMP)");
25870
25871 @ @<Declarations@>=
25872 extern void mp_store_mem_file (MP mp) ;
25873 extern boolean mp_load_mem_file (MP mp);
25874 extern int mp_undump_constants (MP mp);
25875
25876 @ @<Dealloc variables@>=
25877 xfree(mp->mem_ident);
25878
25879
25880 @* \[46] The main program.
25881 This is it: the part of \MP\ that executes all those procedures we have
25882 written.
25883
25884 Well---almost. We haven't put the parsing subroutines into the
25885 program yet; and we'd better leave space for a few more routines that may
25886 have been forgotten.
25887
25888 @c @<Declare the basic parsing subroutines@>
25889 @<Declare miscellaneous procedures that were declared |forward|@>
25890
25891 @ We've noted that there are two versions of \MP. One, called \.{INIMP},
25892 @.INIMP@>
25893 has to be run first; it initializes everything from scratch, without
25894 reading a mem file, and it has the capability of dumping a mem file.
25895 The other one is called `\.{VIRMP}'; it is a ``virgin'' program that needs
25896 @.VIRMP@>
25897 to input a mem file in order to get started. \.{VIRMP} typically has
25898 a bit more memory capacity than \.{INIMP}, because it does not need the
25899 space consumed by the dumping/undumping routines and the numerous calls on
25900 |primitive|, etc.
25901
25902 The \.{VIRMP} program cannot read a mem file instantaneously, of course;
25903 the best implementations therefore allow for production versions of \MP\ that
25904 not only avoid the loading routine for object code, they also have
25905 a mem file pre-loaded. 
25906
25907 @ @<Option variables@>=
25908 int ini_version; /* are we iniMP? */
25909
25910 @ @<Set |ini_version|@>=
25911 mp->ini_version = (opt->ini_version ? true : false);
25912
25913 @ The code below make the final chosen hash size the next larger
25914 multiple of 2 from the requested size, and this array is a list of
25915 suitable prime numbers to go with such values. 
25916
25917 The top limit is chosen such that it is definately lower than
25918 |max_halfword-3*param_size|, because |param_size| cannot be larger
25919 than |max_halfword/sizeof(pointer)|.
25920
25921 @<Declarations@>=
25922 static int mp_prime_choices[] = 
25923   { 12289,        24593,    49157,    98317,
25924     196613,      393241,   786433,  1572869,
25925     3145739,    6291469, 12582917, 25165843,
25926     50331653, 100663319  };
25927
25928 @ @<Find constant sizes@>=
25929 if (mp->ini_version) {
25930   unsigned i = 14;
25931   set_value(mp->mem_top,opt->main_memory,5000);
25932   mp->mem_max = mp->mem_top;
25933   set_value(mp->param_size,opt->param_size,150);
25934   set_value(mp->max_in_open,opt->max_in_open,10);
25935   if (opt->hash_size>0x8000000) 
25936     opt->hash_size=0x8000000;
25937   set_value(mp->hash_size,(2*opt->hash_size-1),16384);
25938   mp->hash_size = mp->hash_size>>i;
25939   while (mp->hash_size>=2) {
25940     mp->hash_size /= 2;
25941     i++;
25942   }
25943   mp->hash_size = mp->hash_size << i;
25944   if (mp->hash_size>0x8000000) 
25945     mp->hash_size=0x8000000;
25946   mp->hash_prime=mp_prime_choices[(i-14)];
25947 } else {
25948   int i = -1;
25949   if (mp->mem_name == NULL) {
25950     mp->mem_name = mp_xstrdup(mp,"plain");
25951   }
25952   if (mp_open_mem_file(mp)) {
25953     i = mp_undump_constants(mp);
25954     if (i != metapost_magic)
25955       goto OFF_BASE;    
25956     set_value(mp->mem_max,opt->main_memory,mp->mem_top);
25957     goto DONE;
25958   } 
25959 OFF_BASE:
25960   wterm_ln("(Fatal mem file error; ");
25961   wterm((mp->find_file)(mp, mp->mem_name, "r", mp_filetype_memfile));
25962   if (i>metapost_old_magic && i<metapost_magic) {
25963     wterm(" was written by an older version)\n");
25964   } else {
25965     wterm(" appears not to be a mem file)\n");
25966   }
25967   mp->history = mp_fatal_error_stop;
25968   mp_jump_out(mp);
25969 }
25970 DONE:
25971
25972
25973 @ Here we do whatever is needed to complete \MP's job gracefully on the
25974 local operating system. The code here might come into play after a fatal
25975 error; it must therefore consist entirely of ``safe'' operations that
25976 cannot produce error messages. For example, it would be a mistake to call
25977 |str_room| or |make_string| at this time, because a call on |overflow|
25978 might lead to an infinite loop.
25979 @^system dependencies@>
25980
25981 This program doesn't bother to close the input files that may still be open.
25982
25983 @ @c
25984 void mp_close_files_and_terminate (MP mp) {
25985   integer k; /* all-purpose index */
25986   integer LH; /* the length of the \.{TFM} header, in words */
25987   int lk_offset; /* extra words inserted at beginning of |lig_kern| array */
25988   pointer p; /* runs through a list of \.{TFM} dimensions */
25989   if (mp->finished) 
25990     return;
25991   @<Close all open files in the |rd_file| and |wr_file| arrays@>;
25992   if ( mp->internal[mp_tracing_stats]>0 )
25993     @<Output statistics about this job@>;
25994   wake_up_terminal; 
25995   @<Do all the finishing work on the \.{TFM} file@>;
25996   @<Explain what output files were written@>;
25997   if ( mp->log_opened  && ! mp->noninteractive ){ 
25998     wlog_cr;
25999     (mp->close_file)(mp,mp->log_file); 
26000     mp->selector=mp->selector-2;
26001     if ( mp->selector==term_only ) {
26002       mp_print_nl(mp, "Transcript written on ");
26003 @.Transcript written...@>
26004       mp_print(mp, mp->log_name); mp_print_char(mp, xord('.'));
26005     }
26006   }
26007   mp_print_ln(mp);
26008   mp->finished = true;
26009 }
26010
26011 @ @<Declarations@>=
26012 static void mp_close_files_and_terminate (MP mp) ;
26013
26014 @ @<Close all open files in the |rd_file| and |wr_file| arrays@>=
26015 if (mp->rd_fname!=NULL) {
26016   for (k=0;k<=(int)mp->read_files-1;k++ ) {
26017     if ( mp->rd_fname[k]!=NULL ) {
26018       (mp->close_file)(mp,mp->rd_file[k]);
26019       xfree(mp->rd_fname[k]);      
26020    }
26021  }
26022 }
26023 if (mp->wr_fname!=NULL) {
26024   for (k=0;k<=(int)mp->write_files-1;k++) {
26025     if ( mp->wr_fname[k]!=NULL ) {
26026      (mp->close_file)(mp,mp->wr_file[k]);
26027       xfree(mp->wr_fname[k]); 
26028     }
26029   }
26030 }
26031
26032 @ @<Dealloc ...@>=
26033 for (k=0;k<(int)mp->max_read_files;k++ ) {
26034   if ( mp->rd_fname[k]!=NULL ) {
26035     (mp->close_file)(mp,mp->rd_file[k]);
26036     xfree(mp->rd_fname[k]); 
26037   }
26038 }
26039 xfree(mp->rd_file);
26040 xfree(mp->rd_fname);
26041 for (k=0;k<(int)mp->max_write_files;k++) {
26042   if ( mp->wr_fname[k]!=NULL ) {
26043     (mp->close_file)(mp,mp->wr_file[k]);
26044     xfree(mp->wr_fname[k]); 
26045   }
26046 }
26047 xfree(mp->wr_file);
26048 xfree(mp->wr_fname);
26049
26050
26051 @ We want to produce a \.{TFM} file if and only if |mp_fontmaking| is positive.
26052
26053 We reclaim all of the variable-size memory at this point, so that
26054 there is no chance of another memory overflow after the memory capacity
26055 has already been exceeded.
26056
26057 @<Do all the finishing work on the \.{TFM} file@>=
26058 if ( mp->internal[mp_fontmaking]>0 ) {
26059   @<Make the dynamic memory into one big available node@>;
26060   @<Massage the \.{TFM} widths@>;
26061   mp_fix_design_size(mp); mp_fix_check_sum(mp);
26062   @<Massage the \.{TFM} heights, depths, and italic corrections@>;
26063   mp->internal[mp_fontmaking]=0; /* avoid loop in case of fatal error */
26064   @<Finish the \.{TFM} file@>;
26065 }
26066
26067 @ @<Make the dynamic memory into one big available node@>=
26068 mp->rover=lo_mem_stat_max+1; mp_link(mp->rover)=empty_flag; mp->lo_mem_max=mp->hi_mem_min-1;
26069 if ( mp->lo_mem_max-mp->rover>max_halfword ) mp->lo_mem_max=max_halfword+mp->rover;
26070 node_size(mp->rover)=mp->lo_mem_max-mp->rover; 
26071 lmp_link(mp->rover)=mp->rover; rmp_link(mp->rover)=mp->rover;
26072 mp_link(mp->lo_mem_max)=null; mp_info(mp->lo_mem_max)=null
26073
26074 @ The present section goes directly to the log file instead of using
26075 |print| commands, because there's no need for these strings to take
26076 up |str_pool| memory when a non-{\bf stat} version of \MP\ is being used.
26077
26078 @<Output statistics...@>=
26079 if ( mp->log_opened ) { 
26080   char s[128];
26081   wlog_ln(" ");
26082   wlog_ln("Here is how much of MetaPost's memory you used:");
26083 @.Here is how much...@>
26084   mp_snprintf(s,128," %i string%s out of %i",(int)mp->max_strs_used-mp->init_str_use,
26085           (mp->max_strs_used!=mp->init_str_use+1 ? "s" : ""),
26086           (int)(mp->max_strings-1-mp->init_str_use));
26087   wlog_ln(s);
26088   mp_snprintf(s,128," %i string characters out of %i",
26089            (int)mp->max_pl_used-mp->init_pool_ptr,
26090            (int)mp->pool_size-mp->init_pool_ptr);
26091   wlog_ln(s);
26092   mp_snprintf(s,128," %i words of memory out of %i",
26093            (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2,
26094            (int)mp->mem_end);
26095   wlog_ln(s);
26096   mp_snprintf(s,128," %i symbolic tokens out of %i", (int)mp->st_count, (int)mp->hash_size);
26097   wlog_ln(s);
26098   mp_snprintf(s,128," %ii,%in,%ip,%ib stack positions out of %ii,%in,%ip,%ib",
26099            (int)mp->max_in_stack,(int)mp->int_ptr,
26100            (int)mp->max_param_stack,(int)mp->max_buf_stack+1,
26101            (int)mp->stack_size,(int)mp->max_internal,(int)mp->param_size,(int)mp->buf_size);
26102   wlog_ln(s);
26103   mp_snprintf(s,128," %i string compactions (moved %i characters, %i strings)",
26104           (int)mp->pact_count,(int)mp->pact_chars,(int)mp->pact_strs);
26105   wlog_ln(s);
26106 }
26107
26108 @ It is nice to have have some of the stats available from the API.
26109
26110 @<Exported function ...@>=
26111 int mp_memory_usage (MP mp );
26112 int mp_hash_usage (MP mp );
26113 int mp_param_usage (MP mp );
26114 int mp_open_usage (MP mp );
26115
26116 @ @c
26117 int mp_memory_usage (MP mp ) {
26118         return (int)mp->lo_mem_max+mp->mem_end-mp->hi_mem_min+2;
26119 }
26120 int mp_hash_usage (MP mp ) {
26121   return (int)mp->st_count;
26122 }
26123 int mp_param_usage (MP mp ) {
26124         return (int)mp->max_param_stack;
26125 }
26126 int mp_open_usage (MP mp ) {
26127         return (int)mp->max_in_stack;
26128 }
26129
26130 @ We get to the |final_cleanup| routine when \&{end} or \&{dump} has
26131 been scanned.
26132
26133 @c
26134 void mp_final_cleanup (MP mp) {
26135   quarterword c; /* 0 for \&{end}, 1 for \&{dump} */
26136   c=mp->cur_mod;
26137   if ( mp->job_name==NULL ) mp_open_log_file(mp);
26138   while ( mp->input_ptr>0 ) {
26139     if ( token_state ) mp_end_token_list(mp);
26140     else  mp_end_file_reading(mp);
26141   }
26142   while ( mp->loop_ptr!=null ) mp_stop_iteration(mp);
26143   while ( mp->open_parens>0 ) { 
26144     mp_print(mp, " )"); decr(mp->open_parens);
26145   };
26146   while ( mp->cond_ptr!=null ) {
26147     mp_print_nl(mp, "(end occurred when ");
26148 @.end occurred...@>
26149     mp_print_cmd_mod(mp, fi_or_else,mp->cur_if);
26150     /* `\.{if}' or `\.{elseif}' or `\.{else}' */
26151     if ( mp->if_line!=0 ) {
26152       mp_print(mp, " on line "); mp_print_int(mp, mp->if_line);
26153     }
26154     mp_print(mp, " was incomplete)");
26155     mp->if_line=if_line_field(mp->cond_ptr);
26156     mp->cur_if=mp_name_type(mp->cond_ptr); mp->cond_ptr=mp_link(mp->cond_ptr);
26157   }
26158   if ( mp->history!=mp_spotless )
26159     if ( ((mp->history==mp_warning_issued)||(mp->interaction<mp_error_stop_mode)) )
26160       if ( mp->selector==term_and_log ) {
26161     mp->selector=term_only;
26162     mp_print_nl(mp, "(see the transcript file for additional information)");
26163 @.see the transcript file...@>
26164     mp->selector=term_and_log;
26165   }
26166   if ( c==1 ) {
26167     if (mp->ini_version) {
26168       mp_store_mem_file(mp); return;
26169     }
26170     mp_print_nl(mp, "(dump is performed only by INIMP)"); return;
26171 @.dump...only by INIMP@>
26172   }
26173 }
26174
26175 @ @<Declarations@>=
26176 static void mp_final_cleanup (MP mp) ;
26177 static void mp_init_prim (MP mp) ;
26178 static void mp_init_tab (MP mp) ;
26179
26180 @ @c
26181 void mp_init_prim (MP mp) { /* initialize all the primitives */
26182   @<Put each...@>;
26183 }
26184 @#
26185 void mp_init_tab (MP mp) { /* initialize other tables */
26186   integer k; /* all-purpose index */
26187   @<Initialize table entries (done by \.{INIMP} only)@>;
26188 }
26189
26190
26191 @ When we begin the following code, \MP's tables may still contain garbage;
26192 thus we must proceed cautiously to get bootstrapped in.
26193
26194 But when we finish this part of the program, \MP\ is ready to call on the
26195 |main_control| routine to do its work.
26196
26197 @<Get the first line...@>=
26198
26199   @<Initialize the input routines@>;
26200   if (mp->mem_ident==NULL) {
26201     if ( ! mp_load_mem_file(mp) ) {
26202       (mp->close_file)(mp, mp->mem_file); 
26203        mp->history = mp_fatal_error_stop;
26204        return mp;
26205     }
26206     (mp->close_file)(mp, mp->mem_file);
26207   }
26208   @<Initializations following first line@>;
26209 }
26210
26211 @ @<Initializations following first line@>=
26212   mp->buffer[limit]=(ASCII_code)'%';
26213   mp_fix_date_and_time(mp);
26214   if (mp->random_seed==0)
26215     mp->random_seed = (mp->internal[mp_time] / unity)+mp->internal[mp_day];
26216   mp_init_randoms(mp, mp->random_seed);
26217   @<Initialize the print |selector|...@>;
26218   if ( loc<limit ) if ( mp->buffer[loc]!='\\' ) 
26219     mp_start_input(mp); /* \&{input} assumed */
26220
26221 @ @<Run inimpost commands@>=
26222 {
26223   mp_get_strings_started(mp);
26224   mp_init_tab(mp); /* initialize the tables */
26225   mp_init_prim(mp); /* call |primitive| for each primitive */
26226   mp->init_str_use=mp->max_str_ptr=mp->str_ptr;
26227   mp->init_pool_ptr=mp->max_pool_ptr=mp->pool_ptr;
26228   mp_fix_date_and_time(mp);
26229 }
26230
26231 @ Saving the filename template
26232
26233 @<Save the filename template@>=
26234
26235   if ( mp->filename_template!=0 ) delete_str_ref(mp->filename_template);
26236   if ( length(mp->cur_exp)==0 ) mp->filename_template=0;
26237   else { 
26238     mp->filename_template=mp->cur_exp; add_str_ref(mp->filename_template);
26239   }
26240 }
26241
26242 @* \[47] Debugging.
26243
26244
26245 @* \[48] System-dependent changes.
26246 This section should be replaced, if necessary, by any special
26247 modification of the program
26248 that are necessary to make \MP\ work at a particular installation.
26249 It is usually best to design your change file so that all changes to
26250 previous sections preserve the section numbering; then everybody's version
26251 will be consistent with the published program. More extensive changes,
26252 which introduce new sections, can be inserted here; then only the index
26253 itself will get a new section number.
26254 @^system dependencies@>
26255
26256 @* \[49] Index.
26257 Here is where you can find all uses of each identifier in the program,
26258 with underlined entries pointing to where the identifier was defined.
26259 If the identifier is only one letter long, however, you get to see only
26260 the underlined entries. {\sl All references are to section numbers instead of
26261 page numbers.}
26262
26263 This index also lists error messages and other aspects of the program
26264 that you might want to look up some day. For example, the entry
26265 for ``system dependencies'' lists all sections that should receive
26266 special attention from people who are installing \MP\ in a new
26267 operating environment. A list of various things that can't happen appears
26268 under ``this can't happen''.
26269 Approximately 25 sections are listed under ``inner loop''; these account
26270 for more than 60\pct! of \MP's running time, exclusive of input and output.