//
// Copyright (C) 1991 Texas Instruments Incorporated.
//
// Permission is granted to any individual or institution to use, copy, modify,
// and distribute this software, provided that this complete copyright and
// permission notice is maintained, intact, in all copies and supporting
// documentation.
//
// Texas Instruments Incorporated provides this software "as is" without
// express or implied warranty.
//
// Created: LGO 01/01/90 -- Initial design and implementation
// 

#include <cool/char.h>

// strfind -- finds the pattern in the source.  Sets start and
// end accordingly and returns a pointer to the beginning of the
// string found, or NULL.  Uses * to mean any number of any characters,
// and ? to mean one of any character.  \? and \* are used in the 
// pattern to look for the actual symbols ? and * in the source.
// Finds the first occurance from the beginning of the source string.

char* strfind(const char* string, const char* pattern, long* start, long* end)
{
  const char* stringp = string;
  const char* startp = string;
  for (; *pattern != '\0'; pattern++, string++) {
    if (*pattern == '\\') {			// Special case \* and \?
      pattern++;
      if (*pattern == '*' || *pattern == '?') {
	if (*string != *pattern)
	  return NULL;
      }
      else if (*string != '\\')
	return NULL;
    }
    else if (*pattern == '*') {
      long endp;
      pattern++;
      if (*pattern == '\0')
	goto match;
      while (strfind(string, pattern, NULL, &endp) == NULL) {
	if (*string++ == '\0')
	  return NULL;
      }
      startp = string;
      string += endp;
      goto match;
    }
    else if (*string == '\0')
      return NULL;
    else if ((*pattern != '?') && (*pattern != *string))
      return NULL;
  }
  if (*string != '\0') return NULL;
 match:						// Match found
  if (start != NULL) *start = startp - stringp;
  if (end != NULL) *end = string - stringp;
  // cast the const away, so we can return char*
  return((char*) startp);
}












