#!/usr/bin/python

from tables import *
import sys

# Define a user record to characterize some kind of particles
class Particle(IsDescription):
    name      = StringCol(16, indexed = True)   # 16-character String

def write (start, stop):
	print "start, stop = %d, %d" % (start, stop)
	if start == 0:
		open_mode = "w"
	else:
		open_mode = "a"
	# Open a file in "w"rite mode
	h5file = openFile("test.h5", mode = open_mode, title = "Test file")

	if start == 0:
		# Create a new group under "/" (root)
		group = h5file.createGroup("/", 'detector', 'Detector information')
		# Create one table on it
		table = h5file.createTable(group, 'readout', Particle, "Readout example")
	else:
		table = h5file.root.detector.readout	
	# Fill the table with 10 particles
	particle = table.row
	for i in xrange(start, stop):
	    particle['name']  = 'Particle: %6d' % (i)
	    # Insert a new particle record
	    particle.append()
	# Close (and flush) the file
	if start > 0:
		table.reIndex()
	h5file.close()

def where (particle_name):
	h5file = openFile("test.h5", mode = "r", title = "Test file")
	index = h5file.root.detector.readout
	count = 0
	for row in index.where (index.cols.name == particle_name):
		count += 1
		print row ["name"] 

	print "indexed search found %d matches" % count

def seq (particle_name):
	h5file = openFile("test.h5", mode = "r", title = "Test file")
	index = h5file.root.detector.readout
	count = 0
	for row in index:#.where (index.cols.name == particle_name):
		if row ['name'] == particle_name:
			count += 1
			print row ["name"]
 
	print "sequential search found %d matches" % count

if __name__ == "__main__":
	if sys.argv [1] == "good" or sys.argv [1] == "bad":
		if sys.argv [1] == "good":
			start = 0
			stop = 40000
			end = 1
		else:
			if sys.argv [1] == "bad":
				start = 0
				stop = 1000
				end = 40

		for x in range (0, end):
			write (start, stop)
			start = stop
			stop += 1000
	else:
		particle_name = "Particle:  36001" # works only with "good" write
	#	particle_name = "Particle:  25001" # always works

		where (particle_name) 
		seq (particle_name)
