Man page wrapping corrected.
[abcde.git] / abcde
diff --git a/abcde b/abcde
index 3fc4cc5..af8c2e5 100755 (executable)
--- a/abcde
+++ b/abcde
@@ -1,17 +1,19 @@
-#!/bin/sh
+#!/bin/bash
 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
-# Copyright (c) 2003-2005 Jesus Climent <jesus.climent@hispalinux.es>
+# Copyright (c) 2003-2006 Jesus Climent <jesus.climent@hispalinux.es>
 # This code is hereby licensed for public consumption under either the
 # GNU GPL v2 or greater, or Larry Wall's Artistic license - your choice.
 #
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 #
 # Copyright for this work is to expire January 1, 2010, after which it
 # shall be public domain.
+#
+# $Id$
 
-VERSION="2.3.99"
+VERSION='2.3.99-$Revision$'
 
 usage ()
 {
@@ -20,7 +22,8 @@ echo "Usage: abcde [options] [tracks]"
 echo "Options:"
 echo "-1     Encode the whole CD in a single file"
 echo "-a <action1[,action2]...>"
-echo "       Actions to perform (cddb,read,normalize,encode,tag,move,replaygain,playlist,clean)"
+echo "       Actions to perform:"
+echo "       cddb,read,normalize,encode,tag,move,replaygain,playlist,clean"
 #echo "-A     Experimental actions (retag, transcode)"
 echo "-b     Enable batch normalization"
 #echo "-B     Disable batch replaygain (do file by file)"
@@ -32,7 +35,6 @@ echo "-d <device>"
 echo "       Specify CDROM device to grab (flac uses a single-track flac file)"
 echo "-D     Debugging mode (equivalent to sh -x abcde)"
 echo "-e     Erase encoded track information from status file"
-#echo "-E     Set the encoding information for the tags"
 echo "-f     Force operations that otherwise are considered harmful. Read \"man abcde\""
 echo "-g     Use \"lame --nogap\" for MP3 encoding. Disables low disk and pipes flags"
 echo "-h     This help information"
@@ -44,20 +46,23 @@ echo "-L     Use local CDDB storage directory"
 echo "-n     No lookup. Don't query CDDB, just create and use template"
 echo "-N     Noninteractive. Never prompt for anything"
 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
-echo "-M     Create a CUE file"
+echo "       WARNING: Deprecated. Use \"cue\" action"
+#echo "-M     Create a CUE file"
 echo "-o <type1[,type2]...>"
-echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc,wav). Defaults to vorbis"
+echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc,wav,m4a). Defaults to vorbis"
 echo "-p     Pad track numbers with 0's (if less than 10 tracks)"
 echo "-P     Use UNIX pipes to read+encode without wav files"
+echo "-q <level>"
+echo "       Set quality level (high,medium,low)"
 echo "-r <host1[,host2]...>"
 echo "       Also encode on these remote hosts"
-#echo "-R     Add replaygain values to the tag info (only for vorbis,flac,mp3)"
+echo "-R     Use local CDDB in recursive mode"
 echo "-s <field>"
 echo "       Show dielfs from the CDDB info (year,genre)"
 echo "-S <#> Set the CD speed"
 echo "-t <#> Start the track numbering at a given number"
 echo "-T <#> Same as -t but modifies tag numbering"
-echo "-u     Use UNICODE tags and comments"
+echo "-U     Do NOT use UNICODE (UTF8) tags and comments"
 echo "-v     Show version number and exit"
 echo "-V     Be a bit more verbose about what is happening behind the scenes"
 echo "-x     Eject CD after all tracks are read"
@@ -85,9 +90,9 @@ log ()
        BLURB="$1"
        shift
        case $BLURB in
-               error)   echo "[ERR] abcde: $@" >&2 ;;
-               warning) echo "[WAR] $@" >&2 ;;
-               info)    echo "[INF] $@" ;;
+               error)   echo "[ERROR] abcde: $@" >&2 ;;
+               warning) echo "[WARNING] $@" >&2 ;;
+               info)    echo "[INFO] $@" ;;
        esac
 }
 
@@ -105,7 +110,7 @@ f_seq_row ()
 f_seq_line ()
 {
        i=$1
-       if echo i | grep -q "[[:digit:]]" ; then
+       if echo $i | grep "[[:digit:]]" > /dev/null 2>&1 ; then
                while [ $i -ne `expr $2 + 1` ]
                do
                        printf $i" "
@@ -166,7 +171,7 @@ checkstatus ()
        fi
 }
 
-# chechwarnings [blurb]
+# checkwarnings [blurb]
 # Returns "0" if the blurb was found (meaning there was an warning),
 # returns 1 if it wasn't (yes this is a little backwards).
 # Does not print the blurb on stdout.
@@ -331,14 +336,82 @@ relpath ()
        echo $TO
 }
 
-# do_getcddbinfo
-# Finds an specific field from cddbinfo
-# 
-#      TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
-#      TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
-#      TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
+new_checkexec ()
+{
+       if [ ! "$@" = "" ]; then
+               # Cut off any command-line option we added in
+               X=$(echo $@ | cut -d' ' -f2)
+               if [ "$(which $X)" = "" ]; then
+                       return 1
+               elif [ ! -x $(which $X) ]; then
+                       return 2
+               fi
+       fi
+       return 0
+}
+
+checkexec ()
+{
+       if [ ! "$@" = "" ]; then
+               # Cut off any command-line option we added in
+               X=$(echo $@ | cut -d' ' -f2)
+               # Test for built-in abcde.function
+               [ "$X" != "${X#abcde.}" ] && type $X >/dev/null 2>&1 && return
+               if [ "$(which $X)" = "" ]; then
+                       log error "$X is not in your path." >&2
+                       log info  "Define the full path to the executable if it exists on your system." >&2
+                       if [ -e /etc/debian_release ] ; then
+                               case $X in
+                                       oggenc) MISSING_PACKAGE=vorbis-tools ;;
+                                       lame)   MISSING_PACKAGE=lame ;;
+                                       flac)   MISSING_PACKAGE=flac ;;
+                               esac
+                               log info "Hint: apt-get install $MISSING_PACKAGE" >&2
+                       exit 1
+               elif [ ! -x "$(which $X)" ]; then
+                       log error "$X is not executable." >&2
+                       exit 1
+               fi
+       fi
+}
+
+# diffentries <filename> <max_value> <entry1>,<entry2>
+# max_value: the range of entries goes from 1 to <max_value>
+diffentries ()
+{
+       FILENAME=$1
+       shift
+       local CDDBDIFFCHOICES=$1
+       shift
+       local CDDBDIFFCHOICE="$@"
+       if [ ! X"$DIFF" = "X" ]; then
+               PARSECHOICE1=$(echo $CDDBDIFFCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
+               PARSECHOICE2=$(echo $CDDBDIFFCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
+               if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBDIFFCHOICES ] || \
+                  [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBDIFFCHOICES ] || \
+                  [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
+                       echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBDIFFCHOICES" >&2
+               else
+                       # We parse the 2 choices to diff, store them in temporary files and diff them.
+                       for PARSECHOICE in $(echo $CDDBDIFFCHOICE | tr , \ ); do
+                               do_cddbparse "$ABCDETEMPDIR/$FILENAME.$PARSECHOICE" > "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE"
+                       done
+                       echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/$FILENAME.diff"
+                       $DIFF $DIFFOPTS "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/$FILENAME.diff"
+                       if [ $(cat "$ABCDETEMPDIR/$FILENAME.diff" | wc -l) -ge 24 ]; then
+                               page "$ABCDETEMPDIR/$FILENAME.diff"
+                       else
+                               cat "$ABCDETEMPDIR/$FILENAME.diff" >&2
+                       fi
+               fi
+       else
+               echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBDIFFCHOICES." >&2
+       fi
+}
 
-do_getcddbinfo()
+# getcddbinfo
+# Finds an specific field from cddbinfo
+getcddbinfo()
 {
        case $1 in
        TRACKNAME1)
@@ -350,9 +423,9 @@ do_getcddbinfo()
        esac
 }
 
-# do_gettracknum
+# gettracknum
 # Get the track number we are going to use for different actions
-do_gettracknum()
+gettracknum()
 {
        if [ -n "$STARTTRACKNUMBER" ] ; then
                # Get the trackpadding from the current track
@@ -363,46 +436,116 @@ do_gettracknum()
        fi
 }
 
+# makeids
+#
+# Calculate cddb disc ids without requiring specialized helper programs.
+# largely copied from cd-discid and musicbrainz examples.  some of the steps
+# don't make sense, but they're necessary to match the ids generated by other
+# programs.
+#
+## FIXME ## Right now, we get 2 frames more than with cue2discid ??
+# data@petit:~$ sh /tmp/cue2discid /home/data/tmp/flac/01.Roisin_Murphy--Ruby_Blue.flac
+# processing offsetimes 00:00:00 04:47:10 08:20:37 11:46:46 17:45:36 21:41:57 27:32:21 32:03:73 35:39:28 38:27:33 43:50:38 44:42:34
+# 980b4b0c 12 150 21685 37687 53146 80061 97782 124071 144448 160603 173208 197438 201334 2895
+# data@petit:~$ metaflac --export-cuesheet-to=- /home/data/tmp/flac/01.Roisin_Murphy--Ruby_Blue.flac| python /home/data/sources/abcde/trunk/examples/cue2discid
+# 980b4b0c 12 150 21685 37687 53146 80061 97782 124071 144448 160603 173208 197438 201334 2893
+#
+# Variables: OFFSETS, TRACKS, LEADOUT, [LEADIN]
+makeids ()
+{
+       if [ X"$LEADOUT" = "X" ]; then
+               log warning "Error trying to calculate disc ids without lead-out information."
+               exit 1
+       fi
+
+       # default to a two second lead-in
+       IDMAGICNUM=150
+       LEADIN=${LEADIN:=150}
+
+       # number of cdframes per second
+       CDFRAMES=75
+
+       # reset cddb checksum for cddb disc-id calululation
+       CDDBCKSUM=0
+
+       COOKEDOFFSETS=""
+       for OFFSET in $(echo $OFFSETS)
+       do
+               COOKEDOFFSETS="${COOKEDOFFSETS} $(($OFFSET + $LEADIN))"
+
+               OFFSETTIME=$(( ($OFFSET + $LEADIN) / $CDFRAMES  ))
+               while [ $OFFSETTIME -gt 0 ]; do
+                       CDDBCKSUM=$(($CDDBCKSUM + $OFFSETTIME % 10))
+                       OFFSETTIME=$(($OFFSETTIME / 10))
+               done
+
+       done
+
+       COOKEDOFFSETS="${COOKEDOFFSETS:1}"  # eat the leading space
+
+       PREGAP=$(($(echo $OFFSETS | cut -f1 -d' ')))
+       TOTALTIME=$(( (($LEADOUT + $LEADIN + $PREGAP) / $CDFRAMES) - (($LEADIN + $PREGAP) / $CDFRAMES)))
+
+       printf -v HEXSUM "%08lx" $(( ($CDDBCKSUM % 0xff) << 24 | $TOTALTIME << 8 | $TRACKS))
+       TRACKINFO="${HEXSUM} $((TRACKS)) ${COOKEDOFFSETS} $((($LEADOUT + $LEADIN + $IDMAGICNUM) / $CDFRAMES))"
+}
+
 do_replaygain()
 {
        if checkstatus replaygain; then :; else
                run_command "" echo "Adding replygain information..."
-               for OUTPUT in $( echo $OUTPUTTYPE | tr , \ )
+               for TMPOUTPUT in $( echo $OUTPUTTYPE | tr , \ )
                do
-                       case $OUTPUT in
+                       case $TMPOUTPUT in
                                vorbis|ogg)
                                        OUTPUT=$OGGOUTPUTCONTAINER
                                        ;;
                                flac)
                                        OUTPUT=$FLACOUTPUTCONTAINER
                                        ;;
