/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * browse.c
 * Copyright (C) 2023 drdev <gualtieri@ieee.org>
 * 
 * browse.c is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * browse.c is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
  //compile with gcc: gcc -o browse browse.c

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

#define extracts 10
#define num_sentences 2

int i,j;
int tot;
int fsize;
int pos;
time_t t;
char buffer[2000]="";
char sentence[2000]="";
char ch;
char fn1[64];
FILE *indata;

/* Prototypes */
char *strcpy(char *dest, const char *src);
int fgetc(FILE *stream);
char *strchr(const char *str, int c);
void srand(unsigned int seed);
void exit(int status);

/* end of prototypes */

int main(int argc, char *argv[])
{

if (argc<2)
{
printf("Usage: browse input.txt\n");
exit(1);
}

strcpy(fn1,argv[1]);
printf("\nInput file selected = %s\n",fn1);
printf("Extracts = %d  Sentences = %d\n", extracts, num_sentences);


if ((indata = fopen(fn1,"rb"))==NULL)
	{printf ("\nInput file cannot be opened.\n");
	exit (1);}
	
	//get file size
	fseek(indata, 0, SEEK_END);
    fsize = (int)ftell(indata);
    printf("File size = %d\n",fsize);
	//go back to file start
	fseek(indata, 0,SEEK_SET);
	
//Intialize random number generator
srand((unsigned) time(&t));

for (j=0;j<extracts;j++)
{
//seek random part of file
fseek(indata, 0,SEEK_SET);
pos = rand()%fsize;
fseek(indata, pos,SEEK_SET);

//Could check here for selection too close to end of file

printf("=============@ %d%%==============\n", (100*pos)/fsize);

for (i=0;i<2000;i++)
{
buffer[i] = fgetc(indata);
}

buffer[2000]='\0';

//find first period and define sentence to next period
strcpy(sentence, "");
strcpy(sentence, strchr(buffer, '.'));

tot =0;

for(i=0;i<2000;i++)
{
	if((sentence[i]==13)||(sentence[i]==10))
	{
		sentence[i] = ' ';
	}
	if((sentence[i]=='.')&&(tot==num_sentences))
	{
		sentence[1+i] = '\0';
		break;
	}
	if(sentence[i]=='.')
	{
		tot++;
	}
}

printf("%s\n",sentence);
}

fclose(indata);

printf("\n>>>Done<<<\n");

return (0);

}
