/*
 * 文字列検索ルーチン
 *
 * 1999/04/19:Eiichiroh Itoh
 *  (1) 作成開始
 * 修正履歴
 * 1999/04/19:Eiichiroh Itoh
 *
 */
#define	STRICT
#include	<windows.h>
#include	<string.h>

static	BYTE	FindStr[ 80 ] ;
static	BYTE	TextBuf[ 80 ] ;
static	char	SkipArray[ 256 ] ;

#define		toupper(c)		(((c)>='a')&&((c)<='z') ? (c)-'a'+'A' : (c))

extern	BOOL	get_char( LPBYTE p ) ;

char *
strrchr_i( const char *dst, int find_c, int f_ignore )
{
	char		c ;
	const char	*found = 0 ;

	find_c = f_ignore ? toupper( find_c ) : find_c ;
	while ( c = *dst ) {
		c = f_ignore ? toupper( c ) : c ;
		if ( c == find_c ) {
			found = dst ;
		}
		dst ++ ;
	}
	c = f_ignore ? toupper( c ) : c ;
	return (char*) (c == find_c ? dst : found) ;
}

static	void
make_skip_array( LPSTR buf, BOOL f_ignore )
{
	char	*ptr ;
	int		c, len, dist ;

	len = strlen( buf ) ;
	for ( c = 0 ; c < 256 ; c ++ ) {
		ptr = strrchr_i( buf, c, f_ignore ) ;
		if ( ptr ) {
			dist = len - (ptr - buf) - 1 ;
			SkipArray[ c ] = dist ? dist : 1 ;
		} else {
			SkipArray[ c ] = len ;
		}
	}
}

BOOL
compare( const BYTE *str1, const BYTE *str2, DWORD len, BOOL f_ignore )
{
	BYTE	c1, c2 ;

	do {
		c1 = *str1++ ;
		c2 = *str2++ ;
		if ( f_ignore ) {
			c1 = toupper( c1 ) ;
			c2 = toupper( c2 ) ;
		}
		if ( c1 != c2 ) {
			return FALSE ;
		}
	} while ( -- len ) ;
	return TRUE ;
}

BOOL
find_text( LPBYTE findstr, BOOL f_ignore )
{
	BYTE	c1, c2 ;
	int		len = strlen( findstr ), readcnt = 0, skip ;

	make_skip_array( findstr, f_ignore ) ;
	while ( 1 ) {
		for ( ; readcnt < len ; readcnt ++ ) {
			if ( !get_char( &c1 ) ) {
				/* ファイルの最後まで到達した場合 */
				return FALSE ;
			}
			TextBuf[ readcnt ] = c1 ;
		}
		c1 = findstr[ len - 1 ] ;
		c2 = TextBuf[ len - 1 ] ;
		if ( f_ignore ) {
			c1 = toupper( c1 ) ;
			c2 = toupper( c2 ) ;
		}
		if ( c1 == c2 ) {
			if ( compare( findstr, TextBuf, len, f_ignore ) ) {
				return TRUE ;
			}
			skip = 1 ;
		} else {
			skip = SkipArray[ c2 ] ;
		}
		if ( len > skip ) {
			memcpy( TextBuf, &TextBuf[ skip ], len - skip ) ;
		}
		readcnt -= skip ;
	}
}