+                               *)
+                                       OUTPUT=$TMPOUTPUT
+                                       ;;
                        esac
                        OUTPUTFILES=""
+                       REPLAYINDEX=0
                        for UTRACKNUM in $TRACKQUEUE
                        do
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                               do_getcddbinfo TRACKNAME
+                               getcddbinfo TRACKNAME
                                splitvarious
                                TRACKFILE="$(mungefilename "$TRACKNAME")"
                                ARTISTFILE="$(mungefilename "$TRACKARTIST")"
                                ALBUMFILE="$(mungefilename "$DALBUM")"
-                               do_gettracknum
-                               if [ "$VARIOUSARTISTS" = "y" ]; then
-                                       OUTPUTFILE="$(eval echo $VAOUTPUTFORMAT)"
-                               else
-                                       OUTPUTFILE="$(eval echo $OUTPUTFORMAT)"
+                               gettracknum
+                               if [ "$ONETRACK" = "y" ]; then 
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
+                                       fi
+                               else    
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
+                                       fi
                                fi
-                               OUTPUTFILES="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT $OUTPUTFILES"
+                               OUTPUTFILES[$REPLAYINDEX]="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
+                               (( REPLAYINDEX = $REPLAYINDEX + 1 ))
                        done
                        case "$OUTPUT" in
                                flac)
-                                       run_command replaygain-flac $METAFLAC --add-replay-gain "$OUTPUTFILES"
+                                       run_command replaygain-flac nice $ENCNICE $METAFLAC --add-replay-gain "${OUTPUTFILES[@]}"
                                        ;;
                                vorbis|ogg)
-                                       run_command replaygain-vorbis $VORBISGAIN --album "$OUTPUTFILES"
+                                       run_command replaygain-vorbis nice $ENCNICE $VORBISGAIN --album "${OUTPUTFILES[@]}"
                                        ;;
                                mp3)
-                                       run_command replaygain-mp3 $MP3GAIN -a "$OUTPUTFILES"
+                                       run_command replaygain-mp3 nice $ENCNICE $MP3GAIN -a "${OUTPUTFILES[@]}"
+                                       ;;
+                               mpc)
+                                       run_command replaygain-mpc nice $ENCNICE $MPPGAIN --auto "${OUTPUTFILES[@]}"
                                        ;;
                                *);;
                        esac
@@ -639,7 +782,7 @@ do_tag ()
        # If we want to start the tracks with a given number, we need to modify the
        # TRACKNUM value before evaluation
        if [ -n "$STARTTRACKNUMBERTAG" ] ; then
-               do_gettracknum
+               gettracknum
        fi
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
@@ -651,18 +794,32 @@ do_tag ()
                        case "$ID3SYNTAX" in
                                id3);;
                                eyed3)
-                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
-                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS --commen=::"$COMMENTOUTPUT" \
-                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -Y "$CDYEAR" \
-                                               -G "$GENREID" -n "${TRACKNUM:-$1}" "${TRACKNUM:+-N $TRACKS}" \
-                                               "${ENCODING:+--set-encoding=$ENCODING}"
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot
+                                       # happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $TAGGER $TAGGEROPTS \
+                                               --comment=::"$COMMENTOUTPUT" -A "$DALBUM" \
+                                               -a "$TRACKARTIST" -t "$TRACKNAME" -Y "$CDYEAR" \
+                                               -G "$GENREID" -n "${TRACKNUM:-$1}" \
+                                               "${TRACKNUM:+-N $TRACKS}" \
+                                               "${ENCODING:+--set-encoding=$ENCODING}" \
+                                               "$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       ;;
+                               # FIXME # Still not activated...
+                               id3ed)
+                                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
+                                               $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
+                                               -a "$DALBUM" -n "$TRACKARTIST" -s "$TRACKNAME" \
+                                               -y "$CDYEAR" -g "$GENREID" -k "${TRACKNUM:-$1}" \
                                                "$ABCDETEMPDIR/track$1.$OUTPUT"
                                        ;;
                                *)
-                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
-                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
-                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
-                                               -g "$GENREID" -T "${TRACKNUM:-$1/$TRACKS}" \
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot
+                                       # happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
+                                               $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
+                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" \
+                                               -y "$CDYEAR" -g "$GENREID" \
+                                               -T "${TRACKNUM:-$1/$TRACKS}" \
                                                "$ABCDETEMPDIR/track$1.$OUTPUT"
                                        ;;
                        esac
@@ -675,7 +832,9 @@ do_tag ()
                                                mv "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
                                        fi
                                        (
-                                       # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
+                                       # These are from
+                                       # http://www.xiph.org/ogg/vorbis/doc/v-comment.html
+
                                        echo ARTIST="$TRACKARTIST"
                                        echo ALBUM="$DALBUM"
                                        echo TITLE="$TRACKNAME"
@@ -693,9 +852,11 @@ do_tag ()
                                                        *)   echo COMMENT="$COMMENTOUTPUT";;
                                                esac    
                                        fi
-                                       ) | run_command tagtrack-$OUTPUT-$1 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
+                                       ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
+                                               $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
                                                "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
-                                       # Doublecheck that the commented file was created successfully before wiping the original
+                                       # Doublecheck that the commented file was created
+                                       # successfully before wiping the original
                                        if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" ]; then
                                                rm -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
                                        else
@@ -723,7 +884,7 @@ do_tag ()
                                        *)   echo COMMENT="$COMMENTOUTPUT";;
                                esac    
                        fi
-                       ) | run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                       ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
                        ;;
                spx)
                        run_command tagtrack-$OUTPUT-$1 true
@@ -731,6 +892,9 @@ do_tag ()
                mpc)
                        run_command tagtrack-$OUTPUT-$1 true
                        ;;
+               m4a)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
                wav)
                        run_command tagtrack-$OUTPUT-$1 true
                        ;;
@@ -747,14 +911,15 @@ do_tag ()
 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
 do_nogap_encode ()
 {
-       # The commands here don't go through run_command because they're never supposed to be silenced
+       # The commands here don't go through run_command because they're never
+       # supposed to be silenced
        echo "Encoding gapless MP3 tracks: $TRACKQUEUE"
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
                case "$OUTPUT" in
                mp3)
                        case "$MP3ENCODERSYNTAX" in
-                       lame)
+                       lame|toolame)
                                (
                                cd "$ABCDETEMPDIR"
                                TRACKFILES=
@@ -786,8 +951,8 @@ do_nogap_encode ()
                        fi
                fi
        fi
-       # Other encoders fall through to normal encoding as the tracks
-       # have not been entered in the status file.
+       # Other encoders fall through to normal encoding as the tracks have not
+       # been entered in the status file.
 }
 
 # do_encode [tracknumber] [hostname]
@@ -813,6 +978,9 @@ do_encode ()
                        mpc)
                                TEMPARG="PIPE_$MPPENCODER"
                                ;;
+                       m4a)
+                               TEMPARG="PIPE_$MPPENCODER"
+                               ;;
                esac
                IN="$( eval echo "\$$TEMPARG" )"
        else
@@ -837,40 +1005,47 @@ do_encode ()
        fi
        # We need IN to proceed, if we are not using pipes.
        if [ -s "$IN" -o X"$USEPIPES" = "Xy" ] ; then
-               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+               for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
                do
-                       if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
-                               continue
-                       fi
-                       case "$OUTPUT" in
+                       case "$TMPOUTPUT" in
                                vorbis|ogg)
-                                       OUT="$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
+                                       OUTPUT=$OGGOUTPUTCONTAINER
                                        ;;
                                flac)
-                                       OUT="$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                                       OUTPUT=$FLACOUTPUTCONTAINER
                                        ;;
                                *)
-                                       OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       OUTPUT=$TMPOUTPUT
                                        ;;
                        esac
+                       OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
+                       if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
+                               continue
+                       fi
                        if [ X"$USEPIPES" = "Xy" ]; then
                                RUN_COMMAND=""
                                # We need a way to store the creation of the files when using PIPES
                                RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
+                               # When pipping it does not make sense to have a higher nice for
+                               # reading than for encoding, since it will be hold by the
+                               # encoding process. Setting an effective nice, to calm down a
+                               # bit the reading process.
+                               EFFECTIVE_NICE=$READNICE
                        else
                                run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
                                RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
+                               EFFECTIVE_NICE=$ENCNICE
                        fi
                        case "$OUTPUT" in
                        mp3)
                                case "$2" in
                                %local*%)
                                        case "$MP3ENCODERSYNTAX" in
-                                       lame|gogo) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
-                                       bladeenc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
-                                       l3enc|xingmp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
+                                       lame|toolame|gogo) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
+                                       bladeenc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
+                                       l3enc|xingmp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
                                        # FIXME # Relates to the previous FIXME since it might need the "-if" removed.
-                                       mp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
+                                       mp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
                                        esac
                                        ;;
                                *)
