# -*- coding: utf-8 -*-
#! python
from __future__ import with_statement

"""This script reads in the fiat file with data, finds all manually segmented files and creates symlinks
to mfcc and lab files for training data set for HTK. Can be run with mfcc.bash
Arguments: name_of_mfcc_file (no extension) metadata_file
The metadata file is in fiat format; each line describes one utterance.
"""

import os
import math
import errno

from gmisclib import die
from gmisclib import fiatio
from gmisclib import dictops
from gmisclib import gpkmisc
from gmisclib import g_encode
# from gmisclib import threaded_io
from gmisclib import nicknames
from gmisclib import wavesurfer_lab as WS

from select_paragraphs import misc

RESP = '/proj/aesop/proc'
MFCC = 'mfcc'
LAB = 'lab'
GRAM = 'gram'
# Drop English ASR sentences and also group!=1 in English
# This helps balance the corpus
Vfile = '/proj/aesop/select_paragraphs/List_of_phones.txt'
TONES = ('_0', '_1', '_2', '_3', '_4')
PHONE_LEN0 = 8
N_HEREST_PASSES = 20
PHONE_MAXLEN = 4000
PHONE_LEN1 = math.log(PHONE_MAXLEN/float(PHONE_LEN0))/N_HEREST_PASSES
MIN_PHONES_PER_UTTERANCE = 4



class NoSuchFileError(OSError):
	def __init__(self, *s):
		OSError.__init__(self, *s)



def force_symlink(file1, file2):
    """Make a symlink so that file2 will refer to file1.  If file2 exists,
    it will be removed and replaced with the symbolic link.
    @param file1: the referent.
    @param file2: the name of the link.
    @type file1: str
    @type file2: str
    """
    file1 = os.path.abspath(file1)
    if not os.path.exists(file1):
	raise NoSuchFileError, "File1=%s does not exist." % file1
    try:
        os.symlink(file1, file2)
    except OSError, e:
        if e.errno == errno.EEXIST:
            os.remove(file2)
            os.symlink(file1, file2)





def link_mfcc_from_elsewhere(inbase, outfile, dataid):
	force_symlink(os.path.join(inbase, dataid+'.mfcc'), outfile)

def link_wav_from_elsewhere(inbase, outfile):
	force_symlink(os.path.join(inbase, 'raw.wav'), outfile)




