/****************************************************************************
   Function: Find the Index of a given string in input string(s)
   Status:   27-feb-2008, wlm.
             10-sep-2010, wlm
   Remarks: Brian W. Kernighan, Dennis M. Ritchie,
              "The C Programming Language, second edition" chap 4.1
   Small modification made for DOS files

 ****************************************************************************/

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>

#define MAXLINE 1000   /* Maximum line length  */
#define LF      '\n'
#define CR      '\r'

int getline(char line[], int max);
int remove_lf_cr(char *_line);
int strindex(char s[], char t[]);

static char * mes[] = {
        "linux",
        "DOS"
    } ;
char pattern[MAXLINE - 1];

int main ()
{
    char line[MAXLINE];
    int found = 0;
    int type;

    printf("Geef de tekst die gezocht moet worden\n");
    getline(line,MAXLINE);                    // Leest de zoek string
    printf("Input string >%s< \n",line);
    
    type = remove_lf_cr(line);                // Cleaning of input regel en type file DOS og linux
    printf("Cleaned string >%s<, the type of file was %s\n",line,mes[type-1]);

    strcpy(pattern,line);
    printf("Toets nu de tekst in waarin de string >%s< gezocht wordt\nStop met ^Z\n\n",pattern);  
      
    while ( getline (line , MAXLINE ) > 0 )      // Regel voor regel inlezen
      if ( strindex(line, pattern) >= 0 ) {
        printf ("\nGevonden in regel: %s", line);
        found ++;
      }                  
#ifdef _WIN32
    printf("\n\n");
    system("PAUSE");
#endif

  return (found);
}
    
/*  get line into string s and return length */
int getline(char s[], int lim) 
{
   int c,i;
   i = 0;
   while (--lim > 0 && (c = getchar())!= EOF && c != LF)  
     s[i++] = c;  
     
   if ( c == LF )
     s[i++] = c;
   s[i] = '\0';
   return i;
}

/*  remove lf and/or cr from string to make it a real c-string */
int remove_lf_cr(char *_line) 
{
  int off,iret;

  if (_line == NULL)
    return 0;
  off = strlen(_line) - 1;
  if ( *(_line + off) == LF || *(_line + off) == CR) {
    iret = 1;                                            /* Unix/Linux file  */
    *(_line + off) = '\0';
    off--;
  }
  if ( *(_line + off) == LF || *(_line + off) == CR) {
    *(_line + off) = '\0';
    iret = 2;                                            /* DOS file         */
  }
  return iret;
}

int strindex(char s[], char 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 (k > 0 && t[k] == '\0' )
          return i;
    }
    return -1;
}
