#define _GNU_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "searcher.h"

#include "sgrep_data.h"


int search_string(char *indata, sgrep_data* sdg) {
  /* Check if args null */
  
  if (indata == NULL || sdg->reg_exp == NULL)
    return SEARCHER_BAD_INDATA;
  

  if (sdg->case_sensitive==1) 
    {
      if (strstr(indata, sdg->reg_exp )==NULL) 
	{
	  return SEARCHER_OK_NO_MATCHES;
	}
    } 
  
  else 
    {
      if (strcasestr(indata, sdg->reg_exp )==NULL) 
	{
	  return SEARCHER_OK_NO_MATCHES;
	} 
    }
  

  if (sdg->line_number_mode == 1)
    fprintf(stdout, "%i: ", sdg->line_count + 1);
 
  if (sdg->count_mode == 0)
    fprintf(stdout, "%s\n", indata);
  
  return SEARCHER_OK_MATCHES;
}


int
search_file(sgrep_data *sgd)  {
  
  /* 
   * Check arguments (incl. reg_exp), NULL is bad
   */
  if (sgd->reg_exp == NULL || 
      sgd->in == NULL || 
      sgd == NULL)
    {
      return SEARCHER_BAD_INDATA; 
    }
  
  /*
   * based on getline manpage example.
   */
  ssize_t read;
  size_t len = 0;
  char * line_from_file = NULL;
  int ret;
  
 while ((read = getline(&line_from_file, &len, sgd->in)) != -1)
   { 
     if (line_from_file == NULL)
       {
	 return SEARCHER_OUT_OF_MEM; /* if getline fails to allocate the memory required */
       }
     
     ret = search_string(line_from_file, sgd);
     if (ret == SEARCHER_OK_MATCHES) 
       {
	 sgd->match_count++;
       }
     
     sgd->line_count++;
   }


 /*
  * after exiting while loop
  */
 if (sgd->count_mode == 1)
   {
     fprintf(stdout, "Number of matched lines: %i\n", sgd->match_count); 
   }

 free(line_from_file);
 free_data(sgd);
 
 if (sgd->match_count > 0)
   {
     return SEARCHER_OK_MATCHES;
   }
 else
   { 
     return SEARCHER_OK_NO_MATCHES;
   }
}


/* 
 * more can be added here eventually
 */
void 
free_data(sgrep_data *sgd)
{
  fclose(sgd->in);
} 


