#!/usr/bin/python

# prints a random line from a text file

import sys, os.path, random

# It is ineffeicient to read the entire file just to count how many
# lines there are.  So, instead, we get the file size, and pick a
# random starting offset within the file.  We seek to that point.
# Since we prolly jumped into the middle of line with our random seek,
# we skip ahead to the first end-of-line character, which puts us at
# the start of the next line.  We read that line and use it as our
# random line.
#
# FIXME no error checking; relies on Python default exceptions

# get file name from command line
# FIXME dies if no argument specified
infile_name = sys.argv[1]

# get file size and a random offset
filesize = os.path.getsize(infile_name)
offset = random.randint(0, filesize)

# open file and seek into it
infile = open(infile_name)
infile.seek(offset, 0)

# skip to EOL
infile.readline()	# discard return value

# get our random line
# FIXME: will die if we already were at EOF (random chance)
line = infile.readline()
infile.close

# strip trailing newline
if (line[-1] == '\n'): line = line[:-1] 

print(line)
 
# EOF