@@ -882,8 +1057,8 @@ do_encode ()
                                case "$2" in
                                %local*%)
                                        case "$OGGENCODERSYNTAX" in
-                                       vorbize) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
-                                       oggenc) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
+                                       vorbize) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
+                                       oggenc) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
                                        esac
                                        ;;
                                *)
@@ -895,7 +1070,7 @@ do_encode ()
                                case "$2" in
                                %local*%)
                                        case "$FLACENCODERSYNTAX" in
-                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
+                                       flac) $RUN_COMMAND nice $EFFECTIVE_NICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
                                        esac
                                                ;;
                                        *)
@@ -915,9 +1090,9 @@ do_encode ()
                                fi
                                # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
                                if [ ! "$DOTAG" = "y" ]; then
-                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
                                else
-                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
                                fi
                                ;;
                        mpc)    
@@ -927,7 +1102,16 @@ do_encode ()
                                # errors, so I have not tried it myself.
                                ## FIXME ## Needs some cleanup to determine if an empty tag sent
                                ## FIXME ## to the encoder ends up empty.
-                               $RUN_COMMAND nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
+                               $RUN_COMMAND nice $EFFECTIVE_NICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
+                               ;;
+                       m4a)
+                               # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
+                               if [ ! "$DOTAG" = "y" ]; then
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" -o "$OUT" "$IN"
+                                       
+                               else
+                                       $RUN_COMMAND nice $ENCNICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
+                               fi
                                ;;
                        wav)
                                # In case of wav output we need nothing. Just keep the wavs.
@@ -1040,7 +1224,7 @@ do_single_gain ()
 
 # do_batch_gain
 # variables used:
-# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
+# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPPGAIN, MPPGAINOPTS
 # FIXME #
 do_batch_gain ()
 {
@@ -1122,8 +1306,12 @@ do_normalize ()
 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
 do_move ()
 {
-       for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+       for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
+               # For now, set OUTPUT as TMPOUTPUT, and then change it once we have
+               # defined the OUTPUTFILE:
+               OUTPUT="$TMPOUTPUT"
+
                # Create ALBUMFILE, ARTISTFILE, TRACKFILE
                # Munge filenames as follows:
                # ' ' -> '_'
@@ -1135,26 +1323,38 @@ do_move ()
                ARTISTFILE="$(mungefilename "$TRACKARTIST")"
                TRACKFILE="$(mungefilename "$TRACKNAME")"
                GENRE="$(mungegenre "$GENRE")"
-               YEAR="$(echo $CDYEAR)"
-               # If we want to start the tracks with a given number, we need to modify the
-               # TRACKNUM value before evaluation
-               do_gettracknum
-               # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
-               # TRACKFILE, and TRACKNUM.
-               if [ "$VARIOUSARTISTS" = "y" ]; then
-                       OUTPUTFILE="$(eval echo "$VAOUTPUTFORMAT")"
-               else
-                       OUTPUTFILE="$(eval echo "$OUTPUTFORMAT")"
-               fi
+               YEAR=${CDYEAR:-$CDYEAR}
+               # If we want to start the tracks with a given number, we need to modify
+               # the TRACKNUM value before evaluation
+               gettracknum
+               # Supported variables for OUTPUTFORMAT are GENRE, YEAR, ALBUMFILE,
+               # ARTISTFILE, TRACKFILE, and TRACKNUM.
+               if [ "$ONETRACK" = "y" ]; then 
+                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                               OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
+                       else
+                               OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
+                       fi
+               else    
+                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                               OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
+                       else
+                               OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
+                       fi
+               fi
                if checkerrors "tagtrack-$OUTPUT-$1"; then :; else
-                       # Once we know the specific output was successful, we can change the OUTPUT to the value containing the container
-                       case $OUTPUT in
+                       # Once we know the specific output was successful, we can change
+                       # the OUTPUT to the value containing the container
+                       case $TMPOUTPUT in
                                vorbis|ogg)
                                        OUTPUT=$OGGOUTPUTCONTAINER
                                        ;;
                                flac)
                                        OUTPUT=$FLACOUTPUTCONTAINER
                                        ;;
+                               *)
+                                       OUTPUT=$TMPOUTPUT
+                                       ;;
                        esac
                        # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
                        OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
@@ -1224,29 +1424,32 @@ do_move ()
 # VARIOUSARTISTS, OUTPUTDIR
 do_playlist ()
 {
-       for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+       for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
-               case $OUTPUT in
+               case $TMPOUTPUT in
                        vorbis|ogg)
                                OUTPUT=$OGGOUTPUTCONTAINER
                                ;;
                        flac)
                                OUTPUT=$FLACOUTPUTCONTAINER
                                ;;
+                       *)
+                               OUTPUT=$TMPOUTPUT
+                               ;;
                esac
                # Create a playlist file for the playlist data to go into.
                # We used to wipe it out if it existed. Now we request permision if interactive.
                for LASTTRACK in $TRACKQUEUE; do :; done
                ALBUMFILE="$(mungefilename "$DALBUM")"
                ARTISTFILE="$(mungefilename "$DARTIST")"
-               GENRE=$(mungegenre "$GENRE")
+               GENRE="$(mungegenre "$GENRE")"
                YEAR=${CDYEAR:-$CDYEAR}
                if [ "$VARIOUSARTISTS" = "y" ] ; then
-                       PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
+                       PLAYLISTFILE="$(eval echo "$VAPLAYLISTFORMAT")"
                else
-                       PLAYLISTFILE=$(eval echo $PLAYLISTFORMAT)
+                       PLAYLISTFILE="$(eval echo "$PLAYLISTFORMAT")"
                fi
-               FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
+               FINALPLAYLISTDIR="$(dirname "$OUTPUTDIR/$PLAYLISTFILE")"
                mkdir -p "$FINALPLAYLISTDIR"
                if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
                        echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
@@ -1255,6 +1458,7 @@ do_playlist ()
                                        read ERASEPLAYLIST
                                        case $ERASEPLAYLIST in
                                                e|E|a|A|k|K) DONE=y ;;
+                                               "") ERASEPLAYLIST=e ; DONE=y ;;
                                                *) ;;
                                        esac
                                done
@@ -1274,19 +1478,18 @@ do_playlist ()
                        do
                                # Shares some code with do_move since the filenames have to match
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                               #TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
-                               do_getcddbinfo TRACKNAME
+                               getcddbinfo TRACKNAME
                                splitvarious
                                TRACKFILE="$(mungefilename "$TRACKNAME")"
                                ARTISTFILE="$(mungefilename "$TRACKARTIST")"
                                ALBUMFILE="$(mungefilename "$DALBUM")"
                                # If we want to start the tracks with a given number, we need to modify the
                                # TRACKNUM value before evaluation
-                               do_gettracknum
+                               gettracknum
                                if [ "$VARIOUSARTISTS" = "y" ]; then
-                                       OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
+                                       OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT\"")"
                                else
-                                       OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
+                                       OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT\"")"
                                fi
                                if [ "$VARIOUSARTISTS" = "y" ]; then
                                        if [ "$VAPLAYLISTDATAPREFIX" ] ; then
@@ -1314,6 +1517,156 @@ do_playlist ()
        done
 }
 
+# abcde.cue2discid
+# This function reads a cuefile on stdin and writes an extended
+# cddb query on stdout.  Any PREGAP for track 1 is properly
+# handled, although cue files embedded in FLAC files do not
+# appear to properly store the PREGAP setting. :(
+abcde.cue2discid () {
+
+       cddb_sum () {
+               val=$1
+               ret=0
+               while [ $val -gt 0 ] ; do
+                       ret=$(( $ret + ( $val % 10) ))
+                       val=$(( $val / 10 ))
+               done
+               echo $ret
+       }
+
+       msf2lba () {
+               OIFS="$IFS"
+               IFS=":"
+               set -- $1
+               IFS="$OIFS"
+               local first second third
+               first=$(expr ${1} + 0 )
+               second=$(expr ${2} + 0 )
+               third=$(expr ${3} + 0 )
+
+               echo $(( ((($first * 60) + $second) * 75) + $third ))
+       }
+
+       OFFSET=150
+       PREGAP=0
+       LEADOUT=0
+       LEADIN=88200
+       i=0
+       N=0
+       
+       while read line ; do
+               set -- $line
+               case "$1" in
+               TRACK)  i=$(( i + 1 ))
+                       ;;
+               INDEX)  if [ "$2" -eq 1 ] ; then
+                               LBA=$(msf2lba $3)
+                               START=$(( $LBA + $PREGAP + $OFFSET ))
+                               eval TRACK$i=$START
+                               X=$(cddb_sum $(( $START / 75 )) )
+                               N=$(( $N + $X ))
+                       fi
+                       ;;
+               PREGAP) PREGAP=$(msf2lba $2)
+                       ;;
+               REM)    case "$2" in 
+                       FLAC__lead-out)
+                               LEADOUT=$(( $4 / 588 ))
+                               ;;
+                       FLAC__lead-in)
+                               LEADIN=$(( $3 / 588 ))
+                               ;;
+                       esac
+                       ;;
+               esac
+               
+       done
+       
+       TRACKS=$i
+       LEADOUT=$(( $LEADOUT + $LEADIN ))
+
+       LENGTH=$(( $LEADOUT/75 - $TRACK1/75 ))
+       DISCID=$(( ( $N % 255 ) * 2**24 | $LENGTH * 2**8 | $TRACKS ))
+       printf "%08x %i" $DISCID $TRACKS
+       
+       j=1
+       while [ $j -le $TRACKS ] ; do
+               eval echo -n "\" \$TRACK$j\""
+               j=$((j+1))
+       done
+       echo " $(( $LEADOUT / 75 ))"
+}
+
+# abcde.mkcue
+# abcde.mkcue [--wholedisk]
+# This creates a cuefile directly from the extended discid information
+# The --wholedisk option controls whether we're ripping data from the
+# start of track one or from the start of the disk (usually, but not
+# always the same thing!)
+#
+# Track one leadin/pregap (if any) handeling:
+# --wholedisk specified:
+#   TRACK 01 AUDIO
+#     INDEX 00 00:00:00
+#     INDEX 01 <pregap value>
+#   Remaining track index values unchanged from disc TOC
+#
+# --wholedisk not specified
+#   TRACK 01 AUDIO
+#     PREGAP <pregap value>
+#     INDEX 01 00:00:00
+#   Remaining track index values offset by <pregap value>
+#
+# Variables used:
+# TRACKINFO
+abcde.mkcue () {
+
+       echomsf () {
+               printf "$1%02i:%02i:%02i\n" $(($2/4500)) $((($2/75)%60)) $(($2%75))
+       } 
+
+       local MODE DISCID TRACKS
+       local i OFFSET LBA 
+
+
+    if [ "$1" = --wholedisc ] ; then
+        MODE=INDEX
+    else
+        MODE=PREGAP
+    fi
+
+    set -- $TRACKINFO
+
+    DISCID=$1
+    TRACKS=$2
+    shift 2
+
+    echo REM DISCID $DISCID
+    echo FILE \"dummy.wav\" WAVE
+
+    if [ $1 -ne 150 ] && [ $MODE = "PREGAP"] ; then
+        OFFSET=$1
+    else
+        OFFSET=150
+    fi
+
+    i=1
+    while [ $i -le "$TRACKS" ] ; do
+        LBA=$(( $1 - $OFFSET ))
+        printf "  TRACK %02i AUDIO\n" $i
+        if [ $i -eq 1 -a $1 -ne 150 ] ; then
+            if [ $MODE = PREGAP ] ; then
+                echomsf "    PREGAP " $(($OFFSET-150))
+            else
+                echo    "    INDEX 00 00:00:00"
+            fi
+               fi
+        echomsf "    INDEX 01 " $LBA
+               i=$(($i+1))
+        shift
+    done
+}
+
 # do_discid
 # This essentially the start of things
 do_discid ()
