#!/usr/bin/env python3
###########################################################################
##                                                                       ##
##                Centre for Speech Technology Research                  ##
##                   (Edinburgh University, UK) and                      ##
##                           Korin Richmond                              ##
##                         Copyright (c) 2004                            ##
##                         All Rights Reserved.                          ##
##                                                                       ##
##  Permission is hereby granted, free of charge, to use and distribute  ##
##  this software and its documentation without restriction, including   ##
##  without limitation the rights to use, copy, modify, merge, publish,  ##
##  distribute, sublicense, and/or sell copies of this work, and to      ##
##  permit persons to whom this work is furnished to do so, subject to   ##
##  the following conditions:                                            ##
##                                                                       ##
##   1. The code must retain the above copyright notice, this list of    ##
##      conditions and the following disclaimer.                         ##
##   2. Any modifications must be clearly marked as such.                ##
##   3. Original authors' names are not deleted.                         ##
##   4. The authors' names are not used to endorse or promote products   ##
##      derived from this software without specific prior written        ##
##      permission.                                                      ##
##                                                                       ##
##  EDINBURGH UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK DISCLAIM      ##
##  ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL           ##
##  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT       ##
##  SHALL EDINBURGH UNIVERSITY OR THE CONTRIBUTORS BE LIABLE FOR         ##
##  ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES        ##
##  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER      ##
##  IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,       ##
##  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       ##
##  THIS SOFTWARE.                                                       ##
##                                                                       ##
###########################################################################
##                                                                       ##
## Script to extract only the relevant time frames from a set of         ##
## coeffient tracks and dump them in a new set of tracks.  This          ##
## reduces the size of the data for distribution, and makes it faster    ##
## to load.                                                              ##
##                                                                       ##
## AUTHOR: KORIN RICHMOND                                                ##
###########################################################################

import sys
import os

try:
    estmoduledir = os.environ["EST_PYTHON"]
except KeyError:
    print("\n** environment variable EST_PYTHON is unset **\n")

sys.path.append( estmoduledir )

import est

# This function for calculating the join point time matches the
# definition in $FESTIVAL/src/modules/MultiSyn/DiphoneVoiceModule.cc
# This duplication is temporary, and will be removed soon when the API
# for diphone units is implemented
def join_point_time(item):
    if item.f_present( "cl_end" ):
        return item.F( "cl_end" )
    elif item.f_present( "dipth" ):
        return (0.75*item.F( "start" )) + (0.25*item.F("end"))
    else :
        return (item.F( "start" ) + item.F("end"))/2

coefdir = sys.argv[1]
outputdir = sys.argv[2]

if not os.path.isdir(coefdir) or not os.path.isdir(outputdir):
    print("Usage: {} coef_dir output_dir *.utt".format(argv[0]))
    exit(1)

utt = est.Utterance()
fulltrack = est.Track()
shorttrack = est.Track()

for file in sys.argv[3:]:
    
    utt.load(file)
    
    bname = os.path.splitext(os.path.basename(file))[0]

    print(bname)
    
    coefile = "%s/%s.coef" % (coefdir, bname)
    fulltrack.load( coefile )

    phones = utt.relation("Segment").items()
    times=est.FVector(len(phones))
    ind=0
    for ph in phones:
        times[ind] = join_point_time( ph )
        ind += 1
        
    fulltrack.copy_sub_track_out( shorttrack, times )

    outfile = '%s/%s.coef' % (outputdir, bname)

    shorttrack.save( outfile, 'est_binary' )
                                                                                                                              