home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / OSK / GNU / SRC / makeinfo_src.lzh / texindex.c < prev   
Text File  |  1991-06-02  |  43KB  |  1,703 lines

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