#!/bin/bash

QUALITY=5	# default variable at around 128kbps
NO_ARGS=0
WAV_TMP=/tmp/tmp.$$.wav

if [ $# -eq "$NO_ARGS" ]
then
  echo "Usage    : `basename $0` -i input.wma -o output.mp3 [-t title] [-q quality]"
  echo "Alternate: `basename $0` -d directory [-q quality]"
  echo
  echo "The alternate usage of -d option will convert every wma to mp3"
  echo
  exit 1
fi

while getopts ":q:t:i:o:d:" Option
do
  case $Option in
    i ) WMA_FILE=$OPTARG;;
    o ) MP3_FILE=$OPTARG;;
    t ) TITLE=$OPTARG;;
    q ) QUALITY=$OPTARG;;
    d ) DIRECTORY=$OPTARG;;
  esac
done

shift $(($OPTIND - 1))

if [ -n "$DIRECTORY" ]
then
  cd "$DIRECTORY"
  for FILE in *.wma
  do
    if [ "$FILE" == "*.wma" ]
    then
      echo "Error: There is no wma files in the '$DIRECTORY'"
      echo
      exit 1
    fi
    TITLE=`echo $FILE | sed 's/\.wma$//'`
    mplayer "$TITLE.wma" -ao pcm -aofile "$WAV_TMP"
    lame -V $QUALITY -q 0 "$WAV_TMP" "$TITLE.mp3"
    rm -f "$WAV_TMP"
    id3tag --song="$TITLE" "$TITLE.mp3"
  done
  exit 0
fi

if [ "X$WMA_FILE" == "X" ]
then
  echo "You must specify an input wma file."
  exit 1
fi

if [ "X$MP3_FILE" == "X" ]
then
  echo "You must specify an ouput mp3 file."
  exit 1
fi

mplayer "$WMA_FILE" -ao pcm -aofile "$WAV_TMP"
lame -V $QUALITY -q 0 "$WAV_TMP" "$MP3_FILE"
rm -f "$WAV_TMP"

if [ "X$TITLE" != "X" ]
then
  id3tag --song="$TITLE" "$MP3_FILE"
fi
