import random
import subprocess
import sys

# This script is used to open a selected number of randomly chosen images on 
# Mac OS X (although it could trivially be ported to Linux). The script 
# requires a index of all image files in order to efficiently choose images.

# To create index (in home directory):
# 
# find -L <PATH_TO_IMAGES> \( ! -name '.*' \) -type f > ~/index.txt

def main():
	
	if len(sys.argv) < 2:
		print 'ERROR: you must specify and index file'
		return -1

	# Grab the 
	try:		
		count = int(sys.argv[2])
	except (IndexError, ValueError):
		count = 10

	index_count = 0
	with open(sys.argv[1]) as index:
		# Count the number of lines in the index
		for line in index:
			index_count += 1

		print 'Index count: {:d}\n'.format(index_count)

		# Generate random numbers corresponding to randomly index into the 
		# index
		random_indexes = []
		for ctr in xrange(count):
			rand_idx = random.randint(1, index_count)
			random_indexes.append(rand_idx)

		# Iterate over the lines in the index again and grab lines that match 
		# the randomly chosen indexes
		iter_idx = 0
		index.seek(0, 0)
		path_list = []
		for line in index:
			iter_idx += 1
			if iter_idx in random_indexes:
				file_path = line.strip()
				print '{:d} - {:s}'.format(iter_idx, file_path)
				path_list.append('"{:s}"'.format(file_path))

		# Open the randomly chosen files
		# print ' '.join(path_list)
		subprocess.call('open {:s}'.format(' '.join(path_list)), shell=True)


if __name__ == '__main__':
	sys.exit(main())