#!/usr/bin/env python

import sys
import gpkimgclass
from gmisclib import die

import autosegment.remote as REM
import autosegment.misc as M
import autosegment.segment as SG
import autosegment.prefs as P
import autosegment.io as IO
import autosegment.as_client as ASC


if __name__ == '__main__':
	# try:
		# import psyco
		# psyco.full()
	# except ImportError:
		# pass
	arglist = sys.argv[1:]
	ll = []
	ilbl = [ ASC.label_c(0.0, '[') ]
	ilblhdr = {}
	labelfile = None
	wavfile = None
	fvdistf = None
	fvshowf = None
	mlf = None
	ChDir = None
	title = []
	Executable = REM.Executable
	while arglist and arglist[0].startswith('-'):
		arg = arglist.pop(0)
		if arg == '--':
			break
		elif arg == '-wav':
			wavfile = arglist.pop(0)
		elif arg in ['-fv', '-fvd']:
			fvdistf = arglist.pop(0)
		elif arg == '-fvs':
			fvshowf = arglist.pop(0)
		elif arg == '-deflbl':
			ll = arglist.pop(0).strip().split()
		elif arg == '-title':
			title.append(arglist.pop(0))
		elif arg == '-lbl':
			labelfile = arglist.pop(0)
			ilblhdr, ilbl = IO.read_labels(labelfile)
		elif arg == '-remote':
			Executable = REM.ExecMaker(arglist.pop(0))
			ChDir = REM.Corresponding_dir(arglist[0], arglist[1])
			arglist = arglist[2:]
		elif arg == '-mlf':
			mlf = arglist.pop(0)
		else:
			die.die('Unrecognized argument: %s' % arg)
	if wavfile is None:
		wavfile = ilblhdr.get('speech', None)
	if len(arglist) > 1:
		die.die('Usage: autosegment [flags] feature_vector.dat')
	if len(arglist) == 1 and fvshowf is None:
		fvshowf = arglist[0]
	if fvdistf is None and fvshowf is None:
		if labelfile is not None:
			fvdistf = IO.get_feature_vectors(labelfile, ilblhdr)
		elif wavfile is not None:
			fvdistf = IO.compute_feature_vectors(wavfile)
	if fvdistf is None and fvshowf is not None:
		fvdistf = fvshowf
	if fvshowf is None and fvdistf is not None:
		fvshowf = fvdistf
	assert fvdistf is not None
	assert fvshowf is not None
	title.append(fvshowf)
	fvdist = gpkimgclass.read(fvdistf)
	if fvshowf != fvdistf:
		fvshow = M.prepare_data(gpkimgclass.read(fvshowf))
	else:
		fvshow = M.prepare_data(fvdist)

	print "MYCLIENT"
	sc = ASC.myclient(fvdist, P.LABELWOBBLE, P.DUR_WOBBLE,
				executable=Executable,
				chdir=ChDir
				)
	print "SEGMENT"
	if wavfile is not None:
		SG.Player.set_wavefile(wavfile)
	SG.segment(fvshow, fvdist, ilbl, labelfile,
			fvshowf, arglist, sc,
			ll=ll, title=title, lblhdr=ilblhdr)
	sc.close()
