home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / pc / unix / grep1_5.zoo / grep.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-09-07  |  37.4 KB  |  1,407 lines

  1. /* grep - print lines matching an extended regular expression   -*-C-*-
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.                       Written June, 1988 by Mike Haertel
  4.                   BMG speedups added July, 1988
  5.             by James A. Woods and Arthur David Olson
  6.  
  7.                NO WARRANTY
  8.  
  9.   BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  10. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  11. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  12. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  13. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  14. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  15. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  16. AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  17. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  18. CORRECTION.
  19.  
  20.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  21. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  22. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  23. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  24. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  25. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  26. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  27. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  28. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  29. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  30.  
  31.         GENERAL PUBLIC LICENSE TO COPY
  32.  
  33.   1. You may copy and distribute verbatim copies of this source file
  34. as you receive it, in any medium, provided that you conspicuously and
  35. appropriately publish on each copy a valid copyright notice "Copyright
  36.  (C) 1988 Free Software Foundation, Inc."; and include following the
  37. copyright notice a verbatim copy of the above disclaimer of warranty
  38. and of this License.  You may charge a distribution fee for the
  39. physical act of transferring a copy.
  40.  
  41.   2. You may modify your copy or copies of this source file or
  42. any portion of it, and copy and distribute such modifications under
  43. the terms of Paragraph 1 above, provided that you also do the following:
  44.  
  45.     a) cause the modified files to carry prominent notices stating
  46.     that you changed the files and the date of any change; and
  47.  
  48.     b) cause the whole of any work that you distribute or publish,
  49.     that in whole or in part contains or is a derivative of this
  50.     program or any part thereof, to be licensed at no charge to all
  51.     third parties on terms identical to those contained in this
  52.     License Agreement (except that you may choose to grant more extensive
  53.     warranty protection to some or all third parties, at your option).
  54.  
  55.     c) You may charge a distribution fee for the physical act of
  56.     transferring a copy, and you may at your option offer warranty
  57.     protection in exchange for a fee.
  58.  
  59. Mere aggregation of another unrelated program with this program (or its
  60. derivative) on a volume of a storage or distribution medium does not bring
  61. the other program under the scope of these terms.
  62.  
  63.   3. You may copy and distribute this program or any portion of it in
  64. compiled, executable or object code form under the terms of Paragraphs
  65. 1 and 2 above provided that you do the following:
  66.  
  67.     a) accompany it with the complete corresponding machine-readable
  68.     source code, which must be distributed under the terms of
  69.     Paragraphs 1 and 2 above; or,
  70.  
  71.     b) accompany it with a written offer, valid for at least three
  72.     years, to give any third party free (except for a nominal
  73.     shipping charge) a complete machine-readable copy of the
  74.     corresponding source code, to be distributed under the terms of
  75.     Paragraphs 1 and 2 above; or,
  76.  
  77.     c) accompany it with the information you received as to where the
  78.     corresponding source code may be obtained.  (This alternative is
  79.     allowed only for noncommercial distribution and only if you
  80.     received the program in object code or executable form alone.)
  81.  
  82. For an executable file, complete source code means all the source code for
  83. all modules it contains; but, as a special exception, it need not include
  84. source code for modules which are standard libraries that accompany the
  85. operating system on which the executable file runs.
  86.  
  87.   4. You may not copy, sublicense, distribute or transfer this program
  88. except as expressly provided under this License Agreement.  Any attempt
  89. otherwise to copy, sublicense, distribute or transfer this program is void and
  90. your rights to use the program under this License agreement shall be
  91. automatically terminated.  However, parties who have received computer
  92. software programs from you with this License Agreement will not have
  93. their licenses terminated so long as such parties remain in full compliance.
  94.  
  95.   5. If you wish to incorporate parts of this program into other free
  96. programs whose distribution conditions are different, write to the Free
  97. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  98. worked out a simple rule that can be stated here, but we will often permit
  99. this.  We will be guided by the two goals of preserving the free status of
  100. all derivatives our free software and of promoting the sharing and reuse of
  101. software.
  102.  
  103.  
  104. In other words, you are welcome to use, share and improve this program.
  105. You are forbidden to forbid anyone else to use, share and improve
  106. what you give them.   Help stamp out software-hoarding!  */
  107.  
  108. /*-
  109.   MODIFIED FOR MSDOS (MICROSOFT C 5.1) BY BARRY SCHWARTZ, SEPT. 1990.
  110.  
  111.   Includes the new option `-d <expression>' that has the same effect as
  112.   `-e <expression>' but strips enclosing quotes off of <expression>.
  113.  */
  114.  
  115. #include <ctype.h>
  116. #include <stdio.h>
  117. #ifdef USG
  118. #include <memory.h>
  119. #include <string.h>
  120. #else
  121. #include <strings.h>
  122. #endif
  123. #ifdef MSDOS
  124. #include <fcntl.h>
  125. #include <stddef.h>
  126. #include "msdosmac.h"
  127. #endif
  128. #include "dfa.h"
  129. #include "regex.h"
  130.  
  131. #ifdef __STDC__
  132. extern getopt(int, char **, const char *);
  133. extern read(int, void *, int);
  134. extern open(const char *, int, ...);
  135. extern void close();
  136. #else
  137. extern char *strrchr();
  138. #endif
  139.  
  140. extern char *optarg;
  141. extern optind, opterr;
  142. #ifndef MSDOS    /* Avoid redefinition errors */
  143. extern errno;
  144. extern char *sys_errlist[];
  145. #endif
  146.  
  147. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  148.  
  149. /* Exit status codes. */
  150. #define MATCHES_FOUND 0        /* Exit 0 if no errors and matches found. */
  151. #define NO_MATCHES_FOUND 1    /* Exit 1 if no matches were found. */
  152. #define ERROR 2            /* Exit 2 if some error occurred. */
  153.  
  154. /* Error is set true if something awful happened. */
  155. static int error;
  156.  
  157. /* The program name for error messages. */
  158. static char *prog;
  159.  
  160. /* One of the flags determined by the options. */
  161. static byte_count;        /* Precede output lines the byte count of the
  162.                    first character on the line. */
  163.  
  164. /* We do all our own buffering by hand for efficiency. */
  165. static char *buffer;        /* The buffer itself, grown as needed. */
  166. static bufbytes;        /* Number of bytes in the buffer. */
  167. static size_t bufalloc;        /* Number of bytes allocated to the buffer. */
  168.  
  169. #ifndef MSDOS
  170.  
  171. static bufprev;            /* Number of bytes that have been forgotten.
  172.                    This is used to get byte offsets from the
  173.                    beginning of the file. */
  174.  
  175. #else
  176.  
  177. /* MSDOS */
  178. static unsigned long bufprev;    /* `static int' isn't long enough */
  179. static char *char_weights;    /* `Weights' of buffer chars.  Normally chars
  180.                    have weight 1, but `\r\n' is considered
  181.                    equivalent to a `\n' of weight 2. */
  182. static last_char_was_CR;    /* True if the last character input was a
  183.                    carriage return and was stripped. */
  184.  
  185. /* The following two variables are used to speed up the handling of
  186.    `char_weights' by saving partial sums between calls to print_line(). */
  187. static char *weights_summing_ptr;
  188. static unsigned long weights_partial_sum;
  189.  
  190. #endif
  191.  
  192. static bufread;            /* Number of bytes to get with each read(). */
  193.  
  194. static void
  195. initialize_buffer()
  196. {
  197. #ifndef MSDOS
  198.  
  199.   bufread = 8192;
  200.   bufalloc = bufread + bufread / 2;
  201.  
  202.   buffer = malloc(bufalloc);
  203.   if (! buffer)
  204.     {
  205.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  206.           sys_errlist[errno]);
  207.       exit(ERROR);
  208.     }
  209.  
  210. #else
  211.  
  212.   /* MSDOS */
  213.  
  214.   bufread = 8192;
  215.   bufalloc = 16383;        /* Twice this is 32766, which is about as
  216.                    big a buffer as we can handle; we really
  217.                    don't want to go increasing buffer size
  218.                    much on MSDOS systems.  B^(  */
  219.  
  220.   last_char_was_CR = 0;
  221.  
  222.   weights_summing_ptr = 0;    /* NULL means `undefined' */
  223.  
  224.   buffer = malloc(bufalloc);
  225.   char_weights = (byte_count) ? malloc(bufalloc) : (char *) -1;
  226.   if (! buffer || ! char_weights)
  227.     {
  228.       fprintf(stderr, "%s: Memory exhausted\n", prog);
  229.       exit(ERROR);
  230.     }
  231.  
  232. #endif
  233. }
  234.  
  235. /* The current input file. */
  236. static fd;
  237. static char *filename;
  238. static eof;
  239.  
  240. /* Fill the buffer retaining the last n bytes at the beginning of the
  241.    newly filled buffer (for backward context).  Returns the number of new
  242.    bytes read from disk. */
  243. static
  244. fill_buffer_retaining(n)
  245.      int n;
  246. {
  247.   char *p, *q;
  248.   int i;
  249. #ifdef MSDOS
  250.   int old_last_char_was_CR;
  251. #endif
  252.  
  253.   /* See if we need to grow the buffer. */
  254.   if (bufalloc - n <= bufread)
  255.     {
  256.       while (bufalloc - n <= bufread)
  257.     {
  258. #ifndef MSDOS
  259.       bufalloc *= 2;
  260.       bufread *= 2;
  261. #else
  262.       unsigned new_bufalloc = (unsigned) bufalloc * 2;
  263.  
  264.       /* This is demented, but I'm having trouble figuring out
  265.          another way to avoid the bizarre behaviour you get when
  266.          a line exceeds length 32767 after `\r\n' conversion.
  267.          (It would seem easy, but the code turns bizarre on me.)
  268.          This method limits buffer allocation to about half what
  269.          is possible without resorting to huge model data. */
  270.       if (new_bufalloc > 32767)
  271.         {
  272.           fprintf(stderr, "\
  273. %s: input buffering limit exceeded (very long line)\n", prog);
  274.           exit(ERROR);
  275.         }
  276.  
  277.       bufalloc = new_bufalloc;
  278.  
  279. #if 0    /* Don't increase `bufread', because little is gained and more
  280.        lines get rejected. */
  281.       bufread *= 2;
  282. #endif
  283.  
  284. #endif
  285.     }
  286.  
  287. #ifndef MSDOS
  288.       buffer = realloc(buffer, bufalloc);
  289.       if (! buffer)
  290.     {
  291.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  292.           sys_errlist[errno]);
  293.       exit(ERROR);
  294.     }
  295. #else
  296.       /* MSDOS */
  297.       buffer = realloc(buffer, bufalloc);
  298.       char_weights = (byte_count) ? realloc(char_weights, bufalloc)
  299.                     : (char *) -1;
  300.       if (! buffer || ! char_weights)
  301.     {
  302.       fprintf(stderr, "%s: Memory exhausted\n", prog);
  303.       exit(ERROR);
  304.     }
  305. #endif
  306.     }
  307.  
  308. #ifndef MSDOS
  309.   bufprev += bufbytes - n;
  310. #else
  311.   if (byte_count)
  312.     {
  313.       /* Increase bufprev by the weights of the unretained characters. */
  314.  
  315.       char *limit = char_weights + (bufbytes - n);
  316.  
  317.       if (weights_summing_ptr)
  318.     {
  319.       p = weights_summing_ptr;
  320.       bufprev += weights_partial_sum;
  321.     }
  322.       else
  323.     p = char_weights;
  324.       while (p != limit)
  325.     bufprev += *(p++);
  326.  
  327.       /* Discard the old partial sum (if it exists), now that it has been
  328.          absorbed into `bufprev'. */
  329.       weights_summing_ptr = 0;
  330.     }
  331. #endif
  332.  
  333.   /* Shift stuff down. */
  334.   for (i = n, p = buffer, q = p + bufbytes - n; i--; )
  335.     *p++ = *q++;
  336. #ifdef MSDOS
  337.   if (byte_count)
  338.     for (i = n, p = char_weights, q = p + bufbytes - n; i--; )
  339.       *p++ = *q++;
  340. #endif
  341.   bufbytes = n;
  342.  
  343.   if (eof)
  344.     return 0;
  345.  
  346.   /* Read in new stuff. */
  347.   i = read(fd, buffer + bufbytes, bufread);
  348. #ifdef MSDOS
  349.   if (i == -1)        /* Other negative values are really wrapped-around
  350.                positive values. */
  351. #else
  352.   if (i < 0)
  353. #endif
  354.     {
  355.       fprintf(stderr, "%s: read on %s failed (%s)\n", prog,
  356.           filename ? filename : "<stdin>", sys_errlist[errno]);
  357.       error = 1;
  358.     }
  359.  
  360. #ifdef MSDOS
  361.   /* Save the old value of `last_char_was_CR', because it is needed below. */
  362.   old_last_char_was_CR = last_char_was_CR;
  363.  
  364.   /* If the last character input is a `\r', strip it but note that
  365.      it has been stripped.  This means that `\r' at the end of a file
  366.      _may or may not_ be stripped, but for grepping I don't think this
  367.      makes much difference.  What do you think? */
  368.   if (i > 0 && buffer[bufbytes + i - 1] == '\r')
  369.     --i, last_char_was_CR = 1;
  370.  
  371.   /* Massage the newly input stuff:  convert most characters to pairs
  372.      consisting of themselves and a weight of 1, but convert each `\r\n'
  373.      sequence to a `\n' character and a weight of 2. */
  374.   {
  375.     char *t;
  376.     char *limit = buffer + (bufbytes + i);
  377.  
  378.     p = q = buffer + bufbytes;
  379.     if (byte_count)
  380.       t = char_weights + bufbytes;
  381.  
  382.     /* If the old value of `last_char_was_CR' is true and the first
  383.        character read is `\n', then give that character a weight of 2,
  384.        because it belongs to a `\r\n' sequence. */
  385.     if (old_last_char_was_CR && q != limit && *q == '\n')
  386.       {
  387.     ++p;  ++q;        /* Leave the newline where it is */
  388.     if (byte_count)
  389.       *(t++) = 2;
  390.       }
  391.  
  392.     while (q != limit)
  393.       {
  394.     if (*q != '\r' || q + 1 == limit || *(q + 1) != '\n')
  395.       {
  396.         *(p++) = *(q++);    /* Either copy the character onto itself
  397.                    or shift it */
  398.         if (byte_count)
  399.           *(t++) = 1;    /* It's weight is 1 */
  400.       }
  401.     else
  402.       {
  403.         ++q;  ++q;        /* Skip past the `\r\n' sequence */
  404.         *(p++) = '\n';    /* Store a newline . . .    */
  405.         if (byte_count)
  406.           *(t++) = 2;    /*   . . . and give it weight 2 */
  407.         --i;        /* Pretend we didn't read the `\r' */
  408.       }
  409.       }
  410.   }
  411. #endif /* MSDOS */
  412.  
  413.   /* Kludge to pretend every nonempty file ends with a newline. */
  414.   if (i == 0 && bufbytes > 0 && buffer[bufbytes - 1] != '\n')
  415.     {
  416.       eof = i = 1;
  417.       buffer[bufbytes] = '\n';
  418.     }
  419.  
  420.   bufbytes += i;
  421.   return i;
  422. }
  423.  
  424. /* Various flags set according to the argument switches. */
  425. static trailing_context;    /* Lines of context to show after matches. */
  426. static leading_context;        /* Lines of context to show before matches. */
  427. static no_filenames;        /* Do not display filenames. */
  428. static line_numbers;        /* Precede output lines with line numbers. */
  429. static silent;            /* Produce no output at all.  This switch
  430.                    is bogus, ever hear of /dev/null? */
  431. static nonmatching_lines;    /* Print lines that don't match the regexp. */
  432.  
  433. static bmgexec;            /* Invoke Boyer-Moore-Gosper routines */
  434.  
  435. /* The compiled regular expression lives here. */
  436. static struct regexp reg;
  437.  
  438. /* The compiled regular expression for the backtracking matcher lives here. */
  439. static struct re_pattern_buffer regex;
  440.  
  441. /* Pointer in the buffer after the last character printed. */
  442. static char *printed_limit;
  443.  
  444. /* True when printed_limit has been artifically advanced without printing
  445.    anything. */
  446. static int printed_limit_fake;
  447.  
  448. /* Print a line at the given line number, returning the number of
  449.    characters actually printed.  Matching is true if the line is to
  450.    be considered a "matching line".  This is only meaningful if
  451.    surrounding context is turned on. */
  452. static
  453. print_line(p, number, matching)
  454.      char *p;
  455. #ifndef MSDOS
  456.      int number;
  457. #else
  458.      long number;
  459. #endif
  460.      int matching;
  461. {
  462.   int count = 0;
  463.  
  464.   if (silent)
  465.     {
  466.       do
  467.     ++count;
  468.       while (*p++ != '\n');
  469.       printed_limit_fake = 0;
  470.       printed_limit = p;
  471.       return count;
  472.     }
  473.  
  474.   if (filename && !no_filenames)
  475.     printf("%s%c", filename, matching ? ':' : '-');
  476. #ifndef MSDOS
  477.   if (byte_count)
  478.     printf("%d%c", p - buffer + bufprev, matching ? ':' : '-');
  479. #else
  480.   if (byte_count)
  481.     {
  482.       register char *q;
  483.       register char *limit = char_weights + (p - buffer);
  484.       register unsigned long sum_of_weights;
  485.  
  486.       if (weights_summing_ptr)
  487.     {
  488.       q = weights_summing_ptr;
  489.       sum_of_weights = weights_partial_sum;
  490.     }
  491.       else
  492.     {
  493.       q = char_weights;
  494.       sum_of_weights = 0L;
  495.     }
  496.  
  497.       while (q != limit)
  498.     sum_of_weights += *(q++);
  499.  
  500.       /* Save the partial sum so we don't have to start from the
  501.      beginning of the buffer each time. */
  502.       weights_summing_ptr = q;        /* == limit */
  503.       weights_partial_sum = sum_of_weights;
  504.  
  505.       printf("%lu%c", sum_of_weights + bufprev, matching ? ':' : '-');
  506.     }
  507. #endif
  508. #ifndef MSDOS
  509.   if (line_numbers)
  510.     printf("%d%c", number, matching ? ':' : '-');
  511. #else
  512.   if (line_numbers)
  513.     printf("%ld%c", number, matching ? ':' : '-');
  514. #endif
  515.   do
  516.     {
  517.       ++count;
  518.       putchar(*p);
  519.     }
  520.   while (*p++ != '\n');
  521.   printed_limit_fake = 0;
  522.   printed_limit = p;
  523.   return count;
  524. }
  525.  
  526. /* Print matching or nonmatching lines from the current file.  Returns a
  527.    count of matching or nonmatching lines. */
  528. static
  529. #ifdef MSDOS
  530. long
  531. #endif
  532. grep()
  533. {
  534.   int retain = 0;        /* Number of bytes to retain on next call
  535.                    to fill_buffer_retaining(). */
  536.   char *search_limit;        /* Pointer to the character after the last
  537.                    newline in the buffer. */
  538.   char saved_char;        /* Character after the last newline. */
  539.   char *resume;            /* Pointer to where to resume search. */
  540.   int resume_index = 0;        /* Count of characters to ignore after
  541.                    refilling the buffer. */
  542. #ifndef MSDOS
  543.   int line_count = 1;        /* Line number. */
  544. #else
  545.   long line_count = 1L;
  546. #endif
  547.   int try_backref;        /* Set to true if we need to verify the
  548.                    match with a backtracking matcher. */
  549. #ifndef MSDOS
  550.   int initial_line_count;    /* Line count at beginning of last search. */
  551. #else
  552.   long initial_line_count;
  553. #endif
  554.   char *match;            /* Pointer to the first character after the
  555.                    string matching the regexp. */
  556. #ifndef MSDOS
  557.   int match_count = 0;        /* Count of matching lines. */
  558. #else
  559.   long match_count = 0L;
  560. #endif
  561.   char *matching_line;        /* Pointer to first character of the matching
  562.                    line, or of the first line of context to
  563.                    print if context is turned on. */
  564.   char *real_matching_line;    /* Pointer to the first character of the
  565.                    real matching line. */
  566.   char *next_line;        /* Pointer to first character of the line
  567.                    following the matching line. */
  568.   int pending_lines = 0;    /* Lines of context left over from last match
  569.                    that we have to print. */
  570.   static first_match = 1;    /* True when nothing has been printed. */
  571.   int i;
  572.   char *tmp;
  573.   char *execute();
  574.  
  575.   printed_limit_fake = 0;
  576.   
  577.   while (fill_buffer_retaining(retain) > 0)
  578.     {
  579.       /* Find the last newline in the buffer. */
  580.       search_limit = buffer + bufbytes;
  581.       while (search_limit > buffer && search_limit[-1] != '\n')
  582.     --search_limit;
  583.       if (search_limit == buffer)
  584.     {
  585.       retain = bufbytes;
  586.       continue;
  587.     }
  588.  
  589.       /* Save the character after the last newline so regexecute can write
  590.      its own sentinel newline. */
  591.       saved_char = *search_limit;
  592.  
  593.       /* Search the buffer for a match. */
  594.       printed_limit = buffer;
  595.       resume = buffer + resume_index;
  596.       initial_line_count = line_count;
  597.  
  598.       while (match = execute(®, resume, search_limit, 0, &line_count, &try_backref))
  599.     {
  600.       ++match_count;
  601.  
  602.       /* Find the beginning of the matching line. */
  603.       matching_line = match;
  604.       while (matching_line > resume && matching_line[-1] != '\n')
  605.         --matching_line;
  606.       real_matching_line = matching_line;
  607.  
  608.       /* Find the beginning of the next line. */
  609.       next_line = match;
  610.       while (next_line < search_limit && *next_line++ != '\n')
  611.         ;
  612.  
  613.       /* If a potential backreference is indicated, try it out with
  614.          a backtracking matcher to make sure the line is a match. */
  615.       if (try_backref && re_search(®ex, matching_line,
  616.                        next_line - matching_line - 1,
  617.                        0,
  618.                        next_line - matching_line - 1,
  619.                        NULL) < 0)
  620.         {
  621.           resume = next_line;
  622.           if (resume == search_limit)
  623.         break;
  624.           else
  625.         continue;
  626.         }
  627.  
  628.       /* Print leftover lines from last time.  If nonmatching_lines is
  629.          turned on, print these as if they were matching lines. */
  630.       while (resume < matching_line && pending_lines)
  631.         {
  632.           resume += print_line(resume, initial_line_count++,
  633.                    nonmatching_lines);
  634.           --pending_lines;
  635.         }
  636.  
  637.       /* Print out the matching or nonmatching lines as necessary. */
  638.       if (! nonmatching_lines)
  639.         {
  640.           /* Back up over leading context if necessary. */
  641.           for (i = leading_context; matching_line > printed_limit
  642.            && i; --i)
  643.         {
  644.           while (matching_line > printed_limit
  645.              && (--matching_line)[-1] != '\n')
  646.             ;
  647.           --line_count;
  648.         }
  649.  
  650.           /* If context is enabled, we may have to print a separator. */
  651.           if ((leading_context || trailing_context) && !silent
  652.           && !first_match && (printed_limit_fake || matching_line
  653.                       > printed_limit))
  654.         printf("----------\n");
  655.           first_match = 0;
  656.  
  657.           /* Print the matching line and its leading context. */
  658.           while (matching_line < real_matching_line)
  659.         matching_line += print_line(matching_line, line_count++, 0);
  660.           matching_line += print_line(matching_line, line_count++, 1);
  661.  
  662.           /* If there's trailing context, leave some lines pending until
  663.          next time. */
  664.           pending_lines = trailing_context;
  665.         }
  666.       else if (matching_line > resume)
  667.         {
  668.           char *real_resume = resume;
  669.  
  670.           /* Back up over leading context if necessary. */
  671.           for (i = leading_context; resume > printed_limit && i; --i)
  672.         {
  673.           while (resume > printed_limit && (--resume)[-1] != '\n')
  674.             ;
  675.           --initial_line_count;
  676.         }
  677.  
  678.           /* If context is enabled, we may have to print a separator. */
  679.           if ((leading_context || trailing_context) && !silent
  680.           && !first_match && (printed_limit_fake || resume
  681.                       > printed_limit))
  682.         printf("----------\n");
  683.           first_match = 0;
  684.  
  685.           /* Print out the presumably matching leading context. */
  686.           while (resume < real_resume)
  687.         resume += print_line(resume, initial_line_count++, 0);
  688.  
  689.           /* Print out the nonmatching lines prior to the matching line. */
  690.           while (resume < matching_line)
  691.         resume += print_line(resume, initial_line_count++, 1);
  692.  
  693.           /* Deal with trailing context. */
  694.           if (trailing_context)
  695.         {
  696.           print_line(matching_line, line_count, 0);
  697.           pending_lines = trailing_context - 1;
  698.         }
  699.  
  700.           /* Count the current line. */
  701.           ++line_count;
  702.         }
  703.       else
  704.         {
  705.           /* The line immediately after a matching line has to be printed
  706.          because it was pending. */
  707.           if (pending_lines > 0)
  708.         {
  709.           --pending_lines;
  710.           print_line(matching_line, line_count, 0);
  711.         }
  712.           ++line_count;
  713.         }
  714.  
  715.       /* Resume searching at the beginning of the next line. */
  716.       initial_line_count = line_count;
  717.       resume = next_line;
  718.  
  719.       if (resume == search_limit)
  720.         break;
  721.     }
  722.  
  723.       /* Restore the saved character. */
  724.       *search_limit = saved_char;
  725.  
  726.       if (! nonmatching_lines)
  727.     {
  728.       while (resume < search_limit && pending_lines)
  729.         {
  730.           resume += print_line(resume, initial_line_count++, 0);
  731.           --pending_lines;
  732.         }
  733.     }
  734.       else if (search_limit > resume)
  735.     {
  736.       char *initial_resume = resume;
  737.  
  738.       /* Back up over leading context if necessary. */
  739.       for (i = leading_context; resume > printed_limit && i; --i)
  740.         {
  741.           while (resume > printed_limit && (--resume)[-1] != '\n')
  742.         ;
  743.           --initial_line_count;
  744.         }
  745.  
  746.       /* If context is enabled, we may have to print a separator. */
  747.       if ((leading_context || trailing_context) && !silent
  748.           && !first_match && (printed_limit_fake || resume
  749.                   > printed_limit))
  750.         printf("----------\n");
  751.       first_match = 0;
  752.  
  753.       /* Print out all the nonmatching lines up to the search limit. */
  754.       while (resume < initial_resume)
  755.         resume += print_line(resume, initial_line_count++, 0);
  756.       while (resume < search_limit)
  757.         resume += print_line(resume, initial_line_count++, 1);
  758.  
  759.       pending_lines = trailing_context;
  760.       resume_index = 0;
  761.       retain = bufbytes - (search_limit - buffer);
  762.       continue;
  763.     }
  764.       
  765.       /* Save the trailing end of the buffer for possible use as leading
  766.      context in the future. */
  767.       i = leading_context;
  768.       tmp = search_limit;
  769.       while (tmp > printed_limit && i--)
  770.     while (tmp > printed_limit && (--tmp)[-1] != '\n')
  771.       ;
  772.       resume_index = search_limit - tmp;
  773.       retain = bufbytes - (tmp - buffer);
  774.       if (tmp > printed_limit)
  775.     printed_limit_fake = 1;
  776.     }
  777.  
  778.   return nonmatching_lines ? (line_count - 1) - match_count : match_count;
  779. }
  780.  
  781. void
  782. usage_and_die()
  783. {
  784. #ifdef MSDOS
  785.   fprintf(stderr,
  786. "\
  787. usage: %s [-CVbchilnsvwx] [-<num>] [-AB <num>] [-f file] [-de] expr [files]\n\
  788.        (`-d expr' strips enclosing quotes off of expr)\n",
  789.           prog);
  790. #else
  791.   fprintf(stderr,
  792. "usage: %s [-CVbchilnsvwx] [-<num>] [-AB <num>] [-f file] [-e] expr [files]\n",
  793.           prog);
  794. #endif
  795.   exit(ERROR);
  796. }
  797.  
  798. static char version[] = "GNU e?grep, version 1.5";
  799.  
  800. #ifdef MSDOS
  801. #ifdef GNU_GLOBBING
  802. /* File attributes used by msd_dir2 routines */
  803. unsigned short dos_file_attributes;
  804. #endif
  805. #endif
  806.  
  807. main(argc, argv)
  808.      int argc;
  809.      char **argv;
  810. {
  811.   int c;
  812.   int ignore_case = 0;        /* Compile the regexp to ignore case. */
  813.   char *the_regexp = 0;        /* The regular expression. */
  814.   int regexp_len;        /* Length of the regular expression. */
  815.   char *regexp_file = 0;    /* File containing parallel regexps. */
  816.   int count_lines = 0;        /* Display only a count of matching lines. */
  817.   int list_files = 0;        /* Display only the names of matching files. */
  818.   int whole_word = 0;        /* Insist that the regexp match a word only. */
  819.   int whole_line = 0;        /* Insist on matching only whole lines. */
  820. #ifndef MSDOS
  821.   int line_count = 0;        /* Count of matching lines for a file. */
  822. #else
  823.   long line_count = 0L;
  824. #endif
  825.   int matches_found = 0;    /* True if matches were found. */
  826.   char *regex_errmesg;        /* Error message from regex routines. */
  827.   char translate[_NOTCHAR];    /* Translate table for case conversion
  828.                    (needed by the backtracking matcher). */
  829.  
  830. #ifdef MSDOS
  831.   /* Leave the output in text mode, but set stdin to binary mode in
  832.      case the input is read from there. */
  833.   setmode(fileno(stdin), O_BINARY);
  834.  
  835.   EXTRACT_PROGRAM_NAME(argv[0]);
  836.   prog = argv[0];
  837. #else
  838.   if (prog = strrchr(argv[0], '/'))
  839.     ++prog;
  840.   else
  841.     prog = argv[0];
  842. #endif
  843.  
  844. #if defined(MSDOS) && defined(GNU_GLOBBING)
  845.   dos_file_attributes = 0x11;        /* Regular, read-only, or directory */
  846.   {
  847.     char **glob_filename ();
  848.     int globargv ();
  849.  
  850.     if (globargv (&argc, &argv, glob_filename))
  851.       {
  852.     fprintf(stderr, "%s: Memory exhausted\n", prog);
  853.     exit(ERROR);
  854.       }
  855.   }
  856. #endif
  857.  
  858.   opterr = 0;
  859. #ifdef MSDOS
  860.   /* Include the `-d <expr>' (strip bracketing quotes) option */
  861.   while ((c = getopt(argc, argv, "0123456789A:B:CVbcd:e:f:hilnsvwx")) != EOF)
  862. #else
  863.   while ((c = getopt(argc, argv, "0123456789A:B:CVbce:f:hilnsvwx")) != EOF)
  864. #endif
  865.     switch (c)
  866.       {
  867.       case '?':
  868.     usage_and_die();
  869.     break;
  870.  
  871.       case '0':
  872.       case '1':
  873.       case '2':
  874.       case '3':
  875.       case '4':
  876.       case '5':
  877.       case '6':
  878.       case '7':
  879.       case '8':
  880.       case '9':
  881.     trailing_context = 10 * trailing_context + c - '0';
  882.     leading_context = 10 * leading_context + c - '0';
  883.     break;
  884.  
  885.       case 'A':
  886.     if (! sscanf(optarg, "%d", &trailing_context)
  887.         || trailing_context < 0)
  888.       usage_and_die();
  889.     break;
  890.  
  891.       case 'B':
  892.     if (! sscanf(optarg, "%d", &leading_context)
  893.         || leading_context < 0)
  894.       usage_and_die();
  895.     break;
  896.  
  897.       case 'C':
  898.     trailing_context = leading_context = 2;
  899.     break;
  900.  
  901.       case 'V':
  902.     fprintf(stderr, "%s\n", version);
  903.     break;
  904.  
  905.       case 'b':
  906.     byte_count = 1;
  907.     break;
  908.  
  909.       case 'c':
  910.     count_lines = 1;
  911.     silent = 1;
  912.     break;
  913.  
  914.       case 'e':
  915.     /* It doesn't make sense to mix -f and -e. */
  916.     if (regexp_file)
  917.       usage_and_die();
  918.     the_regexp = optarg;
  919.     break;
  920.  
  921. #ifdef MSDOS
  922.       case 'd':
  923.     /* It doesn't make sense to mix -f, -e, or -d */
  924.     if (regexp_file)
  925.       usage_and_die();
  926.  
  927.      /* Strip off bracketing quotes */
  928.      if (optarg[0] == '\'' || optarg[0] == '"')
  929.        {
  930.          char opening_quote = optarg[0];
  931.          int len = strlen (optarg);
  932.  
  933.          if (len > 1 && optarg[len - 1] == opening_quote)
  934.            (optarg++)[len - 1] = '\0';
  935.        }
  936.  
  937.     the_regexp = optarg;
  938.     break;
  939. #endif
  940.  
  941.       case 'f':
  942.     /* It doesn't make sense to mix -f and -e. */
  943.     if (the_regexp)
  944.       usage_and_die();
  945.     regexp_file = optarg;
  946.     break;
  947.  
  948.       case 'h':
  949.     no_filenames = 1;
  950.     break;
  951.  
  952.       case 'i':
  953.     ignore_case = 1;
  954.     for (c = 0; c < _NOTCHAR; ++c)
  955.       if (isupper(c))
  956.         translate[c] = tolower(c);
  957.       else
  958.         translate[c] = c;
  959.     regex.translate = translate;
  960.     break;
  961.  
  962.       case 'l':
  963.     list_files = 1;
  964.     silent = 1;
  965.     break;
  966.  
  967.       case 'n':
  968.     line_numbers = 1;
  969.     break;
  970.  
  971.       case 's':
  972.     silent = 1;
  973.     break;
  974.  
  975.       case 'v':
  976.     nonmatching_lines = 1;
  977.     break;
  978.  
  979.       case 'w':
  980.     whole_word = 1;
  981.     break;
  982.  
  983.       case 'x':
  984.     whole_line = 1;
  985.     break;
  986.  
  987.       default:
  988.     /* This can't happen. */
  989.     fprintf(stderr, "%s: getopt(3) let one by!\n", prog);
  990.     usage_and_die();
  991.     break;
  992.       }
  993.  
  994.   /* Set the syntax depending on whether we are EGREP or not. */
  995. #ifdef EGREP
  996.   regsyntax(RE_SYNTAX_EGREP, ignore_case);
  997.   re_set_syntax(RE_SYNTAX_EGREP);
  998. #else
  999.   regsyntax(RE_SYNTAX_GREP, ignore_case);
  1000.   re_set_syntax(RE_SYNTAX_GREP);
  1001. #endif
  1002.  
  1003.   /* Compile the regexp according to all the options. */
  1004.   if (regexp_file)
  1005.     {
  1006. #ifdef MSDOS
  1007.       /* This file must be handled in text mode */
  1008.       FILE *fp = fopen(regexp_file, "rt");
  1009. #else
  1010.       FILE *fp = fopen(regexp_file, "r");
  1011. #endif
  1012.       int len = 256;
  1013.       int i = 0;
  1014.  
  1015.       if (! fp)
  1016.     {
  1017.       fprintf(stderr, "%s: %s: %s\n", prog, regexp_file,
  1018.           sys_errlist[errno]);
  1019.       exit(ERROR);
  1020.     }
  1021.  
  1022.       the_regexp = malloc(len);
  1023.       if (! the_regexp)
  1024.     {
  1025. #ifdef MSDOS
  1026.       fprintf(stderr, "%s: Memory exhausted\n", prog);
  1027. #else
  1028.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  1029.           sys_errlist[errno]);
  1030. #endif
  1031.       exit(ERROR);
  1032.     }
  1033.  
  1034.       while ((c = getc(fp)) != EOF)
  1035.     {
  1036.       the_regexp[i++] = c;
  1037.       if (i == len)
  1038.         {
  1039.           the_regexp = realloc(the_regexp, len *= 2);
  1040.           if (! the_regexp)
  1041.             {
  1042. #ifdef MSDOS
  1043.               fprintf(stderr, "%s: Memory exhausted\n", prog);
  1044. #else
  1045.               fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  1046.                   sys_errlist[errno]);
  1047. #endif
  1048.               exit(ERROR);
  1049.             }
  1050.         }
  1051.     }
  1052.       fclose(fp);
  1053.       /* Nuke the concluding newline so we won't match the empty string. */
  1054.       if (i > 0 && the_regexp[i - 1] == '\n')
  1055.     --i;
  1056.       regexp_len = i;
  1057.     }
  1058.   else if (! the_regexp)
  1059.     {
  1060.       if (optind >= argc)
  1061.     usage_and_die();
  1062.       the_regexp = argv[optind++];
  1063.       regexp_len = strlen(the_regexp);
  1064.     }
  1065.   else
  1066.     regexp_len = strlen(the_regexp);
  1067.   
  1068.   if (whole_word || whole_line)
  1069.     {
  1070.       char *n = malloc(regexp_len + 8);
  1071.       int i = 0;
  1072.  
  1073.       if (! n)
  1074.     {
  1075. #ifdef MSDOS
  1076.       fprintf(stderr, "%s: Memory exhausted\n", prog);
  1077. #else
  1078.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  1079.           sys_errlist[errno]);
  1080. #endif
  1081.       exit(ERROR);
  1082.     }
  1083.  
  1084.       if (whole_line)
  1085.     n[i++] = '^';
  1086.       else
  1087.     n[i++] = '\\', n[i++] = '<';
  1088. #ifndef EGREP
  1089.       n[i++] = '\\';
  1090. #endif
  1091.       n[i++] = '(';
  1092.       memcpy(n + i, the_regexp, regexp_len);
  1093.       i += regexp_len;
  1094. #ifndef EGREP
  1095.       n[i++] = '\\';
  1096. #endif
  1097.       n[i++] = ')';
  1098.       if (whole_line)
  1099.     n[i++] = '$';
  1100.       else
  1101.     n[i++] = '\\', n[i++] = '>';
  1102.       the_regexp = n;
  1103.       regexp_len = i;
  1104.     }
  1105.  
  1106.   regcompile(the_regexp, regexp_len, ®, 1);
  1107.   
  1108.   if (regex_errmesg = re_compile_pattern(the_regexp, regexp_len, ®ex))
  1109.     regerror(regex_errmesg);
  1110.   
  1111.   /*
  1112.     Find the longest metacharacter-free string which must occur in the
  1113.     regexpr, before short-circuiting regexecute() with Boyer-Moore-Gosper.
  1114.     (Conjecture:  The problem in general is NP-complete.)  If there is no
  1115.     such string (like for many alternations), then default to full automaton
  1116.     search.  regmust() code and heuristics [see dfa.c] courtesy
  1117.     Arthur David Olson.
  1118.     */
  1119.   if (line_numbers == 0 && nonmatching_lines == 0)
  1120.     {
  1121.       if (reg.mustn == 0 || reg.mustn == MUST_MAX ||
  1122.         strchr(reg.must, '\0') != reg.must + reg.mustn)
  1123.     bmgexec = 0;
  1124.       else
  1125.     {
  1126.       reg.must[reg.mustn] = '\0';
  1127.       if (getenv("MUSTDEBUG") != NULL)
  1128.         (void) printf("must have: \"%s\"\n", reg.must);
  1129.       bmg_setup(reg.must, ignore_case);
  1130.       bmgexec = 1;
  1131.     }
  1132.     }
  1133.   
  1134.   if (argc - optind < 2)
  1135.     no_filenames = 1;
  1136.  
  1137.   initialize_buffer();
  1138.  
  1139.   if (argc > optind)
  1140.     while (optind < argc)
  1141.       {
  1142.     bufprev = eof = 0;
  1143. #ifdef MSDOS
  1144.     /* Convert backslashes to slashes, and make all letters lower case */
  1145.     CONVERT_TO_SLASHES(argv[optind]);
  1146. #endif
  1147.     filename = argv[optind++];
  1148.     fd = open(filename, 0, 0);
  1149.     if (fd < 0)
  1150.       {
  1151.         fprintf(stderr, "%s: %s: %s\n", prog, filename,
  1152.             sys_errlist[errno]);
  1153.         error = 1;
  1154.         continue;
  1155.       }
  1156.     if (line_count = grep())
  1157.       matches_found = 1;
  1158.     close(fd);
  1159.     if (count_lines)
  1160.       if (!no_filenames)
  1161.         printf("%s:%d\n", filename, line_count);
  1162.       else
  1163.         printf("%d\n", line_count);
  1164.     else if (list_files && line_count)
  1165.       printf("%s\n", filename);
  1166.       }
  1167.   else
  1168.     {
  1169.       if (line_count = grep())
  1170.     matches_found = 1;
  1171.       if (count_lines)
  1172.     printf("%d\n", line_count);
  1173.       else if (list_files && line_count)
  1174.     printf("<stdin>\n");
  1175.     }
  1176.  
  1177.   if (error)
  1178.     exit(ERROR);
  1179.   if (matches_found)
  1180.     exit(MATCHES_FOUND);
  1181.   exit(NO_MATCHES_FOUND);
  1182. }
  1183.  
  1184. /* Needed by the regexp routines.  This could be fancier, especially when
  1185.    dealing with parallel regexps in files. */
  1186. void
  1187. regerror(s)
  1188.      const char *s;
  1189. {
  1190.   fprintf(stderr, "%s: %s\n", prog, s);
  1191.   exit(ERROR);
  1192. }
  1193.  
  1194. /*
  1195.    bmg_setup() and bmg_search() adapted from:
  1196.      Boyer/Moore/Gosper-assisted 'egrep' search, with delta0 table as in
  1197.      original paper (CACM, October, 1977).  No delta1 or delta2.  According to
  1198.      experiment (Horspool, Soft. Prac. Exp., 1982), delta2 is of minimal
  1199.      practical value.  However, to improve for worst case input, integrating
  1200.      the improved Galil strategies (Apostolico/Giancarlo, Siam. J. Comput.,
  1201.      February 1986) deserves consideration.
  1202.  
  1203.      James A. Woods                Copyleft (C) 1986, 1988
  1204.      NASA Ames Research Center
  1205. */
  1206.  
  1207. char *
  1208. execute(r, begin, end, newline, count, try_backref)
  1209.   struct regexp *r;
  1210.   char *begin;
  1211.   char *end;
  1212.   int newline;
  1213. #ifndef MSDOS
  1214.   int *count;
  1215. #else
  1216.   long *count;
  1217. #endif
  1218.   int *try_backref;
  1219. {
  1220.   register char *p, *s;
  1221.   char *match;
  1222.   char *start = begin;
  1223.   char save;            /* regexecute() sentinel */
  1224.   int len;
  1225.   char *bmg_search();
  1226.  
  1227.   if (!bmgexec)            /* full automaton search */
  1228.     return(regexecute(r, begin, end, newline, count, try_backref));
  1229.   else
  1230.     {
  1231.       len = end - begin; 
  1232.       while ((match = bmg_search((unsigned char *) start, len)) != NULL)
  1233.     {
  1234.       p = match;        /* narrow search range to submatch line */
  1235.       while (p > begin && *p != '\n')
  1236.         p--;
  1237.       s = match;
  1238.       while (s < end && *s != '\n')
  1239.         s++;
  1240.       s++;
  1241.  
  1242.       save = *s;
  1243.       *s = '\0';
  1244.       match = regexecute(r, p, s, newline, count, try_backref);
  1245.       *s = save;
  1246.  
  1247.       if (match != NULL)
  1248.         return((char *) match);
  1249.       else
  1250.         {
  1251.           start = s;
  1252.           len = end - start;
  1253.         }
  1254.     }
  1255.       return(NULL);
  1256.     }
  1257. }
  1258.  
  1259. #include <ctype.h>
  1260. int        delta0[256];
  1261. unsigned char   cmap[256];        /* (un)folded characters */
  1262. unsigned char    pattern[5000];
  1263. int        patlen;
  1264.  
  1265. char *
  1266. bmg_search(buffer, buflen)
  1267.   unsigned char *buffer;
  1268.   int buflen;
  1269. {
  1270.   register unsigned char *k, *strend, *s, *buflim;
  1271.   register int t;
  1272.   int j;
  1273.  
  1274.   if (patlen > buflen)
  1275.     return NULL;
  1276.  
  1277.   buflim = buffer + buflen;
  1278.   if (buflen > patlen * 4)
  1279.     strend = buflim - patlen * 4;
  1280.   else
  1281.     strend = buffer;
  1282.  
  1283.   s = buffer;
  1284.   k = buffer + patlen - 1;
  1285.  
  1286.   for (;;)
  1287.     {
  1288.       /* The dreaded inner loop, revisited. */
  1289.       while (k < strend && (t = delta0[*k]))
  1290.     {
  1291.       k += t;
  1292.       k += delta0[*k];
  1293.       k += delta0[*k];
  1294.     }
  1295.       while (k < buflim && delta0[*k])
  1296.     ++k;
  1297.       if (k == buflim)
  1298.     break;
  1299.     
  1300.       j = patlen - 1;
  1301.       s = k;
  1302.       while (--j >= 0 && cmap[*--s] == pattern[j])
  1303.     ;
  1304.       /* 
  1305.     delta-less shortcut for literati, but 
  1306.     short shrift for genetic engineers.
  1307.       */
  1308.       if (j >= 0)
  1309.     k++;
  1310.       else         /* submatch */
  1311.     return ((char *)k);
  1312.     }
  1313.   return(NULL);
  1314. }
  1315.  
  1316. bmg_setup(pat, folded)            /* compute "boyer-moore" delta table */
  1317.   char *pat;
  1318.   int folded;
  1319. {                    /* ... HAKMEM lives ... */
  1320.   int j;
  1321.  
  1322.   patlen = strlen(pat);
  1323.  
  1324.   if (folded)                 /* fold case while saving pattern */
  1325.     for (j = 0; j < patlen; j++) 
  1326.       pattern[j] = (isupper((int) pat[j]) ?
  1327.     (char) tolower((int) pat[j]) : pat[j]);
  1328.   else
  1329.       memcpy(pattern, pat, patlen);
  1330.  
  1331.   for (j = 0; j < 256; j++)
  1332.     {
  1333.       delta0[j] = patlen;
  1334.       cmap[j] = (char) j;        /* could be done at compile time */
  1335.     }
  1336.   for (j = 0; j < patlen - 1; j++)
  1337.     delta0[pattern[j]] = patlen - j - 1;
  1338.   delta0[pattern[patlen - 1]] = 0;
  1339.  
  1340.   if (folded)
  1341.     {
  1342.       for (j = 0; j < patlen - 1; j++)
  1343.     if (islower((int) pattern[j]))
  1344.       delta0[toupper((int) pattern[j])] = patlen - j - 1;
  1345.     if (islower((int) pattern[patlen - 1]))
  1346.       delta0[toupper((int) pattern[patlen - 1])] = 0;
  1347.       for (j = 'A'; j <= 'Z'; j++)
  1348.     cmap[j] = (char) tolower((int) j);
  1349.     }
  1350. }
  1351.  
  1352. #ifndef USG
  1353.  
  1354. /* (groan) compatibility */
  1355.  
  1356. char *
  1357. strchr(s, c)
  1358.      char *s;
  1359. {
  1360.   return index(s, c);
  1361. }
  1362.  
  1363. char *
  1364. strrchr(s, c)
  1365.      char *s;
  1366. {
  1367.   return rindex(s, c);
  1368. }
  1369.  
  1370. char *
  1371. memcpy(d, s, n)
  1372.      char *d, *s;
  1373. {
  1374.   return bcopy(s, d, n);
  1375. }
  1376.  
  1377. #else
  1378.  
  1379. char *
  1380. index(s, c)
  1381.      char *s;
  1382. {
  1383.   return strchr(s, c);
  1384. }
  1385.  
  1386. char *
  1387. bcopy(s, d, n)
  1388.      char *s, *d;
  1389. {
  1390.   return memcpy(d, s, n);
  1391. }
  1392.  
  1393. char *
  1394. bzero(s, n)
  1395.      char *s;
  1396. {
  1397.   return memset(s, 0, n);
  1398. }
  1399.  
  1400. bcmp(s, t, n)
  1401.      char *s, *t;
  1402. {
  1403.   return memcmp(s, t, n);
  1404. }
  1405.  
  1406. #endif
  1407.