/* tiiv_grep.c /
/* 180598 SJ */

/* alkeellinen grep */
/* ottaa syötteen tiedostosta joka voi
   olla tiivistetty */

#define GZIP ".gz"
#define COMPRESS ".Z"
#define PURAMUUTTUJA "ZCAT"
#define PURAOLETUS "gunzip -c"

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

int main(int argc, char *argv[])
{
  int putkesta = 0;
  FILE *syote = NULL;
  char avauskasky[50];
  char rivi[500];

  if (argc != 3) {
	  fprintf(stderr, "%s: usage %s text file\n",
			  argv[0], argv[0]);
	  exit(1);
  }

  if (strstr(argv[2], GZIP) ||
	  strstr(argv[2], COMPRESS)) {

	  putkesta = 1;

	  if (getenv(PURAMUUTTUJA))
		  sprintf(avauskasky, "%s %s",
				  getenv(PURAMUUTTUJA), argv[2]);

	  else
		  sprintf(avauskasky, "%s %s",
				  PURAOLETUS, argv[2]);

	  syote = popen(avauskasky, "r");
  }

  else
	  syote = fopen(argv[2], "r");

  if (! syote) {
	  fprintf(stderr, "%s: could not open file %s\n",
			  argv[0], argv[2]);
	  exit(2);
  }

  fgets(rivi, 500, syote);
  while(!feof(syote)) {
	  if (strstr(rivi, argv[1]))
		  fputs(rivi, stdout);
	  fgets(rivi, 500, syote);
  }

  if (putkesta)
	  pclose(syote);
  else
	  fclose(syote);

  exit(0);
}
