home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / tinfo210.lzh / TINFO210 / C / TEXINDEX.C < prev   
C/C++ Source or Header  |  1991-01-08  |  38KB  |  1,593 lines

  1. /* Prepare Tex index dribble output into an actual index.
  2.    Copyright (C) 1987 Free Software Foundation, Inc.
  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 1, or (at your option)
  7.     any later version.
  8.  
  9.     This program is distributed in the hope that it will be useful,
  10.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.     GNU 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., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.  In other words, you are welcome to use, share and improve this program.
  19.  You are forbidden to forbid anyone else to use, share and improve
  20.  what you give them.   Help stamp out software-hoarding!  */
  21.  
  22.  
  23. #include <stdio.h>
  24. #include <ctype.h>
  25.  
  26. #ifdef VMS
  27. #include <file.h>
  28.  
  29. #define EXIT_SUCCESS ((1 << 28) | 1)
  30. #define EXIT_FATAL ((1 << 28) | 4)
  31. #define unlink delete
  32. #define tell(fd) lseek(fd, 0L, 1)
  33. #else
  34. #include <sys/file.h>
  35.  
  36. #define EXIT_SUCCESS 0
  37. #define EXIT_FATAL 1
  38. #endif
  39.  
  40.  
  41. #ifndef L_XTND
  42. #define L_XTND 2
  43. #endif
  44.  
  45. /* When sorting in core, this structure describes one line
  46.  and the position and length of its first keyfield.  */
  47.  
  48. struct lineinfo
  49.   {
  50.     char *text;        /* The actual text of the line */
  51.     union
  52.       {            /* The start of the key (for textual comparison) */
  53.     char *text;
  54.     long number;    /* or the numeric value (for numeric comparison) */
  55.       } key;
  56.     long keylen;    /* Length of key field */
  57.   };
  58.  
  59. /* This structure describes a field to use as a sort key */
  60.  
  61. struct keyfield
  62.   {
  63.     int startwords;        /* # words to skip  */
  64.     int startchars;        /*  and # additional chars to skip, to start of field */
  65.     int endwords;        /* similar, from beg (or end) of line, to find end of field */
  66.     int endchars;
  67.     char ignore_blanks;        /* Ignore spaces and tabs within the field */
  68.     char fold_case;        /* Convert upper case to lower before comparing */
  69.     char reverse;        /* Compare in reverse order */
  70.     char numeric;        /* Parse text as an integer and compare the integers */
  71.     char positional;        /* Sort according to position within the file */
  72.     char braced;        /* Count balanced-braced groupings as fields */
  73.   };
  74.  
  75. /* Vector of keyfields to use */
  76.  
  77. struct keyfield keyfields[3];
  78.  
  79. /* Number of keyfields stored in that vector.  */
  80.  
  81. int num_keyfields = 3;
  82.  
  83. /* Vector of input file names, terminated with a zero (null pointer) */
  84.  
  85. char **infiles;
  86.  
  87. /* Vector of corresponding output file names, or zero meaning default it */
  88.  
  89. char **outfiles;
  90.  
  91. /* Length of `infiles' */
  92.  
  93. int num_infiles;
  94.  
  95. /* Pointer to the array of pointers to lines being sorted */
  96.  
  97. char **linearray;
  98.  
  99. /* The allocated length of `linearray'. */
  100.  
  101. long lines;
  102.  
  103. /* Directory to use for temporary files.  On Unix, it ends with a slash.  */
  104.  
  105. char *tempdir;
  106.  
  107. /* Start of filename to use for temporary files.  */
  108.  
  109. char *tempbase;
  110.  
  111. /* Number of last temporary file.  */
  112.  
  113. int tempcount;
  114.  
  115. /* Number of last temporary file already deleted.
  116.  Temporary files are deleted by `flush_tempfiles' in order of creation.  */
  117.  
  118. int last_deleted_tempcount;
  119.  
  120. /* During in-core sort, this points to the base of the data block
  121.  which contains all the lines of data.  */
  122.  
  123. char *text_base;
  124.  
  125. /* Additional command switches */
  126.  
  127. int keep_tempfiles;    /* Nonzero means do not delete tempfiles -- for debugging */
  128.  
  129. /* Forward declarations of functions in this file */
  130.  
  131. void decode_command ();
  132. void sort_in_core ();
  133. void sort_offline ();
  134. char **parsefile ();
  135. char *find_field ();
  136. char *find_pos ();
  137. long find_value ();
  138. char *find_braced_pos ();
  139. char *find_braced_end ();
  140. void writelines ();
  141. int compare_full ();
  142. long readline ();
  143. int merge_files ();
  144. int merge_direct ();
  145. char *concat ();
  146. char *maketempname ();
  147. void flush_tempfiles ();
  148. char *tempcopy ();
  149.  
  150. extern char *mktemp ();
  151.  
  152. #define MAX_IN_CORE_SORT 500000
  153.  
  154. int
  155. main (argc, argv)
  156.      int argc;
  157.      char **argv;
  158. {
  159.   int i;
  160.  
  161.   tempcount = 0;
  162.   last_deleted_tempcount = 0;
  163.  
  164.   /* Describe the kind of sorting to do. */
  165.   /* The first keyfield uses the first braced field and folds case */
  166.   keyfields[0].braced = 1;
  167.   keyfields[0].fold_case = 1;
  168.   keyfields[0].endwords = -1;
  169.   keyfields[0].endchars = -1;
  170.   /* The second keyfield uses the second braced field, numerically */
  171.   keyfields[1].braced = 1;
  172.   keyfields[1].numeric = 1;
  173.   keyfields[1].startwords = 1;
  174.   keyfields[1].endwords = -1;
  175.   keyfields[1].endchars = -1;
  176.   /* The third keyfield (which is ignored while discarding duplicates)
  177.      compares the whole line */
  178.   keyfields[2].endwords = -1;
  179.   keyfields[2].endchars = -1;
  180.  
  181.   decode_command (argc, argv);
  182.  
  183.   tempbase = mktemp (concat ("txiXXXXXX", "", ""));
  184.  
  185.   /* Process input files completely, one by one.  */
  186.  
  187.   for (i = 0; i < num_infiles; i++)
  188.     {
  189.       int desc;
  190.       long ptr;
  191.       char *outfile;
  192.       char *p;
  193.  
  194.       desc = open (infiles[i], 0, 0);
  195.       if (desc < 0) pfatal_with_name (infiles[i]);
  196.       lseek (desc, 0, L_XTND);
  197.       ptr = tell (desc);
  198.       close (desc);
  199.  
  200.       outfile = outfiles[i];
  201.       if (!outfile)
  202.     {
  203.       outfile = concat (infiles[i], "s", "");
  204.     }
  205.  
  206.       if (ptr < MAX_IN_CORE_SORT)
  207.         /* Sort a small amount of data */
  208.         sort_in_core (infiles[i], ptr, outfile);
  209.       else
  210.         sort_offline (infiles[i], ptr, outfile);
  211.     }
  212.  
  213.   flush_tempfiles (tempcount);
  214.   exit (EXIT_SUCCESS);
  215. }
  216.  
  217. /* This page decodes the command line arguments to set the parameter variables
  218.  and set up the vector of keyfields and the vector of input files */
  219.  
  220. void
  221. decode_command (argc, argv)
  222.      int argc;
  223.      char **argv;
  224. {
  225.   int i;
  226.   char **ip;
  227.   char **op;
  228.  
  229.   /* Store default values into parameter variables */
  230.  
  231. #ifdef VMS
  232.   tempdir = "sys$scratch:";
  233. #else
  234.   tempdir = "/tmp/";
  235. #endif
  236.  
  237.   keep_tempfiles = 0;
  238.  
  239.   /* Allocate argc input files, which must be enough.  */
  240.  
  241.   infiles = (char **) xmalloc (argc * sizeof (char *));
  242.   outfiles = (char **) xmalloc (argc * sizeof (char *));
  243.   ip = infiles;
  244.   op = outfiles;
  245.  
  246.   /* First find all switches that control the default kind-of-sort */
  247.  
  248.   for (i = 1; i < argc; i++)
  249.     {
  250.       int tem = classify_arg (argv[i]);
  251.       char c;
  252.       char *p;
  253.  
  254.       if (tem <= 0)
  255.     {
  256.       *ip++ = argv[i];
  257.       *op++ = 0;
  258.       continue;
  259.     }
  260.       if (tem > 1)
  261.     {
  262.       if (i + 1 == argc)
  263.         fatal ("switch %s given with no argument following it", argv[i]);
  264.       else if (!strcmp (argv[i], "-T"))
  265.         tempdir = argv[i + 1];
  266.       else if (!strcmp (argv[i], "-o"))
  267.         *(op - 1) = argv[i + 1];
  268.       i += tem - 1;
  269.       continue;
  270.     }
  271.  
  272.       p = &argv[i][1];
  273.       while (c = *p++)
  274.     switch (c)
  275.       {
  276.       case 'k':
  277.         keep_tempfiles = 1;
  278.         break;
  279.  
  280.       default:
  281.         fatal ("invalid command switch %c", c);
  282.       }
  283.     switchdone: ;
  284.     }
  285.  
  286.   /* Record number of keyfields, terminate list of filenames */
  287.  
  288.   num_infiles = ip - infiles;
  289.   *ip = 0;
  290. }
  291.  
  292. /* Return 0 for an argument that is not a switch;
  293.  for a switch, return 1 plus the number of following arguments that the switch swallows.
  294. */
  295.  
  296. int
  297. classify_arg (arg)
  298.      char *arg;
  299. {
  300.   if (!strcmp (arg, "-T") || !strcmp (arg, "-o"))
  301.     return 2;
  302.   if (arg[0] == '-')
  303.     return 1;
  304.   return 0;
  305. }
  306.  
  307. /* Create a name for a temporary file */
  308.  
  309. char *
  310. maketempname (count)
  311.      int count;
  312. {
  313.   char tempsuffix[10];
  314.   sprintf (tempsuffix, "%d", count);
  315.   return concat (tempdir, tempbase, tempsuffix);
  316. }
  317.  
  318. /* Delete all temporary files up to the specified count */
  319.  
  320. void
  321. flush_tempfiles (to_count)
  322.      int to_count;
  323. {
  324.   if (keep_tempfiles) return;
  325.   while (last_deleted_tempcount < to_count)
  326.     unlink (maketempname (++last_deleted_tempcount));
  327. }
  328.  
  329. /* Copy an input file into a temporary file, and return the temporary file name */
  330.  
  331. #define BUFSIZE 1024
  332.  
  333. char *
  334. tempcopy (idesc)
  335.      int idesc;
  336. {
  337.   char *outfile = maketempname (++tempcount);
  338.   int odesc;
  339.   char buffer[BUFSIZE];
  340.  
  341.   odesc = open (outfile, O_WRONLY | O_CREAT, 0666);
  342.  
  343.   if (odesc < 0) pfatal_with_name (outfile);
  344.  
  345.   while (1)
  346.     {
  347.       int nread = read (idesc, buffer, BUFSIZE);
  348.       write (odesc, buffer, nread);
  349.       if (!nread) break;
  350.     }
  351.  
  352.   close (odesc);
  353.  
  354.   return outfile;
  355. }
  356.  
  357. /* Compare two lines, provided as pointers to pointers to text,
  358.  according to the specified set of keyfields */
  359.  
  360. int
  361. compare_full (line1, line2)
  362.      char **line1, **line2;
  363. {
  364.   int i;
  365.  
  366.   /* Compare using the first keyfield;
  367.      if that does not distinguish the lines, try the second keyfield; and so on. */
  368.  
  369.   for (i = 0; i < num_keyfields; i++)
  370.     {
  371.       long length1, length2;
  372.       char *start1 = find_field (&keyfields[i], *line1, &length1);
  373.       char *start2 = find_field (&keyfields[i], *line2, &length2);
  374.       int tem = compare_field (&keyfields[i], start1, length1, *line1 - text_base,
  375.                           start2, length2, *line2 - text_base);
  376.       if (tem)
  377.     {
  378.       if (keyfields[i].reverse)
  379.         return - tem;
  380.           return tem;
  381.     }
  382.     }
  383.  
  384.   return 0;    /* Lines match exactly */
  385. }
  386.  
  387. /* Compare two lines described by structures
  388.  in which the first keyfield is identified in advance.
  389.  For positional sorting, assumes that the order of the lines in core
  390.  reflects their nominal order.  */
  391.  
  392. int
  393. compare_prepared (line1, line2)
  394.      struct lineinfo *line1, *line2;
  395. {
  396.   int i;
  397.   int tem;
  398.   char *text1, *text2;
  399.  
  400.   /* Compare using the first keyfield, which has been found for us already */
  401.   if (keyfields->positional)
  402.     {
  403.       if (line1->text - text_base > line2->text - text_base)
  404.     tem = 1;
  405.       else
  406.     tem = -1;
  407.     }
  408.   else if (keyfields->numeric)
  409.     tem = line1->key.number - line2->key.number;
  410.   else
  411.     tem = compare_field (keyfields, line1->key.text, line1->keylen, 0, line2->key.text, line2->keylen, 0);
  412.   if (tem)
  413.     {
  414.       if (keyfields->reverse)
  415.     return - tem;
  416.       return tem;
  417.     }
  418.  
  419.   text1 = line1->text;
  420.   text2 = line2->text;
  421.  
  422.   /* Compare using the second keyfield;
  423.      if that does not distinguish the lines, try the third keyfield; and so on. */
  424.  
  425.   for (i = 1; i < num_keyfields; i++)
  426.     {
  427.       long length1, length2;
  428.       char *start1 = find_field (&keyfields[i], text1, &length1);
  429.       char *start2 = find_field (&keyfields[i], text2, &length2);
  430.       int tem = compare_field (&keyfields[i], start1, length1, text1 - text_base,
  431.                           start2, length2, text2 - text_base);
  432.       if (tem)
  433.     {
  434.       if (keyfields[i].reverse)
  435.         return - tem;
  436.           return tem;
  437.     }
  438.     }
  439.  
  440.   return 0;    /* Lines match exactly */
  441. }
  442.  
  443. /* Like compare_full but more general.
  444.  You can pass any strings, and you can say how many keyfields to use.
  445.  `pos1' and `pos2' should indicate the nominal positional ordering of
  446.  the two lines in the input.  */
  447.  
  448. int
  449. compare_general (str1, str2, pos1, pos2, use_keyfields)
  450.      char *str1, *str2;
  451.      long pos1, pos2;
  452.      int use_keyfields;
  453. {
  454.   int i;
  455.  
  456.   /* Compare using the first keyfield;
  457.      if that does not distinguish the lines, try the second keyfield; and so on. */
  458.  
  459.   for (i = 0; i < use_keyfields; i++)
  460.     {
  461.       long length1, length2;
  462.       char *start1 = find_field (&keyfields[i], str1, &length1);
  463.       char *start2 = find_field (&keyfields[i], str2, &length2);
  464.       int tem = compare_field (&keyfields[i], start1, length1, pos1, start2, length2, pos2);
  465.       if (tem)
  466.     {
  467.       if (keyfields[i].reverse)
  468.         return - tem;
  469.           return tem;
  470.     }
  471.     }
  472.  
  473.   return 0;    /* Lines match exactly */
  474. }
  475.  
  476. /* Find the start and length of a field in `str' according to `keyfield'.
  477.  A pointer to the starting character is returned, and the length
  478.  is stored into the int that `lengthptr' points to.  */
  479.  
  480. char *
  481. find_field (keyfield, str, lengthptr)
  482.      struct keyfield *keyfield;
  483.      char *str;
  484.      long *lengthptr;
  485. {
  486.   char *start;
  487.   char *end;
  488.   char *(*fun) ();
  489.  
  490.   if (keyfield->braced) fun = find_braced_pos;
  491.   else fun = find_pos;
  492.  
  493.   start = ( *fun )(str, keyfield->startwords, keyfield->startchars,
  494.            keyfield->ignore_blanks);
  495.   if (keyfield->endwords < 0)
  496.     {
  497.       if (keyfield->braced)
  498.     end = find_braced_end (start);
  499.       else
  500.     {
  501.       end = start;
  502.       while (*end && *end != '\n') end++;
  503.     }
  504.     }
  505.   else
  506.     {
  507.       end = ( *fun )(str, keyfield->endwords, keyfield->endchars, 0);
  508.       if (end - str < start - str) end = start;
  509.     }
  510.   *lengthptr = end - start;
  511.   return start;
  512. }
  513.  
  514. /* Find a pointer to a specified place within `str',
  515.  skipping (from the beginning) `words' words and then `chars' chars.
  516.  If `ignore_blanks' is nonzero, we skip all blanks
  517.  after finding the specified word.  */
  518.  
  519. char *
  520. find_pos (str, words, chars, ignore_blanks)
  521.      char *str;
  522.      int words, chars;
  523.      int ignore_blanks;
  524. {
  525.   int i;
  526.   char *p = str;
  527.  
  528.   for (i = 0; i < words; i++)
  529.     {
  530.       char c;
  531.       /* Find next bunch of nonblanks and skip them. */
  532.       while ((c = *p) == ' ' || c == '\t') p++;
  533.       while ((c = *p) && c != '\n' && !(c == ' ' || c == '\t')) p++;
  534.       if (!*p || *p == '\n') return p;
  535.     }
  536.  
  537.   while (*p == ' ' || *p == '\t') p++;
  538.  
  539.   for (i = 0; i < chars; i++)
  540.     {
  541.       if (!*p  || *p == '\n') break;
  542.       p++;
  543.     }
  544.   return p;
  545. }
  546.  
  547. /* Like find_pos but assumes that each field is surrounded by braces
  548.  and that braces within fields are balanced. */
  549.  
  550. char *
  551. find_braced_pos (str, words, chars, ignore_blanks)
  552.      char *str;
  553.      int words, chars;
  554.      int ignore_blanks;
  555. {
  556.   int i;
  557.   int bracelevel;
  558.   char *p = str;
  559.   char c;
  560.  
  561.   for (i = 0; i < words; i++)
  562.     {
  563.       bracelevel = 1;
  564.       while ((c = *p++) != '{' && c != '\n' && c);
  565.       if (c != '{')
  566.     return p - 1;
  567.       while (bracelevel)
  568.     {
  569.       c = *p++;
  570.       if (c == '{') bracelevel++;
  571.       if (c == '}') bracelevel--;
  572.       if (c == '\\') c = *p++;    /* \ quotes braces and \ */
  573.       if (c == 0 || c == '\n') return p-1;
  574.     }
  575.     }
  576.  
  577.   while ((c = *p++) != '{' && c != '\n' && c);
  578.  
  579.   if (c != '{')
  580.     return p-1;
  581.  
  582.   if (ignore_blanks)
  583.     while ((c = *p) == ' ' || c == '\t') p++;
  584.   
  585.   for (i = 0; i < chars; i++)
  586.     {
  587.       if (!*p  || *p == '\n') break;
  588.       p++;
  589.     }
  590.   return p;
  591. }
  592.  
  593. /* Find the end of the balanced-brace field which starts at `str'.
  594.   The position returned is just before the closing brace. */
  595.  
  596. char *
  597. find_braced_end (str)
  598.      char *str;
  599. {
  600.   int bracelevel;
  601.   char *p = str;
  602.   char c;
  603.  
  604.   bracelevel = 1;
  605.   while (bracelevel)
  606.     {
  607.       c = *p++;
  608.       if (c == '{') bracelevel++;
  609.       if (c == '}') bracelevel--;
  610.       if (c == '\\') c = *p++;
  611.       if (c == 0 || c == '\n') return p-1;
  612.     }
  613.   return p - 1;
  614. }
  615.  
  616. long
  617. find_value (start, length)
  618.      char *start;
  619.      long length;
  620. {
  621.   while (length != 0L) {
  622.     if (isdigit(*start))
  623.       return atol(start);
  624.     length--;
  625.     start++;
  626.   }
  627.   return 0l;
  628. }
  629.  
  630. /* Vector used to translate characters for comparison.
  631.    This is how we make all alphanumerics follow all else,
  632.    and ignore case in the first sorting.  */
  633. int char_order[256];
  634.  
  635. init_char_order ()
  636. {
  637.   int i;
  638.   for (i = 1; i < 256; i++)
  639.     char_order[i] = i;
  640.  
  641.   for (i = '0'; i <= '9'; i++)
  642.     char_order[i] += 512;
  643.  
  644.   for (i = 'a'; i <= 'z'; i++) {
  645.     char_order[i] = 512 + i;
  646.     char_order[i + 'A' - 'a'] = 512 + i;
  647.   }
  648. }
  649.  
  650. /* Compare two fields (each specified as a start pointer and a character count)
  651.  according to `keyfield'.  The sign of the value reports the relation between the fields */
  652.  
  653. int
  654. compare_field (keyfield, start1, length1, pos1, start2, length2, pos2)
  655.      struct keyfield *keyfield;
  656.      char *start1;
  657.      long length1;
  658.      long pos1;
  659.      char *start2;
  660.      long length2;
  661.      long pos2;
  662. {
  663.   if (keyfields->positional)
  664.     {
  665.       if (pos1 > pos2)
  666.     return 1;
  667.       else
  668.     return -1;
  669.     }
  670.   if (keyfield->numeric)
  671.     {
  672.     long value = find_value (start1, length1) - find_value (start2, length2);
  673.       if (value > 0) return 1;
  674.       if (value < 0) return -1;
  675.       return 0;
  676.     }
  677.   else
  678.     {
  679.       char *p1 = start1;
  680.       char *p2 = start2;
  681.       char *e1 = start1 + length1;
  682.       char *e2 = start2 + length2;
  683.  
  684.       int fold_case = keyfield->fold_case;
  685.  
  686.       while (1)
  687.     {
  688.       int c1, c2;
  689.  
  690.       if (p1 == e1) c1 = 0;
  691.       else c1 = *p1++;
  692.       if (p2 == e2) c2 = 0;
  693.       else c2 = *p2++;
  694.  
  695.       if (char_order[c1] != char_order[c2])
  696.         return char_order[c1] - char_order[c2];
  697.       if (!c1) break;
  698.     }
  699.  
  700.       /* Strings are equal except possibly for case.  */
  701.       p1 = start1;
  702.       p2 = start2;
  703.       while (1)
  704.     {
  705.       int c1, c2;
  706.  
  707.       if (p1 == e1) c1 = 0;
  708.       else c1 = *p1++;
  709.       if (p2 == e2) c2 = 0;
  710.       else c2 = *p2++;
  711.  
  712.       if (c1 != c2)
  713.         /* Reverse sign here so upper case comes out last.  */
  714.         return c2 - c1;
  715.       if (!c1) break;
  716.     }
  717.  
  718.       return 0;
  719.     }
  720. }
  721.  
  722. /* A `struct linebuffer' is a structure which holds a line of text.
  723.  `readline' reads a line from a stream into a linebuffer
  724.  and works regardless of the length of the line.  */
  725.  
  726. struct linebuffer
  727.   {
  728.     long size;
  729.     char *buffer;
  730.   };
  731.  
  732. /* Initialize a linebuffer for use */
  733.  
  734. void
  735. initbuffer (linebuffer)
  736.      struct linebuffer *linebuffer;
  737. {
  738.   linebuffer->size = 200;
  739.   linebuffer->buffer = (char *) xmalloc (200);
  740. }
  741.  
  742. /* Read a line of text from `stream' into `linebuffer'.
  743.  Return the length of the line.  */
  744.  
  745. long
  746. readline (linebuffer, stream)
  747.      struct linebuffer *linebuffer;
  748.      FILE *stream;
  749. {
  750.   char *buffer = linebuffer->buffer;
  751.   char *p = linebuffer->buffer;
  752.   char *end = p + linebuffer->size;
  753.  
  754.   while (1)
  755.     {
  756.       int c = getc (stream);
  757.       if (p == end)
  758.     {
  759.       buffer = (char *) xrealloc (buffer, linebuffer->size *= 2);
  760.       p += buffer - linebuffer->buffer;
  761.       end += buffer - linebuffer->buffer;
  762.       linebuffer->buffer = buffer;
  763.     }
  764.       if (c < 0 || c == '\n')
  765.     {
  766.       *p = 0;
  767.       break;
  768.     }
  769.       *p++ = c;
  770.     }
  771.  
  772.   return p - buffer;
  773. }
  774.  
  775. /* Sort an input file too big to sort in core.  */
  776.  
  777. void
  778. sort_offline (infile, nfiles, total, outfile)
  779.      char *infile;
  780.      long total;
  781.      char *outfile;
  782. {
  783.   int ntemps = 2 * (total + MAX_IN_CORE_SORT - 1) / MAX_IN_CORE_SORT;  /* More than enough */
  784.   char **tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
  785.   FILE *istream = fopen (infile, "r");
  786.   int i;
  787.   struct linebuffer lb;
  788.   long linelength;
  789.   int failure = 0;
  790.  
  791.   initbuffer (&lb);
  792.  
  793.   /* Read in one line of input data.  */
  794.  
  795.   linelength = readline (&lb, istream);
  796.  
  797.   if (lb.buffer[0] != '\\')
  798.     {
  799.       error ("%s: not a texinfo index file", infile);
  800.       return;
  801.     }
  802.  
  803.   /* Split up the input into `ntemps' temporary files, or maybe fewer,
  804.     and put the new files' names into `tempfiles' */
  805.  
  806.   for (i = 0; i < ntemps; i++)
  807.     {
  808.       char *outname = maketempname (++tempcount);
  809.       FILE *ostream = fopen (outname, "w");
  810.       long tempsize = 0;
  811.  
  812.       if (!ostream) pfatal_with_name (outname);
  813.       tempfiles[i] = outname;
  814.  
  815.       /* Copy lines into this temp file as long as it does not make file "too big"
  816.     or until there are no more lines.  */
  817.  
  818.       while (tempsize + linelength + 1 <= MAX_IN_CORE_SORT)
  819.     {
  820.       tempsize += linelength + 1;
  821.       fputs (lb.buffer, ostream);
  822.       putc ('\n', ostream);
  823.  
  824.       /* Read another line of input data.  */
  825.  
  826.       linelength = readline (&lb, istream);
  827.       if (!linelength && feof (istream)) break;
  828.  
  829.       if (lb.buffer[0] != '\\')
  830.         {
  831.           error ("%s: not a texinfo index file", infile);
  832.           failure = 1;
  833.           goto fail;
  834.         }
  835.     }
  836.       fclose (ostream);
  837.       if (feof (istream)) break;
  838.     }
  839.  
  840.   free (lb.buffer);
  841.  
  842.  fail:
  843.   /* Record number of temp files we actually needed.  */
  844.  
  845.   ntemps = i;
  846.  
  847.   /* Sort each tempfile into another tempfile.
  848.     Delete the first set of tempfiles and put the names of the second into `tempfiles' */
  849.  
  850.   for (i = 0; i < ntemps; i++)
  851.     {
  852.       char *newtemp = maketempname (++tempcount);
  853.       sort_in_core (&tempfiles[i], MAX_IN_CORE_SORT, newtemp);
  854.       if (!keep_tempfiles)
  855.         unlink (tempfiles[i]);
  856.       tempfiles[i] = newtemp;
  857.     }
  858.  
  859.   if (failure)
  860.     return;
  861.  
  862.   /* Merge the tempfiles together and indexify */
  863.  
  864.   merge_files (tempfiles, ntemps, outfile);
  865. }
  866.  
  867. /* Sort `infile', whose size is `total',
  868.  assuming that is small enough to be done in-core,
  869.  then indexify it and send the output to `outfile' (or to stdout).  */
  870.  
  871. void
  872. sort_in_core (infile, total, outfile)
  873.      char *infile;
  874.      long total;
  875.      char *outfile;
  876. {
  877.   char **nextline;
  878.   char *data = (char *) xmalloc (total + 1);
  879.   char *file_data;
  880.   long file_size;
  881.   int i;
  882.   FILE *ostream = stdout;
  883.   struct lineinfo *lineinfo;
  884.  
  885.   /* Read the contents of the file into the moby array `data' */
  886.  
  887.   int desc = open (infile, 0, 0);
  888.  
  889.   if (desc < 0)
  890.     fatal ("failure reopening %s", infile);
  891.   for (file_size = 0; ; )
  892.     {
  893.       if ((i = read (desc, data + file_size, total - file_size)) <= 0)
  894.     break;
  895.       file_size += i;
  896.     }
  897.   file_data = data;
  898.   data[file_size] = 0;
  899.  
  900.   close (desc);
  901.  
  902.   if (file_size > 0 && data[0] != '\\')
  903.     {
  904.       error ("%s: not a texinfo index file", infile);
  905.       return;
  906.     }
  907.  
  908.   init_char_order ();
  909.  
  910.   /* Sort routines want to know this address */
  911.  
  912.   text_base = data;
  913.  
  914.   /* Create the array of pointers to lines, with a default size frequently enough.  */
  915.  
  916.   lines = total / 50;
  917.   if (!lines) lines = 2;
  918.   linearray = (char **) xmalloc (lines * sizeof (char *));
  919.  
  920.   /* `nextline' points to the next free slot in this array.
  921.      `lines' is the allocated size.  */
  922.  
  923.   nextline = linearray;
  924.  
  925.   /* Parse the input file's data, and make entries for the lines.  */
  926.  
  927.   nextline = parsefile (infile, nextline, file_data, file_size);
  928.   if (nextline == 0)
  929.     {
  930.       error ("%s: not a texinfo index file", infile);
  931.       return;
  932.     }
  933.  
  934.   /* Sort the lines */
  935.  
  936.   /* If we have enough space, find the first keyfield of each line in advance.
  937.     Make a `struct lineinfo' for each line, which records the keyfield
  938.     as well as the line, and sort them.  */
  939.  
  940.   lineinfo = (struct lineinfo *) malloc ((nextline - linearray) * sizeof (struct lineinfo));
  941.  
  942.   if (lineinfo)
  943.     {
  944.       struct lineinfo *lp;
  945.       char **p;
  946.  
  947.       for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
  948.     {
  949.       lp->text = *p;
  950.       lp->key.text = find_field (keyfields, *p, &lp->keylen);
  951.       if (keyfields->numeric)
  952.         lp->key.number = find_value (lp->key.text, lp->keylen);
  953.     }
  954.  
  955.       qsort (lineinfo, nextline - linearray, sizeof (struct lineinfo), compare_prepared);
  956.  
  957.       for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
  958.     *p = lp->text;
  959.  
  960.       free (lineinfo);
  961.     }
  962.   else
  963.     qsort (linearray, nextline - linearray, sizeof (char *), compare_full);
  964.  
  965.   /* Open the output file */
  966.  
  967.   if (outfile)
  968.     {
  969.       ostream = fopen (outfile, "w");
  970.       if (!ostream)
  971.     pfatal_with_name (outfile);
  972.     }
  973.  
  974.   writelines (linearray, nextline - linearray, ostream);
  975.   if (outfile) fclose (ostream);
  976.  
  977.   free (linearray);
  978.   free (data);
  979. }
  980.  
  981. /* Parse an input string in core into lines.
  982.    DATA is the input string, and SIZE is its length.
  983.    Data goes in LINEARRAY starting at NEXTLINE.
  984.    The value returned is the first entry in LINEARRAY still unused.
  985.    Value 0 means input file contents are invalid.  */
  986.  
  987. char **
  988. parsefile (filename, nextline, data, size)
  989.      char *filename;
  990.      char **nextline;
  991.      char *data;
  992.      long size;
  993. {
  994.   char *p, *end;
  995.   char **line = nextline;
  996.  
  997.   p = data;
  998.   end = p + size;
  999.   *end = 0;
  1000.  
  1001.   while (p != end)
  1002.     {
  1003.       if (p[0] != '\\')
  1004.     return 0;
  1005.  
  1006.       *line = p;
  1007.       while (*p && *p != '\n') p++;
  1008.       if (p != end) p++;
  1009.  
  1010.       line++;
  1011.       if (line == linearray + lines)
  1012.     {
  1013.       char **old = linearray;
  1014.       linearray = (char **) xrealloc (linearray, sizeof (char *) * (lines *= 4));
  1015.       line += linearray - old;
  1016.     }
  1017.     }
  1018.  
  1019.   return line;
  1020. }
  1021.  
  1022. /* Indexification is a filter applied to the sorted lines
  1023.  as they are being written to the output file.
  1024.  Multiple entries for the same name, with different page numbers,
  1025.  get combined into a single entry with multiple page numbers.
  1026.  The first braced field, which is used for sorting, is discarded.
  1027.  However, its first character is examined, folded to lower case,
  1028.  and if it is different from that in the previous line fed to us
  1029.  a \initial line is written with one argument, the new initial.
  1030.  
  1031.  If an entry has four braced fields, then the second and third
  1032.  constitute primary and secondary names.
  1033.  In this case, each change of primary name
  1034.  generates a \primary line which contains only the primary name,
  1035.  and in between these are \secondary lines which contain
  1036.  just a secondary name and page numbers.
  1037. */
  1038.  
  1039. /* The last primary name we wrote a \primary entry for.
  1040.  If only one level of indexing is being done, this is the last name seen */
  1041. char *lastprimary;
  1042. int lastprimarylength;  /* Length of storage allocated for lastprimary */
  1043.  
  1044. /* Similar, for the secondary name. */
  1045. char *lastsecondary;
  1046. int lastsecondarylength;
  1047.  
  1048. /* Zero if we are not in the middle of writing an entry.
  1049.  One if we have written the beginning of an entry but have not
  1050.   yet written any page numbers into it.
  1051.  Greater than one if we have written the beginning of an entry
  1052.   plus at least one page number. */
  1053. int pending;
  1054.  
  1055. /* The initial (for sorting purposes) of the last primary entry written.
  1056.  When this changes, a \initial {c} line is written */
  1057.  
  1058. char * lastinitial;
  1059.  
  1060. int lastinitiallength;
  1061.  
  1062. /* When we need a string of length 1 for the value of lastinitial,
  1063.    store it here.  */
  1064.  
  1065. char lastinitial1[2];
  1066.  
  1067. /* Initialize static storage for writing an index */
  1068.  
  1069. void
  1070. init_index ()
  1071. {
  1072.   pending = 0;
  1073.   lastinitial = lastinitial1;
  1074.   lastinitial1[0] = 0;
  1075.   lastinitial1[1] = 0;
  1076.   lastinitiallength = 0;
  1077.   lastprimarylength = 100;
  1078.   lastprimary = (char *) xmalloc (lastprimarylength + 1);
  1079.   bzero (lastprimary, lastprimarylength + 1);
  1080.   lastsecondarylength = 100;
  1081.   lastsecondary = (char *) xmalloc (lastsecondarylength + 1);
  1082.   bzero (lastsecondary, lastsecondarylength + 1);
  1083. }
  1084.  
  1085. /* Indexify.  Merge entries for the same name,
  1086.  insert headers for each initial character, etc.  */
  1087.  
  1088. indexify (line, ostream)
  1089.      char *line;
  1090.      FILE *ostream;
  1091. {
  1092.   char *primary, *secondary, *pagenumber;
  1093.   int primarylength, secondarylength, pagelength;
  1094.   int len = strlen (line);
  1095.   int nosecondary;
  1096.   int initiallength;
  1097.   char *initial;
  1098.   char initial1[2];
  1099.   register char *p;
  1100.  
  1101.   /* First, analyze the parts of the entry fed to us this time */
  1102.  
  1103.   p = find_braced_pos (line, 0, 0, 0);
  1104.   if (*p == '{')
  1105.     {
  1106.       initial = p;
  1107.       /* Get length of inner pair of braces starting at p,
  1108.      including that inner pair of braces.  */
  1109.       initiallength = find_braced_end (p + 1) + 1 - p;
  1110.     }
  1111.   else
  1112.     {
  1113.       initial = initial1;
  1114.       initial1[0] = *p;
  1115.       initial1[1] = 0;
  1116.       initiallength = 1;
  1117.  
  1118.       if (initial1[0] >= 'a' && initial1[0] <= 'z')
  1119.     initial1[0] -= 040;
  1120.     }
  1121.  
  1122.   pagenumber = find_braced_pos (line, 1, 0, 0);
  1123.   pagelength = find_braced_end (pagenumber) - pagenumber;
  1124.   if (pagelength == 0)
  1125.     abort ();
  1126.  
  1127.   primary = find_braced_pos (line, 2, 0, 0);
  1128.   primarylength = find_braced_end (primary) - primary;
  1129.  
  1130.   secondary = find_braced_pos (line, 3, 0, 0);
  1131.   nosecondary = !*secondary;
  1132.   if (!nosecondary)
  1133.     secondarylength = find_braced_end (secondary) - secondary;
  1134.  
  1135.   /* If the primary is different from before, make a new primary entry */
  1136.   if (strncmp (primary, lastprimary, primarylength))
  1137.     {
  1138.       /* Close off current secondary entry first, if one is open */
  1139.       if (pending)
  1140.     {
  1141.       fputs ("}\n", ostream);
  1142.       pending = 0;
  1143.     }
  1144.  
  1145.       /* If this primary has a different initial, include an entry for the initial */
  1146.       if (initiallength != lastinitiallength ||
  1147.       strncmp (initial, lastinitial, initiallength))
  1148.     {
  1149.       fprintf (ostream, "\\initial {");
  1150.       fwrite (initial, 1, initiallength, ostream);
  1151.       fprintf (ostream, "}\n", initial);
  1152.       if (initial == initial1)
  1153.         {
  1154.           lastinitial = lastinitial1;
  1155.           *lastinitial1 = *initial1;
  1156.         }
  1157.       else
  1158.         {
  1159.           lastinitial = initial;
  1160.         }
  1161.       lastinitiallength = initiallength;
  1162.     }
  1163.  
  1164.       /* Make the entry for the primary.  */
  1165.       if (nosecondary)
  1166.     fputs ("\\entry {", ostream);
  1167.       else
  1168.     fputs ("\\primary {", ostream);
  1169.       fwrite (primary, primarylength, 1, ostream);
  1170.       if (nosecondary)
  1171.     {
  1172.       fputs ("}{", ostream);
  1173.       pending = 1;
  1174.     }
  1175.       else
  1176.     fputs ("}\n", ostream);
  1177.  
  1178.       /* Record name of most recent primary */
  1179.       if (lastprimarylength < primarylength)
  1180.     {
  1181.           lastprimarylength = primarylength + 100;
  1182.       lastprimary = (char *) xrealloc (lastprimary,
  1183.                        1 + lastprimarylength);
  1184.     }
  1185.       strncpy (lastprimary, primary, primarylength);
  1186.       lastprimary[primarylength] = 0;
  1187.  
  1188.       /* There is no current secondary within this primary, now */
  1189.       lastsecondary[0] = 0;
  1190.     }
  1191.  
  1192.   /* Should not have an entry with no subtopic following one with a subtopic */
  1193.  
  1194.   if (nosecondary && *lastsecondary)
  1195.     error ("entry %s follows an entry with a secondary name", line);
  1196.  
  1197.   /* Start a new secondary entry if necessary */
  1198.   if (!nosecondary && strncmp (secondary, lastsecondary, secondarylength))
  1199.     {
  1200.       if (pending)
  1201.     {
  1202.       fputs ("}\n", ostream);
  1203.       pending = 0;
  1204.     }
  1205.  
  1206.       /* Write the entry for the secondary.  */
  1207.       fputs ("\\secondary {", ostream);
  1208.       fwrite (secondary, secondarylength, 1, ostream);
  1209.       fputs ("}{", ostream);
  1210.       pending = 1;
  1211.  
  1212.       /* Record name of most recent secondary */
  1213.       if (lastsecondarylength < secondarylength)
  1214.     {
  1215.           lastsecondarylength = secondarylength + 100;
  1216.       lastsecondary = (char *) xrealloc (lastsecondary,
  1217.                        1 + lastsecondarylength);
  1218.     }
  1219.       strncpy (lastsecondary, secondary, secondarylength);
  1220.       lastsecondary[secondarylength] = 0;
  1221.     }
  1222.  
  1223.   /* Here to add one more page number to the current entry */
  1224.   if (pending++ != 1)
  1225.     fputs (", ", ostream);    /* Punctuate first, if this is not the first */
  1226.   fwrite (pagenumber, pagelength, 1, ostream);
  1227. }
  1228.  
  1229. /* Close out any unfinished output entry */
  1230.  
  1231. void
  1232. finish_index (ostream)
  1233.      FILE *ostream;
  1234. {
  1235.   if (pending)
  1236.     fputs ("}\n", ostream);
  1237.   free (lastprimary);
  1238.   free (lastsecondary);
  1239. }
  1240.  
  1241. /* Copy the lines in the sorted order.
  1242.  Each line is copied out of the input file it was found in. */
  1243.  
  1244. void
  1245. writelines (linearray, nlines, ostream)
  1246.      char **linearray;
  1247.      int nlines;
  1248.      FILE *ostream;
  1249. {
  1250.   char **stop_line = linearray + nlines;
  1251.   char **next_line;
  1252.  
  1253.   init_index ();
  1254.  
  1255.   /* Output the text of the lines, and free the buffer space */
  1256.  
  1257.   for (next_line = linearray; next_line != stop_line; next_line++)
  1258.     {
  1259.       /* If -u was specified, output the line only if distinct from previous one.  */
  1260.       if (next_line == linearray
  1261.       /* Compare previous line with this one, using only the explicitly specd keyfields */
  1262.       || compare_general (*(next_line - 1), *next_line, 0L, 0L, num_keyfields - 1))
  1263.     {
  1264.       char *p = *next_line;
  1265.       char c;
  1266.       while ((c = *p++) && c != '\n');
  1267.       *(p-1) = 0;
  1268.       indexify (*next_line, ostream);
  1269.     }
  1270.     }
  1271.  
  1272.   finish_index (ostream);
  1273. }
  1274.  
  1275. /* Assume (and optionally verify) that each input file is sorted;
  1276.  merge them and output the result.
  1277.  Returns nonzero if any input file fails to be sorted.
  1278.  
  1279.  This is the high-level interface that can handle an unlimited number of files.  */
  1280.  
  1281. #define MAX_DIRECT_MERGE 10
  1282.  
  1283. int
  1284. merge_files (infiles, nfiles, outfile)
  1285.      char **infiles;
  1286.      int nfiles;
  1287.      char *outfile;
  1288. {
  1289.   char **tempfiles;
  1290.   int ntemps;
  1291.   int i;
  1292.   int value = 0;
  1293.   int start_tempcount = tempcount;
  1294.  
  1295.   if (nfiles <= MAX_DIRECT_MERGE)
  1296.     return merge_direct (infiles, nfiles, outfile);
  1297.  
  1298.   /* Merge groups of MAX_DIRECT_MERGE input files at a time,
  1299.      making a temporary file to hold each group's result.  */
  1300.  
  1301.   ntemps = (nfiles + MAX_DIRECT_MERGE - 1) / MAX_DIRECT_MERGE;
  1302.   tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
  1303.   for (i = 0; i < ntemps; i++)
  1304.     {
  1305.       int nf = MAX_DIRECT_MERGE;
  1306.       if (i + 1 == ntemps)
  1307.     nf = nfiles - i * MAX_DIRECT_MERGE;
  1308.       tempfiles[i] = maketempname (++tempcount);
  1309.       value |= merge_direct (&infiles[i * MAX_DIRECT_MERGE], nf, tempfiles[i]);
  1310.     }
  1311.  
  1312.   /* All temporary files that existed before are no longer needed
  1313.      since their contents have been merged into our new tempfiles.
  1314.      So delete them.  */
  1315.   flush_tempfiles (start_tempcount);
  1316.  
  1317.   /* Now merge the temporary files we created.  */
  1318.  
  1319.   merge_files (tempfiles, ntemps, outfile);
  1320.  
  1321.   free (tempfiles);
  1322.  
  1323.   return value;
  1324. }  
  1325.  
  1326. /* Assume (and optionally verify) that each input file is sorted;
  1327.  merge them and output the result.
  1328.  Returns nonzero if any input file fails to be sorted.
  1329.  
  1330.  This version of merging will not work if the number of
  1331.  input files gets too high.  Higher level functions
  1332.  use it only with a bounded number of input files.  */
  1333.  
  1334. int
  1335. merge_direct (infiles, nfiles, outfile)
  1336.      char **infiles;
  1337.      int nfiles;
  1338.      char *outfile;
  1339. {
  1340.   char **ip = infiles;
  1341.   struct linebuffer *lb1, *lb2;
  1342.   struct linebuffer **thisline, **prevline;
  1343.   FILE **streams;
  1344.   int i;
  1345.   int nleft;
  1346.   int lossage = 0;
  1347.   int *file_lossage;
  1348.   struct linebuffer *prev_out = 0;
  1349.   FILE *ostream = stdout;
  1350.  
  1351.   if (outfile)
  1352.     {
  1353.       ostream = fopen (outfile, "w");
  1354.     }
  1355.   if (!ostream) pfatal_with_name (outfile);
  1356.  
  1357.   init_index ();
  1358.  
  1359.   if (nfiles == 0)
  1360.     {
  1361.       if (outfile)
  1362.         fclose (ostream);
  1363.       return 0;
  1364.     }
  1365.  
  1366.   /* For each file, make two line buffers.
  1367.      Also, for each file, there is an element of `thisline'
  1368.      which points at any time to one of the file's two buffers,
  1369.      and an element of `prevline' which points to the other buffer.
  1370.      `thisline' is supposed to point to the next available line from the file,
  1371.      while `prevline' holds the last file line used,
  1372.      which is remembered so that we can verify that the file is properly sorted. */
  1373.  
  1374.   /* lb1 and lb2 contain one buffer each per file */
  1375.   lb1 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
  1376.   lb2 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
  1377.  
  1378.   /* thisline[i] points to the linebuffer holding the next available line in file i,
  1379.      or is zero if there are no lines left in that file.  */
  1380.   thisline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *));
  1381.   /* prevline[i] points to the linebuffer holding the last used line from file i.
  1382.      This is just for verifying that file i is properly sorted.  */
  1383.   prevline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *));
  1384.   /* streams[i] holds the input stream for file i.  */
  1385.   streams = (FILE **) xmalloc (nfiles * sizeof (FILE *));
  1386.   /* file_lossage[i] is nonzero if we already know file i is not properly sorted.  */
  1387.   file_lossage = (int *) xmalloc (nfiles * sizeof (int));
  1388.  
  1389.   /* Allocate and initialize all that storage */
  1390.  
  1391.   for (i = 0; i < nfiles; i++)
  1392.     {
  1393.       initbuffer (&lb1[i]);
  1394.       initbuffer (&lb2[i]);
  1395.       thisline[i] = &lb1[i];
  1396.       prevline[i] = &lb2[i];
  1397.       file_lossage[i] = 0;
  1398.       streams[i] = fopen (infiles[i], "r");
  1399.       if (!streams[i])
  1400.     pfatal_with_name (infiles[i]);
  1401.  
  1402.       readline (thisline[i], streams[i]);
  1403.     }
  1404.  
  1405.   /* Keep count of number of files not at eof */
  1406.   nleft = nfiles;
  1407.  
  1408.   while (nleft)
  1409.     {
  1410.       struct linebuffer *best = 0;
  1411.       struct linebuffer *exch;
  1412.       int bestfile = -1;
  1413.       int i;
  1414.  
  1415.       /* Look at the next avail line of each file; choose the least one.  */
  1416.  
  1417.       for (i = 0; i < nfiles; i++)
  1418.     {
  1419.       if (thisline[i] &&
  1420.           (!best ||
  1421.            0 < compare_general (best->buffer, thisline[i]->buffer,
  1422.                     (long) bestfile, (long) i, num_keyfields)))
  1423.         {
  1424.           best = thisline[i];
  1425.           bestfile = i;
  1426.         }
  1427.     }
  1428.  
  1429.       /* Output that line, unless it matches the previous one and we don't want duplicates */
  1430.  
  1431.       if (!(prev_out &&
  1432.         !compare_general (prev_out->buffer, best->buffer, 0L, 1L, num_keyfields - 1)))
  1433.     indexify (best->buffer, ostream);
  1434.       prev_out = best;
  1435.  
  1436.       /* Now make the line the previous of its file, and fetch a new line from that file */
  1437.  
  1438.       exch = prevline[bestfile];
  1439.       prevline[bestfile] = thisline[bestfile];
  1440.       thisline[bestfile] = exch;
  1441.  
  1442.       while (1)
  1443.     {
  1444.       /* If the file has no more, mark it empty */
  1445.  
  1446.       if (feof (streams[bestfile]))
  1447.         {
  1448.           thisline[bestfile] = 0;
  1449.           nleft--;        /* Update the number of files still not empty */
  1450.           break;
  1451.         }
  1452.       readline (thisline[bestfile], streams[bestfile]);
  1453.       if (thisline[bestfile]->buffer[0] || !feof (streams[bestfile])) break;
  1454.     }
  1455.     }
  1456.  
  1457.   finish_index (ostream);
  1458.  
  1459.   /* Free all storage and close all input streams */
  1460.  
  1461.   for (i = 0; i < nfiles; i++)
  1462.     {
  1463.       fclose (streams[i]);
  1464.       free (lb1[i].buffer);
  1465.       free (lb2[i].buffer);
  1466.     }
  1467.   free (file_lossage);
  1468.   free (lb1);
  1469.   free (lb2);
  1470.   free (thisline);
  1471.   free (prevline);
  1472.   free (streams);
  1473.  
  1474.   if (outfile)
  1475.     fclose (ostream);
  1476.  
  1477.   return lossage;
  1478. }
  1479.  
  1480. /* Print error message and exit.  */
  1481.  
  1482. fatal (s1, s2)
  1483.      char *s1, *s2;
  1484. {
  1485.   error (s1, s2);
  1486.   exit (EXIT_FATAL);
  1487. }
  1488.  
  1489. /* Print error message.  `s1' is printf control string, `s2' is arg for it. */
  1490.  
  1491. error (s1, s2)
  1492.      char *s1, *s2;
  1493. {
  1494.   printf ("texindex: ");
  1495.   printf (s1, s2);
  1496.   printf ("\n");
  1497. }
  1498.  
  1499. perror_with_name (name)
  1500.      char *name;
  1501. {
  1502. #ifdef VMS
  1503. #include <errno.h>
  1504.   extern noshare int sys_nerr;
  1505.   extern noshare char *sys_errlist[];
  1506. #else
  1507.   extern int errno, sys_nerr;
  1508.   extern char *sys_errlist[];
  1509. #endif
  1510.   char *s;
  1511.  
  1512.   if (errno < sys_nerr)
  1513.     s = concat ("", sys_errlist[errno], " for %s");
  1514.   else
  1515.     s = "cannot open %s";
  1516.   error (s, name);
  1517. }
  1518.  
  1519. pfatal_with_name (name)
  1520.      char *name;
  1521. {
  1522.   extern int errno, sys_nerr;
  1523.   extern char *sys_errlist[];
  1524.   char *s;
  1525.  
  1526.   if (errno < sys_nerr)
  1527.     s = concat ("", sys_errlist[errno], " for %s");
  1528.   else
  1529.     s = "cannot open %s";
  1530.   fatal (s, name);
  1531. }
  1532.  
  1533. /* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */
  1534.  
  1535. char *
  1536. concat (s1, s2, s3)
  1537.      char *s1, *s2, *s3;
  1538. {
  1539.   int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  1540.   char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  1541.  
  1542.   strcpy (result, s1);
  1543.   strcpy (result + len1, s2);
  1544.   strcpy (result + len1 + len2, s3);
  1545.   *(result + len1 + len2 + len3) = 0;
  1546.  
  1547.   return result;
  1548. }
  1549.  
  1550. /* Like malloc but get fatal error if memory is exhausted.  */
  1551.  
  1552. int
  1553. xmalloc (size)
  1554.      int size;
  1555. {
  1556.   int result = malloc (size);
  1557.   if (!result)
  1558.     fatal ("virtual memory exhausted", 0);
  1559.   return result;
  1560. }
  1561.  
  1562.  
  1563. int
  1564. xrealloc (ptr, size)
  1565.      char *ptr;
  1566.      int size;
  1567. {
  1568.   int result = realloc (ptr, size);
  1569.   if (!result)
  1570.     fatal ("virtual memory exhausted");
  1571.   return result;
  1572. }
  1573.  
  1574. bzero (b, length)
  1575.      register char *b;
  1576.      register int length;
  1577. {
  1578. #ifdef VMS
  1579.   short zero = 0;
  1580.   long max_str = 65535;
  1581.  
  1582.   while (length > max_str) {
  1583.     (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
  1584.     length -= max_str;
  1585.     b += max_str;
  1586.   }
  1587.   (void) LIB$MOVC5 (&zero, &zero, &zero, &length, b);
  1588. #else
  1589.   while (length-- > 0)
  1590.     *b++ = 0;
  1591. #endif /* not VMS */
  1592. }
  1593.