#!/bin/sh

# mp3to 1.0.1 (2000-Dec-20-Wed)
# Adam M. Costello <amc@cs.berkeley.edu>

# mp3to <format> <infile> [ <outfile> ]
#
# Converts an MP3 file to another audio format.  If <outfile> is - or
# missing, stdout is used.  <format> may be au, wav, aiff, or any other
# format supported by sox.
#
# Depends on basename, mp3info (http://www.ibiblio.org/mp3info/),
# mpg123, and sox.

fail() {
  echo "$*" >&2
  exit 1
}

PATH=`dirname $0`:$PATH
export PATH

progname=`basename "$0"`

[ $# -ge 2 -a $# -le 3 ] || fail "usage:
$progname <format> <infile> [ <outfile> ]"

format=$1
infile=$2
outfile=${3:--}

rate=`mp3info -p %Q "$infile"` ||
  fail "$progname: could not get sample rate of input file $infile"

mode=`mp3info -p %o "$infile"` ||
  fail "$progname: could not get mode of input file $infile"

case "$mode" in
  mono) channels=1 ; mpg123mode=--mono ;;
     *) channels=2 ; mpg123mode=--stereo ;;
esac

mpg123 -q -s $mpg123mode "$infile" |
  sox -t raw -sw -r "$rate" -c $channels - -t "$format" "$outfile"
