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

#define LINES 5000
#define MAXLINE 1024

char *buffers[LINES];

void printlines(int numlines)
{  
  int i;
  int line;
  
  for (i= numlines-1; 0 < i; i--) {
    line= rand() % i;
    fputs(buffers[line], stdout);
    buffers[line]= buffers[i];
  }
}

int readfile(FILE *f)
{
  int bufcnt= 0;
  char oneline[MAXLINE];
  char *buf;
  
  while (! feof(f)) {
    fgets(oneline, MAXLINE, f);
    if (bufcnt >= LINES || ((buf= malloc(strlen(oneline)+1))== NULL)) {
      fprintf(stderr, "Out of memory.\n");
      exit(1);
    }
    strcpy(buf, oneline);
    buffers[bufcnt]= buf;
    bufcnt++;
  }
  return bufcnt;
}

int main(int argc, char *argv[])
{
  FILE *f;
  int  bufcnt;


  if (argc < 2) { 
    f= stdin;
    }
  else {
    if ((f= fopen(argv[1], "r"))== NULL) {
      perror(argv[1]);
      return 1;
    }
  }

  bufcnt= readfile(f);
  fclose(f);
  printf("%d lines read.\n", bufcnt-1);
  printlines(bufcnt);

  return 0;
}







