/*

Copyright (C) 1995 Andrew Tefft. I liked Henry Spencer's terms so:

        Permission is granted to anyone to use this software for any
        purpose on any computer system, and to redistribute it freely,
        subject to the following restrictions:

        1. The author is not responsible for the consequences of use of
                this software, no matter how awful, even if they arise
                from defects in it.

        2. The origin of this software must not be misrepresented, either
                by explicit claim or by omission.

        3. Altered versions must be plainly marked as such, and must not
                be misrepresented as being the original software.

*/

/* count the number of times a given string is found in stdin.
   This is done on a word basis. So "hat" will not be a hit in "that". */

/* thecase = 1 for case insensitive. fast = 1 for partial word matches */

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char *mystrstr();

int hits(key,buf,thecase,fast)
     char *key, *buf ;
     int thecase;
{
  char *p,*x;
  int hits,keylen;

/* if case insensitive, lowercase the search key */

  keylen=strlen(key);

  if (thecase) {
    p=key;
    while (*p != NULL){
      *p = tolower(*(p)); 
      p++;
    }
  }

  hits=0;

    p=buf;
 
#if 0
  while (*p != NULL) {
#endif

    while ((x = mystrstr(p,key,thecase)) != NULL) {
      p=x;
#ifdef DEBUG
      printf("Got a find... \n");
#endif
      if (fast || (p==buf || !isalpha(*(p-1))) && !isalpha(*(p+keylen))) {
#ifdef DEBUG
	printf("hit!\n");
#endif
	hits++;
	p += keylen;
      }
      else {
#ifdef DEBUG
	printf("\n");
#endif
/* why is this even here? */
	p++;
/* oh yeah in case we get a match but not a hit */
      }
    }
#if 0
  }
#endif
  return hits;
}

/* does a strstr. case insensitive if thecase=1 */
/* this function kicks butt compared to strstr -- don't know why! */
/* what happened? it used to work! */

char *mystrstr(s1,s2,thecase)
     char *s1, *s2;
     int thecase;
{
  char *p,*q;
#ifdef SLOW_STRSTR
if (!thecase) return mystrstr(s1,s2);
#else

  p=s1; /* buffer */
  q=s2; /* key */

#define THECASE

  while (*p != NULL) {
    if (*p == *q 
#ifdef THECASE
	|| (thecase && (*q == tolower(*p)))
#endif
	) {  /* start of a match */
      while ((*p != NULL && *q != NULL) && /* as long as it goes. */
	     (*p == *q 
#ifdef THECASE
	      ||     /* case sensitive: we have a match or */
	      (thecase &&     /* case insensitive and... */
	       (*q == tolower(*p))  /* match any (key already lowercased) */
	       )
#endif
	     )) { 
	p++;
        q++;
      }
      if (*q == NULL) return (p - strlen(s2));  /* finished key; it's a match! */
    }
    else {
      q=s2; /* reset key */
      p++;  /* next char */
    }
  }

#endif	      
return NULL;  /* no match fall through */

}


