#!/bin/bash
# Shell wrapper for Open JTalk.

CMDNAME=`basename $0`

usage() {
  echo "Usage: $CMDNAME [-h|--help] [-i|--infile infile] \\"
  echo "          [-v|--voice nitech|mei] \\"
  echo "          [-t|--tone angry|bashful|happy|normal|sad] \\"
  echo "          [infile]"
  exit 1
}

DIC_DIR=@prefix@/lib/open_jtalk/dic

VOICE_ROOT=@prefix@/lib/open_jtalk/voice
VOICE_NITECH="$VOICE_ROOT/nitech"
VOICE_MEI_BASE="$VOICE_ROOT/mei_"
VOICE_TONE=normal
VOICE_MEI="$VOICE_MEI_BASE$VOICE_TONE"
VOICE_DIR="$VOICE_MEI"

INFILE=/dev/stdin

while test -n "$1"; do
    case "$1" in
        -h|--help)   usage ;;
        -i|--infile) INFILE="$2"; shift 2 ;;
        -v|--voice)  [ "$2" == "nitech" ] && VOICE_DIR="$VOICE_NITECH"; shift 2 ;;
        -t|--tone)   VOICE_DIR="$VOICE_MEI_BASE$2"; shift 2 ;;
        "")          INFILE=/dev/stdin ;;
        *)           INFILE="$1"; shift ;;
    esac
done

WAVFILE="/tmp/$CMDNAME-$$.wav"

while read LINE
do
    echo $LINE | @prefix@/bin/iconv -t EUC-JP | \
        @prefix@/bin/open_jtalk -s 48000 -p 240 -a 0.55 \
        -td $VOICE_DIR/tree-dur.inf \
        -tf $VOICE_DIR/tree-lf0.inf \
        -tm $VOICE_DIR/tree-mgc.inf \
        -tl $VOICE_DIR/tree-lpf.inf \
        -md $VOICE_DIR/dur.pdf \
        -mf $VOICE_DIR/lf0.pdf \
        -mm $VOICE_DIR/mgc.pdf \
        -ml $VOICE_DIR/lpf.pdf \
        -df $VOICE_DIR/lf0.win1 \
        -df $VOICE_DIR/lf0.win2 \
        -df $VOICE_DIR/lf0.win3 \
        -dm $VOICE_DIR/mgc.win1 \
        -dm $VOICE_DIR/mgc.win2 \
        -dm $VOICE_DIR/mgc.win3 \
        -dl $VOICE_DIR/lpf.win1 \
        -cf $VOICE_DIR/gv-lf0.pdf \
        -cm $VOICE_DIR/gv-mgc.pdf \
        -ef $VOICE_DIR/tree-gv-lf0.inf \
        -em $VOICE_DIR/tree-gv-mgc.inf \
        -k  $VOICE_DIR/gv-switch.inf \
        -x  $DIC_DIR \
        -ow $WAVFILE && afplay $WAVFILE
done < "$INFILE"

rm -f $WAVFILE
exit 0
