#!/bin/sh
# -*- coding: utf-8 -*-

import os
import sys
import shutil
import hashlib
from gmisclib import die
from gmisclib import gpkmisc
from gmisclib import MLF_file

sys.path.insert(0, 'lib')
import HTK_write as HW


#: If the resulting phoneme sequence is too short (shorter than MIN_PHONES),
#: it will *not* report an error, but it will simply not create an output file.
MIN_PHONES = 1
TGT = 'tmpM'


def write_1_column(ibmf, ofile):
	ofd = open(ofile, 'w')
	n = 0
	for (s, e, lbl) in ibmf.get3(''):
		ofd.write('%s\n' % lbl)
		n += 1
	return n >= MIN_PHONES


def write_3_columns(ibmf, ofile):
	ofd = open(ofile, 'w')
	for (s, e, lbl) in ibmf.get3(''):
		ofd.write('%.4f %.4f %s\n' % (s, e, HW.HTKiformat(lbl)))


def symlink(src, dst):
	if dst.startswith('/'):
		src = os.path.abspath(src)
	else:
		dst = os.path.normpath(dst)
		n = len(dst.split('/'))
		src0 = src
		src = '../' * (n-1) + src
		die.info("Making link: %s %s to %s" % (src0, src, dst))
	os.symlink(src, dst)


ifile, tj, name, tdata = sys.argv[1:]
olab = os.path.join(tj, 'lab', name) + '.lab'
sub = hashlib.md5(ifile).hexdigest()[:2]
gpkmisc.makedirs(os.path.join(TGT, sub))
shutil.rmtree(os.path.join(TGT, sub, name), ignore_errors=True)

imlf = MLF_file.block_MLF_file(ifile, preprocessor=lambda x: '')
if write_1_column(imlf, olab + '.tmp'):
	write_3_columns(imlf, os.path.join(TGT, sub, name) + '.lab')
	os.rename(olab + '.tmp', olab)
	symlink(os.path.join(tdata, 'mfcc', name) + '.mfcc',
			os.path.join(TGT, sub, name) + '.mfcc')
	symlink(os.path.join(tdata, 'wav', name) + '.wav',
			os.path.join(TGT, sub, name) + '.wav')
	symlink(os.path.join(tdata, 'gram', name) + '.grammar',
			os.path.join(TGT, sub, name) + '.grammar')
else:
	die.warn("MLF_to_lab.sh: Output file $olab.tmp would have been too short.")
	os.remove(olab + '.tmp')