@@ -1329,11 +1682,64 @@ do_discid ()
                if [ "$OSFLAVOUR" = "OSX" ]; then
                        disktool -u ${CDROM#/dev/}
                fi
-               if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
-                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
-               else
-                       TRACKINFO=$($CDDISCID $CDROM)
-               fi
+               case "$CDROMREADERSYNTAX" in
+                       flac)
+                               if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" > /dev/null 2>&1 ; then
+                                       case "$CUE2DISCID" in
+                                               # FIXME # right now we have 2 cue2discid internal
+                                               # implementations: builtin and abcde.cue2discid. Test
+                                               # both of them and decide which one we want to use.
+                                               builtin)
+                                                       #vecho "Using builtin cue2discid implementation..."
+                                                       CUESHEET="$(metaflac $METAFLACOPTS --export-cuesheet-to=- "$CDROM")"
+
+                                                       #TRACKS=$(echo $CUESHEET | egrep "TRACK \+[[:digit:]]\+ \+AUDIO" |wc -l)
+                                                       #TRACKS=0
+                                                       OFFSETTIMES=( $(echo "$CUESHEET" | sed -n -e's/\ *INDEX 01\ \+//p' ) )
+                                                       TRACKS=${#OFFSETTIMES[@]}
+                                                       unset OFFSETS
+                                                       #echo "processing offsetimes ${OFFSETTIMES[@]}"
+                                                       for OFFSETTIME in ${OFFSETTIMES[@]}; do
+                                                               OFFSETS="$OFFSETS $(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))"
+                                                               #OFFSETS[${#OFFSETS[*]}]=$(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))
+                                                       done
+
+                                                       LEADOUT=$(( $(echo "$CUESHEET" | grep lead-out | get_last) / 44100 * 75 ))
+                                                       LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) / 44100 * 75 ))
+                                                       makeids
+                                               ;;
+                                               *)
+                                                       #vecho "Using external python cue2discid implementation..."
+                                                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" | $CUE2DISCID)
+                                               ;;
+                                       esac
+                               else
+                                       log error "the input flac file does not contain a cuesheet."
+                                       exit 1
+                               fi
+                               ;;
+#                      cdparanoia|debug)
+#                              CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
+#                              RET=$?
+#                              if [ ! "$RET" = "0" ];then
+#                                      log warning "something went wrong while querying the CD... Maybe a DATA CD?"
+#                              fi
+#
+#                              TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
+#                              CDPARANOIAAUDIOTRACKS="$TRACKS"
+#
+#                              LEADOUT="$(echo "$CDPARANOIAOUTPUT" | egrep -o '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
+#                              OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')" 
+#                              makeids
+#                              ;;
+                       *)
+                               case "$CDDBMETHOD" in
+                                       cddb) TRACKINFO=$($CDDISCID "$CDROM") ;;
+                                       # FIXME # musicbrainz needs a cleanup
+                                       musicbrainz) TRACKINFO=$($MUSICBRAINZ -c "$CDROM" ) ;;
+                               esac
+                               ;;
+               esac
                # Make sure there's a CD in there by checking cd-discid's return code
                if [ ! "$?" = "0" ]; then
                        if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
@@ -1350,6 +1756,7 @@ do_discid ()
                        disktool -m ${CDROM#/dev/}
                fi
                WEHAVEACD=y
+               DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
        else
                TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
        fi
@@ -1368,12 +1775,12 @@ do_discid ()
 
        ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
        if [ -z "$TRACKQUEUE" ]; then
-               if [ ! "$STRIPDATATRACKS" = "y" ]; then
+               if [ ! "$STRIPDATATRACKS" = "n" ]; then
                        case "$CDROMREADERSYNTAX" in
                                cdparanoia|debug)
                                        if [ "$WEHAVEACD" = "y" ]; then
                                                vecho "Querying the CD for audio tracks..."
-                                               CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
+                                               CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
                                                RET=$?
                                                if [ ! "$RET" = "0" ];then
                                                        log warning "something went wrong while querying the CD... Maybe a DATA CD?"
@@ -1381,6 +1788,11 @@ do_discid ()
                                                TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
                                                CDPARANOIAAUDIOTRACKS="$TRACKS"
                                        else
+                                               # Previous versions of abcde would store the tracks on a file, instead of the status record.
+                                               if [ -f "$ABCDETEMPDIR/cdparanoia-audio-tracks" ]; then
+                                                       echo cdparanoia-audio-tracks=$( cat "$ABCDETEMPDIR/cdparanoia-audio-tracks" ) >> "$ABCDETEMPDIR/status"
+                                                       rm -f "$ABCDETEMPDIR/cdparanoia-audio-tracks"
+                                               fi
                                                if [ -f "$ABCDETEMPDIR/status" ] && TRACKS=$(checkstatus cdparanoia-audio-tracks); then :; else
                                                        TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
                                                fi
@@ -1467,7 +1879,7 @@ do_discid ()
                                exit 1
                        fi
                        rm -rf "$ABCDETEMPDIR" || exit 1
-                       mkdir "$ABCDETEMPDIR"
+                       mkdir -p "$ABCDETEMPDIR"
                        if [ "$?" -gt "0" ]; then
                                # Directory already exists or could not be created
                                echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
@@ -1489,25 +1901,38 @@ do_discid ()
                fi
        else
                # We are starting from scratch
-               mkdir "$ABCDETEMPDIR"
+               mkdir -p "$ABCDETEMPDIR"
                if [ "$?" -gt "0" ]; then
                        # Directory already exists or could not be created
                        echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
                        exit 1
                fi
                cat /dev/null > "$ABCDETEMPDIR/status"
+               # Store the abcde version in the status file.
+               echo "abcde-version=$VERSION" >> "$ABCDETEMPDIR/status"
        fi
-       if [ X"$MAKECUEFILE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
+       if [ X"$DOCUE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
                if checkstatus cuefile > /dev/null 2>&1 ; then :; else
                        CUEFILE=cue-$(echo "$TRACKINFO" | cut -f1 -d' ').txt
                        vecho "Creating cue file..."
-                       if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
-                               echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
-                       else
-                               log warning "reading the CUE sheet with mkcue is still considered experimental"
-                               log warning "and there was a problem with the CD reading. abcde will continue,"
-                               log warning "but consider reporting the problem to the abcde author"
-                       fi
+                       case $CDROMREADERSYNTAX in
+                               flac)
+                                       if $METAFLAC --export-cuesheet-to=- "$CDROM" > "$ABCDETEMPDIR/$CUEFILE"; then 
+                                               echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
+                                       else
+                                               log warning "the input flac file does not contain a cuesheet."
+                                       fi
+                                       ;;
+                               *)
+                                       if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
+                                               echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
+                                       else
+                                               log warning "reading the CUE sheet is still considered experimental"
+                                               log warning "and there was a problem with the CD reading. abcde will continue,"
+                                               log warning "but consider reporting the problem to the abcde author"
+                                       fi
+                                       ;;
+                       esac
                fi
        fi
        # If we got the CDPARANOIA status and it is not recorded, save it now
@@ -1519,6 +1944,9 @@ do_discid ()
        
        # Create the discid file
        echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
+       if checkstatus cddbmethod > /dev/null 2>&1 ; then :; else
+               echo "cddbmethod=$CDDBMETHOD" >> "$ABCDETEMPDIR/status"
+       fi
 }
 
 # do_cleancue
@@ -1535,16 +1963,24 @@ do_cleancue()
                        n=1
                        echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
                        echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
+                       # Set IFS to <newline> to prevent read from swallowing spaces and tabs
+                       OIFS="$IFS"
+                       IFS='
+'
                        cat "$CUEFILE_IN" | while read line
                        do
-                               if echo "$line" | grep -q "INDEX"
-                               then
+                               if echo "$line" | grep "INDEX 01" > /dev/null 2>&1 ; then
+# FIXME # Possible patch: remove the line above, uncomment the 2 lines below.
+#                              echo "$line" >> "$CUEFILE_OUT"
+#                              if echo "$line" | grep "^[[:space:]]*TRACK" > /dev/null 2>&1 ; then
                                        eval track="\$TRACK$n"
                                        n=$(expr $n + 1)
-                                       echo "TITLE \"$track\"" >> "$CUEFILE_OUT"
+                                       echo "    TITLE \"$track\"" >> "$CUEFILE_OUT"
                                fi
+# FIXME # If the lines above are uncommented, remove the line below.
                                echo "$line" >> "$CUEFILE_OUT"
                        done
+                       IFS="$OIFS"
                        mv "$CUEFILE_OUT" "$CUEFILE_IN"
                        echo "cleancuefile" >> "$ABCDETEMPDIR/status"
                fi
