/* This program uses code from "Algorithms in C, Third Edition,"
 *               by Robert Sedgewick, Addison-Wesley, 1998.
 */

#include <stdio.h>
#include <stdlib.h>

#include "basic_strings.h"

/* Prints out the starting positions of all occurrences of P in A.
 * This could be modified to return a list of those positions, instead
 * of just printing them. 
 */
void string_search(char * P, char * A)
{
   int p_length = strlen1(P);
   int counter = 0;
   int i;
   for (i = 0; A[i] != 0; i++)
   {
      if (strncmp1(P, &(A[i]), p_length) == 0)
      {
         counter++;
         printf("occurence %d at position %d\n", counter, i);
      }
   }
   printf("\n%d occurrences found\n", counter);
}

// command line argument. A (presumably short) string P.
// input text: The user is asked to enter some (presumably long) text A.
// The program finds all occurrences of string P in A, and prints out
// the starting position of those occurrences.
int main(int argc, char ** argv)
{
   const int N = 10000;
   
   char * P = argv[1];
   
   char A[N];
   int i;
   for (i = 0; i < N-1; i++)
   {
      char t = getchar();
      if (t == EOF) break;
      A[i] = t;
   }
   A[i] = 0;

   string_search(P, A);   
}
