OSDN Git Service

3f230b7e660885a4bf44e282a267b3dd10def542
[putex/putex.git] / src / texsourc / local.c
1 /* Copyright 2007 TeX Users Group
2    Copyright 2014 Clerk Ma   
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301 USA.  */
18
19 #define EXTERN extern
20
21 #include "texd.h"
22
23 #define USEOUREALLOC
24 #define USEMEMSET
25
26 #ifdef USEOUREALLOC
27   #define REALLOC ourrealloc
28 #else
29   #define REALLOC realloc
30 #endif
31
32 int wantcopyrght = 1;
33
34 char *compiletime  =  __TIME__;
35 char *compiledate  =  __DATE__;
36 char *www          = "http://www.tug.org/yandy";
37 char *copyright    = "\nCopyright (C) 1993--2000 Y&Y, Inc.\n"
38                      "Copyright (C) 2007 TeX Users Group.\n"
39                      "Copyright (C) 2014 Clerk Ma.\n\n"
40                      "This program is free software; you can redistribute it and/or modify\n"
41                      "it under the terms of the GNU General Public License as published by\n"
42                      "the Free Software Foundation; either version 2 of the License, or\n"
43                      "(at your option) any later version.\n\n  ";
44 char *yandyversion = "2.3.0";
45 char *application  = "Y&Y TeX";
46 char *tex_version  = "This is TeX, Version 3.14159265";
47
48 clock_t start_time, main_time, finish_time;
49
50 char * dvi_directory = "";
51 char * log_directory = "";
52 char * aux_directory = "";
53 char * fmt_directory = "";
54 char * pdf_directory = "";
55
56 char * texpath = "";
57
58 char log_line[MAXLINE];  // used also in tex9.c
59
60 int mem_spec_flag     = 0;    /* non-zero if `-m=...' was used */ 
61 int format_spec       = 0;    /* non-zero if a format specified on command line */
62 int closed_already    = 0;    /* make sure we don't try this more than once */
63 boolean reorder_arg_flag = true; /* put command line flags/arguments first */
64
65 /* Mapping from Windows ANSI to DOS code page 850 96/Jan/20 */
66 /* Used in tex0.c with wintodos[c-128]                      */
67
68 unsigned char wintodos[128] =
69 {
70     0,   0,   0, 159,   0,   0,   0,   0,
71    94,   0,   0,   0,   0,   0,   0,   0,
72     0,  96,  39,   0,   0,   7,   0,   0,
73   126,   0,   0,   0,   0,   0,   0,   0,
74    32, 173, 189, 156, 207, 190, 221,  21,
75     0, 184, 166, 174, 170,  45, 169,   0,
76   248, 241, 253, 252,   0, 230,  20, 250,
77     0, 251, 167, 175, 172, 171, 243, 168,
78   183, 181, 182, 199, 142, 143, 146, 128,
79   212, 144, 210, 211, 222, 214, 215, 216,
80   209, 165, 227, 224, 226, 229, 153, 158,
81   157, 235, 233, 234, 154, 237, 232, 225,
82   133, 160, 131, 198, 132, 134, 145, 135,
83   138, 130, 136, 137, 141, 161, 140, 139,
84   208, 164, 149, 162, 147, 228, 148, 246,
85   155, 151, 163, 150, 129, 236, 231, 152
86 };  
87
88 void show_usage (void)
89 {
90   printf("\n"
91       " Useage: yanytex [OPTION]... [+format_file] [tex_file]\n\n"
92       "    --help    -?\n"
93       "        show this usage summary\n"
94       "    --initex  -i\n"
95       "        start up as iniTeX (create format file)\n"
96       "    --verbose -v\n"
97       "        be verbose (show implementation version number)\n"
98       "    -n    do not allow `non ASCII' characters in input files (complain instead)\n"
99       "    --showhex -w\n"
100       "        do not show `non ASCII' characters in hexadecimal (show as is)\n"
101       "    -d    do not allow DOS style file names - i.e. do not convert \\ to /\n"
102       "    -r    do not allow Mac style termination - i.e. do not convert \\r to \\n\n"
103       "    --patterns    -p\n"
104       "        allow use of \\patterns after loading format (iniTeX only)\n"
105       "    --knuthify    -K\n"
106       "        disable all extensions to basic TeX\n"
107       "    --main-memory -m\n"
108       "        initial main memory size in kilo words (iniTeX only)\n"
109       "    --hyph-size   -e\n"
110       "        hyphenation exception dictionary size (iniTeX only)\n"
111       "    --trie-size   -h\n"
112       "        hyphenation pattern trie size (iniTeX only)\n"
113       "    --xchr-file   -x\n"
114       "        use `non ASCII' character mapping (xchr[]) defined in file\n"
115       "    --key-file    -k\n"
116       "        use `key replacement' defined in file\n"
117       "    --dvi-dir     -o\n"
118       "        write DVI file in specified directory (default current directory)\n"
119       "    --log-dir     -l\n"
120       "        write LOG file in specified directory (default current directory)\n"
121       "    --aux-dir     -a\n"
122       "        write AUX file in specified directory (default current directory)\n");
123
124 #ifndef _WINDOWS
125   uexit(EXIT_FAILURE);     // has this been setup yet ???
126 #endif
127 }
128
129 /* -z    do not discard control-Z at end of input file (treat as character)\n\ */
130
131 /* \t-d\tallow DOS style file names - i.e. convert \\ to / \n\ */
132 /* \t\t(applies to file name and format file name, if present)\n\ */
133 /* \t-r\tallow Mac style line termination - i.e. convert \\r to \\n \n\ */
134
135 // Sep 27 1990 => 1990 Sep 27
136 // 012456789      0123456789
137 void scivilize (char * date)
138 {
139   int k;
140   char pyear[6];
141
142   strcpy (pyear, date + 7);
143
144   for (k = 5; k >= 0; k--)
145     date[k + 5] = date[k];
146
147   for (k = 0; k < 4; k++)
148     date[k] = pyear[k];
149
150   date[4] = ' ';
151
152   if (date[9] == ' ')
153     date[9] = '0'; /* replace space by '0' */
154 }
155
156 // Thu Sep 27 06:26:35 1990 => 1990 Sep 27 06:26:35
157 void lcivilize (char * date)
158 {
159   int k;
160   char pyear[6];
161
162   strcpy (pyear, date + 20);
163
164   for (k = 18; k >= 0; k--)
165     date[k+1] = date[k];
166
167   date[20] = '\0';
168
169   for (k = 0; k < 4; k++)
170     date[k] = pyear[k];
171
172   date[4] = ' ';
173 }
174
175 // now writes result into given buffer
176 void stamp_it (char *s)
177 {
178   char date[11 + 1];
179
180   strcpy(date, compiledate);
181   scivilize(date);
182   sprintf(s, "%s %s ", application, yandyversion);
183   s += strlen(s);
184   sprintf(s, "(compiled time: %s %s)", date, compiletime);
185   s += strlen(s);
186 }
187
188 void stampcopy (char *s)
189 {
190   if (wantcopyrght)
191   {
192     sprintf(s, "%s %s", copyright, www);
193   }
194 }
195
196 #define MAXCHRS 256
197 #define NOTDEF  127
198
199 void read_xchr_sub (FILE * xchr_input)
200 {
201   char buffer[file_name_size];
202   int k, from, to, count = 0;
203   char *s;
204
205   memset(xchr, NOTDEF, MAXCHRS);
206   memset(xord, NOTDEF, MAXCHRS);
207
208 #ifdef ALLOCATEBUFFER
209   while (fgets(buffer, current_buf_size, xchr_input) != NULL)
210 #else
211   while (fgets(buffer, sizeof(buffer), xchr_input) != NULL)
212 #endif
213   {
214     if (*buffer == '%' || *buffer == ';' || *buffer == '\n')
215       continue;
216
217     from = (int) strtol (buffer, &s, 0);
218     to = (int) strtol (s, NULL, 0);
219
220     if (from >= 0 && from < MAXCHRS && to >= 0 && to < MAXCHRS)
221     {
222       if (xchr[from] == (unsigned char) NOTDEF)
223       {
224         xchr[from] = (unsigned char) to;
225       }
226       else
227       {
228         sprintf(log_line, "NOTE: %s collision: %d => %d, %d\n", "xchr", from, xchr[from], to);
229         show_line(log_line, 0);
230       }
231
232       if (xord[to] == NOTDEF)
233       {
234         xord[to] = (unsigned char) from;
235       }
236       else
237       {
238         sprintf(log_line, "NOTE: %s collision: %d => %d, %d\n", "xord", to, xord[to], from);
239         show_line(log_line, 0);
240       }
241
242       count++;
243     }
244   }
245
246   for (k = 0; k < MAXCHRS; k++)
247   {
248     if (xchr[k] == NOTDEF)   /* if it has not been filled */
249     {
250       if (xord[k] == NOTDEF) /* see whether used already */
251       {
252         xchr[k] = (unsigned char) k; /* no, so make identity */
253         xord[k] = (unsigned char) k; /* no, so make identity */
254       }
255     }
256   }
257
258   xchr[NOTDEF] = NOTDEF;         /* fixed point of mapping */
259
260   if (trace_flag)
261   {
262     sprintf(log_line, "Read %d xchr[] pairs:\n", count);
263     show_line(log_line, 0);
264
265     for (k = 0; k < MAXCHRS; k++)
266     {
267       if (xchr[k] != NOTDEF)
268       {
269         sprintf(log_line, "%d => %d\n", k, xchr[k]);
270         show_line(log_line, 0);
271       }
272     }
273   }
274 }
275
276 char *replacement[MAXCHRS];     /* pointers to replacement strings */
277
278 void read_repl_sub (FILE * repl_input)
279 {
280   int k, n, m, chrs;
281   char buffer[file_name_size];
282   char charname[128];
283   int charnum[10];
284   char *s, *t;
285   
286   memset(replacement, 0, MAXCHRS * sizeof(replacement[ 0]));
287
288
289   while (fgets(buffer, file_name_size, repl_input) != NULL)
290   {
291     if (*buffer == '%' || *buffer == ';' || *buffer == '\n')
292       continue;
293
294     if ((m = sscanf(buffer, "%d%n %s", &chrs, &n, &charname)) == 0)
295       continue;
296     else if (m == 2)
297     {
298       if (*charname == '"')   /* deal with quoted string "..." */
299       {
300         s = buffer + n;
301         t = charname;
302
303         while (*s != '"' && *s != '\0')
304           s++;  /* step up to " */
305
306         if (*s++ == '\0')
307           continue;       /* sanity check */
308
309         while (*s != '\0')
310         {
311           if (*s == '"')
312           {
313             s++;            /* is it "" perhaps ? */
314
315             if (*s != '"')
316               break;   /* no, end of string */
317           }
318
319           *t++ = *s++;          /* copy over */
320         }
321
322         *t = '\0';              /* and terminate */
323       }
324
325       if (chrs >= 0 && chrs < MAXCHRS)
326         replacement[chrs] = xstrdup(charname);
327     }
328 /*    presently the following can never get triggered */
329 /*    which is good, because it is perhaps not right ... */
330     else if ((m = sscanf (buffer, "%d %d %d %d %d %d %d %d %d %d %d",
331       &chrs, charnum, charnum+1, charnum+2, charnum+3, charnum+4,
332         charnum+5, charnum+6, charnum+7, charnum+8, charnum+9)) > 1) {
333 /*      for (k = 0; k < n-1; k++) charname[k] = (char) charnum; */
334       for (k = 0; k < n-1; k++) charname[k] = (char) charnum[k];
335       charname[m] = '\0';
336       if (chrs >= 0 && chrs < MAXCHRS)
337         replacement[chrs] = xstrdup(charname);      
338     }
339     else {
340       sprintf(log_line, "ERROR: don't understand %s", buffer);
341       show_line(log_line, 1);
342     }
343   }
344
345   if (trace_flag)
346   {
347     puts("Key replacement table\n");
348
349     for (k = 0; k < MAXCHRS; k++)
350     {
351       if (replacement[k] != NULL)
352       {
353         sprintf(log_line, "%d\t%s\n", k, replacement[k]);
354         show_line(log_line, 0);
355       }
356     }
357   }
358 }
359
360 /* Following used both to read xchr[] file and key replacement file */
361 /* the flag is 0 for -x=... and the flag is 1 for -k=... */
362 int read_xchr_file (char *filename, int flag, char *argv[])
363 {
364   FILE *pinput;
365   char infile[file_name_size];
366   char *s;
367
368   if (filename == NULL)
369     return -1;
370
371   if (trace_flag)
372   {
373     sprintf(log_line, "Reading xchr/repl %s\n", filename);
374     show_line(log_line, 0);
375   }
376
377 /*  first try using file as specified */
378   strcpy(infile, filename);
379
380   if (trace_flag)
381   {
382     sprintf(log_line, "Trying %s\n", infile);
383     show_line(log_line, 0);
384   }
385
386   pinput = fopen (infile, "r");
387
388   if (pinput == NULL)
389   {
390     if (strrchr(infile, '.') == NULL)
391     {
392       if (flag == 0)
393         strcat(infile, ".map");
394       else
395         strcat(infile, ".key");
396
397       if (trace_flag)
398       {
399         sprintf(log_line, "Trying %s\n", infile);
400         show_line(log_line, 0);
401       }
402       
403       pinput = fopen (infile, "r");
404     }
405   }
406
407   if (pinput == NULL)
408   {
409     strcpy(infile, argv[0]);     /* try TeX program path */
410
411     if ((s = strrchr (infile, '\\')) != NULL) *(s+1) = '\0';
412     else if ((s = strrchr (infile, '/')) != NULL) *(s+1) = '\0';
413     else if ((s = strrchr (infile, ':')) != NULL) *(s+1) = '\0';
414
415     strcat (infile, filename);
416
417     if (trace_flag)
418     {
419       sprintf(log_line, "Trying %s\n", infile);
420       show_line(log_line, 0);
421     }
422
423     pinput = fopen (infile, "r");
424
425     if (pinput == NULL)
426     {
427       if (strchr(infile, '.') == NULL)
428       {
429         if (flag == 0)
430           strcat(infile, ".map");
431         else
432           strcat(infile, ".key");
433
434         if (trace_flag)
435         {
436           sprintf(log_line, "Trying %s\n", infile);
437           show_line(log_line, 0);
438         }
439
440         pinput = fopen (infile, "r");
441       }
442     }
443   }
444
445   if (pinput == NULL)   /* 97/July/31 */
446   {
447     strcpy (infile, argv[0]);     /* try TeX program path */
448
449     if ((s = strrchr (infile, '\\')) != NULL) *(s+1) = '\0';
450     else if ((s = strrchr (infile, '/')) != NULL) *(s+1) = '\0';
451     else if ((s = strrchr (infile, ':')) != NULL) *(s+1) = '\0';
452
453     strcat (infile, "keyboard\\");
454     strcat (infile, filename);
455
456     if (trace_flag)
457     {
458       sprintf(log_line, "Trying %s\n", infile);
459       show_line(log_line, 0);
460     }
461
462     pinput = fopen (infile, "r");
463
464     if (pinput == NULL)
465     {
466       if (strchr(infile, '.') == NULL)
467       {
468         if (flag == 0)
469           strcat(infile, ".map");
470         else
471           strcat(infile, ".key");
472
473         if (trace_flag)
474         {
475           sprintf(log_line, "Trying %s\n", infile);
476           show_line(log_line, 0);
477         }
478
479         pinput = fopen (infile, "r");
480       }
481     }
482   }
483 /*  Note: can't look in TeX source file dir, since that is not known yet */
484   if (pinput == NULL)
485   {
486     sprintf(log_line, "ERROR: Sorry, cannot find %s file %s",
487         flag ? " xchr[]" : "key mapping", filename);
488     show_line(log_line, 1);
489     perrormod (filename);
490     return 0;         // failed
491   }
492
493   if (flag == 0)
494     read_xchr_sub (pinput);
495   else
496     read_repl_sub (pinput);
497
498   (void) fclose (pinput);
499   return 1;
500 }
501
502 /* need to also set `key_replace' here based on command line */
503 /* need to also allocate `buffercopy' here and free at end */
504 /* need to call `readreplace' in appropriate place */
505
506 /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
507
508 #define MAXSPLITS 3
509
510 /* ad hoc default minimum growth in memory realloc is 62% */
511 /* golden ratio (1 + \sqrt{5}) / 2 = 1.618033989... */
512 int percent_grow    = 62; /* default minimum growth in memory realloc is 62% */
513 int total_allocated = 0;  /* total memory allocated so far */
514 int ini_max_address = 0;  /* maximum address when starting */
515 int max_address     = 0;  /* maximum address seen in allocated memory */
516
517
518 void show_maximums (FILE * output)
519 {
520   sprintf(log_line, "Max allocated %d --- max address %d\n", total_allocated, max_address);
521   fputs(log_line, output);
522 }
523
524 /* our own version of realloc --- avoid supposed MicroSoft version bug */
525 /* also tries _expand first, which can avoid address growth ... */
526
527 #ifdef USEOUREALLOC 
528 void *ourrealloc (void *old, size_t new_size)
529 {
530   void * mnew;
531   size_t old_size, overlap;
532   
533   /*  round up to nearest multiple of four bytes */
534   /* avoid unlikely alignment */
535   if ((new_size % 4) != 0)
536     new_size = ((new_size / 4) + 1) * 4;
537
538   if (old == NULL)
539     return malloc (new_size);  /* no old block - use malloc */
540
541 #ifdef _WIN32
542   old_size = _msize (old);
543 #else
544   old_size = malloc_usable_size (old);
545 #endif
546
547   if (old_size >= new_size && old_size < new_size + 4)
548     return old;
549
550 #ifdef _WIN32
551   mnew = _expand (old, new_size); /* first try and expand in place MSVC */
552 #else
553   mnew = realloc (old, new_size);
554 #endif
555
556   if (mnew != NULL)
557   {
558     if (trace_flag)
559     {
560       sprintf(log_line, "EXPANDED! %p (%d) == %p (%d)\n",
561           mnew, new_size, old, old_size);
562       show_line(log_line, 0);
563     }
564
565     return mnew;
566   }
567
568   /*  do this if you want to call the real realloc next -  */
569   mnew = realloc (old, new_size);
570
571   if (mnew != NULL)
572     return mnew;
573
574   /*  we are screwed typically if we ever drop through here - no more space */
575   mnew = malloc (new_size); /* otherwise find new space */
576
577   if (mnew == NULL)
578     return mnew;        /* if unable to allocate */
579
580   if (old_size < new_size)
581     overlap = old_size;
582   else
583     overlap = new_size;
584
585   memcpy (mnew, old, overlap); /* copy old data to new area */
586   free(old); /* free the old area */
587
588   return mnew;
589 }
590 #endif
591
592 void memory_error (char *s, int n)
593 {
594   if (log_opened)
595   {
596     fprintf(log_file, "\n! Unable to allocate %d bytes for %s\n", n, s);
597     show_maximums(log_file);
598   }
599
600   sprintf(log_line, "\n! Unable to allocate %d bytes for %s\n", n, s);
601   show_line(log_line, 1);
602   show_maximums(stderr);
603 }
604
605 void trace_memory (char *s, int n)
606 {
607   printf("Allocating %d bytes for %s\n", n, s);
608 }
609
610 void update_statistics (int address, int size, int old_size)
611 {
612   if (address + size > max_address)
613     max_address = address + size;
614
615   total_allocated =  total_allocated + size - old_size;
616 }
617
618 void probe_memory (void)
619 {
620   char *s = (char *) malloc(4); /* get current top address */
621   free(s);
622   update_statistics ((int) s, 0, 0); /* show where we are */
623 }
624
625 void probe_show (void)
626 {
627   probe_memory();
628   show_maximums(stdout);
629 }
630
631 size_t roundup (size_t n)
632 {
633   if ((n % 4) == 0)
634     return n;
635   else
636     return ((n / 4) + 1) * 4;
637 }
638
639 #ifdef ALLOCATETRIES
640 /* returns -1 if it fails */
641
642 int allocate_tries (int trie_max)
643 {
644   int n, nl, no, nc;
645
646   if (trie_max > 1000000)
647     trie_max = 1000000;
648
649   nl = (trie_max + 1) * sizeof(halfword);
650   no = (trie_max + 1) * sizeof(halfword);
651   nc = (trie_max + 1) * sizeof(quarterword);
652   n = nl + no + nc;
653
654   if (trace_flag)
655     trace_memory("hyphen trie", n);
656
657   trie_trl = (halfword *) malloc(roundup(nl));
658   trie_tro = (halfword *) malloc(roundup(no));
659   trie_trc = (quarterword *) malloc(roundup(nc));
660
661   if (trie_trl == NULL || trie_tro == NULL || trie_trc == NULL)
662   {
663     memory_error("hyphen trie", n);
664     return -1;
665   }
666
667   if (trace_flag)
668   {
669     sprintf(log_line, "Addresses trie_trl %p trie_tro %p trie_trc %p\n", trie_trl, trie_tro, trie_trc);
670     show_line(log_line, 0);
671   }
672
673   update_statistics((int) trie_trl, nl, 0);
674   update_statistics((int) trie_tro, no, 0);
675   update_statistics((int) trie_trc, nc, 0);
676
677   trie_size = trie_max;
678
679   if (trace_flag)
680     probe_show();
681
682   return 0; // success
683 }
684 #endif
685
686 #ifdef ALLOCATEHYPHEN
687 boolean prime(int); /* test function later in this file */
688
689 int current_prime = 0; /* remember in case reallocated later */
690
691 /* we don't return an address here, since TWO memory regions allocated */
692 /* plus, we don't really reallocate, we FLUSH the old information totally */
693 /* returns -1 if it fails */
694
695 int realloc_hyphen (int hyphen_prime)
696 {
697   int n, nw, nl;
698
699   if (!prime(hyphen_prime))
700   {
701     sprintf(log_line, "ERROR: non-prime hyphen exception number (%d)\n", hyphen_prime);
702     show_line(log_line, 1);
703     return -1;
704   }
705
706 /*  need not/cannot preserve old contents when hyphen prime is changed */
707 /*  if (hyph_list != NULL) free(hyph_list); */
708 /*  if (hyph_word != NULL) free(hyph_word); */
709 /*  important + 1 since str_number hyph_word[hyphen_prime + 1]  in original etc. */
710   nw = (hyphen_prime + 1) * sizeof(str_number);
711   nl = (hyphen_prime + 1) * sizeof(halfword);
712   n = nw + nl;
713
714   if (trace_flag)
715     trace_memory("hyphen exception", n);
716
717   hyph_word = (str_number *) REALLOC (hyph_word, nw);
718   hyph_list = (halfword *) REALLOC (hyph_list, nl);
719
720   if (hyph_word == NULL || hyph_list == NULL)
721   {
722     memory_error("hyphen exception", n);
723     return -1;
724   }
725
726   if (trace_flag)
727   {
728     sprintf(log_line, "Addresses hyph_word %p hyph_list %p\n", hyph_word, hyph_list);
729     show_line(log_line, 0);
730   }
731
732 /*  cannot preserve old contents when hyphen prime is changed */
733 #ifdef USEMEMSET
734   memset(hyph_word, 0, (hyphen_prime + 1) * sizeof (hyph_word[0]));
735 #else
736   for (k = 0; k <= hyphen_prime; k++)
737     hyph_word[k]= 0;
738 #endif
739
740 #ifdef USEMEMSET
741   memset(hyph_list, 0, (hyphen_prime + 1) * sizeof (hyph_list[0]));
742 #else
743   for (k = 0; k <= hyphen_prime; k++)
744     hyph_list[k]= 0;
745 #endif
746
747   hyph_count = 0;
748
749   if (current_prime != 0)
750   {
751     update_statistics((int) hyph_word, nw, (current_prime + 1) * sizeof(str_number));
752     update_statistics((int) hyph_list, nl, (current_prime + 1) * sizeof(halfword));
753   }
754   else
755   {
756     update_statistics((int) hyph_word, nw, 0);
757     update_statistics((int) hyph_list, nl, 0);
758   }
759
760   current_prime = hyphen_prime;
761
762   if (trace_flag)
763     probe_show();
764
765   return 0; // success
766 }
767 #endif
768
769 int current_mem_size = 0;   /* current total words in main mem allocated -1 */
770
771 /* this gets called from itex.c when it figures out what mem_top is */
772 /* or gets called from here when in ini_TeX mode */ /* and nowhere else */
773 /* initial allocation only, may get expanded later */
774 /* NOTE: we DON't use ALLOCATEHIGH & ALLOCATELOW anymore */
775 /* returns NULL if it fails */
776
777 #ifdef ALLOCATEMAIN   
778 /* initial main memory alloc - mem_top */
779 memory_word *allocate_main_memory (int size)
780 {
781   int n;
782
783   if (main_memory != NULL)
784   {
785     if (trace_flag)
786       puts("Reallocating initial memory allocation");
787   }
788
789   mem_top = mem_bot + size;
790   mem_max = mem_top;
791   mem_start = 0;     /* bottom of memory allocated by system */
792   mem_min = 0;       /* bottom of area made available to TeX */
793   n = (mem_max - mem_start + 1) * sizeof (memory_word); /* 256k * 8 = 2000 k */
794
795   if (trace_flag)
796     trace_memory("main memory", n);
797
798   main_memory = (memory_word *) REALLOC (main_memory, n);
799
800   if (main_memory == NULL)
801   {
802     memory_error("initial main memory", n);
803 //    exit (1);
804     return NULL;
805   }
806
807   if (trace_flag)
808   {
809     sprintf(log_line, "Address main memory == %p\n", main_memory);
810     show_line(log_line, 0);
811   }
812
813   mem = main_memory;
814
815   if (mem_start != 0 && !is_initex)
816     mem = main_memory - mem_start;
817
818   if (trace_flag)
819   {
820     sprintf(log_line, "Offset address main memory == %p\n", mem);
821     show_line(log_line, 0);
822   }
823
824   update_statistics((int) main_memory, n, (current_mem_size + 1) * sizeof (memory_word));
825 /*  current_mem_size = (mem_max - mem_start + 1); */
826   current_mem_size = mem_max - mem_start;   /* total number of words - 1 */
827
828   if (trace_flag)
829     probe_show();
830
831   return mem;
832 }
833 #endif
834
835 #ifdef ALLOCATEMAIN
836 /* int firstallocation = 1; */
837
838 /* increase main memory allocation at low end and high end */
839 /* called only from tex0.c *//* called with one of lo_size or hi_size == 0 */
840 /* returns NULL if it fails */
841
842 memory_word * realloc_main (int lo_size, int hi_size)
843 {  
844   int k, min_size;
845   int new_size = 0;
846   int n = 0;
847   memory_word * new_memory = NULL;
848
849   if (trace_flag)
850   {
851     sprintf(log_line, "WARNING: Entering realloc_main lo %d hi %d\n", lo_size, hi_size);
852     show_line(log_line, 0);
853   }
854
855   if (is_initex)
856   {
857     puts("ERROR: Cannot extent main memory in iniTeX\n");
858
859     if (!knuth_flag)
860       puts("Please use `-m=...' on command line");
861
862     return NULL;
863   }
864
865   if (trace_flag)
866   {
867     sprintf(log_line, "Old Address %s == %p\n", "main memory", main_memory);
868     show_line(log_line, 0);
869   }
870
871   /* if we REALLY run up to limit ! */
872   if (current_mem_size + 1 == max_mem_size)
873   {
874     memory_error("main memory", (max_mem_size + 1) * sizeof(memory_word));
875
876     return NULL;
877   }
878
879 /*  first allocation should expand *both* lo and hi */
880   if (hi_size == 0 && mem_end == mem_max)
881     hi_size = lo_size;
882
883   if (lo_size == 0 && mem_start == mem_min)
884     lo_size = hi_size;
885
886 /*  try and prevent excessive frequent reallocations */
887 /*  while avoiding over allocation by too much */
888   min_size = current_mem_size / 100 * percent_grow;
889
890   if (lo_size + hi_size < min_size)
891   {
892     if (lo_size > 0 && hi_size > 0)
893     {
894       lo_size = min_size / 2;
895       hi_size = min_size / 2;
896     }
897     else if (lo_size > 0)
898       lo_size = min_size;
899     else if (hi_size > 0)
900       hi_size = min_size;
901   }
902
903   if (lo_size > 0 && lo_size < mem_top / 2)
904     lo_size = mem_top / 2;
905
906   if (hi_size > 0 && hi_size < mem_top / 2)
907     hi_size = mem_top / 2;
908
909   for (k = 0; k < MAXSPLITS; k++)
910   {
911     new_size = current_mem_size + lo_size + hi_size;
912
913     if (new_size >= max_mem_size) /* bump against limit - ha ha ha */
914     {
915       while (new_size >= max_mem_size)
916       {
917         lo_size = lo_size / 2;
918         hi_size = hi_size / 2;
919         new_size = current_mem_size + lo_size + hi_size;
920       }
921     }
922
923     n = (new_size + 1) * sizeof (memory_word);
924
925     if (trace_flag)
926       trace_memory("main memory", n);
927
928     new_memory = (memory_word *) REALLOC (main_memory, n);
929
930     if (new_memory != NULL)
931       break; /* did we get it ? */
932
933     if (current_mem_size == 0)
934       break; /* in case we ever use for initial */
935
936     lo_size = lo_size / 2; hi_size = hi_size / 2;
937   }
938
939   if (new_memory == NULL)
940   {
941     memory_error("main memory", n);
942     return mem;
943   }
944
945   if (trace_flag)
946   {
947     sprintf(log_line, "New Address %s == %p\n", "main memory", new_memory);
948     show_line(log_line, 0);
949   }
950
951   if (lo_size > 0)
952   {
953 /*  shift everything upward to make space for new low area */
954     if (trace_flag)
955     {
956       sprintf(log_line, "memmove %p %p %d \n", new_memory + lo_size,
957           new_memory, (current_mem_size + 1) * sizeof(memory_word));
958       show_line(log_line, 0);
959     }
960
961     memmove (new_memory + lo_size, new_memory,
962       (current_mem_size + 1) * sizeof(memory_word));
963 /*  could reduce words moved by (mem_max - mem_end) */
964   }
965
966   main_memory = new_memory;       /* remember for free later */
967
968   if (lo_size > 0)
969     mem_start = mem_start - lo_size; /* update lower limit */
970
971   if (hi_size > 0)
972     mem_max = mem_max + hi_size;   /* update upper limit */
973
974   update_statistics ((int) main_memory, n,
975     (current_mem_size + 1) * sizeof (memory_word));
976   current_mem_size = new_size;
977
978   if (current_mem_size != mem_max - mem_start)
979   {
980     puts("ERROR: Impossible Memory Error");
981   }
982
983   if (mem_start != 0)
984     mem = main_memory - mem_start;
985   else
986     mem = main_memory;
987
988   if (trace_flag)
989     probe_show();
990
991   return mem;
992 }
993 #endif
994
995 #ifdef ALLOCATEFONT
996 int current_font_mem_size = 0;
997
998 /* fmemoryword can be either halfword or memory_word */
999 memory_word * realloc_font_info (int size)
1000 {
1001   memory_word * new_font_info = NULL;
1002   int k, min_size;
1003   int new_size = 0;
1004   int n = 0;
1005
1006   if (trace_flag)
1007   {
1008     sprintf(log_line, "Old Address %s == %p\n",  "font_info", font_info);
1009     show_line(log_line, 0);
1010   }
1011 /*  during initial allocation, font_info == NULL - realloc acts like malloc */
1012 /*  during initial allocation current_font_mem_size == 0 */
1013   if (current_font_mem_size == font_mem_size)  /* if we REALLY run up to limit */
1014   {
1015 /*    memory_error("font", (font_mem_size + 1) * sizeof(memory_word)); */
1016     return font_info;    /* pass it back to TeX 99/Fabe/4 */
1017   }
1018 /*  try and prevent excessive frequent reallocations */
1019 /*  while avoiding over allocation by too much */
1020 /*  min_size = current_font_mem_size / 2; */
1021   min_size = current_font_mem_size / 100 * percent_grow;
1022
1023   if (size < min_size)
1024     size = min_size;
1025
1026   if (size < initial_font_mem_size)
1027     size = initial_font_mem_size;
1028
1029   for (k=0; k < MAXSPLITS; k++)
1030   {
1031     new_size = current_font_mem_size + size;
1032
1033     if (new_size > font_mem_size)
1034       new_size = font_mem_size; /* bump against limit */
1035
1036 /*    important + 1 since fmemoryword font_info[font_mem_size + 1]  original */
1037     n = (new_size + 1) * sizeof (memory_word);
1038
1039     if (trace_flag)
1040       trace_memory("font_info", n);
1041
1042     new_font_info = (memory_word *) REALLOC (font_info, n);
1043
1044     if (new_font_info != NULL)
1045       break;   /* did we get it ? */
1046
1047     if (current_font_mem_size == 0)
1048       break; /* initial allocation must work */
1049
1050     size = size / 2;
1051   }
1052
1053   if (new_font_info == NULL)
1054   {
1055     memory_error("font", n);
1056     return font_info;        /* try and continue !!! */
1057   }
1058
1059   font_info = new_font_info;
1060
1061   if (trace_flag)
1062   {
1063     sprintf(log_line, "New Address %s == %p\n", "font_info", font_info);
1064     show_line(log_line, 0);
1065   }
1066
1067   update_statistics ((int) font_info, n, current_font_mem_size * sizeof(memory_word));
1068   current_font_mem_size = new_size;
1069
1070   if (trace_flag)
1071     probe_show();
1072
1073   return font_info;
1074 }
1075 #endif
1076
1077 #ifdef ALLOCATESTRING
1078 int current_pool_size = 0;
1079
1080 packed_ASCII_code * realloc_str_pool (int size)
1081 {
1082   int k, min_size;
1083   int new_size = 0;
1084   int n = 0;
1085   packed_ASCII_code *newstrpool = NULL;
1086
1087   if (trace_flag)
1088   {
1089     sprintf(log_line, "Old Address %s == %p\n", "string pool", str_pool);
1090     show_line(log_line, 0);
1091   }
1092
1093   if (current_pool_size == pool_size)
1094   {
1095 /*    memory_error ("string pool", (pool_size + 1) * sizeof(packed_ASCII_code)); */
1096 /*    exit (1); */
1097     return str_pool;   /* pass it back to TeX 99/Fabe/4 */
1098   }
1099
1100   min_size =  current_pool_size / 100 * percent_grow;
1101
1102   if (size < min_size)
1103     size = min_size;
1104
1105   if (size < initial_pool_size)
1106     size = initial_pool_size;
1107
1108   for (k = 0; k < MAXSPLITS; k++)
1109   {
1110     new_size = current_pool_size + size;
1111
1112     if (new_size > pool_size)
1113       new_size = pool_size;
1114 /* important + 1 since  packed_ASCII_code str_pool[pool_size + 1]; in original */
1115     n = (new_size + 1) * sizeof (packed_ASCII_code);
1116
1117     if (trace_flag)
1118       trace_memory("str_pool", n);
1119
1120     newstrpool = (packed_ASCII_code *) REALLOC (str_pool, n); /* 95/Sep/24 */
1121
1122     if (newstrpool != NULL)
1123       break;    /* did we get it ? */
1124
1125     if (current_pool_size == 0)
1126       break;  /* initial allocation must work */
1127
1128     size = size / 2;          /* else can retry smaller */
1129   }
1130
1131   if (newstrpool == NULL)
1132   {
1133     memory_error("string pool", n);
1134     return str_pool;           /* try and continue !!! */
1135   }
1136
1137   str_pool = newstrpool;
1138   update_statistics ((int) str_pool, n, current_pool_size);
1139   current_pool_size = new_size;
1140
1141   if (trace_flag)
1142   {
1143     sprintf(log_line, "New Address %s == %p\n", "string pool", str_pool);
1144     show_line(log_line, 0);
1145   }
1146   
1147   if (trace_flag)
1148     probe_show();
1149
1150   return str_pool;
1151 }
1152 #endif
1153
1154 #ifdef ALLOCATESTRING
1155 int current_max_strings = 0;
1156
1157 pool_pointer *realloc_str_start (int size)
1158 {
1159   int k, min_size;
1160   int n = 0;
1161   int new_size = 0;
1162   pool_pointer * new_str_start = NULL;
1163
1164   if (trace_flag)
1165   {
1166     sprintf(log_line, "Old Address %s == %p\n", "string start", str_start);
1167     show_line(log_line, 0);
1168   }
1169
1170   if (current_max_strings == max_strings)
1171   {
1172 /*    memory_error ("string pointer", (max_strings + 1) * sizeof(pool_pointer)); */
1173 /*    exit (1); */
1174     return str_start;    /* pass it back to TeX 99/Fabe/4 */
1175   }
1176
1177   min_size = current_max_strings / 100 * percent_grow;
1178
1179   if (size < min_size)
1180     size = min_size;
1181
1182   if (size < initial_max_strings)
1183     size = initial_max_strings;
1184
1185   for (k = 0; k < MAXSPLITS; k++)
1186   {
1187     new_size = current_max_strings + size;
1188
1189     if (new_size > max_strings)
1190       new_size = max_strings;
1191 /*    important + 1 since str_start[maxstring + 1] originally */
1192     n = (new_size + 1) * sizeof (pool_pointer);
1193
1194     if (trace_flag)
1195       trace_memory("str_start", n);
1196
1197     new_str_start = (pool_pointer *) REALLOC (str_start, n);
1198
1199     if (new_str_start != NULL)
1200       break;   /* did we get it ? */
1201
1202     if (current_max_strings == 0)
1203       break;  /* initial allocation must work */
1204
1205     size = size / 2;          /* otherwise can try smaller */
1206   }
1207
1208   if (new_str_start == NULL)
1209   {
1210     memory_error("string pointer", n);
1211     return str_start;          /* try and continue */
1212   }
1213
1214   str_start = new_str_start;
1215   update_statistics((int) str_start, n, current_max_strings * sizeof (pool_pointer));
1216   current_max_strings = new_size;
1217
1218   if (trace_flag)
1219   {
1220     sprintf(log_line, "New Address %s == %p\n", "string start", str_start);
1221     show_line(log_line, 0);
1222   }
1223
1224   if (trace_flag)
1225     probe_show();
1226
1227   return str_start;
1228 }
1229 #endif
1230
1231 #ifdef ALLOCATEINI
1232 /* returns -1 if it fails */
1233 /* size == trie_size */
1234 int allocate_ini (int size)
1235 {
1236   int n, nl, no, nc, nr, nh, nt;
1237
1238   nh = nr = nl = (size + 1) *  sizeof(trie_pointer);
1239   no = (size + 1) *  sizeof(trie_op_code);
1240   nc = (size + 1) *  sizeof(packed_ASCII_code);
1241 /*    nt = (size + 1) *  sizeof(boolean); */
1242   nt = (size + 1) *  sizeof(char);
1243   n = nl + no + nc + nr + nh + nt;
1244 /*    n = (size + 1) * (sizeof(packed_ASCII_code) + sizeof(trie_op_code) +
1245       3 *  sizeof(trie_pointer) + sizeof (char)); */
1246   if (trace_flag)
1247     trace_memory ("iniTeX hyphen trie", n);
1248
1249   trie_l = (trie_pointer *) malloc (roundup(nl));
1250   trie_o = (trie_op_code *) malloc (roundup(no));
1251   trie_c = (packed_ASCII_code *) malloc (roundup(nc));
1252   trie_r = (trie_pointer *) malloc (roundup(nr));
1253   trie_hash = (trie_pointer *) malloc (roundup(nh));
1254   trie_taken = (char *) malloc (roundup(nt));
1255   
1256   if (trie_c == NULL || trie_o == NULL || trie_l == NULL || trie_r == NULL ||
1257       trie_hash == NULL || trie_taken == NULL)
1258   {
1259     memory_error("iniTeX hyphen trie", n);
1260 //      exit (1);           /* serious error */
1261     return -1;
1262   }
1263   
1264   if (trace_flag)
1265   {
1266     sprintf(log_line, "Addresses trie_l %p trie_o %p trie_c %p\n", trie_l, trie_o, trie_c);
1267     show_line(log_line, 0);
1268     sprintf(log_line, "Addresses trie_r %p trie_hash %p trie_taken %p\n",
1269       trie_r, trie_hash, trie_taken);
1270     show_line(log_line, 0);
1271   }
1272
1273   update_statistics ((int) trie_l, nl, 0);
1274   update_statistics ((int) trie_o, no, 0);
1275   update_statistics ((int) trie_c, nc, 0);
1276   update_statistics ((int) trie_r, nr, 0);
1277   update_statistics ((int) trie_hash, nh, 0);
1278   update_statistics ((int) trie_taken, nt, 0);
1279 /*    trie_size = size; */ /* ??? */
1280   if (trace_flag)
1281     probe_show();
1282
1283   return 0; // success
1284 }
1285 #endif
1286
1287 #ifdef ALLOCATESAVESTACK
1288 int current_save_size = 0;
1289
1290 memory_word *realloc_save_stack (int size)
1291 {
1292   int k, min_size;
1293   int n = 0, new_size = 0;
1294   memory_word * new_save_stack = NULL;
1295
1296   if (trace_flag)
1297   {
1298     sprintf(log_line, "Old Address %s == %p\n", "save stack", save_stack);
1299     show_line(log_line, 0);
1300   }
1301
1302   if (current_save_size == save_size)  /* arbitrary limit */
1303   {
1304 /*    memory_error ("save stack", (save_size + 1) * sizeof(memory_word)); */
1305 /*    exit (1); */
1306     return save_stack;       /* let TeX handle the error */
1307   }
1308
1309   min_size =  current_save_size / 100 * percent_grow;
1310
1311   if (size < min_size)
1312     size = min_size;
1313
1314   if (size < initial_save_size)
1315     size = initial_save_size;
1316
1317   for (k = 0; k < MAXSPLITS; k++)
1318   {
1319     new_size = current_save_size + size;
1320
1321     if (new_size > save_size)
1322       new_size = save_size;
1323
1324     n = (new_size + 1) * sizeof (memory_word); /* save_stack[save_size + 1] */
1325
1326     if (trace_flag)
1327       trace_memory("save_stack", n);
1328
1329     new_save_stack = (memory_word *) REALLOC (save_stack, n);
1330
1331     if (new_save_stack != NULL)
1332       break;    /* did we get it ? */
1333
1334     if (current_save_size == 0)
1335       break;  /* initial allocation must work */
1336
1337     size = size / 2;          /* else can retry smaller */
1338   }
1339
1340   if (new_save_stack == NULL)
1341   {
1342     memory_error("save stack", n);
1343     return save_stack;           /* try and continue !!! */
1344   }
1345
1346   save_stack = new_save_stack;
1347   update_statistics ((int) save_stack, n, current_save_size);
1348   current_save_size = new_size;
1349
1350   if (trace_flag)
1351   {
1352     sprintf(log_line, "Current %s %d\n", "save_size", current_save_size);
1353     show_line(log_line, 0);
1354     sprintf(log_line, "New Address %s == %p\n", "save stack", save_stack);
1355     show_line(log_line, 0);
1356   }
1357
1358   if (trace_flag)
1359     probe_show();
1360
1361   return save_stack;
1362 }
1363 #endif
1364
1365 #ifdef ALLOCATEINPUTSTACK
1366 int current_stack_size = 0;       /* input stack size */
1367
1368 in_state_record *realloc_input_stack (int size)
1369 {
1370   int k, min_size;
1371   int n = 0, new_size = 0;
1372   in_state_record * new_input_stack = NULL;
1373
1374   if (trace_flag)
1375   {
1376     sprintf(log_line, "Old Address %s == %p\n",  "input stack", input_stack);
1377     show_line(log_line, 0);
1378   }
1379
1380   if (current_stack_size == stack_size)  /* arbitrary limit */
1381   {
1382 /*    memory_error ("input stack", (stack_size + 1) * sizeof(in_state_record)); */
1383 /*    exit (1); */
1384     return input_stack;
1385   }
1386
1387   min_size =  current_stack_size / 100 * percent_grow;
1388
1389   if (size < min_size)
1390     size = min_size;
1391
1392   if (size < initial_stack_size)
1393     size = initial_stack_size;
1394
1395   for (k = 0; k < MAXSPLITS; k++)
1396   {
1397     new_size = current_stack_size + size;
1398
1399     if (new_size > stack_size)
1400       new_size = stack_size;
1401
1402     n = (new_size + 1) * sizeof (in_state_record); /* input_stack[stack_size + 1] */
1403
1404     if (trace_flag)
1405       trace_memory("input_stack", n);
1406
1407     new_input_stack = (in_state_record *) REALLOC (input_stack, n);
1408
1409     if (new_input_stack != NULL)
1410       break;   /* did we get it ? */
1411
1412     if (current_stack_size == 0)
1413       break; /* initial allocation must work */
1414
1415     size = size / 2;          /* else can retry smaller */
1416   }
1417
1418   if (new_input_stack == NULL)
1419   {
1420     memory_error("input stack", n);
1421     return input_stack;            /* try and continue !!! */
1422   }
1423
1424   input_stack = new_input_stack;
1425   update_statistics ((int) input_stack, n, current_stack_size);
1426   current_stack_size = new_size;
1427
1428   if (trace_flag)
1429   {
1430     sprintf(log_line, "Current %s %d\n", "stack_size", current_stack_size);
1431     show_line(log_line, 0);
1432     sprintf(log_line, "New Address %s == %p\n", "input stack", input_stack);
1433     show_line(log_line, 0);
1434   }
1435
1436   if (trace_flag)
1437     probe_show();     /* 94/Mar/25 */
1438
1439   return input_stack;
1440 }
1441 #endif
1442
1443 #ifdef ALLOCATENESTSTACK
1444 int current_nest_size = 0;        /* current nest size */
1445
1446 list_state_record *realloc_nest_stack (int size)
1447 {
1448   int k, min_size;
1449   int n = 0, new_size = 0;
1450   list_state_record * new_nest = NULL;
1451
1452   if (trace_flag)
1453   {
1454     sprintf(log_line, "Old Address %s == %p\n",  "nest stack", nest);
1455     show_line(log_line, 0);
1456   }
1457
1458   if (current_nest_size == nest_size)  /* arbitrary limit */
1459   {
1460 /*    memory_error ("nest stack", (nest_size + 1) * sizeof(list_state_record)); */
1461 /*    exit (1); */
1462     return nest;        /* let TeX handle the error */
1463   }
1464
1465   min_size =  current_nest_size / 100 * percent_grow;
1466
1467   if (size < min_size)
1468     size = min_size;
1469
1470   if (size < initial_nest_size)
1471     size = initial_nest_size;
1472
1473   for (k = 0; k < MAXSPLITS; k++)
1474   {
1475     new_size = current_nest_size + size;
1476
1477     if (new_size > nest_size)
1478       new_size = nest_size;
1479
1480     n = (new_size + 1) * sizeof (list_state_record); /* nest[nest_size + 1] */
1481
1482     if (trace_flag)
1483       trace_memory("nest stack", n);
1484
1485     new_nest = (list_state_record *) REALLOC (nest, n);
1486
1487     if (new_nest != NULL)
1488       break;   /* did we get it ? */
1489
1490     if (current_nest_size == 0)
1491       break;  /* initial allocation must work */
1492
1493     size = size / 2;          /* else can retry smaller */
1494   }
1495
1496   if (new_nest == NULL)
1497   {
1498     memory_error("nest stack", n);
1499     return nest;            /* try and continue !!! */
1500   }
1501
1502   nest = new_nest;
1503   update_statistics ((int) nest, n, current_nest_size);
1504   current_nest_size = new_size;
1505
1506   if (trace_flag)
1507   {
1508     sprintf(log_line, "Current %s %d\n", "nest_size", current_nest_size);
1509     show_line(log_line, 0);
1510     sprintf(log_line, "New Address %s == %p\n", "nest stack", nest);
1511     show_line(log_line, 0);
1512   }
1513
1514   if (trace_flag)
1515     probe_show();
1516
1517   return nest;
1518 }
1519 #endif
1520
1521 #ifdef ALLOCATEPARAMSTACK
1522 int current_param_size = 0;
1523
1524 halfword *realloc_param_stack (int size)
1525 {
1526   int k, min_size;
1527   int n = 0, new_size = 0;
1528   halfword * new_param = NULL;
1529
1530   if (trace_flag)
1531   {
1532     sprintf(log_line, "Old Address %s == %p\n",  "param stack", param_stack);
1533     show_line(log_line, 0);
1534   }
1535
1536   if (current_param_size == param_size) /* arbitrary limit */
1537   {
1538 /*    memory_error ("param stack", (param_size + 1) * sizeof(halfword)); */
1539 /*    exit (1); */
1540     return param_stack;        /* let TeX handle the error */
1541   }
1542
1543   min_size =  current_param_size / 100 * percent_grow;
1544
1545   if (size < min_size)
1546     size = min_size;
1547
1548   if (size < initial_param_size)
1549     size = initial_param_size;
1550
1551   for (k = 0; k < MAXSPLITS; k++)
1552   {
1553     new_size = current_param_size + size;
1554
1555     if (new_size > param_size)
1556       new_size = param_size;
1557
1558     n = (new_size + 1) * sizeof (halfword); /* param_stack[param_size + 1] */
1559
1560     if (trace_flag)
1561       trace_memory("param stack", n);
1562
1563     new_param = (halfword *) REALLOC (param_stack, n); 
1564
1565     if (new_param != NULL)
1566       break;    /* did we get it ? */
1567
1568     if (current_param_size == 0)
1569       break; /* initial allocation must work */
1570
1571     size = size / 2;          /* else can retry smaller */
1572   }
1573
1574   if (new_param == NULL)
1575   {
1576     memory_error("param stack", n);
1577     return param_stack;            /* try and continue !!! */
1578   }
1579
1580   param_stack = new_param;
1581   update_statistics ((int) param_stack, n, current_param_size);
1582   current_param_size = new_size;
1583
1584   if (trace_flag)
1585   {
1586     sprintf(log_line, "Current %s %d\n", "param_size", current_param_size);
1587     show_line(log_line, 0);
1588     sprintf(log_line, "New Address %s == %p\n", "param stack", param_stack);
1589     show_line(log_line, 0);
1590   }
1591
1592   if (trace_flag)
1593     probe_show();     /* 94/Mar/25 */
1594
1595   return param_stack;
1596 }
1597 #endif
1598
1599 #ifdef ALLOCATEBUFFER
1600 int current_buf_size = 0;
1601
1602 ASCII_code * realloc_buffer (int size)
1603 {
1604   int k, min_size;
1605   int n = 0, new_size = 0;
1606   ASCII_code * new_buffer = NULL;
1607
1608   if (trace_flag)
1609   {
1610     sprintf(log_line, "Old Address %s == %p\n", "buffer", buffer);
1611     show_line(log_line, 0);
1612   }
1613
1614   if (current_buf_size == buf_size)
1615   {
1616 /*    memory_error ("buffer", buf_size); */
1617 /*    exit (1); */
1618     return buffer;    /* pass it back to TeX 99/Fabe/4 */
1619   }
1620
1621   min_size =  current_buf_size / 100 * percent_grow;
1622
1623   if (size < min_size)
1624     size = min_size;
1625
1626   if (size < initial_buf_size)
1627     size = initial_buf_size;
1628
1629   for (k = 0; k < MAXSPLITS; k++)
1630   {
1631     new_size = current_buf_size + size;
1632
1633     if (new_size > buf_size)
1634       new_size = buf_size;
1635
1636     n = (new_size + 1) * sizeof(ASCII_code);
1637
1638     if (trace_flag)
1639       trace_memory("buffer", n);
1640
1641     new_buffer = (ASCII_code *) REALLOC (buffer, n);
1642
1643     if (new_buffer != NULL)
1644       break;   /* did we get it ? */
1645
1646     if (current_buf_size == 0)
1647       break;   /* initial allocation must work */
1648
1649     size = size / 2;
1650   }
1651
1652   if (new_buffer == NULL)
1653   {
1654     memory_error("buffer", n);
1655     return buffer;            /* try and continue !!! */
1656   }
1657
1658   buffer = new_buffer;
1659   update_statistics ((int) buffer, n, current_buf_size);
1660
1661 #ifdef USEMEMSET
1662   memset(buffer + current_buf_size, 0, new_size - current_buf_size);
1663 #else
1664   for (k = current_buf_size; k < new_size; k++) buffer[k]= 0;
1665 #endif
1666
1667   current_buf_size = new_size;
1668
1669   if (trace_flag)
1670   {
1671     sprintf(log_line, "Current %s %d\n", "buffer", current_buf_size);
1672     show_line(log_line, 0);
1673     sprintf(log_line, "New Address %s == %p\n", "buffer", buffer);
1674     show_line(log_line, 0);
1675   }
1676
1677   if (trace_flag)
1678     probe_show();
1679
1680   return buffer;
1681 }
1682 #endif
1683
1684 /* here is the main memory allocation routine -- calls the above */
1685 /* returns -1 if it fails */
1686 /* allocate rather than static 93/Nov/26 */
1687 int allocate_memory (void)
1688 {
1689 #ifdef ALLOCATEINPUTSTACK
1690   input_stack = NULL;
1691   current_stack_size = 0;
1692   input_stack = realloc_input_stack (initial_stack_size);  /* + 1 */
1693 #endif
1694
1695 #ifdef ALLOCATENESTSTACK
1696   nest = NULL;
1697   current_nest_size = 0;
1698   nest = realloc_nest_stack (initial_nest_size);  /* + 1 */
1699 #endif
1700
1701 #ifdef ALLOCATEPARAMSTACK
1702   param_stack = NULL;
1703   current_param_size = 0;
1704   param_stack = realloc_param_stack (initial_param_size); /* + 1 */
1705 #endif
1706
1707 #ifdef ALLOCATESAVESTACK
1708   save_stack = NULL;
1709   current_save_size = 0;
1710   save_stack = realloc_save_stack (initial_save_size);
1711 #endif
1712
1713 #ifdef IGNORED
1714   buffer = NULL;        /* need to do earlier */
1715   current_buf_size = 0;
1716   buffer = realloc_buffer (initial_buf_size);
1717 #endif
1718
1719 #ifdef ALLOCATESTRING
1720   str_pool = NULL;
1721   current_pool_size = 0;
1722   str_start = NULL;
1723   current_max_strings = 0;
1724
1725 /*  maybe taylor allocations to actual pool file 1300 strings 27000 bytes ? */
1726   if (is_initex)
1727   {
1728     if (trace_flag)
1729       puts("ini TeX pool and string allocation\n");
1730
1731     str_pool = realloc_str_pool(initial_pool_size); 
1732     str_start = realloc_str_start(initial_max_strings);
1733   }
1734 #endif
1735
1736 /* the following can save a lot of the usual 800k fixed allocation */
1737 #ifdef ALLOCATEFONT
1738   font_info = NULL;
1739   current_font_mem_size = 0;
1740 /*  if not iniTeX, then do initial allocation on fmt file read in itex.c */
1741 /*  if ini-TeX we need to do it here - no format file read later */
1742   if (is_initex)
1743     font_info = realloc_font_info (initial_font_mem_size);
1744 #endif
1745
1746 #ifdef ALLOCATEMAIN
1747   main_memory = NULL;
1748   mem = NULL;
1749   mem_min = mem_bot;        /* just to avoid complaints in texbody */
1750   mem_top = mem_initex;
1751   mem_max = mem_top;
1752 /*  allocate main memory here if this is iniTeX */
1753 /*  otherwise wait for format undumping in itex.c ... */  
1754   if (is_initex)
1755   {
1756 /*    avoid this if format specified on command line ??? */
1757 /*    allocate_main_memory(mem_initex); */   /* made variable ! */
1758     mem = allocate_main_memory(mem_initex);  /* made variable ! */
1759     if (mem == NULL)
1760 //      exit (1);
1761       return -1;            /* serious error */
1762   }
1763 #endif
1764
1765 /* now for the hyphenation exception stuff */
1766 #ifdef ALLOCATEHYPHEN
1767   hyph_word = NULL;
1768   hyph_list = NULL;
1769 /*  this will be overridden later by what is in format file */
1770   hyphen_prime = default_hyphen_prime;
1771 /*  non ini-TeX use assumes format will be read and that specifies size */
1772   if (is_initex)
1773   {
1774     if (new_hyphen_prime)
1775       hyphen_prime = new_hyphen_prime;
1776
1777     if (realloc_hyphen(hyphen_prime)) /* allocate just in case no format */
1778       return -1;
1779   }
1780 #endif
1781
1782 /*  now for memory for the part of the hyphenation stuff that always needed */
1783 /*  if iniTeX, need to allocate pre-determined fixed amount - trie_size */
1784 /*  if iniTeX not selected, allocate only enough later - undump in itex.c ! */
1785 #ifdef ALLOCATETRIES
1786   if (is_initex)
1787   {
1788     if (allocate_tries (trie_size))
1789       return -1;
1790   }
1791 #endif
1792
1793 /*  now for memory for hyphenation stuff needed only when running iniTeX */
1794 #ifdef ALLOCATEINI
1795   if (is_initex)
1796   {
1797     if (allocate_ini(trie_size))
1798       return -1;
1799   }
1800   else
1801   {
1802     trie_l = trie_r = trie_o = trie_hash = NULL; /* (trie_size + 1) * integer */
1803     trie_c = NULL;       /* (trie_size + 1) * char */
1804     trie_taken = NULL;     /* (trie_size + 1) * boolean */
1805   }
1806 #endif
1807
1808   return 0; // success
1809 }
1810
1811 /* returns non-zero if error - done to test integrity of stack mostly */
1812 int free_memory (void)
1813 {
1814   unsigned int heap_total = 0;
1815
1816   if (trace_flag)
1817     puts("free_memory ");
1818
1819   if (verbose_flag || trace_flag)
1820     show_maximums(stdout); 
1821
1822   if (trace_flag)
1823   {
1824     sprintf(log_line, "Heap total: %u bytes --- max address %u\n", 
1825         heap_total, max_address);
1826     show_line(log_line, 0);
1827   }
1828
1829   if (trace_flag)
1830   {
1831     printf("Main Memory: variable node %lld (%lld - %ld);\n"
1832       "             one word %ld (%ld - %ld)\n",
1833       lo_mem_max - mem_min, mem_min, lo_mem_max,
1834       mem_end - hi_mem_min, hi_mem_min, mem_end);
1835   }
1836
1837   if (trace_flag)
1838     puts("Freeing memory again");
1839
1840 /*  only free memory if safe ... additional check */
1841 #ifdef ALLOCATEINI
1842   if (is_initex)
1843   {
1844     if (trie_taken != NULL)
1845       free(trie_taken);
1846
1847     if (trie_hash != NULL)
1848       free(trie_hash);
1849
1850     if (trie_r != NULL)
1851       free(trie_r);
1852
1853     if (trie_c != NULL)
1854       free(trie_c);
1855
1856     if (trie_o != NULL)
1857       free(trie_o);
1858
1859     if (trie_l != NULL)
1860       free(trie_l);
1861
1862     trie_taken = NULL;
1863     trie_hash = trie_l = trie_r = NULL;
1864     trie_c = NULL;
1865     trie_o = NULL;
1866   }
1867 #endif
1868
1869 #ifdef ALLOCATETRIES
1870   if (trie_trc != NULL)
1871     free (trie_trc);
1872
1873   if (trie_tro != NULL)
1874     free (trie_tro);
1875
1876   if (trie_trl != NULL)
1877     free (trie_trl);
1878
1879   trie_trc = NULL;
1880   trie_tro = trie_trl = NULL;
1881 #endif
1882
1883 #ifdef ALLOCATEHYPHEN
1884   if (hyph_list != NULL)
1885     free(hyph_list);
1886
1887   if (hyph_word != NULL)
1888     free(hyph_word);
1889
1890   hyph_list = NULL;
1891   hyph_word = NULL;
1892 #endif
1893
1894 #ifdef ALLOCATEMAIN
1895   if (main_memory != NULL)
1896     free(main_memory);
1897
1898   main_memory = NULL;
1899 #endif
1900
1901 #ifdef ALLOCATEFONT
1902   if (font_info != NULL)
1903     free(font_info);
1904
1905   font_info = NULL;
1906 #endif
1907
1908 #ifdef ALLOCATESTRING
1909   if (str_start != NULL)
1910     free(str_start);
1911
1912   if (str_pool != NULL)
1913     free(str_pool);
1914
1915   str_start = NULL;
1916   str_pool = NULL;
1917 #endif
1918
1919 #ifdef ALLOCATEPARAMSTACK
1920   if (param_stack != NULL)
1921     free(param_stack);
1922
1923   param_stack = NULL;
1924 #endif
1925
1926 #ifdef ALLOCATENESTSTACK
1927   if (nest != NULL)
1928     free(nest);
1929
1930   nest = NULL;
1931 #endif
1932
1933 #ifdef ALLOCATEINPUTSTACK
1934   if (input_stack != NULL)
1935     free(input_stack);
1936
1937   input_stack = NULL;
1938 #endif
1939
1940 #ifdef ALLOCATESAVESTACK
1941   if (save_stack != NULL)
1942     free(save_stack);
1943
1944   save_stack = NULL;
1945 #endif
1946
1947   if (format_file != NULL)
1948     free(format_file);
1949
1950   if (source_direct != NULL)
1951     free(source_direct);
1952
1953   format_file = source_direct = NULL;
1954
1955   if (dvi_file_name != NULL)
1956     free(dvi_file_name);
1957
1958   if (log_file_name != NULL)
1959     free(log_file_name);
1960
1961   if (pdf_file_name != NULL)
1962     free(pdf_file_name);
1963
1964   pdf_file_name = log_file_name = dvi_file_name = NULL;
1965
1966   return 0;
1967 }
1968
1969 boolean prime (int x)
1970 {
1971   int k;
1972   int sum = 1;    /* 1 + 3 + 5 + k = (k + 1) * (k + 1) / 4 */
1973
1974   if (x % 2 == 0)
1975     return false;
1976
1977   for (k = 3; k < x; k = k + 2)
1978   {
1979     if (x % k == 0)
1980       return false;
1981
1982     if (sum * 4 > x)
1983       return true;
1984
1985     sum += k;
1986   }
1987
1988   return true;
1989 }
1990
1991 int quitflag  = 0;
1992 boolean show_use = false;
1993 boolean floating = false;
1994
1995 void complainarg (int c, char *s)
1996 {
1997   sprintf(log_line, "ERROR: Do not understand `%c' argument value `%s'\n", c, s);
1998   show_line(log_line, 1);
1999   show_use = 1;
2000 }
2001
2002 /* following is list of allowed command line flags and args */
2003
2004 char *allowedargs = "+bcdfijnpqrstvwyzABCDFGIJKLMNOPQRSTVWXYZ023456789?a=e=g=h=k=l=m=o=u=x=E=H=P=U=";
2005
2006 void reorderargs (int ac, char **av)
2007 {
2008   int n, m;
2009   char *s, *t;
2010   char takeargs[256];   /* large enough for all command line arg chars */
2011
2012   if (ac < 3)
2013   {
2014     return; /* no args ! */
2015   }
2016
2017   s = allowedargs;
2018   t = takeargs;   /* list of those that take args */
2019
2020   while (*s != '\0' && *(s + 1) != '\0')
2021   {
2022     if (*(s + 1) == '=')
2023       *t++ = *s++;   /* copy over --- without the = */
2024
2025     s++;
2026   }
2027
2028   *t = '\0';
2029
2030   if (trace_flag)
2031   {
2032     show_line(takeargs, 0);
2033     show_char('\n');
2034   }
2035   
2036   n = 1;
2037
2038   for (;;)
2039   {
2040     if (*av[n] != '-')
2041       break;
2042
2043     if (n + 1 < ac && *(av[n] + 2) == '\0' &&
2044       strchr(takeargs, *(av[n] + 1)) != NULL)
2045       n += 2; /* step over it */
2046     else
2047       n++;
2048
2049     if (n == ac)
2050       break;
2051   }
2052
2053   for (;;)
2054   {
2055     if (n == ac)
2056       break;
2057
2058     m = n;
2059
2060     while (m < ac && *av[m] != '-')
2061       m++;  /* first command */
2062
2063     if (m == ac)
2064       break;
2065 /* does it take an argument ? and is this argument next ? */
2066 /* check first whether the `-x' is isolated, or arg follows directly */
2067 /* then check whether this is one of those that takes an argument */
2068     if (m+1 < ac && *(av[m] + 2) == '\0' &&
2069       strchr(takeargs, *(av[m] + 1)) != NULL)
2070     {
2071       s = av[m];      /*  move command down before non-command */
2072       t = av[m + 1];
2073
2074       for (; m > n; m--)
2075         av[m + 1] = av[m - 1];
2076
2077       av[n] = s;
2078       av[n + 1] = t;
2079       n += 2;       /* step over moved args */
2080     }
2081     else
2082     {
2083       s = av[m];      /*  move command down before non-command */
2084
2085       for (; m > n; m--)
2086         av[m] = av[m - 1];
2087
2088       av[n] = s;
2089       n++;        /* step over moved args */
2090     }
2091   }
2092 }
2093
2094 int test_align (int address, int size, char *str)
2095 {
2096   int n;
2097
2098   if (size > 4)
2099     n = address % 4;
2100   else
2101     n = address % size;
2102
2103   if (n != 0)
2104   {
2105     sprintf(log_line, "OFFSET %d (ELEMENT %d) in %s\n", n, size, str);
2106     show_line(log_line, 0);
2107   }
2108
2109   return n;
2110 }
2111
2112 /* activate detailed checking of alignment when trace_flag is set */
2113
2114 void check_fixed_align (int flag)
2115 {
2116   (void) flag;
2117
2118   if (test_align ((int) &mem_top, 4, "FIXED ALIGNMENT"))
2119   {
2120     puts("PLEASE RECOMPILE ME!\n");
2121   }
2122
2123 #ifdef CHECKALIGNMENT
2124   if (!flag)
2125     return;
2126
2127   test_align ((int) &mem_top, 4, "mem_top");
2128   test_align ((int) &mem_max, 4, "mem_max");
2129   test_align ((int) &mem_min, 4, "mem_min");
2130   test_align ((int) &bad, 4, "bad");
2131   test_align ((int) &trie_size, 4, "trie_size");
2132   test_align ((int) &xord, sizeof(xord[0]), "xord"); /* no op */
2133   test_align ((int) &xchr, sizeof(xchr[0]), "xchr"); /* no op */
2134   test_align ((int) &name_length, 4, "name_length");
2135   test_align ((int) &first, 4, "first");
2136   test_align ((int) &last, 4, "last");
2137   test_align ((int) &max_buf_stack, 4, "max_buf_stack");
2138   test_align ((int) &pool_ptr, 4, "pool_ptr");
2139   test_align ((int) &str_ptr, 4, "str_ptr");
2140   test_align ((int) &init_pool_ptr, 4, "init_pool_ptr");
2141   test_align ((int) &init_str_ptr, 4, "init_str_ptr");
2142   test_align ((int) &log_file, 4, "log_file");
2143   test_align ((int) &tally, 4, "tally");
2144   test_align ((int) &term_offset, 4, "term_offset");
2145   test_align ((int) &file_offset, 4, "file_offset");
2146   test_align ((int) &trick_count, 4, "trick_count");
2147   test_align ((int) &first_count, 4, "first_count");
2148   test_align ((int) &deletions_allowed, 4, "deletions_allowed");
2149   test_align ((int) &set_box_allowed, 4, "set_box_allowed");
2150   test_align ((int) &help_line, sizeof(help_line[0]), "help_line");
2151   test_align ((int) &use_err_help, 4, "use_err_help");
2152   test_align ((int) &interrupt, 4, "interrupt");
2153   test_align ((int) &OK_to_interrupt, 4, "OK_to_interrupt");
2154   test_align ((int) &arith_error, 4, "arith_error");
2155   test_align ((int) &tex_remainder, 4, "tex_remainder");
2156   test_align ((int) &temp_ptr, 4, "temp_ptr");
2157   test_align ((int) &lo_mem_max, 4, "lo_mem_max");
2158   test_align ((int) &hi_mem_min, 4, "hi_mem_min");
2159   test_align ((int) &var_used, 4, "var_used");
2160   test_align ((int) &dyn_used, 4, "dyn_used");
2161   test_align ((int) &avail, 4, "avail");
2162   test_align ((int) &mem_end, 4, "mem_end");
2163   test_align ((int) &mem_start, 4, "mem_start");
2164   test_align ((int) &rover, 4, "rover");
2165   test_align ((int) &font_in_short_display, 4, "font_in_short_display");
2166   test_align ((int) &depth_threshold, 4, "depth_threshold");
2167   test_align ((int) &breadth_max, 4, "breadth_max");
2168   test_align ((int) &nest, sizeof(nest[0]), "nest");
2169 /*  test_align ((int) &xeq_level, sizeof(xeq_level[0]), "xeq_level"); */
2170   test_align ((int) &zzzad, sizeof(zzzad[0]), "zzzad");
2171 /*  test_align ((int) &hash, sizeof(hash[0]), "hash"); */
2172   test_align ((int) &zzzae, sizeof(zzzae[0]), "zzzae");
2173
2174   test_align ((int) &save_stack, sizeof(save_stack[0]), "save_stack");
2175   test_align ((int) &input_stack, sizeof(input_stack[0]), "input_stack");
2176   test_align ((int) &input_file, sizeof(input_file[0]), "input_file");
2177   test_align ((int) &line_stack, sizeof(line_stack[0]), "line_stack");
2178   test_align ((int) &param_stack, sizeof(param_stack[0]), "param_stack");
2179   test_align ((int) &cur_mark, sizeof(cur_mark[0]), "cur_mark");
2180   test_align ((int) &pstack, sizeof(pstack[0]), "pstack");
2181   test_align ((int) &read_file, sizeof(read_file[0]), "read_file");
2182
2183   test_align ((int) &font_check, sizeof(font_check[0]), "font_check");
2184   test_align ((int) &font_size, sizeof(font_size[0]), "font_size");
2185   test_align ((int) &font_dsize, sizeof(font_dsize[0]), "font_dsize");
2186   test_align ((int) &font_params, sizeof(font_params[0]), "font_params");
2187   test_align ((int) &font_name, sizeof(font_name[0]), "font_name");
2188   test_align ((int) &font_area, sizeof(font_area[0]), "font_area");
2189   test_align ((int) &font_bc, sizeof(font_bc[0]), "font_bc");
2190   test_align ((int) &font_ec, sizeof(font_ec[0]), "font_ec");
2191   test_align ((int) &font_glue, sizeof(font_glue[0]), "font_glue");
2192   test_align ((int) &font_used, sizeof(font_used[0]), "font_used");
2193   test_align ((int) &hyphen_char, sizeof(hyphen_char[0]), "hyphen_char");
2194   test_align ((int) &skew_char, sizeof(skew_char[0]), "skew_char");
2195   test_align ((int) &bchar_label, sizeof(bchar_label[0]), "bchar_label");
2196   test_align ((int) &font_bchar, sizeof(font_bchar[0]), "font_bchar");
2197   test_align ((int) &font_false_bchar, sizeof(font_false_bchar[0]), "font_false_bchar");
2198   test_align ((int) &char_base, sizeof(char_base[0]), "char_base");
2199   test_align ((int) &width_base, sizeof(width_base[0]), "width_base");
2200   test_align ((int) &height_base, sizeof(height_base[0]), "height_base");
2201   test_align ((int) &depth_base, sizeof(depth_base[0]), "depth_base");
2202   test_align ((int) &italic_base, sizeof(italic_base[0]), "italic_base");
2203   test_align ((int) &lig_kern_base, sizeof(lig_kern_base[0]), "lig_kern_base");
2204   test_align ((int) &kern_base, sizeof(kern_base[0]), "kern_base");
2205   test_align ((int) &exten_base, sizeof(exten_base[0]), "exten_base");
2206   test_align ((int) &param_base, sizeof(param_base[0]), "param_base");
2207
2208 #ifdef ALLOCATEDVIBUF
2209   test_align ((int) &zdvibuf, sizeof(zdvibuf[0]), "zdvibuf"); /* no op */
2210 #endif
2211
2212   test_align ((int) &total_stretch, sizeof(total_stretch[0]), "total_stretch");
2213   test_align ((int) &total_shrink, sizeof(total_shrink[0]), "total_shrink");
2214   test_align ((int) &active_width, sizeof(active_width[0]), "active_width");
2215   test_align ((int) &cur_active_width, sizeof(cur_active_width[0]), "cur_active_width");
2216   test_align ((int) &background, sizeof(background[0]), "background");
2217   test_align ((int) &break_width, sizeof(break_width[0]), "break_width");
2218   test_align ((int) &minimal_demerits, sizeof(minimal_demerits[0]), "minimal_demerits");
2219   test_align ((int) &best_place, sizeof(best_place[0]), "best_place");
2220   test_align ((int) &best_pl_line, sizeof(best_pl_line[0]), "best_pl_line");
2221   test_align ((int) &hc, sizeof(hc[0]), "hc");
2222   test_align ((int) &hu, sizeof(hu[0]), "hu");
2223   test_align ((int) &hyf, sizeof(hyf[0]), "hyf");
2224 /*  test_align ((int) &x, sizeof(x[0]), "x"); */
2225
2226   test_align ((int) &hyf_distance, sizeof(hyf_distance[0]), "hyf_distance");
2227   test_align ((int) &hyf_num, sizeof(hyf_num[0]), "hyf_num");
2228   test_align ((int) &hyf_next, sizeof(hyf_next[0]), "hyf_next");
2229   test_align ((int) &op_start, sizeof(op_start[0]), "op_start");
2230
2231 /*  test_align ((int) &trie_op_hash, sizeof(trie_op_hash[0]), "trie_op_hash"); */
2232   test_align ((int) &zzzaf, sizeof(zzzaf[0]), "zzzaf");
2233   test_align ((int) &trie_used, sizeof(trie_used[0]), "trie_used");
2234 /*  test_align ((int) &trie_op_lang, sizeof(trie_op_lang[0]), "trie_op_lang");*/
2235   test_align ((int) &trie_op_val, sizeof(trie_op_val[0]), "trie_op_val");
2236
2237   test_align ((int) &trie_min, sizeof(trie_min[0]), "trie_min");
2238   test_align ((int) &page_so_far, sizeof(page_so_far[0]), "page_so_far");
2239   test_align ((int) &write_file, sizeof(write_file[0]), "write_file");
2240   test_align ((int) &write_open, sizeof(write_open[0]), "write_open");
2241 #endif
2242 }
2243
2244 void check_alloc_align (int flag)
2245 {
2246   (void) flag;
2247
2248   if (test_align((int) eqtb, sizeof(eqtb[0]), "ALLOCATED ALIGNMENT"))
2249     puts("PLEASE RECOMPILE ME!\n");
2250
2251 #ifdef CHECKALIGNMENT
2252   if (!flag)
2253     return;
2254
2255 #ifndef ALLOCZEQTB
2256   test_align ((int) zeqtb, sizeof(zeqtb[0]), "zeqtb"); 
2257 #endif
2258
2259 #ifndef ALLOCATEDVIBUF
2260   test_align ((int) &zdvibuf, sizeof(zdvibuf[0]), "zdvibuf");  /* no op */
2261 #endif
2262
2263   test_align ((int) str_pool, sizeof(str_pool[0]), "str_pool"); /* no op */
2264   test_align ((int) str_start, sizeof(str_start[0]), "str_start");
2265   test_align ((int) zmem, sizeof(zmem[0]), "main memory");
2266   test_align ((int) font_info, sizeof(font_info[0]), "font memory");
2267   test_align ((int) trie_trl, sizeof(trie_trl[0]), "trie_trl");
2268   test_align ((int) trie_tro, sizeof(trie_tro[0]), "trie_tro");
2269   test_align ((int) trie_trc, sizeof(trie_trc[0]), "trie_trc");
2270   test_align ((int) hyph_word, sizeof(hyph_word[0]), "hyph_word");
2271   test_align ((int) hyph_list, sizeof(hyph_list[0]), "hyph_list");
2272 /*  test_align ((int) trie_c, sizeof(trie_c[0]), "trie_c"); *//* no op */
2273   test_align ((int) trie_o, sizeof(trie_o[0]), "trie_o");
2274   test_align ((int) trie_l, sizeof(trie_l[0]), "trie_l");
2275   test_align ((int) trie_r, sizeof(trie_r[0]), "trie_r");
2276   test_align ((int) trie_hash, sizeof(trie_hash[0]), "trie_hash");
2277   test_align ((int) trie_taken, sizeof(trie_taken[0]), "trie_taken");
2278 #endif
2279 }
2280
2281 boolean backwardflag       = false; /* don't cripple all advanced features */
2282 boolean shorten_file_name  = false; /* don't shorten file names to 8+3 for DOS */
2283 boolean usesourcedirectory = true;  /* use source file directory as local when WorkingDirectory is set */
2284
2285 /* cache to prevent allocating twice in a row */
2286
2287 char *lastname = NULL, *lastvalue = NULL;
2288
2289 /* returns allocated string -- these strings are not freed again */
2290 /* is it safe to do that now ? 98/Jan/31 */
2291 char * grabenv (char * varname)
2292 {
2293   char *s;
2294
2295   if (varname == NULL)
2296     return NULL;
2297
2298   if (*varname == '\0')
2299     return NULL;
2300
2301   if (lastname != NULL && strcasecmp(lastname, varname) == 0)
2302   {
2303     if (trace_flag)
2304     {
2305       sprintf(log_line, "Cache hit: %s=%s\n", lastname, lastvalue);
2306       show_line(log_line, 0);
2307     }
2308
2309     return xstrdup(lastvalue);
2310   }
2311
2312   s = getenv(varname);
2313
2314   if (s != NULL)
2315   {
2316     if (lastname != NULL)
2317       free(lastname);
2318
2319     lastname = xstrdup(varname);
2320
2321     if (lastvalue != NULL)
2322       free(lastvalue);
2323
2324     lastvalue = xstrdup(s);
2325
2326     return xstrdup(s);
2327   }
2328   else
2329     return NULL;
2330 }
2331
2332 void flush_trailing_slash (char *directory)
2333 {
2334   char *s;
2335
2336   if (strcmp(directory, "") != 0)
2337   {
2338     s = directory + strlen(directory) - 1;
2339
2340     if (*s == '\\' || *s == '/')
2341       *s = '\0';
2342   }
2343 }
2344
2345 void knuthify (void)
2346 {
2347   restrict_to_ascii     = false; /* don't complain non ASCII */
2348   allow_patterns        = false; /* don't allow pattern redefinition */
2349   show_in_hex           = true;  /* show character code in hex */
2350   show_in_dos           = false; /* redundant with previous */
2351   show_numeric          = false; /* don't show character code decimal */
2352   show_missing          = false; /* don't show missing characters */
2353   civilize_flag         = false; /* don't reorder date fields */
2354   c_style_flag          = false; /* don't add file name to error msg */
2355   show_fmt_flag         = false; /* don't show format file in log */
2356   show_tfm_flag         = false; /* don't show metric file in log */
2357   tab_step              = 0;
2358   show_line_break_stats = false; /* do not show line break stats */
2359   show_fonts_used       = false;
2360   default_rule          = 26214; /* revert to default rule thickness */
2361   pseudo_tilde          = false;
2362   pseudo_space          = false;
2363   show_texinput_flag    = false;
2364   truncate_long_lines   = false;
2365   allow_quoted_names    = false;
2366   show_cs_names         = false;
2367   font_dimen_zero       = false;
2368   ignore_frozen         = false;
2369   suppress_f_ligs       = false;
2370   full_file_name_flag   = false;
2371   knuth_flag            = true;  /* so other code can know about this */
2372 }
2373
2374 /* following made global so analyze_flag can be made separate procedure */
2375
2376 char * xchr_file = NULL;
2377 char * repl_file = NULL;
2378
2379 char * short_options = "m:e:h:0:H:g:P:o:l:a:wvpiKLZMdp2t?u";
2380
2381 static struct option long_options[] =
2382 {
2383   {"main-memory",   1, 0, 'm'},
2384   {"hyph-size",     1, 0, 'e'},
2385   {"trie-size",     1, 0, 'h'},
2386   {"backend",       1, 0, '0'},
2387   {"tab-step",      1, 0, 'H'},
2388   {"percent-grow",  1, 0, 'g'},
2389   {"default-rule",  1, 0, 'P'},
2390   {"dvi-dir",       1, 0, 'o'},
2391   {"log-dir",       1, 0, 'l'},
2392   {"aux-dir",       1, 0, 'a'},
2393   {"showhex",       0, 0, 'w'},
2394   {"verbose",       0, 0, 'v'},
2395   {"patterns",      0, 0, 'p'},
2396   {"initex",        0, 0, 'i'},
2397   {"knuthify",      0, 0, 'K'},
2398   {"cstyle",        0, 0, 'L'},
2399   {"showtfm",       0, 0, 'Z'},
2400   {"showmissing",   0, 0, 'M'},
2401   {"deslash",       0, 0, 'd'},
2402   {"patterns",      0, 0, 'p'},
2403   {"suppressflig",  0, 0, '2'},
2404   {"trace",         0, 0, 't'},
2405   {"help",          0, 0, '?'},
2406   {"usage",         0, 0, 'u'},
2407   {NULL,            0, 0, 0}
2408 };
2409
2410 int analyze_flag (int c, char *optarg)
2411 {
2412   switch (c)
2413   {
2414     case 'v':
2415       want_version = true;
2416       verbose_flag = true;
2417       break;
2418     case 'i':
2419       is_initex = true;
2420       break;
2421     case 'Q':
2422       interaction = batch_mode; /* quiet mode */
2423       break;
2424     case 'R':
2425       interaction = nonstop_mode; /* run mode */
2426       break;
2427     case 'S':
2428       interaction = scroll_mode; /* scroll mode */
2429       break;
2430     case 'T':
2431       interaction = error_stop_mode; /* tex mode */
2432       break;
2433     case 'K':
2434       backwardflag = true;
2435       knuthify(); /* revert to `standard' Knuth TeX */
2436       break;
2437     case 'L':
2438       c_style_flag = true; /* C style error msg 94/Mar/21 */
2439       break;
2440     case 'Z':
2441       show_tfm_flag = true; /* show TFM in log file 94/Jun/21 */
2442       break;
2443     case 'M':
2444       show_missing = false; /* do not show missing 94/June/10 */
2445       break;
2446     case 'd':
2447       deslash = false; /* flipped 93/Nov/18 */
2448       /* pseudo_tilde = 0; */ /* new 95/Sep/26 */
2449       break;
2450     case 'p':
2451       allow_patterns = true; /* 93/Nov/26 */
2452       /* reset_exceptions = true; */ /* 93/Dec/23 */
2453       break;
2454 /*  case 'w':  show_in_hex = false; */ /* 94/Jan/26 */
2455     case 'w':
2456       show_in_hex = true; /* flipped 00/Jun/18 */
2457       break;
2458     case 'j':
2459       show_in_dos = true; /* 96/Jan/26 */
2460       break;
2461     case 'n':
2462       restrict_to_ascii = true; /* 0 - 127 1994/Jan/21 */
2463       break;
2464     case '7':
2465       usesourcedirectory = false; /* use working dir 98/Sep/29 */
2466       break;
2467     case 'f':
2468       show_fonts_used = false; /* 97/Dec/24 */
2469       break;
2470     case '8':
2471       shorten_file_name = true; /* 95/Feb/20 */
2472       break;
2473     case '9':
2474       show_cs_names = true; /* 98/Mar/31 */
2475       break;
2476     case '4':
2477       ignore_frozen = true; /* 98/Oct/5 */
2478       break;
2479     case '5':
2480       font_dimen_zero = false; /* 98/Oct/5 */
2481       break;
2482     case 'F':
2483       show_texinput_flag = false; /* 98/Jan/28 */
2484       break;
2485 /*  case 'X':  truncate_long_lines = false; */ /* 98/Feb/2 */
2486               /* break; */
2487     case 'J':
2488       show_line_break_stats = false; /* 96/Feb/8 */
2489       break;
2490     case 'O':
2491       show_fmt_flag = false; /* 94/Jun/21 */
2492       break;
2493     case '2':
2494       suppress_f_ligs = true; /* 99/Jan/5 f-lig */
2495       break;
2496     case 'z':
2497       full_file_name_flag = false; // 00 Jun 18
2498       break;
2499     case 't':
2500       trace_flag = true;
2501       break;
2502     case 'q':
2503       quitflag++; /* 93/Dec/16 */
2504       break;
2505 /* The following are really obscure and should not be advertized */
2506     case 's':
2507       show_current = false; /* tex8 93/Dec/14 */
2508       break;
2509     case 'N':
2510       show_numeric = false; /* 93/Dec/21 */
2511       break;
2512     case 'A':
2513       civilize_flag = false; /* 93/Dec/16 */
2514       break; 
2515     case 'B':
2516       open_trace_flag = true; /* openinou 1994/Jan/8 */
2517       break;
2518     case 'Y':
2519       reorder_arg_flag = false; /* local */
2520       break;
2521
2522     case 'm':
2523       if (optarg == 0)
2524         mem_initex = mem_top;
2525       else
2526         mem_initex = atoi(optarg) * 1024;
2527
2528       if (mem_initex == 0)
2529         complainarg(c, optarg);
2530
2531       mem_spec_flag = 1;
2532       break;
2533
2534 #ifdef VARIABLETRIESIZE
2535     case 'h':
2536       if (optarg == 0)
2537         trie_size = default_trie_size;
2538       else
2539         trie_size = atoi(optarg);
2540
2541       if (trie_size == 0)
2542         complainarg(c, optarg);
2543       break;
2544 #endif
2545
2546 #ifdef ALLOCATEHYPHEN
2547     case 'e':
2548       if (optarg == 0)
2549         new_hyphen_prime = hyphen_prime * 2;
2550       else
2551         new_hyphen_prime = atoi(optarg);
2552
2553       if (new_hyphen_prime == 0)
2554         complainarg(c, optarg);
2555
2556       break;
2557 #endif
2558     case 'g':
2559       if (optarg == 0)
2560         percent_grow = 62;
2561       else
2562         percent_grow = atoi(optarg);
2563
2564       if (percent_grow == 0)
2565         complainarg(c, optarg);
2566
2567       break;
2568
2569     case 'U':
2570       if (optarg == 0)
2571         pseudo_tilde = 0;
2572       else
2573         pseudo_tilde = atoi(optarg);
2574
2575       if (pseudo_tilde > 255)
2576         pseudo_tilde = 255;
2577       else if (pseudo_tilde < 128)
2578         pseudo_tilde = 128;
2579
2580       break;
2581
2582     case 'H':
2583       if (optarg == 0)
2584         tab_step = 8;
2585       else
2586         tab_step = atoi(optarg);
2587       if (tab_step == 0)
2588         complainarg(c, optarg);
2589       break;
2590     case 'x':
2591       if (optarg == 0)
2592         xchr_file = xstrdup("xchr.map");
2593       else
2594         xchr_file = xstrdup(optarg);
2595
2596       if (xchr_file == NULL || *xchr_file == '\0')
2597         complainarg(c, optarg);
2598       break;
2599     case 'k':
2600       if (optarg == 0)
2601         repl_file = xstrdup("repl.key");
2602       else
2603         repl_file = xstrdup(optarg);
2604
2605       if (repl_file == NULL || *repl_file == '\0')
2606         complainarg(c, optarg);
2607       break;
2608     case 'P':
2609       if (optarg == 0)
2610         default_rule = 26214;
2611       else
2612         default_rule = atoi(optarg);
2613
2614       if (default_rule == 0)
2615         complainarg(c, optarg);
2616       break;
2617     case 'E':
2618       if (optarg != 0)
2619         putenv(optarg);
2620       else
2621         complainarg(c, optarg);
2622       break;
2623     case 'o':
2624       if (optarg == 0)
2625         dvi_directory = "";
2626       else
2627         dvi_directory = xstrdup(optarg);
2628
2629       if (strcmp(dvi_directory, "") == 0)
2630         complainarg(c, optarg);
2631
2632       break;
2633     case '0':
2634       {
2635         char * format_spec = NULL;
2636
2637         if (optarg != 0)
2638           format_spec = xstrdup(optarg);
2639
2640         if (!strcmp(format_spec, "pdf"))
2641           shipout_flag = out_pdf_flag;
2642         else if (!strcmp(format_spec, "dvi"))
2643           shipout_flag = out_dvi_flag;
2644         else if (!strcmp(format_spec, "xdv"))
2645           shipout_flag = out_xdv_flag;
2646         else
2647         {
2648           sprintf(log_line, "ERROR: Do not understand shipout flag `%s'\n", format_spec);
2649           show_line(log_line, 1);
2650         }
2651       }
2652       break;
2653     case 'l':
2654       if (optarg == 0)
2655         log_directory = "";
2656       else
2657         log_directory = xstrdup(optarg);
2658
2659       if (strcmp(log_directory, "") == 0)
2660         complainarg(c, optarg);
2661
2662       break;
2663
2664     case 'a':
2665       if (optarg == 0)
2666         aux_directory = "";
2667       else
2668         aux_directory = xstrdup(optarg);
2669
2670       if (strcmp(aux_directory, "") == 0)
2671         complainarg(c, optarg);
2672
2673       break;
2674
2675     case '?':
2676     default:
2677       show_use = true;
2678       return -1;
2679       break;
2680   }
2681
2682   return 0;
2683 }
2684
2685 void strip_name (char *pathname)
2686 {
2687   char *s;
2688
2689   if ((s = strrchr(pathname, '\\')) != NULL)
2690     ;
2691   else if ((s = strrchr(pathname, '/')) != NULL)
2692     ;
2693   else if ((s = strrchr(pathname, ':')) != NULL)
2694     s++;
2695   else
2696     s = pathname;
2697
2698   *s = '\0';
2699 }
2700
2701 int read_command_line (int ac, char **av)
2702
2703   int c;
2704   char *optargnew;
2705   int option_idx = 0;
2706
2707   if (ac < 2)
2708     return 0;
2709
2710   while ((c = getopt_long_only(ac, av, short_options, long_options, &option_idx)) != EOF)
2711   {
2712     if (optarg != 0 && *optarg == '=')
2713       optargnew = optarg + 1;
2714     else
2715       optargnew = optarg;
2716
2717     analyze_flag (c, optargnew);
2718   }
2719
2720   if (show_use || quitflag == 3)
2721   {
2722     stamp_it(log_line);
2723     strcat(log_line, "\n");
2724     show_line(log_line, 0);
2725     //stampcopy(log_line);
2726     //strcat(log_line, "\n");
2727     //show_line(log_line, 0);
2728
2729     if (show_use)
2730       show_usage();
2731     else if (quitflag == 3)
2732     {
2733       strcat(log_line, "\n");
2734       show_line(log_line, 0);
2735     }
2736
2737     return -1; // failure
2738   } 
2739
2740   if (repl_file != NULL && *repl_file != '\0')
2741   {
2742     if (read_xchr_file(repl_file, 1, av))
2743     {
2744       if (trace_flag)
2745         puts("KEY REPLACE ON\n");
2746
2747       key_replace = true;
2748     }
2749   } 
2750
2751   if (xchr_file != NULL && *xchr_file != '\0')
2752   {
2753     if (read_xchr_file(xchr_file, 0, av))
2754     {
2755       if (trace_flag)
2756         puts("NON ASCII ON\n");
2757
2758       non_ascii = true;
2759     }
2760   } 
2761
2762   return 0;
2763 }
2764
2765 int init_commands (int ac, char **av)
2766 {
2767   shipout_flag          = out_dvi_flag;
2768   is_initex             = false; 
2769   allow_patterns        = false;
2770   reset_exceptions      = false;
2771   non_ascii             = false;
2772   key_replace           = false;
2773   want_version          = false;
2774   open_trace_flag       = false;
2775   trace_flag            = false;
2776   verbose_flag          = false;
2777   restrict_to_ascii     = false;
2778   show_in_hex           = false; /* default is not to show as hex code ^^ 00/Jun/18 */
2779   show_in_dos           = false; /* default is not to translate to DOS 850 */ 
2780   return_flag           = true;  // hard wired now
2781   trimeof               = true;  // hard wired now
2782   deslash               = true;
2783   pseudo_tilde          = 254;   /* default '~' replace 95/Sep/26 filledbox DOS 850 */
2784   pseudo_space          = 255;   /* default ' ' replace 97/June/5 nbspace DOS 850 */
2785   default_rule          = 26214; /* default rule variable 95/Oct/9 */
2786   show_current          = true;
2787   civilize_flag         = true;
2788   show_numeric          = true;
2789   show_missing          = true;
2790   c_style_flag          = false; /* use c-style error output */
2791   show_fmt_flag         = true;  /* show format file in log */
2792   show_tfm_flag         = false; /* don't show metric file in log */
2793   shorten_file_name     = false; /* don't shorten file names to 8+3 */
2794   show_texinput_flag    = true;  /* show TEXINPUTS and TEXFONTS */
2795   truncate_long_lines   = true;  /* truncate long lines */
2796   tab_step              = 0;     /* do not replace tabs with spaces */
2797   show_line_break_stats = true;  /* show line break statistics 96/Feb/8 */
2798   show_fonts_used       = true;  /* show fonts used in LOG file 97/Dec/24 */
2799   allow_quoted_names    = true;  /* allow quoted names with spaces 98/Mar/15 */
2800   show_cs_names         = false;
2801   knuth_flag            = false; /* allow extensions to TeX */
2802   full_file_name_flag   = true;  /* new default 2000 June 18 */
2803   errout                = stdout; /* as opposed to stderr say --- used ??? */
2804   new_hyphen_prime      = 0;
2805
2806 #ifdef VARIABLETRIESIZE
2807 /*  trie_size = default_trie_size; */
2808   trie_size = 0;
2809 #endif
2810
2811   mem_extra_high = 0;
2812   mem_extra_low  = 0;
2813   mem_initex     = 0;
2814
2815   format_name = "plain";
2816
2817   encoding_name = "";
2818
2819   if (read_command_line(ac, av) < 0)
2820     return -1;
2821
2822   if (optind == 0)
2823     optind = ac;
2824
2825 /*
2826   if (want_version)
2827   {
2828     stamp_it(log_line);
2829     strcat(log_line, "\n");
2830     show_line(log_line, 0);
2831     stampcopy(log_line);
2832     strcat(log_line, "\n");
2833     show_line(log_line, 0);
2834   }
2835 */
2836
2837   return 0;
2838 }
2839
2840 void initial_memory (void)
2841 {
2842   /* set initial memory allocations */
2843   if (mem_extra_high < 0)
2844     mem_extra_high = 0;
2845
2846   if (mem_extra_low < 0)
2847     mem_extra_low = 0;
2848
2849   if (mem_initex < 0)
2850     mem_initex = 0;
2851
2852   if (is_initex)
2853   {
2854  #if defined(ALLOCATEHIGH) || defined(ALLOCATELOW)
2855     if (mem_extra_high != 0 || mem_extra_low != 0)
2856     {
2857       puts("ERROR: Cannot extend main memory in iniTeX\n");
2858       mem_extra_high = 0;   mem_extra_low = 0;
2859     }
2860 #endif
2861   }
2862   else
2863   {
2864     if (mem_initex != 0)
2865     {
2866       puts("ERROR: Can only set initial main memory size in iniTeX\n");
2867       mem_initex = 0;
2868     }
2869
2870     if (trie_size != 0)
2871     {
2872       puts("ERROR: Need only set hyphenation trie size in iniTeX\n");
2873 /* trie_size = 0; */
2874     }
2875   }
2876   if (mem_initex == 0)
2877     mem_initex = default_mem_top;
2878
2879   if (trie_size == 0)
2880     trie_size = default_trie_size;
2881 /* Just in case user mistakenly specified words instead of kilo words */
2882   if (mem_extra_high > 10000L * 1024L)
2883     mem_extra_high = mem_extra_high / 1024;
2884
2885   if (mem_extra_low > 10000L * 1024L)
2886     mem_extra_low = mem_extra_low / 1024;
2887
2888   if (mem_initex > 10000L * 1024L)
2889     mem_initex = mem_initex / 1024;
2890
2891   if (mem_initex > 2048L * 1024L) /* extend main memory by 16 mega byte! */
2892   {
2893     puts("WARNING: There may be no benefit to asking for so much memory\n");
2894 /* mem_initex = 2048 * 1024; */
2895   }
2896
2897   if (new_hyphen_prime < 0)
2898     new_hyphen_prime = 0;
2899
2900   if (new_hyphen_prime > 0)
2901   {
2902     if (! is_initex)
2903       puts("ERROR: Can only set hyphen prime in iniTeX\n");
2904     else
2905     {
2906       if (new_hyphen_prime % 2 == 0)
2907         new_hyphen_prime++;
2908
2909       while (!prime(new_hyphen_prime))
2910         new_hyphen_prime = new_hyphen_prime + 2;
2911
2912       if (trace_flag)
2913       {
2914         sprintf(log_line, "Using %d as hyphen prime\n", new_hyphen_prime);
2915         show_line(log_line, 0);
2916       }
2917     }
2918   }
2919
2920   if (percent_grow > 100)
2921     percent_grow = percent_grow - 100;
2922
2923   if (percent_grow > 100)
2924     percent_grow = 100;   /* upper limit - double */
2925
2926   if (percent_grow < 10)
2927     percent_grow = 10;   /* lower limit - 10% */
2928 }
2929
2930 /**********************************************************************/
2931
2932 void perrormod (char *s)
2933 {
2934   sprintf(log_line, "`%s': %s\n", s, strerror(errno));
2935   show_line(log_line, 1);
2936 }
2937
2938 /*************************************************************************/
2939
2940 /* convert tilde to pseudo_tilde to hide it from TeX --- 95/Sep/26 */
2941 /* convert space to pseudo_space to hide it from TeX --- 97/Jun/5 */
2942 /* called only if pseudo_tilde != 0 or pseudo_space != 0 */
2943 /* this is then undone in tex3.c both for fopen input and output */
2944 /* not ideal, since pseudo name appears in log and in error messages ... */
2945
2946 void hidetwiddle (char *tname)
2947 {
2948   char *s = tname;
2949
2950 #ifdef DEBUGTWIDDLE
2951   if (trace_flag)
2952   {
2953     sprintf(log_line, "Hidetwiddle %s", tname);
2954     show_line(log_line, 0);
2955   }
2956 #endif
2957
2958   while (*s != '\0')
2959   {
2960     if (*s == '~' && pseudo_tilde != 0)
2961       *s = (char) pseudo_tilde;  /* typically 254 */
2962     else if (*s == ' ' && pseudo_space != 0)
2963       *s = (char) pseudo_space;  /* typically 255 */
2964     s++;
2965   }
2966
2967 #ifdef DEBUGTWIDDLE
2968   if (trace_flag)
2969   {
2970     sprintf(log_line, "=> %s\n", tname);
2971     show_line(log_line, 0);
2972   }
2973 #endif
2974 }
2975
2976 void deslash_all (int ac, char **av)
2977 {
2978   char buffer[file_name_size];  
2979   char *s;
2980
2981   if ((s = grabenv("TEXDVI")) != NULL)
2982     dvi_directory = s;
2983
2984   if ((s = grabenv("TEXLOG")) != NULL)
2985     log_directory = s;
2986
2987   if ((s = grabenv("TEXAUX")) != NULL)
2988     aux_directory = s;
2989
2990   if ((s = grabenv("TEXFMT")) != NULL)
2991     fmt_directory = s;
2992
2993   if ((s = grabenv("TEXPDF")) != NULL)
2994     pdf_directory = s;
2995
2996   strcpy(buffer, av[0]);
2997
2998   if ((s = strrchr(buffer, '\\')) != NULL)
2999     *(s + 1) = '\0';
3000   else if ((s = strrchr(buffer, '/')) != NULL)
3001     *(s + 1) = '\0';
3002   else if ((s = strrchr(buffer, ':')) != NULL)
3003     *(s + 1) = '\0';
3004
3005   s = buffer + strlen(buffer) - 1;
3006
3007   if (*s == '\\' || *s == '/')
3008     *s = '\0';
3009
3010   texpath = xstrdup(buffer);
3011
3012   if (strcmp(dvi_directory, "") != 0)
3013     flush_trailing_slash(dvi_directory);
3014
3015   if (strcmp(log_directory, "") != 0)
3016     flush_trailing_slash(log_directory);
3017
3018   if (strcmp(aux_directory, "") != 0)
3019     flush_trailing_slash(aux_directory);
3020
3021   if (strcmp(fmt_directory, "") != 0)
3022     flush_trailing_slash(fmt_directory);
3023
3024   if (strcmp(pdf_directory, "") != 0)
3025     flush_trailing_slash(pdf_directory);
3026
3027   if (deslash)
3028   {
3029     unixify (texpath);
3030     
3031     if (strcmp(dvi_directory, "") != 0)
3032       unixify(dvi_directory);
3033     
3034     if (strcmp(log_directory, "") != 0)
3035       unixify(log_directory);
3036
3037     if (strcmp(aux_directory, "") != 0)
3038       unixify(aux_directory);
3039
3040     if (strcmp(fmt_directory, "") != 0)
3041       unixify(fmt_directory);
3042
3043     if (strcmp(pdf_directory, "") != 0)
3044       unixify(pdf_directory);
3045   }
3046
3047   format_spec = 0;
3048
3049   if (optind < ac && optind > 0)
3050   {
3051     if (deslash)
3052     {
3053       if (trace_flag || debug_flag)
3054       {
3055         sprintf(log_line, "deslash: k %d argv[k] %s (argc %d)\n",
3056           optind, av[optind], ac);
3057         show_line(log_line, 0);
3058       }
3059
3060       unixify(av[optind]);
3061     }
3062
3063     if (pseudo_tilde != 0 || pseudo_space != 0)
3064       hidetwiddle (av[optind]);
3065
3066     if (*av[optind] == '&' || *av[optind] == '+')
3067     {
3068       format_spec = 1;
3069       format_name = xstrdup(av[optind] + 1);
3070
3071       if (optind + 1 < ac)
3072       {
3073         if (deslash)
3074         {
3075           if (trace_flag || debug_flag)
3076           {
3077             sprintf(log_line, "deslash: k %d argv[k] %s (argc %d)\n",
3078               optind + 1, av[optind + 1], ac);
3079             show_line(log_line, 0);
3080           }
3081
3082           unixify(av[optind + 1]);
3083         }
3084
3085         if (pseudo_tilde != 0 || pseudo_space != 0)
3086           hidetwiddle (av[optind + 1]);
3087       }
3088     }         
3089   }
3090 }
3091
3092 /* note: those optarg == 0 test don't really work ... */
3093 /* note: optarg starts at = in case of x=... */
3094
3095 int main_init (int ac, char **av)
3096 {
3097   kpse_set_program_name(av[0], NULL);
3098   xputenv("engine", "yandytex");
3099
3100   if (sizeof(memory_word) != sizeof(halfword) * 2)
3101     printf("ERROR: Bad word size %d!\n", sizeof(memory_word));
3102
3103   start_time = clock();
3104   main_time  = start_time;
3105
3106 /* reset all allocatable memory pointers to NULL - in case we drop out */
3107   main_memory = NULL;
3108   font_info   = NULL;
3109   str_pool    = NULL;
3110   str_start   = NULL;
3111
3112 #ifdef ALLOCATESAVESTACK
3113   save_stack = NULL; 
3114 #endif
3115
3116 #ifdef ALLOCATEBUFFER
3117   buffer           = NULL;
3118   current_buf_size = 0;
3119   buffer           = realloc_buffer (initial_buf_size);
3120 #endif
3121
3122   hyph_list  = NULL;
3123   hyph_word  = NULL;
3124   trie_taken = NULL;
3125   trie_hash  = NULL;
3126   trie_r     = NULL;
3127   trie_c     = NULL;
3128   trie_o     = NULL;
3129   trie_l     = NULL;
3130   trie_trc   = NULL;
3131   trie_tro   = NULL;
3132   trie_trl   = NULL;
3133
3134   log_opened          = false;  /* so can tell whether opened */
3135   interaction         = -1;     /* default state => 3 */
3136   missing_characters  = 0;      /* none yet! */
3137   font_dimen_zero     = true;   /* \fontdimen0 for checksum 98/Oct/5 */
3138   ignore_frozen       = false;  /* default is not to ignore 98/Oct/5 */
3139   suppress_f_ligs     = false;  /* default is not to ignore f-ligs */
3140
3141   if (ac > 1 && !strncmp(av[1], "-Y", 2))
3142     reorder_arg_flag = false;
3143
3144   if (reorder_arg_flag)
3145     reorderargs(ac, av);  
3146
3147   if (init_commands(ac, av))
3148     return -1;
3149
3150   check_fixed_align(trace_flag);
3151
3152   format_file   = NULL;
3153   source_direct = NULL;
3154   dvi_file_name = NULL;
3155   log_file_name = NULL;
3156   pdf_file_name = NULL;
3157
3158   first_pass_count  = 0;
3159   second_pass_count = 0;
3160   final_pass_count  = 0;
3161   paragraph_failed  = 0;
3162   single_line       = 0;
3163   overfull_hbox     = 0;
3164   underfull_hbox    = 0;
3165   overfull_vbox     = 0;
3166   underfull_vbox    = 0;
3167   closed_already    = 0;
3168
3169   if (trace_flag)
3170     puts("Entering init (local.c)");
3171
3172   probe_memory();
3173   ini_max_address = max_address;
3174
3175   if (trace_flag)
3176     show_maximums(stdout);
3177
3178   initial_memory();
3179   deslash_all(ac, av);
3180   no_interrupts = 0;
3181
3182   if (format_spec && mem_spec_flag)
3183     puts("WARNING: Cannot change initial main memory size when format specified");
3184
3185   if (allocate_memory() != 0)
3186     return -1;
3187
3188   check_alloc_align(trace_flag);
3189
3190   if (trace_flag)
3191     puts("Leaving init (local.c)");
3192
3193   return 0;
3194 }
3195
3196 #define CLK_TCK CLOCKS_PER_SEC
3197
3198 void show_inter_val (clock_t inter_val)
3199 {
3200   int seconds, tenths, hundredth, thousands;
3201
3202   if (inter_val >= CLK_TCK * 10)
3203   {
3204     tenths = (inter_val * 10 + CLK_TCK / 2) / CLK_TCK; 
3205     seconds = tenths / 10; 
3206     tenths = tenths % 10;
3207     printf("%d.%d", seconds, tenths);
3208   }
3209   else if (inter_val >= CLK_TCK)
3210   {
3211     hundredth = (inter_val * 100 + CLK_TCK / 2) / CLK_TCK;
3212     seconds = hundredth / 100;
3213     hundredth = hundredth % 100;
3214     printf("%d.%02d", seconds, hundredth);
3215   }
3216   else if (inter_val > 0)
3217   {
3218     thousands = (inter_val * 1000 + CLK_TCK / 2) / CLK_TCK;
3219     seconds = thousands / 1000;
3220     thousands = thousands % 1000;
3221     printf("%d.%03d", seconds, thousands);
3222   }
3223   else
3224     show_line("0", 0);
3225 }
3226
3227 int endit(int flag)
3228 {
3229   finish_time = clock();
3230
3231   if (missing_characters != 0)
3232     flag = 1;
3233
3234   if (missing_characters)
3235   {
3236     sprintf(log_line, "! There %s %d missing character%s --- see log file\n",
3237       (missing_characters == 1) ? "was" : "were",  missing_characters,
3238       (missing_characters == 1) ? "" : "s");
3239     show_line(log_line, 0);
3240   }
3241
3242   if (free_memory() != 0)
3243     flag++;
3244
3245   if (verbose_flag)
3246   {
3247     printf("Total ");
3248     show_inter_val(finish_time - start_time);
3249     printf(" sec (");
3250     show_inter_val(main_time - start_time);
3251     printf(" format load + ");
3252     show_inter_val(finish_time - main_time);
3253     printf(" processing) ");
3254
3255     if (total_pages > 0)
3256     {
3257       show_inter_val((finish_time - main_time) / total_pages);
3258       printf(" sec per page.");
3259     }
3260   }
3261
3262   return flag;
3263 }
3264 // printf control sequences' name
3265 void print_cs_name (FILE *output, int h)
3266 {
3267   int c, textof, n;
3268
3269   memset(log_line, 0, sizeof(log_line));
3270
3271   textof = hash[h].rh;
3272
3273   if (textof == 0)
3274     return;
3275
3276   c = sprintf(log_line, "(%d), ", h);
3277   n = length(textof);
3278
3279   memmove(log_line + c, str_pool + str_start[textof], n);
3280   memmove(log_line + c + n, "\n", 2);
3281
3282   if (output == stderr)
3283   {
3284     show_line(log_line, 1);
3285   }
3286   else
3287   {
3288     if (output == stdout)
3289       show_line(log_line, 0);
3290     else
3291       fprintf(output, "%s", log_line);
3292   }
3293
3294 }
3295 // prototype
3296 int compare_strn (int, int, int, int);
3297 /* compare two csnames in qsort */
3298 int compare_cs (const void *cp1, const void *cp2)
3299 {
3300   int c1, c2, l1, l2, k1, k2, textof1, textof2;
3301
3302   c1 = *(int *)cp1;
3303   c2 = *(int *)cp2;
3304   textof1 = hash[c1].rh;
3305   textof2 = hash[c2].rh;
3306   l1 = length(textof1);
3307   l2 = length(textof2);
3308   k1 = str_start[textof1];
3309   k2 = str_start[textof2];
3310
3311   return compare_strn(k1, l1, k2, l2);
3312 }
3313
3314 char * csused = NULL;
3315
3316 /* Allocate table of indeces to allow sorting on csname */
3317 /* Allocate flags to remember which ones already listed at start */
3318 /* pass = 0 --> fmt   */
3319 /* pass = 1 --> after */
3320 void print_cs_names (FILE *output, int pass)
3321 {
3322   int h, k, ccount, repeatflag;
3323   int *cnumtable;
3324   int nfcs = frozen_control_sequence;
3325
3326   if (pass == 0 && csused == NULL)
3327   {
3328     csused = (char *) malloc (nfcs);
3329
3330     if (csused == NULL)
3331       return;
3332
3333 #ifdef USEMEMSET
3334     memset(csused, 0, nfcs);
3335 #else
3336     for (h = 0; h < (hash_size + 780); h++)
3337       csused[h] = 0;
3338 #endif
3339   }
3340
3341   ccount = 0;
3342
3343   for (h = hash_base + 1; h < nfcs; h++)
3344   {
3345     if (pass == 1 && csused[h])
3346       continue;
3347
3348     if (hash[h].rh != 0)
3349     {
3350       if (pass == 0)
3351         csused[h] = 1;
3352
3353       ccount++;
3354     }
3355   }
3356
3357   sprintf(log_line, "\n%d %s multiletter control sequences:\n",
3358       ccount, (pass == 1) ? "new" : "");
3359
3360   if (output == stderr)
3361   {
3362     show_line(log_line, 1);
3363   }
3364   else
3365   {
3366     if (output == stdout)
3367       show_line(log_line, 0);
3368     else
3369       fprintf(output, "%s", log_line);
3370   }
3371
3372   if (ccount > 0)
3373   {
3374     cnumtable = (int *) malloc (ccount * sizeof(int));
3375
3376     if (cnumtable == NULL)
3377       return;
3378
3379     ccount = 0;
3380
3381     for (h = hash_base + 1; h < nfcs; h++)
3382     {
3383       if (pass == 1 && csused[h])
3384         continue;
3385
3386       if (hash[h].rh != 0)
3387         cnumtable[ccount++] = h;
3388     }
3389
3390     //qsort ((void *)cnumtable, ccount, sizeof (int), &compare_cs);
3391
3392     repeatflag = 0;
3393
3394     for (k = 0; k < ccount; k++)
3395     {
3396       h = cnumtable[k];
3397
3398       if (pass == 1 && csused[h])
3399         continue;
3400
3401       print_cs_name(output, h);
3402     }
3403
3404     sprintf(log_line, "\n");
3405
3406     if (output == stderr)
3407     {
3408       show_line(log_line, 1);
3409     }
3410     else
3411     {
3412       if (output == stdout)
3413         show_line(log_line, 0);
3414       else
3415         fprintf(output, "%s", log_line);
3416     }
3417
3418     free((void *)cnumtable);
3419   }
3420
3421   if (pass == 1 && csused != NULL)
3422   {
3423     free(csused);
3424     csused = NULL;
3425   }
3426 }
3427
3428 /* k1 and k2 are positions in string pool */
3429 /* l1 and l2 are lengths of strings */
3430 int compare_strn (int k1, int l1, int k2, int l2)
3431 {
3432   int c1, c2;
3433
3434   while (l1 > 0 && l2 > 0)
3435   {
3436     c1 = str_pool[k1];
3437     c2 = str_pool[k2];
3438
3439     if (c1 > c2)
3440       return 1;
3441     else if (c2 > c1)
3442       return -1;
3443
3444     l1--; l2--;
3445     k1++; k2++;
3446   }
3447
3448   if (l1 > 0)
3449     return 1;   /* first string longer */
3450   else if (l2 > 0)
3451     return -1; /* second string longer */
3452
3453   return 0;         /* strings match */
3454 }
3455 /* compare two font names and their at sizes in qsort */
3456 int compare_fnt (const void *fp1, const void *fp2)
3457 {
3458   int f1, f2, l1, l2, k1, k2, s;
3459
3460   f1 = *(short *)fp1;
3461   f2 = *(short *)fp2;
3462   l1 = length(font_name[f1]);
3463   l2 = length(font_name[f2]);
3464   k1 = str_start[font_name[f1]]; 
3465   k2 = str_start[font_name[f2]]; 
3466
3467   s = compare_strn (k1, l1, k2, l2);
3468
3469   if (s != 0)
3470     return s;
3471
3472   if (font_size[f1] > font_size[f2])
3473     return 1;
3474   else if (font_size[f1] < font_size[f2])
3475     return -1;
3476
3477   return 0;         /* should not ever get here */
3478 }
3479 /* compare two font names */
3480 int compare_fnt_name (int f1, int f2)
3481 {
3482   int l1, l2, k1, k2, s;
3483
3484   l1 = length(font_name[f1]);
3485   l2 = length(font_name[f2]); 
3486   k1 = str_start[font_name[f1]]; 
3487   k2 = str_start[font_name[f2]]; 
3488
3489   s = compare_strn (k1, l1, k2, l2);
3490
3491   return s;
3492 }
3493 /* decode checksum information */
3494 unsigned long checkdefault = 0x59265920; /* default signature */
3495 int decode_fourty (unsigned long checksum, char *codingvector)
3496 {
3497   int c;
3498   int k;
3499
3500   if (checksum == 0)
3501   {
3502     strcpy(codingvector, "unknwn");
3503     return 1;
3504   }
3505   else if ((checksum >> 8) == (checkdefault >> 8))
3506   {
3507     strcpy (codingvector, "fixed ");
3508     return 1;
3509   }
3510   else
3511   {
3512     for (k = 0; k < 6; k++)
3513     {
3514       c = (int) (checksum % 40);
3515       checksum = checksum / 40;
3516       
3517       if (c <= 'z' - 'a')
3518         c = c + 'a';
3519       else if (c < 36)
3520         c = (c + '0') - ('z' - 'a') - 1;
3521       else if (c == 36)
3522         c = '-';
3523       else if (c == 37)
3524         c = '&';
3525       else if (c == 38)
3526         c = '_';
3527       else
3528         c = '.';
3529       
3530       codingvector[5-k] = (char) c;
3531     }
3532     codingvector[6] = '\0';
3533   }
3534
3535   return 0;
3536 }
3537
3538 double sclpnt (long x)
3539 {
3540   double pt;
3541
3542   pt = (double) x / 65536.0;
3543   pt = (double) ((int) (pt * 1000.0 + 0.5)) / 1000.0;
3544
3545   return (pt);
3546 }
3547
3548 void dvi_font_show(internal_font_number f, int suppressname)
3549 {
3550   int a, l, k, n;
3551   unsigned long checksum;
3552   char checksumvector[8];
3553   char buffer[32];
3554
3555   putc(' ', log_file);
3556
3557   if (suppressname == 0)
3558   {
3559     a = length(font_area[f]);
3560     l = length(font_name[f]);
3561
3562     k = str_start[font_area[f]];
3563
3564     memcpy(buffer, str_pool + k, length(font_area[f]));
3565     fwrite(buffer, sizeof(char), length(font_area[f]), log_file);
3566
3567     k = str_start[font_name[f]];
3568
3569     memcpy(buffer, str_pool + k, length(font_name[f]));
3570     fwrite(buffer, sizeof(char), length(font_name[f]), log_file);
3571   }
3572   else a = l = 0;
3573
3574   for (k = a + l; k < 16; k++)
3575     putc(' ', log_file);
3576
3577   sprintf(buffer, "at %lgpt ", sclpnt(font_size[f]));
3578   fputs(buffer, log_file);
3579
3580   if (suppressname == 0)
3581   {
3582     n = strlen(buffer);
3583
3584     for (k = n; k < 16; k++)
3585       putc(' ', log_file);
3586
3587     checksum = (((font_check[f].b0) << 8 | font_check[f].b1) << 8 | font_check[f].b2) << 8 | font_check[f].b3;
3588     decode_fourty(checksum, checksumvector);
3589     fprintf(log_file, "encoding: %s..", checksumvector);
3590   }
3591
3592   putc('\n', log_file);
3593 }
3594 /* Allocate table of indeces to allow sorting on font name */
3595 void show_font_info (void)
3596 {
3597   int k, m, fcount, repeatflag;
3598   short *fnumtable;
3599
3600   fcount = 0;
3601
3602   for (k = 1; k <= font_ptr; k++)
3603     if (font_used[k])
3604       fcount++;
3605
3606   if (fcount == 0)
3607     return;
3608
3609   fnumtable = (short *) malloc(fcount * sizeof(short));
3610
3611   fprintf(log_file, "\nUsed %d font%s:\n", fcount, (fcount == 1) ? "" : "s");
3612
3613   fcount = 0;
3614
3615   for (k = 1; k <= font_ptr; k++) 
3616     if (font_used[k])
3617       fnumtable[fcount++] = (short) k;
3618
3619   qsort ((void *)fnumtable, fcount, sizeof(short), &compare_fnt);
3620
3621   repeatflag = 0;
3622
3623   for (m = 0; m < fcount; m++)
3624   {
3625     if (m > 0)
3626     {
3627       if (compare_fnt_name(fnumtable[m-1], fnumtable[m]) == 0)
3628         repeatflag = 1;
3629       else
3630         repeatflag = 0;
3631     }
3632
3633     dvi_font_show(fnumtable[m], repeatflag);
3634   }
3635
3636   free((void *)fnumtable);
3637 }