@@ -1588,45 +2024,142 @@ do_localcddb ()
 {
        if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
        
-               CDDBLOCALSUCCESS="n"
+               CDDBLOCALSTATUS="notfound"
                CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
-               CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
                USELOCALRESP="y"
-               
-               # If the user has selected to check a local CDDB repo, we proceed with it
-               if [ -r "${CDDBLOCALFILE}" ]; then
-                       # List out disc title/author and contents
-                       do_cddbparse "${CDDBLOCALFILE}"
-                       echo -n "Locally cached CDDB entry found, use it? [y/n] (y): "
-                       if [ "$INTERACTIVE" = "y" ]; then
-                               read USELOCALRESP
-                               while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
-                                       echo -n 'Invalid selection. Please answer "y" or "n": '
-                                       read USELOCALRESP
-                               done
-                               [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
-                       else
-                               echo "y" >&2
-                       fi
-                       if [ "$USELOCALRESP" = "y" ]; then
-                               #echo "Using local copy of CDDB data"
-                               echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
-                               cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
-                               echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
-                               echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
-                               do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
-                               echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
-                               CDDBLOCALSUCCESS="y"
+
+               if [ "$CDDBLOCALRECURSIVE" = "y" ]; then
+                       CDDBLOCALRESULTS="$(find ${CDDBLOCALDIR} -name "${CDDBDISCID}" -type f 2> /dev/null)"
+                       if [ ! "${CDDBLOCALRESULTS}" = "" ]; then
+                               if   (( $(echo "${CDDBLOCALRESULTS}" | wc -l) == 1 )); then
+                                       CDDBLOCALFILE="${CDDBLOCALRESULTS}"
+                                       CDDBLOCALMATCH=single
+                               elif (( $(echo "${CDDBLOCALRESULTS}" | wc -l) > 1 )); then
+                                       CDDBLOCALMATCH=multiple
+                               fi
                        else
-                               #echo "Not using local copy of CDDB data"
-                               CDDBLOCALSUCCESS="n"
+                               CDDBLOCALMATCH=none
                        fi
+               elif [ "$CDDBLOCALMATCH" = "none" ] && [ -r "${CDDBLOCALDIR}/${CDDBDISCID}" ]; then
+                       CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
+                       CDDBLOCALMATCH=single
                else
-                       CDDBLOCALSUCCESS="n"
+                       CDDBLOCALMATCH=none
                fi
+               
+               # If the user has selected to check a local CDDB repo, we proceed with it
+               case $CDDBLOCALMATCH in
+                       multiple)
+                               echo "Processing multiple matching CDDB entries..." > "$ABCDETEMPDIR/cddblocalchoices"
+                               X=0
+                               echo "$CDDBLOCALRESULTS" | while read RESULT ; do
+                                       X=$(expr $X + 1)
+                                       # List out disc title/author and contents
+                                       CDDBLOCALREAD="$ABCDETEMPDIR/cddblocalread.$X"
+                                       cat "$RESULT" > "${CDDBLOCALREAD}"
+                                       {       
+                                               echo -n "#$X: "
+                                               do_cddbparse "${CDDBLOCALREAD}" 
+                                               echo ""
+                                               ##FIXME## QUICK HACK !!!!
+                                               if [ ! "$INTERACTIVE" = "y" ]; then break ; fi
+                                       } >> "$ABCDETEMPDIR/cddblocalchoices"
+                               done
+                               if [ $(cat "$ABCDETEMPDIR/cddblocalchoices" | wc -l) -ge 24 ] && [ "$INTERACTIVE" = "y" ]; then
+                                       page "$ABCDETEMPDIR/cddblocalchoices"
+                               else
+                                       # It's all going to fit in one page, cat it
+                                       cat "$ABCDETEMPDIR/cddblocalchoices" >&2
+                               fi
+                               CDDBLOCALCHOICES=$( echo "$CDDBLOCALRESULTS" | wc -l )
+                               # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
+                               CDDBLOCALCHOICENUM=-1
+                               if [ "$INTERACTIVE" = "y" ]; then
+                                       while [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; do
+                                               echo -n "Locally cached CDDB entries found. Which one would you like to use (0 for none)? [0-$CDDBLOCALCHOICES]: " >&2
+                                               read CDDBLOCALCHOICE
+                                               [ x"$CDDBLOCALCHOICE" = "x" ] && CDDBLOCALCHOICE="1"
+                                               # FIXME # Introduce diff's
+                                               if echo $CDDBLOCALCHOICE | egrep "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
+                                               elif echo $CDDBLOCALCHOICE | egrep "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       # Make sure we get a valid choice
+                                                       CDDBLOCALCHOICENUM=$(echo $CDDBLOCALCHOICE | xargs printf %d 2>/dev/null)
+                                                       if [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; then
+                                                               echo "Invalid selection. Please choose a number between 0 and $CDDBLOCALCHOICES." >&2
+                                                       fi
+                                               fi
+                                       done
+                               else
+                                       ### FIXME ###
+                                       #echo "Selected ..."
+                                       CDDBLOCALRESP=y
+                                       CDDBLOCALCHOICENUM=1
+                               fi
+                               if [ ! "$CDDBLOCALCHOICENUM" = "0" ]; then
+                                       #echo "Using local copy of CDDB data"
+                                       echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
+                                       cat "$ABCDETEMPDIR/cddblocalread.$CDDBLOCALCHOICENUM" >> "$ABCDETEMPDIR/cddbread.1"
+                                       echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
+                                       echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
+                                       do_cddbparse "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbchoices"
+                                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                                       CDDBLOCALSTATUS="found"
+                               else
+                                       #echo "Not using local copy of CDDB data"
+                                       CDDBLOCALSTATUS="notfound"
+                               fi
+                               ;;
+                       single)
+                               # List out disc title/author and contents
+                               do_cddbparse "${CDDBLOCALFILE}"
+                               #if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
+                               #       echo -n "Embedded cuesheet entry found, use it? [y/n] (y): " >&2
+                               #else
+                                       echo -n "Locally cached CDDB entry found, use it? [y/n] (y): " >&2
+                               #fi
+                               if [ "$INTERACTIVE" = "y" ]; then
+                                       read USELOCALRESP
+                                       while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
+                                               echo -n 'Invalid selection. Please answer "y" or "n": ' >&2
+                                               read USELOCALRESP
+                                       done
+                                       [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
+                               else
+                                       echo "y" >&2
+                               fi
+                               if [ "$USELOCALRESP" = "y" ]; then
+                                       #echo "Using local copy of CDDB data"
+                                       echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
+                                       cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
+                                       echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
+                                       echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
+                                       do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
+                                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                                       CDDBLOCALSTATUS="single"
+                               else
+                                       #echo "Not using local copy of CDDB data"
+                                       CDDBLOCALSTATUS="notfound"
+                               fi
+                               ;;
+                       none)
+                               CDDBLOCALSTATUS="notfound"
+                               ;;
+               esac
        fi
 }
 
+do_musicbrainzstat ()
+{
+       :
+}
+
+do_musicbrainz ()
+{
+# Use MBE_TOCGetCDIndexId on a perl query
+       :
+}
+
 # do_cddbstat
 do_cddbstat ()
 {
@@ -1672,7 +2205,7 @@ do_cddbquery ()
                if [ "$CDDBAVAIL" = "n" ]; then
                        ERRORCODE=no_query
                        echo 503 > "$ABCDETEMPDIR/cddbquery"
-               # The default CDDBLOCALSUCCESS is "n"
+               # The default CDDBLOCALSTATUS is "notfound"
                # This part will be triggered if the user CDDB repo does not 
                # contain the entry, or if we are not trying to use the repo.
                else
@@ -1811,7 +2344,7 @@ do_cddbedit ()
        if [ "$INTERACTIVE" = "y" ]; then
                # We should show the CDDB results both when we are not using the local CDDB repo
                # or when we are using it but we could not find a proper match
-               if [ "$CDDBUSELOCAL" = "y" ] && [ ! "$CDDBLOCALSUCCESS" = "y" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
+               if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSTATUS" = "notfound" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
                        # Display the $ABCDETEMPDIR/cddbchoices file created above
                        # Pick a pager so that if the tracks overflow the screen the user can still view everything
                        if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
@@ -1819,6 +2352,13 @@ do_cddbedit ()
                                CHOICE=$(checkstatus cddb-choice)
                                if [ -n "$CHOICE" ] ; then
                                        case $CDDBCHOICES in
+                                               -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep "^$" > /dev/null 2>&1 ; then
+                                                               log error "CDDB query failed!" 
+                                                               exit 1
+                                                       else
+                                                               cat "$ABCDETEMPDIR/cddbchoices"
+                                                       fi
+                                                       ;;
                                                1) cat "$ABCDETEMPDIR/cddbchoices" ;;
                                                *)
                                                echo "Selected: #$CHOICE"
@@ -1842,16 +2382,15 @@ do_cddbedit ()
                                                echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
                                                read CDDBCHOICE
                                                [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
-                                               if echo $CDDBCHOICE | egrep -q "[[:digit:]]+,[[:digit:]]+" ; then
+                                               if echo $CDDBCHOICE | egrep "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
                                                        if [ ! X"$DIFF" = "X" ]; then
-                                                               PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1)
-                                                               PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2)
+                                                               PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
+                                                               PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
                                                                if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBCHOICES ] || \
                                                                   [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBCHOICES ] || \
                                                                   [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
                                                                        echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBCHOICES" >&2
                                                                else
-
                                                                        # We parse the 2 choices to diff, store them in temporary files and diff them.
                                                                        for PARSECHOICE in $(echo $CDDBCHOICE | tr , \ ); do
                                                                                do_cddbparse "$ABCDETEMPDIR/cddbread.$PARSECHOICE" > "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE"
@@ -1867,10 +2406,10 @@ do_cddbedit ()
                                                        else
                                                                echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
                                                        fi
-                                               else
+                                               elif echo $CDDBCHOICE | egrep "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       # Make sure we get a valid choice
+                                                       CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
                                                        if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
-                                                               # Make sure we get a valid choice
-                                                               CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
                                                                echo "Invalid selection. Please choose a number between 0 and $CDDBCHOICES." >&2
                                                        fi
                                                fi
@@ -1918,7 +2457,7 @@ do_cddbedit ()
                        # Show the choice if we are not using the locally stored one
                        # or when the local search failed to find a match.
                        PREVIOUSCHOICE=$(checkstatus cddb-choice)
-                       if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSUCCESS" = "n" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
+                       if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSTATUS" = "notfound" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
                                #if [ "$PREVIOUSCHOICE" ]; then
                                        cat "$ABCDETEMPDIR/cddbchoices"
                                #fi
@@ -2108,10 +2647,12 @@ do_cddbedit ()
                        fi
                fi
        fi
-       # Make sure the cache directory exists
-       mkdir -p $CDDBLOCALDIR
+       ### FIXME ###
+       # User CDDBLOCALPOLICY to find out if we store the file or not...
        # Cache edited CDDB entry in the user's cddb dir
-       if [ "$CDDBCOPYLOCAL" = "y" ] || [ "$COPYCDDBLOCAL" = "Y" ]; then
+       if [ "$CDDBCOPYLOCAL" = "y" ]; then
+               # Make sure the cache directory exists
+               mkdir -p $CDDBLOCALDIR
                cat "$CDDBDATA" | tail -n $(expr $(cat "$CDDBDATA" | wc -l ) - 1 ) > ${CDDBLOCALDIR}/$(echo "$TRACKINFO" | cut -d' ' -f1)
        fi
 
@@ -2131,15 +2672,17 @@ do_cdread ()
                # the user said
                # We need the first and last track for cdda2wav
                FIRSTTRACK=$2
-               LASTTRACK=$3
+               LASTTRACK=$(expr $3 + 0)
                UTRACKNUM=$FIRSTTRACK
                case "$CDROMREADERSYNTAX" in
-                       ### FIXME ### How are we calculating the tracks in flac mode?
                        flac) READTRACKNUMS="$FIRSTTRACK.1-$(($LASTTRACK + 1)).0" ;;
