//
// 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>

static const char* _strrfind(const char* strstart,
			     const char* string,
			     const char* patstart,
			     const char* pattern,
			     long* end)
{
  const char* startp = string;
  for (; pattern >= patstart; pattern--, string--) {
    if (*pattern == '*') {		// '*' matches anything or nothing
      --pattern;
      if (pattern >= patstart && *pattern == '\\') { // Special case \*
	if (string < strstart || *string != '*')
	  return NULL;
      }
      else {
	const char* res;
	if (pattern < patstart) {
	  string++;
	  goto match;
	}
	while ((res=_strrfind(strstart,string,patstart,pattern,end)) == NULL) {
	  if (--string < strstart)
	    return NULL;
	}
	startp = string;
	string = res;
	goto match;
      }
    }
    else if (string < strstart)			// check end of string
      return NULL;
    else if (*pattern == '?') {			// '?' matches any character
      if (pattern > patstart && *(pattern-1) == '\\') { // Special case \?
	pattern--;
	if (*string != '?')
	  return NULL;
      }
    }
    else if (*pattern != *string)
      return NULL;
  }
  if (++string != strstart) return NULL;
 match:						// Match found
  *end = startp - strstart + 1;
  return(string);
}


// strrfind -- 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 last occurance from the end of the source string.

char* strrfind(const char* string, const char* pattern, long* start, long* end)
{
  long endp;
  const char* res = _strrfind(string, string + strlen(string) - 1,
			      pattern, pattern + strlen(pattern) - 1, &endp);
  if (res != NULL) {
    if (start != NULL) *start = res - string;
    if (end != NULL) *end = endp;
  }
  // cast the const away, so we can return char*
  return((char*) res);
}

