#!/bin/bash -e
[ $# -lt 1 ] && echo "$0 (wma[asf,wmv] file)" && exit 1
LANG=C
#if  [ -e ~/.profile ]; then
#	. ~/.profile
#else
#	. ~/.bash_profile
#fi
#unalias -a
starttime=`date +%s`
PLACE="`dirname "${1}"`"
TARGETFILE=${1##*/}  # 最後の/より後ろを取り出す
basename=${TARGETFILE%\.*}
TARGETEXT=${TARGETFILE##*\.}
MP3="${basename}.mp3"
test "${PLACE}" = "${TARGETFILE}" && PLACE=.
cd "${PLACE}"
PLACE="`pwd`"
set +e
title="`get-wma-info.pl -tags -TITLE "${TARGETFILE}"`"
testtitle="`echo "${title}"|tr -d '\000-\177'`"
if test -n "${testtitle}"; then
utf8title="`echo "${title}"|iconv -f UTF-16 -t UTF-8`"
else
utf8title=${title}
fi
utf8title="`echo ${utf8title}|tr -d '\n\r'`"
cp932title="`echo "${utf8title}"|iconv -f UTF-8 -t CP932`"
sample_rate="`get-wma-info.pl -info -sample_rate "${TARGETFILE}"`"
set -e
enc_rate=44.1
if test -n "${sample_rate}"; then
testrate="`echo ${sample_rate}|tr -cd '0-9'`"
if test "${testrate}" = "${sample_rate}"; then
enc_rate=`echo "scale=2;${sample_rate} / 1000"|bc`
fi
fi

exitproc(){ rm -rf "${TEMPFIFO}" "${TEMPFILE}";}

trap '
exitproc
exit 1
' 2 15

export TMPDIR="${PLACE}"
TEMPFILE="`mktemp`"
mplayer "${TARGETFILE}" -vo null -really-quiet -quiet \
-ao pcm:file=/dev/stdout | \
lame --nohist --resample ${enc_rate} -b 64 -c -o --add-id3v2 \
--tg 101 --tt "${cp932title}" - "${TEMPFILE}"
set +e
chmod go+r "${TEMPFILE}"
set -e
mv "${TEMPFILE}" "${MP3}"
endtime=`date +%s`
elapsed=`expr $endtime - $starttime`
MODTIME=`stat -c %y "${TARGETFILE}"|sed 's/\-/\//g'|cut -b1-19`
touch -t `date -d "$MODTIME $elapsed seconds" "+%Y%m%d%H%M.%S"` "${MP3}"
echo "Transcodeing: Done."
