# -*- coding: utf-8 -*-
import codecs, random, sys


def count_lines(filename):
	"""
	Counts no of lines in file.
	"""
	l = 0
	print "Counting no of lines in", filename
	for line in codecs.open(filename, 'r', 'utf'):
		l += 1
	print "Found %s lines" % l
	return l

def draw_sample(file_in, file_out, sample_size, no_of_lines = None):
	"""

	params:
	file_in - name of file with all the data
	file_out - name of file for writing random sample from file_in
	sample_size - no of lines to draw randomly from file_in
	no_of_lines - no of lines of file_in, if not provided, then this number will be calculated
	"""

	if no_of_lines == None:
		no_of_lines = count_lines(file_in)

	print "Drawing sentences indices.."
	hits = set([])
	while len(hits) < sample_size:
		hits.add( random.randint(0, no_of_lines) )

	out = codecs.open(file_out, 'w', 'utf8')

	print "Retrieving and saving sample to", file_out
	line_no = 0
	for line in codecs.open(file_in, 'r', 'utf'):
		if line_no in hits:
			out.write(line)
		line_no += 1

	out.close()

	print "All done."
		
if __name__ == '__main__':

	if len(sys.argv) not in [4,5]:
		print "Usage: python draw_random_lines.py file_in file_out sample_size [no_of_lines]"
	elif len(sys.argv) == 4:
		draw_sample(sys.argv[1], sys.argv[2], int(sys.argv[3]) )
	else:
		draw_sample(sys.argv[1], sys.argv[2], int(sys.argv[3]),int(sys.argv[4]) )

