/* FIND.C - Find pattern from first argument in file from second argument */
/*	    Usage:  FIND -options pattern file				  */
/*	    Options: -x: find lines except those with pattern		  */
/*	   	     -n: print with line number				  */
/*	    Note: file can be an ambiguous file name			  */

/* 14 Feb 1987	Andreas Herrmann					  */


#include "stdio.h"

#define TRUE	1
#define FALSE	0
#define MAXLINE 1000

main(argc,argv)
int argc;
char *argv[];
{
	FILE	*fp;
	char	patstr[MAXLINE], *pattern;
	char	*fname;
	char	line[MAXLINE], upcline[MAXLINE], *s, *t;
	long	lineno = 0;
	int	except = FALSE, number = FALSE;
	int	ambig, newfile;
	int	i;

	char	*getffn(), *getnfn();	/* get first, next file name	*/
	int	s_index();		/* index of substring		*/


	while (--argc > 0 && (*++argv)[0] == '-')
		for (s = argv[0]+1; *s != '\0'; s++)
			switch (*s) {
			case 'X':
				except = TRUE;
				break;
			case 'N':
				number = TRUE;
				break;
			default:
				printf("Illegal option %c\n", *s);
				argc = 0;
				break;
			}
	if (argc != 2) {
		printf("Usage: FIND -x -n pattern file\n");
		exit(1);
	}
	pattern = strcpy(patstr,*argv);
	fname = *(argv+1);
	if ((ambig = index(fname,'*') || index(fname,'?'))) {
		fname = getffn(fname);
	}
	do {
		if ((fp = fopen(fname, "r")) == NULL)
			printf("Can't open file %s\n", fname);
		else {
			newfile = TRUE;
			while (getline(line,MAXLINE,fp) > 0) {
				lineno++;
				s=line, t=upcline; 
				while (*t++ = toupper(*s++)) ;
				if ((s_index(upcline,pattern)>=0) != except) {
					if (ambig && newfile) {
						printf("\n*** %s ***\n",fname);
						newfile = FALSE;
					}
					if (number)
						printf("%ld: ",lineno);
					printf("%s", line);
				}
			}
			fclose(fp);
		}
	} while ( ambig && (fname=getnfn()) != NULL);
}


int getline(s, lim, fp)		/* get line from file into s, return length */
char s[];
int lim;
FILE *fp;
{
	int c, i;

	for (i=0; i<lim-1 && (c=getc(fp))!=EOF && c!='\n'; ++i)
		s[i] = c;
	if (c == '\n') {
		s[i] = c;
		++i;
	}
	s[i] = '\0';
	return(i);
}

int s_index(s,t)	/* returns index of substring t in s, -1 if none */
char s[], t[];
{
	int i,j,k;

	for (i=0; s[i] != '\0'; i++) {
		for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
			;
		if (t[k] == '\0')
			return(i);
	}
	return(-1);
}
