#!/usr/bin/env python

"""This module reads the output of
fft_over_phrases.py to make it easy to use for
a classifier or something that needs a feature vector.
"""

import fiatio
import re
import die
import chunkio
import types


def read(f):
	if type(f) == types.StringType:
		f = open(f, 'r')
	_spc = re.compile(r'\s')
	header, data, comments = fiatio.read(f)

	for d in data:
		if 'dialect' in d:
			die.note('dialect', d['dialect'])
		if 'speaker' in d:
			die.note('speaker', d['speaker'])
		if 'd' in d and 'f' in d:
			die.note('name', (d['d'], d['f']) )

		if d.has_key('subtask') and d.has_key('utype'):
			die.die("Shouldn't be both subtask and utype")
		elif d.has_key('subtask'):
			sut = d['subtask']
		elif d.has_key('utype'):
			sut = d['utype']
		else:
			sut = 'X'
		sut = _spc.sub('_', sut)
	
		d['subtask:utype'] = sut
		if 'A' in d:
			d['A'] = chunkio.stringchunk(d['A']).read_NumArray()
		if 'TDW' in d:
			d['TDW'] = chunkio.stringchunk(d['TDW']).read_NumArray()
		if 'AUTOC' in d:
			d['AUTOC'] = chunkio.stringchunk(d['AUTOC']).read_NumArray()
	return (header, data, comments)


def equalize_length(d, maxlength=None):
	"""This takes the output of read() and makes all the 'A'
	arrays the same length.
	"""
	import Num
	import gpkmisc

	ll = [ tmp['A'].shape[0] for tmp in d ]
	l = int(gpkmisc.median(ll))
	if maxlength is not None and l > maxlength:
		l = maxlength

	for tmp in d:
		if tmp['A'].shape[0] > l:
			tmp['A'] = tmp['A'][:l]
		elif tmp['A'].shape[0] < l:
			o = Num.zeros((l,), Num.Float)
			o[:tmp['A'].shape[0]] = tmp['A']
			tmp['A'] = o
	return d
