from gmisclib import xwaves_lab
from gmisclib import xwaves_errs


def _get_stars(dlist):
	"""Select out stars from a set of labels."""
	return [ x for x in dlist if x[1].startswith('*') ]



def empty_to_star(d):
	o = d[:]
	for (i, (t, lab)) in enumerate(d):
		assert isinstance(t, float)
		if lab == '':
			o[i] = (t, '*')
	return o


def add_backup_word_beginnings(wds, other):
	"""Pass through wds, but if there are beginnings marked
	in other (i.e. asterisks) that are not present in wds,
	add those extra beginning marks in.
	"""
	o = wds[:]
	for (t, label) in other:
		assert isinstance(t, float)
		if label.startswith('*'):
			o.append( (t, '*OTHER') )
	o.sort()
	oo = []
	for (i, (t, label)) in enumerate(o):
		assert isinstance(t, float)
		if label == '*OTHER' and i>0 and o[i-1][1].startswith('*'):
			pass
		elif label == '*OTHER' and i+1<len(o) and o[i+1][1].startswith('*'):
			pass
		elif label == '*OTHER':
			oo.append( (t, '*') )
		else:
			oo.append( (t, label) )
	return oo


def read_with_beginnings(nm, loose, suffix='wds'):
	try:
		bgph, bgpd = xwaves_lab.read('%s.bgp' % nm, loose)
	except xwaves_errs.NoSuchFileError:
		if loose:
			bgpd = []
		else:
			raise
	# print 'OPENING %s.%s' % (nm, suffix)
	markh, markd = xwaves_lab.read('%s.%s' % (nm, suffix), loose)
	markd = empty_to_star(markd)
	return add_backup_word_beginnings(markd, _get_stars(bgpd))

read_words_with_beginnings = read_with_beginnings
