
"""This makes an iterator that captures all the speech in
a one-utterance data file.
"""


import os.path
import gpkimgclass
import find_utterance_edges_n as Fue
import oxi_entity


PADDING = 0.0


class utterance(oxi_entity.entity):
	def __init__(self, utt_info, t0, tf):
		oxi_entity.entity.__init__(self, utt_info, t0, tf)


def try_pms(name):
	return (None, None)



def try_rms(fbase, suffix, colname):
	try:
		x = gpkimgclass.read('%s.%s' % (fbase, suffix))
	except IOError, x:
		print 'NO RMS ON ', x
		return (None, None)
	tstart, tend = Fue.find_trim_times_rms(x, colname, PADDING, xexp=0.3)
	return (tstart, tend)



def try_loud(fbase, suffix, colname):
	try:
		x = gpkimgclass.read('%s.%s' % (fbase, suffix))
	except IOError, x:
		print 'NO LOUDNESS ON ', x
		return (None, None)
	tstart, tend = Fue.find_trim_times_rms(x, colname, PADDING, xexp=1)
	return (tstart, tend)


class utterances(oxi_entity.entity_list):
	def __init__(self, uttrec, root=None):
		oxi_entity.entity_list.__init__(self)
		if root is None:
			nm = os.path.join( uttrec['d'], uttrec['f'])
		else:
			nm = os.path.join( root, uttrec['d'], uttrec['f'])
		
		tstart, tend = try_pms(nm)
		if tstart is None or tend is None:
			tstart, tend = try_rms(nm, suffix='rms.dat', colname='rms')
		if tstart is None or tend is None:
			tstart, tend = try_loud(nm, suffix='loud.dat', colname='loudness')

		if tstart is not None and tend is not None:
			self.append( utterance(uttrec, tstart, tend) )



class whole_file(oxi_entity.entity_list):
	def __init__(self, uttrec, root=None):
		oxi_entity.entity_list.__init__(self)
		if root is None:
			nm = os.path.join( uttrec['d'], uttrec['f'])
		else:
			nm = os.path.join( root, uttrec['d'], uttrec['f'])
		
		x = gpkimgclass.read('%s.loud.dat' % nm)
		tstart = x.start()
		tend = x.end()

		if tstart is not None and tend is not None:
			self.append( utterance(uttrec, tstart, tend) )