-                       cdparanoia) READTRACKNUMS="$FIRSTTRACK-$LASTTRACK" ;;
-                       cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTRACK" ;;
-                       *) log error "$CDROMREADERSYNTAX does not support ONETRACK mode"
-                          exit 1 ;;
+                       cdparanoia) 
+                               #XX FIXME XX
+                               # Add a variable to check if tracks are provided in command line and if not, use "0-" to rip the tracks
+                               READTRACKNUMS="$FIRSTTRACK-$LASTTRACK" ;;
+                       cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTTRACK" ;;
+                       *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
+                               exit 1 ;;
                esac
        else
                UTRACKNUM=$1
@@ -2170,8 +2713,7 @@ do_cdread ()
                echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK as one track ..." >&2
        else
                if [ -r "$CDDBDATA" ]; then
-                       #TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
                else
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
@@ -2181,9 +2723,11 @@ do_cdread ()
                ### FIXME ### use an exception for flac, since it uses -o
                ### FIXME ### Shall we just use -o $FILEARG ??
                flac)
-                       nice $READNICE $FLAC -d --cue=${READTRACKNUMS:-$UTRACKNUM.1-$(($UTRACKNUM + 1)).0} "$FILEARG" "$CDROM" ;;
+                       # Avoid problems wit math expressions by unpadding the given UTRACKNUM
+                       STRIPTRACKNUM=$(expr $UTRACKNUM + 0)
+                       nice $READNICE $FLAC -d -f --cue=${READTRACKNUMS:-$STRIPTRACKNUM.1-$(($STRIPTRACKNUM + 1)).0} "$FILEARG" "$CDROM" ;;
                cdparanoia) 
-                       nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
+                       nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
                cdda2wav)
                        if [ "$OSFLAVOUR" = "OSX" ] ; then
                                # Hei, we have to unmount the device before running anything like cdda2wav in OSX
@@ -2203,7 +2747,7 @@ do_cdread ()
                        ;;
                ## FIXME ## We have an exception for dagrab, since it uses -f
                ## FIXME ## Shall we just use -f $FILEARG ??
-               dagrab) nice $READNICE $CDROMREADER -d $CDROM -v $UTRACKNUM "$FILEARG" $REDIR
+               dagrab) nice $READNICE $CDROMREADER -d "$CDROM" -v $UTRACKNUM "$FILEARG" $REDIR
                        ;;
                cddafs)
                        # Find the track's mounted path
@@ -2216,7 +2760,7 @@ do_cdread ()
                        else
                                false
                        fi ;;
-               debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
+               debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
                        ;;
        esac
        RETURN=$?
@@ -2239,9 +2783,9 @@ do_cdread ()
                        echo readencodetrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
                else
                        echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
-                       if [ "$1" = "onetrack" ]; then
-                               echo onetrack >> "$ABCDETEMPDIR/status"
-                       fi
+               fi
+               if [ "$1" = "onetrack" ]; then
+                       echo onetrack >> "$ABCDETEMPDIR/status"
                fi
        fi
 }
@@ -2264,7 +2808,7 @@ vecho ()
 {
 if [ x"$EXTRAVERBOSE" != "x" ]; then
        case $1 in
-               warning) log warning "$@" ;;
+               warning) shift ; log warning "$@" ;;
                *) echo "$@" ;;
        esac
 fi
@@ -2276,7 +2820,7 @@ fi
 decho ()
 {
 if [ x"$DEBUG" != "x" ]; then
-       if echo $1 | grep -q "^\[" ; then
+       if echo $1 | grep "^\[" > /dev/null 2>&1 ; then
                DEBUGECHO=$(echo "$@" | tr -d '[]')
                echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
        else
@@ -2320,11 +2864,17 @@ post_read ()
 ###############################################################################
 
 # Builtin defaults
+
+# CDDB
+# Defaults to FreeDB, but a python musicbrainz can be used
+CDDBMETHOD=cddb
 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
 CDDBSUBMIT=freedb-submit@freedb.org
-CDDBPROTO=5
+CDDBPROTO=6
 HELLOINFO="$(whoami)@$(hostname)"
 CDDBCOPYLOCAL="n"
+CDDBLOCALPOLICY="always"
+CDDBLOCALRECURSIVE="y"
 CDDBLOCALDIR="$HOME/.cddb"
 CDDBUSELOCAL="n"
 
@@ -2332,7 +2882,7 @@ CDDBUSELOCAL="n"
 SHOWCDDBFIELDS="year,genre"
 
 INTERACTIVE=y
-CDROMREADERSYNTAX=cdparanoia
+#CDROMREADERSYNTAX=cdparanoia
 ENCODERSYNTAX=default
 
 MP3ENCODERSYNTAX=default
@@ -2340,6 +2890,7 @@ OGGENCODERSYNTAX=default
 FLACENCODERSYNTAX=default
 SPEEXENCODERSYNTAX=default
 MPPENCODERSYNTAX=default
+AACENCODERSYNTAX=default
 NORMALIZERSYNTAX=default
 CUEREADERSYNTAX=default
 
@@ -2365,6 +2916,7 @@ KEEPWAVS=n
 PADTRACKS=n
 NOGAP=n
 BATCHNORM=n
+NOCDDBQUERY=n
 
 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
 # i.e. CDROMID="1,0,0"
@@ -2391,6 +2943,8 @@ FLAC=flac
 SPEEXENC=speexenc
 # mpp (Musepack)
 MPPENC=mppenc
+# m4a
+AACENC=faac
 
 ID3=id3
 ID3V2=id3v2
@@ -2401,6 +2955,7 @@ DAGRAB=dagrab
 CDDAFS=cp
 CDDISCID=cd-discid
 CDDBTOOL=cddb-tool
+MUSICBRAINZ=musicbrainz-get-tracks
 EJECT=eject
 MD5SUM=md5sum
 DISTMP3=distmp3
@@ -2410,10 +2965,11 @@ NORMALIZE=normalize-audio
 CDSPEED=eject
 VORBISGAIN=vorbisgain
 MP3GAIN=mp3gain
+MPPGAIN=replaygain
 MKCUE=mkcue
 MKTOC=cdrdao
 DIFF=diff
-CUE2DISCID=cue2discid
+CUE2DISCID=builtin
 
 # Options for programs called from abcde
 # mp3
@@ -2428,11 +2984,13 @@ MP3ENCOPTS=
 VORBIZEOPTS=
 OGGENCOPTS=
 # flac
-FLACOPTS="-f"
+FLACOPTS=
 # speex
 SPEEXENCOPTS=
 # mpc
 MPPENCOPTS=
+# m4a
+AACENCOPTS=
 
 ID3OPTS=
 ID3V2OPTS=
@@ -2458,12 +3016,23 @@ MAXPROCS=1
 # List of actions to perform - by default, run to completion
 ACTIONS=cddb,read,encode,tag,move,clean
 
+# This option is basicaly for Debian package dependencies: 
 # List of prefered outputs - by default, run with whatever we have in the path
-# This option is basicaly for Debian package dependencies
-DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:lame,mp3:bladeenc,spx:speex
+DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:toolame,mp3:lame,mp3:bladeenc,spx:speex,m4a:faac
+
+# List of prefered cdromreaders - by default, run whichever we have in the path
+DEFAULT_CDROMREADERS="cdparanoia cdda2wav"
 
-# Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
-# Let's use these checkings to determine the OS flavour, which will be used later
+# List of quality levels associated with the encoders:
+DEFAULT_QUALITY_XLO="oggenc:-q -1,lame:-q 9,speex:--quality 1,m4a:"
+DEFAULT_QUALITY_LO="oggenc:-q 1,lame:-q 7,speex:--quality 5,m4a:"
+DEFAULT_QUALITY_HI="oggenc:-q 7,lame:--preset standard,speex:--quality 9,m4a:"
+DEFAULT_QUALITY_XHI="oggenc:-q 10,lame:--preset extreme,speex:--quality 10,m4a:"
+
+# Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for
+# Linux/OpenBSD. ftp is user for NetBSD.
+# Let's use these checkings to determine the OS flavour, which will be used
+# later
 if [ X$(uname) = "XFreeBSD" ] ; then
        HTTPGET=fetch
        MD5SUM=md5
@@ -2478,9 +3047,15 @@ elif [ X$(uname) = "XDarwin" ] ; then
 elif [ X$(uname) = "XOpenBSD" ] ; then
        HTTPGET=wget
        MD5SUM=md5
+       OSFLAVOUR=OBSD
 elif [ X$(uname) = "XNetBSD" ] ; then
        HTTPGET=ftp
        MD5SUM=md5
+       OSFLAVOUR=NBSD
+elif [ X$(uname) = "SunOS" ] ; then
+       HTTPGET=""
+       MD5SUM=md5
+       OSFLAVOUR=SunOS
 else
        HTTPGET=wget
 fi
@@ -2491,6 +3066,12 @@ CDDBAVAIL=y
 USEID3=y
 USEID3V2=y
 
+# There we go..
+# But before we get into business, let us chop off any GREP environmental
+# variables.
+GREP_OPTIONS=""
+GREP_COLOR=""
+
 if [ -z "$OUTPUTDIR" ]; then
        OUTPUTDIR=$(pwd)
 fi
@@ -2513,10 +3094,10 @@ fi
 
 if [ "$HTTPGETOPTS" = "" ] ; then
        case $HTTPGET in
-               wget) HTTPGETOPTS="-q -O -";;
+               wget) HTTPGETOPTS="-q -nv -O -";;
                curl) HTTPGETOPTS="-f -s";;
                fetch)HTTPGETOPTS="-q -o -";;
