home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / txnf214s.lzh / TXNF214S / TEXINDEX.C < prev    next >
C/C++ Source or Header  |  1993-07-29  |  43KB  |  1,803 lines

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