/*
  Chris Siefert's random_l.c 3/3/99
  Reads a random line from a file.
  Email : cmsief@cs.wm.edu
  syntax : random_l <filename> <filelength>
*/

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "rng.h"

#define LINESIZE 1024

long Equilikely (long a, long b, double u) {
  return (a + (long) ((b - a + 1) * u));
}

int main (int argc, char* argv[]) {
  FILE* ifs;
  long num_lines,tgt_line,i;
  char* str;
  double u;
  
  /*Initializaiton*/
  if(argc!=3) { printf("syntax : random-l <filename> <num_lines>\n");exit(1);}

  num_lines=strtol(argv[2],(char**)NULL,10);
  PutSeed(-1);
  

  /*File Prep*/
  ifs=fopen(argv[1],"r");
  if(ifs==NULL) exit(1);
  str=(char*)malloc(LINESIZE*sizeof(char));

  u=Random();
  tgt_line=Equilikely(1,num_lines,u);
  
  for(i=0;i<tgt_line;i++) fgets(str,LINESIZE,ifs);
  if(strlen(str)!=0) {
    printf("%s",str);
  }/*end if*/
  close(ifs);
  return(0);  
}/*end main*/