-               ftp)  HTTPGETOPTS="-q -o -";;
+               ftp)  HTTPGETOPTS="-a -V -o - ";;
                *) log warning "HTTPGET in non-standard and HTTPGETOPTS are not defined." ;;
        esac
 fi
@@ -2539,8 +3120,8 @@ if [ "$CDROM" = "" ] ; then
 fi
 
 # Parse command line options
-#while getopts 1a:A:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
-while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
+#while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPq:r:Rs:S:t:T:vVxw:W: opt ; do
+while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:UvVxX:w:W:z opt ; do
        case "$opt" in
                1) ONETRACK=y ;;
                a) ACTIONS="$OPTARG" ;;
@@ -2548,10 +3129,9 @@ while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
                b) BATCHNORM=y ;;
                B) NOBATCHREPLAYGAIN=y ;;
                c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else log error "config file \"$OPTARG\" cannot be found." ; exit 1 ; fi ;;
-               C) DISCID="${OPTARG#abcde.}" ;;
+               C) DISCID="$( echo ${OPTARG#abcde.} | tr -d /)" ;;
                d) CDROM="$OPTARG" ;;
                D) set -x ;;
-               e) ERASEENCODEDSTATUS=y ;;
                h) usage; exit ;;
                e) ERASEENCODEDSTATUS=y ;;
                E) ENCODING="$OPTARG" ;;
@@ -2565,17 +3145,18 @@ while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
                n) CDDBAVAIL=n ;;
                N) INTERACTIVE=n ;;
                m) DOSPLAYLIST=y ;;
-               M) MAKECUEFILE=y ;;
+               M) DOCUE=y ;;
                o) OUTPUTTYPE="$OPTARG" ;;
                p) PADTRACKS=y ;;
                P) USEPIPES=y ;;
+               q) QUALITYLEVEL="$OPTARG" ;;
                r) REMOTEHOSTS="$OPTARG" ;;
-               R) DOREPLAYGAIN=y ;;
+               R) CDDBLOCALRECURSIVE=y ;;
                s) SHOWCDDBFIELDS="$OPTARG" ;;
                S) CDSPEEDVALUE="$OPTARG" ;;
                t) STARTTRACKNUMBER="$OPTARG" ;;
                T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
-               u) CDDBPROTO=6 ;;
+               U) CDDBPROTO=5 ;;
                v) 
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
@@ -2584,8 +3165,9 @@ while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
                   ;;
                V) EXTRAVERBOSE="y" ;;
                x) EJECTCD="y" ;;
+               X) CUE2DISCID="$OPTARG" ;;
                w) COMMENT="$OPTARG" ;;
-               W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
+               W) if echo $OPTARG | grep "[[:digit:]]" > /dev/null 2>&1 ; then 
                     STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
                   else
                     log error "argument of -W must be integer"
@@ -2599,18 +3181,49 @@ done
 
 shift $(($OPTIND - 1))
 
+# Here it comes the worse part of the whole thing. From here until we start
+# ripping, we have a mixture of sanity checks, verifications, default settigs
+# and other crazy stuff that interdepends, but hey, someone has to do it.
+
+# If NOCDDBQUERY is set, don't query the CDDB server.
+if [ "$NOCDDBQUERY" = "y" ]; then
+       CDDBAVAIL="n"
+fi
+
 # If the user specified a flac file, then switch to special flac mode
-if echo $CDROM | grep -i -q '.flac$'; then
-       vecho "abcde: switching to flac CDROMREADERSYNTAX..."
-       CDROMREADERSYNTAX=flac
-       if [ "$EJECTCD" = "y" ];then
-               vecho "abcde: CDROM flac mode, deactivating EJECTCD..."
-               EJECTCD=n
+if echo "$CDROM" | grep -i '.flac$' > /dev/null 2>&1 ; then
+       if [ ! -f "$CDROM" ]; then
+               log error "the defined file for FLAC ripping cannot be found" >&2
+               exit 1
        fi
+       vecho warning "switching to flac CDROMREADERSYNTAX..."
+       CDROMREADERSYNTAX=flac
+       # We have a builtin version of cue2discid...
+       case "$CUE2DISCID" in
+               builtin);;
+               *) NEEDCUE2DISCID=y;;
+       esac
+       NEEDMETAFLAC=y
+       EJECTCD=n
 fi
 
 # If the user provided a DISCID, disable eject
-if [ -n "$DISCID" ]; then EJECTCD=n ; fi
+if [ -n "$DISCID" ] || [ "$CDROMREADERSYNTAX" = "flac" ]; then EJECTCD=n ; fi
+
+# Check the available cd rippers in the system, from the ones we know.
+if [ "$CDROMREADERSYNTAX" = "" ]; then
+       for DEFAULT_CDROMREADER in $DEFAULT_CDROMREADERS; do
+               if new_checkexec $DEFAULT_CDROMREADER; then
+                       CDROMREADERSYNTAX=$DEFAULT_CDROMREADER
+                       break
+               fi
+       done
+       if [ "$CDROMREADERSYNTAX" = "" ]; then
+               log error "no cdreader found in your PATH"
+               log error "hints: are all dependencies installed? has the \$PATH been modified?"
+               exit 1
+       fi
+fi
 
 # Decide if we can continue.
 if [ "$ONETRACK" = "y" ]; then 
@@ -2666,10 +3279,14 @@ DOMOVE=n
 DOREPLAYGAIN=n
 DOPLAYLIST=n
 DOCLEAN=n
+## FIXME ## Lets keep compatibility with -M
+[ "$DOCUE" != "y" ] && DOCUE=n
 
 for ACTION in $(echo $ACTIONS | tr , \ )
 do
        case $ACTION in
+               default) DOCDDB=y; DOREAD=y; DOENCODE=y; DOTAG=y; DOMOVE=y; DOCLEAN=y;;
+               cue) DOCUE=y ; MAKECUEFILE=y ;;
                cddb) DOCDDB=y;;
                read) DOREAD=y;;
                normalize) DONORMALIZE=y; DOREAD=y;;
@@ -2697,13 +3314,11 @@ for SHOWCDDBFIELD in $(echo $SHOWCDDBFIELDS | tr , \ ); do
        esac
 done
 
-# Sanity checks:
-
 # At this point a CDROM has to be defined, so we check it exists.
 if [ X"$CDROM" != "X" ] ; then 
        if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
                if [ "$OSFLAVOUR" = "FBSD" ]; then
-                       if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
+                       if echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then :; else
                                log error "CDROMID not in the right format for $CDROMREADERSYNTAX"
                                log error "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
                                exit 1
@@ -2775,7 +3390,7 @@ if [ "$BATCHNORM" = "y" ] && [ "$DONORMALIZE" = "n" ]; then
        BATCHNORM=n
 fi
 
-# Check the encoding format from the ones available in the system, if nothing has been configured in the system.
+# Check the encoding format from the ones available in the system, if nothing has been configured.
 if [ X"$OUTPUTTYPE" = "X" ]; then
        for DEFAULT_OUTPUT in $( echo "$DEFAULT_OUTPUT_BINARIES" | tr , \ ); do
                DEFAULT_OUTPUT_FORMAT="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 1)"
@@ -2827,13 +3442,14 @@ esac
 
 # Allow -o OUTPUT(1):OPTIONS(1),...,OUTPUT(N):OPTIONS(N) mode of operation
 if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
-       for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
+       for OUTPUT in "$(echo "$OUTPUTTYPE" | tr \  \|| tr , \ | tr \| \ )"; do
                case "$OUTPUT" in
                        vorbis:*|ogg:*) OGGENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        mp3:*)  MP3ENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        flac:*) FLACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        spx:*)  SPEEXENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        mpc:*)  MPPENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
+                       m4a:*)  AACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                esac
        done
        for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
@@ -2843,7 +3459,8 @@ if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
        OUTPUTTYPE="$TEMPOUTPUTTYPE"
 fi
 
-# If nothing has been specified, use oggenc for oggs and lame for mp3s and flac for flacs and speexenc for speex and mppenc for mpps
+# If nothing has been specified, use oggenc for oggs and lame for mp3s and flac
+# for flacs and speexenc for speex and mppenc for mpps and faac for m4as
 
 # Getting ready for multiple output changes
 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
@@ -2864,16 +3481,22 @@ do
                        [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
                        [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
                        [ "$DOREPLAYGAIN" = "y" ] && NEEDMETAFLAC=y
+                       [ "$ONETRACK" = "y" ] && [ "$DOCUE" = "y" ] && NEEDMETAFLAC=y 
                        ;;
                spx)
                        [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
+#                      [ "$DOREPLAYGAIN" = "y" ] &&
                        ;;
                mpc)
                        [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDMPPGAIN=y
+                       ;;
+               m4a)
+                       [ "$AACENCODERSYNTAX" = "default" ] && AACENCODERSYNTAX=faac
                        ;;
                wav)
                        if [ "$KEEPWAVS" = "y" ]; then
-                               vecho "Unsetting the KEEPWAVS option, since the resulting wav files were requested..."
+                               vecho "Setting the KEEPWAVS option, since the resulting wav files were requested..."
                        fi
                        KEEPWAVS=move
                        ;;
@@ -2929,7 +3552,7 @@ case "$FLACENCODERSYNTAX" in
                FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
                FLACENCODER="$FLAC"     
                # FLAC streams can be encapsulated on a Ogg transport layer
-               if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
+               if echo "$FLACENCODEROPTS" | egrep -- "(^| )--ogg($| )" > /dev/null 2>&1 ;then
                        log error "FLAC on an Ogg container is not yet supported"
                        log error "due to problem with adding comments to such files"
                        exit 1
@@ -2951,9 +3574,14 @@ case "$MPPENCODERSYNTAX" in
                MPPENCODER="$MPPENC"
                ;;
 esac
