/*********************************************************************/
/* Author: Suzanne Miller Dorney                                     */
/* File: lab4.c                                                      */
/* Class:  CPSC-202                                                  */
/* Project:  Lab 4                                                   */
/* Purpose:  This program implements a simple grep function.         */
/*********************************************************************/
#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 250

int main( int argc, char *argv[] )
{
  char  line[MAX_LENGTH+1];  /* line of text                    */
  FILE  *inputFile;          /* pointer to input file           */
  char  word[20];            /* word to be looked for in file   */ 
  int   found;               /* flag for when value is found    */
  int   lineIndex;           /* index into line string          */
  int   wordIndex;           /* index into word string          */

  /* make sure that 3 values were entered on the command line */
  if ( argc != 3 )
  {
    printf( "ERROR: improper usage of process\n" );
    printf( "Usage: a.out word file\n" );
    exit( 1 );
  }

  /* set the word to be looked for */
  strcpy( word, argv[1] ); 

  /* open up the data file */
  if ( !( inputFile = fopen( argv[2], "r" ) ) )
  {
    printf( "ERROR: could not open file %s\n", argv[2] );
    exit( 1 );
  }

  /* read in one line at a time and search for word */
  while ( fgets( line, MAX_LENGTH, inputFile ) != NULL )
  {
    found = 0;
    lineIndex = 0;
    wordIndex = 0;
    while ( !found && lineIndex > strlen( line ) )
    {
      if ( line[lineIndex] == word[wordIndex] )
        wordIndex++;
      else
        wordIndex = 0;
      lineIndex++; 

      if ( wordIndex == strlen( word ) )
      {
        found = 1;
        printf( "%s", line );
      }
    }
  }
 
  /* close input file */ 
  fclose( inputFile );
  return 0;
}
