#!/bin/sh
#
# output a random line from a text file
# args: a filename
# does: gets number of lines then a random fraction and use that
#
# note: this version has extensive comments
# note: students: you are not expected to be able to code something
#       like this until much later in the course.  I show this because
#       I mentioned in class that I could write a tool to pick a random
#	line from a file.  And here one is.
# hits: 2020-09-03 bmolay commented version
#

	#
	# if there is no file with name $1 then print usage message
	# test ! -f "$1"  means test if not (!) is a file (-f) "$1" first arg
	#
	if test ! -f "$1"
	then
		echo "usage: random_line filename" 1>&2
		exit 1
	fi

	#
	# count number of lines in the file by using wc -l
	# The variable NUM_LINES now stores the number of lines in the file
	#
	NUM_LINES=$(wc -l < "$1")		# count lines

	# now we build a fraction by taking the nanoseconds part of the
	# current time.  The date command will print out all or parts of
	# the current date and time.  the %N pattern asks for the nano-
	# seconds part of the current time.  This is a an integer 0.. 99999999
	# Then put a dot in front to make it into a fraction
	NANOSECS=.$(date '+%N')		# get a decimal number 0 to .999999
	
	# then use the bc calculator to do arithmetic of multiplying
	# the fraction times the number of lines and adding 0.5 for rounding
	# then use cut to trim off the decimal point and fractional part
	#
	PICKED=$(echo $NANOSECS \* $NUM_LINES + 0.5 | bc | cut -d. -f1)

	# on the off chance that the line number is .2  or something
	# then force the integer part to be 1.  There is a cleaner way to
	# do this
	if test "$PICKED" = ""
	then
		PICKED=1
	fi

	# then use sed to print the line number $PICKED
	sed -n -e "${PICKED}p" -e "${PICKED}q" $1