-               
-# and which tagger
+case "$AACENCODERSYNTAX" in
+       faac)
+               AACENCODEROPTS="${AACENCODEROPTSCLI:-$AACENCOPTS}"
+               AACENCODER="$AACENC"
+               ;;
+esac
 
+# and which tagger
 if [ "$ID3TAGV" = "1" ]; then
        TAGGER="$ID3"
        TAGGEROPTS="$ID3OPTS"
@@ -2976,6 +3604,12 @@ case "$CUEREADERSYNTAX" in
                ;;
 esac
 
+# which information retrieval tool are we using?
+case "$CDDBTOOL" in
+       cddb) ;;
+       musicbrainz) ;;
+esac
+
 # Check if both OGGEOUTPUTCONTAINER and FLACOUTPUTCONTAINER are the same, and differentiante them
 if [ X"$OGGOUTPUTCONTAINER" = "Xogg" ] && [ X"$FLACOUTPUTCONTAINER" = "Xogg" ]; then
        log error "FLAC on an Ogg container is not yet supported"
@@ -3009,17 +3643,21 @@ if [ "$EJECTCD" = "y" ]; then
        NEEDEJECT=y
 fi
 if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
-       NEEDHTTPGET=y
+       if [ "$CDDBMETHOD" = "cddb" ]; then
+               NEEDHTTPGET=y
+       elif [ "$CDDBMETHOD" = "musicbrainz" ]; then
+               :
+       fi
 fi
-if [ "$MAKECUEFILE" = "y" ]; then
+if [ "$DOCUE" = "y" ]; then
        NEEDCUEREADER=y
 fi
 
-if [ X"$CDSPEEDVALUE" != "X" ]; then
+if [ X"$CDSPEEDVALUE" != "X" ] && [ "$DOREAD" = "y" ]; then
        case "$CDROMREADERSYNTAX" in
                cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
                ### FIXME ### translate "cue2discid" from python to bash
-               flac) NEEDMETAFLAC=y ; NEEDCUE2DISCID=y ;;
+               flac) NEEDMETAFLAC=y ; NEEDCUE2DISCID=y ; CDSPEEDVALUE="" ;;
                *) NEEDCDSPEED=y ;;
        esac
 fi
@@ -3076,64 +3714,87 @@ fi
 # Make sure a buncha things exist
 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
        $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
+       $AACENCODER \
        ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
        ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
        ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
        ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
        ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMP3GAIN+$MP3GAIN} \
-       ${NEEDCUEREADER+$CUEREADER} ${NEEDCUE2DISCID+$CUE2DISCID}
+       ${NEEDMPPGAIN+$MPPGAIN} ${NEEDCUEREADER+$CUEREADER} \
+       ${NEEDCUE2DISCID+$CUE2DISCID}
 do
-       # Cut off the command-line options we just added in
-       X=$(echo $X | cut -d' ' -f2)
-       if [ "$(which $X)" = "" ]; then
-               log error "$X is not in your path." >&2
-               exit 1
-       elif [ ! -x $(which $X) ]; then
-               log error "$X is not executable." >&2
-               exit 1
-       fi
+       checkexec "$X"
 done
 
-CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
-CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
-HTTPGET="$HTTPGET $HTTPGETOPTS"
-
-# And last but not least, check if we can diff between files
+# And last but not least, check if we can diff between files. We do not abort,
+# since diffing is not critical...
 if [ -x $(which $DIFF) ]; then :; else
        vecho warning "Disabling diff since we cannot find it in the \$PATH..."
        DIFF=""
 fi
 
+## Now that we have metaflac, check if we need cue2discid
+#case $CDROMREADERSYNTAX in
+#      flac)
+#              TRACKINFO=$($METAFLAC --show-tag=CDDB $CDROM | cut -d"=" -f2 | egrep "[a-f0-9]{8}")
+#              if [ "$TRACKINFO" = "" ]; then 
+#                      checkexec ${NEEDCUE2DISCID+$CUE2DISCID}
+#              fi
+#              ;;
+#esac
+
+CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
+CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
+HTTPGET="$HTTPGET $HTTPGETOPTS"
+
 # Here it used to say:
 # One thousand lines in, we can start doing stuff with things
-# Well, right now we are at line 2736 ;)
+# Well, right now we are at line 3737 ;)
 
 # Export needed things so they can be read in this subshell
 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
 
-# User-definable function to set some things. Use it for
-#  - closing the CD tray with eject -t
-#  - set the CD speed value with eject -x
-vecho -n "Executing customizable pre-read function... "
+if [ "$DOREAD" = "y" ]; then
+       # User-definable function to set some things. Use it for
+       #  - closing the CD tray with eject -t
+       #  - set the CD speed value with eject -x
+       vecho -n "Executing customizable pre-read function... "
 
-pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
+       pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
 
-vecho "done."
+       vecho "done."
+fi
 
-do_discid # Get ABCDETEMPDIR created and status file initialized
+case "$CDDBMETHOD" in
+       cddb)
+               do_discid # Get ABCDETEMPDIR created and status file initialized
+               ;;
+       musicbrainz)
+               do_musicbrainz id
+               ;;
+esac
 
 if [ "$DOCDDB" = "y" ]; then
+       # start with a sane default:
+       CDDBLOCALSTATUS=notfound
        if [ $CDDBUSELOCAL = "y" ]; then
                do_localcddb
        fi
        if checkstatus cddb-choice > /dev/null; then
                :
        else 
-               if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
-                       do_cddbstat
-                       do_cddbquery
-                       do_cddbread
+               if [ "$CDDBLOCALSTATUS" = "notfound" ] ; then
+                       case "$CDDBMETHOD" in
+                               cddb)
+                                       do_cddbstat
+                                       do_cddbquery
+                                       do_cddbread
+                                       ;;
+                               musicbrainz)
+                                       do_musicbrainz
+                                       ;;
+                       esac
                fi
        fi
        do_cddbedit
@@ -3161,6 +3822,15 @@ if [ -f "$ABCDETEMPDIR/status" ] && [ X"$ERASEENCODEDSTATUS" = "Xy" ]; then
                | grep -v ^encode-output > "$ABCDETEMPDIR/status"
 fi
 
+if checkstatus onetrack ; then ONETRACK=y ; fi
+
+if [ "$ONETRACK" = "y" ]; then 
+       # Reuse the CUEFILE in case we created it (now or in a previous run)
+       if CUEFILE=$(checkstatus cuefile); then
+               IMPORTCUESHEET=y
+       fi
+fi
+
 # Create playlist if needed (backgroundable) and start reading in tracks
 
 (
@@ -3180,10 +3850,12 @@ fi
 
 if [ "$ONETRACK" = "y" ]; then 
        TRACKS="$FIRSTTRACK"
-       if checkstatus readtrack-$FIRSTTRACK; then :; else
-               if [ "$USEPIPES" = "y" ]; then
+       if [ "$USEPIPES" = "y" ]; then
+               if checkstatus readencodetrack-$FIRSTTRACK; then :; else
                        do_cdread onetrack $FIRSTTRACK $LASTTRACK | do_encode $FIRSTTRACK %local0% > /dev/null 2>&1
-               else
+               fi
+       else
+               if checkstatus readtrack-$FIRSTTRACK; then :; else
                        do_cdread onetrack $FIRSTTRACK $LASTTRACK
                fi
        fi
@@ -3266,7 +3938,7 @@ if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
        elif [ X"$(uname)" = X"Darwin" ] ; then
                disktool -e ${CDROM#/dev/} 0
        else
-               $EJECT $EJECTOPTS $CDROM
+               $EJECT $EJECTOPTS "$CDROM"
        fi
        #fi
 fi
@@ -3384,6 +4056,8 @@ do
        fi
        # Don't proceed with the rest of the loop if we can't encode
        if [ "$ABORT" ]; then continue; fi
+       ## FIXME ## Add here 
+       ## run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
        # Set TRACKNUM, TRACKNAME
        if [ -e "$CDDBDATA" ]; then
                if [ "$ONETRACK" = "y" ]; then 
@@ -3391,11 +4065,9 @@ do
                        TRACKNUM="$FIRSTTRACK"
                        splitvarious
                else
-#                      TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
                        TRACKNUM=$UTRACKNUM
                        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                       #TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        splitvarious
                fi
        fi
@@ -3442,8 +4114,9 @@ done
 
 # Go through it again and make sure there's no distmp3 stragglers, otherwise
 # we'll delete the files they're working on
+# Do NOT play ball if there is no ball to play (so ABORT if needed)
 ## FIXME ## Check also for files which are encoded using PIPEs.
-if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
+if [ "$DOENCODE" = "y" ] && [ "$USEPIPES" != "y" ] && [ ! "$ABORT" ]; then
        PROCEED=
        until [ $PROCEED ]
        do
@@ -3470,10 +4143,6 @@ if [ "$DOREPLAYGAIN" = "y" ]; then
        do_replaygain
 fi
 
-# FIXME #
-# Check if all the encoded formats have been actually moved to the final destination
-# ...
-
 # Check to see if run_command logged any errors
 if [ -f "$ABCDETEMPDIR/errors" ]; then
        log error "The following commands failed to run:"
@@ -3489,11 +4158,11 @@ fi
 if [ "$DOCLEAN" = "y" ] && [ ! "$FORCE" = "y" ]; then
        ENCODED_FORMATS=$(egrep "^encodetrack-(.{3,6})-(.{1,2})$" "$ABCDETEMPDIR/status" | cut -d"-" -f2 | sort -u | tr '\n' '|')
        MOVED_FORMATS=$(egrep "^movetrack-output-(.{3,6})$" "$ABCDETEMPDIR/status" | cut -d"-" -f3 | sort -u | tr '\n' '|')
-       decho [ENCODED_FORMATS]
-       decho [MOVED_FORMATS]
        if [ "$ENCODED_FORMATS" != "$MOVED_FORMATS" ]; then
-               log warning "Not all encoded formats have been requested to be moved."
-               log warning "Use \"-a clean -f -C $DISCID\" to force the removal of the remaining data."
+               log warning "The encoded formats does not match with the moved ones"
+               log warning "Formats encoded: $( echo $ENCODED_FORMATS | tr "|" " " )"
+               log warning "Formats moved: $( echo $MOVED_FORMATS | tr "|" " " )"
+               log warning "Use \"abcde -a clean -f -C $DISCID\" to force the removal of the remaining data."
                DOCLEAN=n
        fi
 fi