Typo in cdda2wav LASTTRACK corrected.
[abcde.git] / abcde
diff --git a/abcde b/abcde
index 4c0501d..b6271fc 100755 (executable)
--- a/abcde
+++ b/abcde
@@ -1,4 +1,4 @@
-#!/bin/sh
+#!/bin/bash
 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
 # Copyright (c) 2003-2005 Jesus Climent <jesus.climent@hispalinux.es>
 # This code is hereby licensed for public consumption under either the
 #
 # 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,9 +22,11 @@ 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,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)"
 echo "-c <file>"
 echo "       Specify a configuration file (overrides system and user config files)"
 echo "-C <discid#>"
@@ -31,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"
@@ -45,17 +48,19 @@ 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 "-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 "-r <host1[,host2]...>"
 echo "       Also encode on these remote hosts"
-echo "-R     Add replaygain values to the tag info (only for vorbis,flac)"
+echo "-R     Use local CDDB in recursive mode"
+#echo "-R     Add replaygain values to the tag info (only for vorbis,flac,mp3)"
 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 "-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"
@@ -70,6 +75,25 @@ echo ""
 #echo "Double hyphens are used to concatenate tracks"
 }
 
+addstatus ()
+{
+       echo "$@" >> "$ABCDETEMPDIR/status"
+}
+
+# log [level] [message]
+# 
+# log outputs the right message in a common format
+log ()
+{
+       BLURB="$1"
+       shift
+       case $BLURB in
+               error)   echo "[ERROR] abcde: $@" >&2 ;;
+               warning) echo "[WARNING] $@" >&2 ;;
+               info)    echo "[INFO] $@" ;;
+       esac
+}
+
 # Funtions to replace the need of seq, which is too distribution dependant.
 f_seq_row ()
 {
@@ -84,7 +108,7 @@ f_seq_row ()
 f_seq_line ()
 {
        i=$1
-       if echo i | grep -q "[[:digit:]]" ; then
+       if echo $i | grep -q "[[:digit:]]" ; then
                while [ $i -ne `expr $2 + 1` ]
                do
                        printf $i" "
@@ -92,7 +116,7 @@ f_seq_line ()
                done
                echo
        else
-               echo "abcde: syntax error while processing track numbers" >&2
+               log error "syntax error while processing track numbers"
                exit 1
        fi
 }
@@ -310,13 +334,23 @@ relpath ()
        echo $TO
 }
 
+checkexec ()
+{
+       if [ ! "$@" = "" ]; then
+               # Cut off the command-line options we just added in
+               X=$(echo $@ | 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
+       fi
+}
+
 # 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/\ \+$//')"
-
 do_getcddbinfo()
 {
        case $1 in
@@ -347,7 +381,6 @@ do_replaygain()
        if checkstatus replaygain; then :; else
                run_command "" echo "Adding replygain information..."
                for OUTPUT in $( echo $OUTPUTTYPE | tr , \ )
-               # THE OUTPUT NEEDS TO BE CORRECTED WITH THE CONTAINER?
                do
                        case $OUTPUT in
                                vorbis|ogg)
@@ -358,6 +391,7 @@ do_replaygain()
                                        ;;
                        esac
                        OUTPUTFILES=""
+                       REPLAYINDEX=0
                        for UTRACKNUM in $TRACKQUEUE
                        do
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
@@ -368,23 +402,30 @@ do_replaygain()
                                ALBUMFILE="$(mungefilename "$DALBUM")"
                                do_gettracknum
                                if [ "$VARIOUSARTISTS" = "y" ]; then
-                                       OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
+                                       OUTPUTFILE="$(eval echo $VAOUTPUTFORMAT)"
                                else
-                                       OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
+                                       OUTPUTFILE="$(eval echo $OUTPUTFORMAT)"
                                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 $METAFLAC --add-replay-gain "${OUTPUTFILES[@]}"
                                        ;;
                                vorbis|ogg)
-                                       run_command replaygain-vorbis $VORBISGAIN --album $OUTPUTFILES
+                                       run_command replaygain-vorbis $VORBISGAIN --album "${OUTPUTFILES[@]}"
+                                       ;;
+                               mp3)
+                                       run_command replaygain-mp3 $MP3GAIN -a "${OUTPUTFILES[@]}"
+                                       ;;
+                               mpc)
+                                       run_command replaygain-mpc $MPPGAIN --auto "${OUTPUTFILES[@]}"
                                        ;;
                                *);;
                        esac
                done
-               if checkerrors replaygain-.{3,6}; then :; else
+               if checkerrors "replaygain-.{3,6}"; then :; else
                        run_command replaygain true
                fi
        fi
@@ -700,7 +741,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 $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
                        ;;
                spx)
                        run_command tagtrack-$OUTPUT-$1 true
@@ -708,6 +749,9 @@ do_tag ()
                mpc)
                        run_command tagtrack-$OUTPUT-$1 true
                        ;;
+               m4a)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
                wav)
                        run_command tagtrack-$OUTPUT-$1 true
                        ;;
@@ -790,6 +834,9 @@ do_encode ()
                        mpc)
                                TEMPARG="PIPE_$MPPENCODER"
                                ;;
+                       m4a)
+                               TEMPARG="PIPE_$MPPENCODER"
+                               ;;
                esac
                IN="$( eval echo "\$$TEMPARG" )"
        else
@@ -816,22 +863,26 @@ do_encode ()
        if [ -s "$IN" -o X"$USEPIPES" = "Xy" ] ; then
                for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
                do
-                       if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
-                               continue
-                       fi
                        case "$OUTPUT" in
                                vorbis|ogg)
                                        OUT="$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
+                                       OUTPUT=$OGGOUTPUTCONTAINER
                                        ;;
                                flac)
                                        OUT="$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                                       OUTPUT=$FLACOUTPUTCONTAINER
                                        ;;
                                *)
                                        OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
                                        ;;
                        esac
+                       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"
                        else
                                run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
                                RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
@@ -868,16 +919,15 @@ do_encode ()
                                ;;
                        flac)
                                case "$2" in
-                               %local*%)
+                               %local*%)
                                        case "$FLACENCODERSYNTAX" in
-                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
+                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
                                        esac
-                                       ;;
-       
-                               *)
-                                       echo -n "DISTMP3:"
-                                       echo "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
-                                       $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
+                                               ;;
+                                       *)
+                                               vecho -n "DISTMP3:"
+                                               vecho "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
+                                               $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
                                        ;;
                                esac
                                ;;
@@ -905,11 +955,20 @@ do_encode ()
                                ## 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"
                                ;;
+                       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 $ENCNICE $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.
-                               run_command encodetrack-$OUTPUT-$1 true
                                ;;
                        esac
+                       $RUN_COMMAND_PIPES
                done
                # Only remove .wav if the encoding succeeded
                if checkerrors "encodetrack-(.{3,6})-$1"; then :; else
@@ -1016,7 +1075,7 @@ do_single_gain ()
 
 # do_batch_gain
 # variables used:
-# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
+# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPPGAIN, MPPGAINOPTS
 # FIXME #
 do_batch_gain ()
 {
@@ -1250,7 +1309,6 @@ 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
                                splitvarious
                                TRACKFILE="$(mungefilename "$TRACKNAME")"
@@ -1306,18 +1364,27 @@ do_discid ()
                        disktool -u ${CDROM#/dev/}
                fi
                if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
-                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
+                       if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM > /dev/null 2>&1 ; then
+                               TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
+                       else
+                               log error "the input flac file does not contain a cuesheet."
+                               exit 1
+                       fi
                else
-                       TRACKINFO=$($CDDISCID $CDROM)
+                       case "$CDDBMETHOD" in
+                               cddb) TRACKINFO=$($CDDISCID $CDROM) ;;
+                               # FIXME # musicbrainz needs a cleanup
+                               musicbrainz) TRACKINFO=$($MUSICBRAINZ -c $CDROM ) ;;
+                       esac
                fi
                # Make sure there's a CD in there by checking cd-discid's return code
                if [ ! "$?" = "0" ]; then
                        if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
-                               echo "abcde error: cuesheet information from the flac file could not be read." >&2
-                               echo "abcde error: Perhaps the flac file does not contain a cuesheet?." >&2
+                               log error "cuesheet information from the flac file could not be read."
+                               log error "Perhaps the flac file does not contain a cuesheet?."
                                exit 1
                        else
-                               echo "abcde error: CD could not be read. Perhaps there's no CD in the drive?" >&2
+                               log error "CD could not be read. Perhaps there's no CD in the drive?"
                                exit 1
                        fi
                fi
@@ -1326,6 +1393,7 @@ do_discid ()
                        disktool -m ${CDROM#/dev/}
                fi
                WEHAVEACD=y
+               DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
        else
                TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
        fi
@@ -1352,11 +1420,16 @@ do_discid ()
                                                CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
                                                RET=$?
                                                if [ ! "$RET" = "0" ];then
-                                                       echo "Warning: Something went wrong while querying the CD... Maybe a DATA CD?"
+                                                       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"
                                        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
@@ -1368,7 +1441,7 @@ do_discid ()
                        TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
                fi
                if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
-                       echo "The disc does not contain any tracks. Giving up..."
+                       log info "The disc does not contain any tracks. Giving up..."
                        exit 0
                fi
                echo -n "Grabbing entire CD - tracks: "
@@ -1443,7 +1516,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
@@ -1465,13 +1538,15 @@ 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 checkstatus cuefile > /dev/null 2>&1 ; then :; else
@@ -1480,9 +1555,9 @@ do_discid ()
                        if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
                                echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
                        else
-                               echo "abcde: reading the CUE sheet with mkcue is still considered experimental"
-                               echo "abcde: and there was a problem with the CD reading. abcde will continue,"
-                               echo "abcde: but consider reporting the problem to the abcde author"
+                               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
                fi
        fi
@@ -1495,6 +1570,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
@@ -1564,45 +1642,122 @@ 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 ""
+                                       } >> "$ABCDETEMPDIR/cddblocalchoices"
+                               done
+                               CDDBLOCALCHOICES=$( echo "$CDDBLOCALRESULTS" | wc -l )
+                               cat "$ABCDETEMPDIR/cddblocalchoices"
+                               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 CDDBLOCALCHOICENUM
+                                               [ x"$CDDBLOCALCHOICENUM" = "x" ] && CDDBLOCALCHOICENUM="1"
+                                       done
+                               else
+                                       ### FIXME ###
+                                       echo "Selected ..."
+                                       CDDBLOCALRESP=y
+                               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_musizbrainz ()
+{
+       :
+}
+
 # do_cddbstat
 do_cddbstat ()
 {
@@ -1648,7 +1803,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
@@ -1787,7 +1942,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
@@ -1795,6 +1950,13 @@ do_cddbedit ()
                                CHOICE=$(checkstatus cddb-choice)
                                if [ -n "$CHOICE" ] ; then
                                        case $CDDBCHOICES in
+                                               -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep -q "^$" ; then
+                                                               log error "CDDB query failed!" 
+                                                               exit 1
+                                                       else
+                                                               cat "$ABCDETEMPDIR/cddbchoices"
+                                                       fi
+                                                       ;;
                                                1) cat "$ABCDETEMPDIR/cddbchoices" ;;
                                                *)
                                                echo "Selected: #$CHOICE"
@@ -1818,16 +1980,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 -q "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" ; 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"
@@ -1843,10 +2004,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 -q "[[:space:]]*[[:digit:]]+[[:space:]]*" ; 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
@@ -1894,7 +2055,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
@@ -1963,7 +2124,7 @@ do_cddbedit ()
                        /usr/bin/mg "$CDDBDATA"
                # bomb out
                else
-                       echo "No editor available. Check your EDITOR environment variable." >&2
+                       log warning "no editor available. Check your EDITOR environment variable."
                fi
                # delete editor backup file if it exists
                if [ -w "$CDDBDATA~" ]; then
@@ -2084,10 +2245,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
 
@@ -2107,22 +2270,21 @@ 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" ;;
+                       cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTTRACK" ;;
                        *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
-                          exit 1 ;;
+                               exit 1 ;;
                esac
        else
                UTRACKNUM=$1
        fi
        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
        if [ "$USEPIPES" = "y" ]; then
-               TEMPARG="PIPE_$CDROMREADERSYNTAX"
+               TEMPARG="PIPERIPPER_$CDROMREADERSYNTAX"
                FILEARG="$( eval echo "\$$TEMPARG" )"
                REDIR=""
                PIPE_MESSAGE="and encoding "
@@ -2146,7 +2308,6 @@ 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
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
                else
@@ -2157,7 +2318,9 @@ 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 ;;
                cdda2wav)
@@ -2215,9 +2378,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
 }
@@ -2239,7 +2402,10 @@ do_cdspeed ()
 vecho ()
 {
 if [ x"$EXTRAVERBOSE" != "x" ]; then
-       echo $@
+       case $1 in
+               warning) shift ; log warning "$@" ;;
+               *) echo "$@" ;;
+       esac
 fi
 }
 
@@ -2249,8 +2415,12 @@ fi
 decho ()
 {
 if [ x"$DEBUG" != "x" ]; then
-       DEBUGECHO=$(echo "$@" | tr -d '[]')
-       echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
+       if echo $1 | grep -q "^\[" ; then
+               DEBUGECHO=$(echo "$@" | tr -d '[]')
+               echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
+       else
+               echo "[DEBUG] $1"
+       fi
 fi
 }
 
@@ -2289,11 +2459,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
 HELLOINFO="$(whoami)@$(hostname)"
 CDDBCOPYLOCAL="n"
+CDDBLOCALPOLICY="always"
+CDDBLOCALRECURSIVE="y"
 CDDBLOCALDIR="$HOME/.cddb"
 CDDBUSELOCAL="n"
 
@@ -2301,7 +2477,7 @@ CDDBUSELOCAL="n"
 SHOWCDDBFIELDS="year,genre"
 
 INTERACTIVE=y
-CDROMREADERSYNTAX=cdparanoia
+#CDROMREADERSYNTAX=cdparanoia
 ENCODERSYNTAX=default
 
 MP3ENCODERSYNTAX=default
@@ -2309,6 +2485,7 @@ OGGENCODERSYNTAX=default
 FLACENCODERSYNTAX=default
 SPEEXENCODERSYNTAX=default
 MPPENCODERSYNTAX=default
+AACENCODERSYNTAX=default
 NORMALIZERSYNTAX=default
 CUEREADERSYNTAX=default
 
@@ -2360,6 +2537,8 @@ FLAC=flac
 SPEEXENC=speexenc
 # mpp (Musepack)
 MPPENC=mppenc
+# m4a
+AACENC=faac
 
 ID3=id3
 ID3V2=id3v2
@@ -2370,6 +2549,7 @@ DAGRAB=dagrab
 CDDAFS=cp
 CDDISCID=cd-discid
 CDDBTOOL=cddb-tool
+MUSICBRAINZ=musicbrainz-get-tracks
 EJECT=eject
 MD5SUM=md5sum
 DISTMP3=distmp3
@@ -2378,6 +2558,8 @@ METAFLAC=metaflac
 NORMALIZE=normalize-audio
 CDSPEED=eject
 VORBISGAIN=vorbisgain
+MP3GAIN=mp3gain
+MPPGAIN=replaygain
 MKCUE=mkcue
 MKTOC=cdrdao
 DIFF=diff
@@ -2396,11 +2578,13 @@ MP3ENCOPTS=
 VORBIZEOPTS=
 OGGENCOPTS=
 # flac
-FLACOPTS="-f"
+FLACOPTS=
 # speex
 SPEEXENCOPTS=
 # mpc
 MPPENCOPTS=
+# m4a
+AACENCOPTS=
 
 ID3OPTS=
 ID3V2OPTS=
@@ -2418,6 +2602,7 @@ MKCUEOPTS=
 MKTOCOPTS=""
 VORBISCOMMENTOPTS="-R"
 METAFLACOPTS="--no-utf8-convert"
+DIFFOPTS=
 
 # Default to one process if -j isn't specified
 MAXPROCS=1
@@ -2425,10 +2610,13 @@ 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
 
+# 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
 if [ X$(uname) = "XFreeBSD" ] ; then
@@ -2484,7 +2672,7 @@ if [ "$HTTPGETOPTS" = "" ] ; then
                curl) HTTPGETOPTS="-f -s";;
                fetch)HTTPGETOPTS="-q -o -";;
                ftp)  HTTPGETOPTS="-q -o -";;
-               *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
+               *) log warning "HTTPGET in non-standard and HTTPGETOPTS are not defined." ;;
        esac
 fi
 
@@ -2506,15 +2694,16 @@ 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:bc:C:d:Defghj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W:z opt ; do
+#while getopts 1a: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
        case "$opt" in
                1) ONETRACK=y ;;
                a) ACTIONS="$OPTARG" ;;
                A) EXPACTIONS="$OPTARG" ;;
                b) BATCHNORM=y ;;
-               c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
-               C) DISCID="${OPTARG#abcde.}" ;;
+               B) NOBATCHREPLAYGAIN=y ;;
+               c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else log error "config file \"$OPTARG\" cannot be found." ; exit 1 ; fi ;;
+               C) DISCID="$( echo ${OPTARG#abcde.} | tr -d /)" ;;
                d) CDROM="$OPTARG" ;;
                D) set -x ;;
                e) ERASEENCODEDSTATUS=y ;;
@@ -2536,14 +2725,12 @@ while getopts 1a:bc:C:d:Defghj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W:z opt ; do
                p) PADTRACKS=y ;;
                P) USEPIPES=y ;;
                r) REMOTEHOSTS="$OPTARG" ;;
-               R) REPLAYGAIN=y ;;
+               R) DOREPLAYGAIN=y ;;
                s) SHOWCDDBFIELDS="$OPTARG" ;;
                S) CDSPEEDVALUE="$OPTARG" ;;
-#              t) PREPROCESSFORMATS="$OPTARG"
-#                 PREPROCESS=y ;;
-#              T) POSTPROCESSFORMATS="$OPTARG" ;;
                t) STARTTRACKNUMBER="$OPTARG" ;;
                T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
+               u) CDDBPROTO=6 ;;
                v) 
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
@@ -2556,7 +2743,7 @@ while getopts 1a:bc:C:d:Defghj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W:z opt ; do
                W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
                     STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
                   else
-                    echo "abcde error: argument of -W must be integer"
+                    log error "argument of -W must be integer"
                         exit 1
                   fi
                   ;;
@@ -2569,11 +2756,29 @@ shift $(($OPTIND - 1))
 
 # 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..."
+       vecho warning "abcde: switching to flac CDROMREADERSYNTAX..."
        CDROMREADERSYNTAX=flac
-       if [ "$EJECTCD" = "y" ];then
-               vecho "abcde: CDROM flac mode, deactivating EJECTCD..."
-               EJECTCD=n
+       # Added a need on CUE2DISCID until we manage to convert the python script to bash.
+       NEEDCUE2DISCID=y
+       NEEDMETAFLAC=y
+       EJECTCD=n
+fi
+
+# If the user provided a DISCID, disable eject
+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 [ -x $( which $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
 
@@ -2584,21 +2789,21 @@ if [ "$ONETRACK" = "y" ]; then
                flac) ;;
                cdparanoia) ;;
                cdda2wav) ;;
-               *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
+               *) log error "$CDROMREADERSYNTAX does not support ONETRACK mode"
                   exit 1 ;;
        esac
        if [ "$BATCHNORM" = "y" ]; then
-               echo "abcde warning: BATCHNORM mode is not compatible with ONETRACK mode. Disabling..."
+               log warning "BATCHNORM mode is not compatible with ONETRACK mode. Disabling..."
                BATCHNORM=n
        fi
        if [ "$NOGAP" = "y" ]; then
-               echo "abcde warning: NOGAP mode is not compatible with ONETRACK mode. Disabling..."
+               log warning "NOGAP mode is not compatible with ONETRACK mode. Disabling..."
                NOGAP=n
        fi
        # It does not matter how many tracks we want. In ONETRACK mode we grab them all
        # FIXME # allow ranges of tracks to be selected for onetrack ripping
        if [ $# -gt 0 ]; then
-               vecho "abcde warning: ONETRACK mode selected, grabbing all tracks..."
+               log warning "ONETRACK mode selected, grabbing all tracks..."
        fi
 else
        while [ $# -gt 0 ]; do
@@ -2651,7 +2856,7 @@ done
 
 if [ "$DONORMALIZE" = "y" ] && [ "$DOREPLAYGAIN" = "y" ]; then
        # FIXME # should we abort on error or just inform the user?
-       :
+       log warning "selected both normalize and replaygain actions"
 fi
 
 for SHOWCDDBFIELD in $(echo $SHOWCDDBFIELDS | tr , \ ); do
@@ -2669,18 +2874,18 @@ 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
-                               echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
-                               echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
+                               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
                        fi
                fi
        elif [ ! -e "$CDROM" -a X"$DOREAD" = "Xy" ]; then
-               echo "abcde error: CDROM device cannot be found." >&2
+               log error "CDROM device cannot be found."
                exit 1
        fi
 # avoid processing if we are not going to hit the CDROM.
 elif [ X"$DOREAD" = "Xy" ]; then
-       echo "abcde error: CDROM has not been defined or cannot be found" >&2
+       log error "CDROM has not been defined or cannot be found"
        exit 1
 fi
 
@@ -2692,28 +2897,28 @@ fi
 # - anything else?
 if [ X"$USEPIPES" = "Xy" ]; then
        if [ $(echo "$OUTPUTTYPE" | tr , \  | wc -w ) -gt 1 ]; then
-               echo "abcde error: Unix pipes not compatible with multiple outputs" >&2
+               log error "Unix pipes not compatible with multiple outputs"
                exit 1
        fi
        if [ X"$DONORMALIZE" = "Xy" ]; then
-               echo "abcde error: Unix pipes not compatible with normalizer"
+               log error "Unix pipes not compatible with normalizer"
                # FIXME # Do we need to exit or shall we just disable the mode?
                exit 1
        fi
        if [ X"$BATCHNORM" = "Xy" ]; then
-               echo "abcde error: Unix pipes not compatible with BATCHNORM encoding"
+               log error "Unix pipes not compatible with BATCHNORM encoding"
                exit 1
        fi
        if [ X"$NOGAP" = "Xy" ]; then
-               echo "abcde error: Unix pipes not compatible with NOGAP encoding"
+               log error "Unix pipes not compatible with NOGAP encoding"
                exit 1
        fi
        if [ X"$DOENCODE" = "Xn" ]; then
-               vecho "Disabling Unix pipes since we are not encoding!"
+               vecho warning "Disabling Unix pipes since we are not encoding!"
                USEPIPES=n
        fi
        if [ X"$LOWDISK" = "Xy" ]; then
-               vecho "abcde error: Unix pipes not compatible with lowdisk algorithm"
+               log error "Unix pipes not compatible with lowdisk algorithm"
                exit 1
        fi
 fi
@@ -2724,15 +2929,22 @@ fi
 # - NOGAP lame mode
 if [ X"$LOWDISK" = "Xy" ]; then
        if [ X"$BATCHNORM" = "Xy" ]; then
-               echo "abcde error: Unix pipes not compatible with BATCHNORM encoding"
+               log error "Unix pipes not compatible with BATCHNORM encoding"
                exit 1
        fi
        if [ X"$NOGAP" = "Xy" ]; then
-               echo "abcde error: Unix pipes not compatible with NOGAP encoding"
+               log error "Unix pipes not compatible with NOGAP encoding"
                exit 1
        fi
 fi
 
+# BATCHNORM pre-tests, before we get into serious problems
+# Not compatible with 
+if [ "$BATCHNORM" = "y" ] && [ "$DONORMALIZE" = "n" ]; then
+       vecho warning "Disabling BATCHNORM since we are not normalizing!"
+       BATCHNORM=n
+fi
+
 # Check the encoding format from the ones available in the system, if nothing has been configured in the system.
 if [ X"$OUTPUTTYPE" = "X" ]; then
        for DEFAULT_OUTPUT in $( echo "$DEFAULT_OUTPUT_BINARIES" | tr , \ ); do
@@ -2745,8 +2957,8 @@ if [ X"$OUTPUTTYPE" = "X" ]; then
                fi
        done
        if [ X"$OUTPUTTYPE" = "X" ]; then
-               echo "abcde error: no encoder found in the PATH" >&2
-               echo "hits: are all dependencies installed? has the \$PATH been modified?" >&2
+               log error "no encoder found in the PATH"
+               log error "hints: are all dependencies installed? has the \$PATH been modified?"
                exit 1
        fi
 fi
@@ -2792,6 +3004,7 @@ if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
                        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
@@ -2801,7 +3014,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 , \ )
@@ -2810,24 +3024,29 @@ do
                vorbis|ogg)
                        [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
                        [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
-                       [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
                        OGGOUTPUTCONTAINER=ogg
                        ;;
                mp3)
                        [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
                        [ "$DOTAG" = "y" ] && NEEDTAGGER=y
-                       #[ "$NOGAP" = "y" ]
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDMP3GAIN=y
                        ;;
                flac)
                        [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
-                       [ "$REPLAYGAIN" = "y" ] && NEEDMETAFLAC=y
                        [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
+                       [ "$DOREPLAYGAIN" = "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
@@ -2835,7 +3054,7 @@ do
                        fi
                        KEEPWAVS=move
                        ;;
-               *)      echo "abcde error: Invalid OUTPUTTYPE defined" >&2
+               *)      log error "Invalid OUTPUTTYPE defined"
                        exit 1
                        ;;
        esac
@@ -2888,8 +3107,8 @@ case "$FLACENCODERSYNTAX" in
                FLACENCODER="$FLAC"     
                # FLAC streams can be encapsulated on a Ogg transport layer
                if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
-                       echo "abcde error: FLAC on an Ogg container is not yet supported" >&2
-                       echo "             due to problem with adding comments to such files" >&2
+                       log error "FLAC on an Ogg container is not yet supported"
+                       log error "due to problem with adding comments to such files"
                        exit 1
                        FLACOUTPUTCONTAINER=ogg
                else
@@ -2909,7 +3128,12 @@ case "$MPPENCODERSYNTAX" in
                MPPENCODER="$MPPENC"
                ;;
 esac
-               
+case "$AACENCODERSYNTAX" in
+       faac)
+               AACENCODEROPTS="${AACENCODEROPTSCLI:-$AACENCOPTS}"
+               AACENCODER="$AACENC"
+               ;;
+esac
 # and which tagger
 
 if [ "$ID3TAGV" = "1" ]; then
@@ -2922,7 +3146,7 @@ fi
 
 # Specific for NOGAP is the use of lame. Another encoder fails...
 if [ "$NOGAP" = "y" ] && [ ! "$MP3ENCODER" = "lame" ]; then
-       "abcde warning: the NOGAP option is specific of lame. Deactivating..."
+       log warning "the NOGAP option is specific of lame. Deactivating..."
        NOGAP=n
 fi
 
@@ -2934,14 +3158,20 @@ 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
-       echo "abcde error: FLAC on an Ogg container is not yet supported" >&2
-       echo "             due to problem with adding comments to such files" >&2
+       log error "FLAC on an Ogg container is not yet supported"
+       log error "due to problem with adding comments to such files"
        exit 1
        OGGOUTPUTCONTAINER=ogg.ogg
        FLACOUTPUTCONTAINER=flac.ogg
-       vecho "abcde warning: modified file endings due to conflicting transport layers in Ogg/Vorbis and Ogg/FLAC"
+       vecho warning "modified file endings due to conflicting transport layers in Ogg/Vorbis and Ogg/FLAC"
 fi
 
 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
@@ -2967,36 +3197,44 @@ 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
        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
 
+###USEPIPESSUPPORT###
+
 # Rippers with USEPIPE support
 # FIXME # Include here all the rippers we can figure out support pipes
-PIPE_cdparanoia="-"
-PIPE_flac="-c "
+PIPERIPPER_cdparanoia="-"
+PIPERIPPER_debug="-"
+PIPERIPPER_flac="-c "
 
 # Encoders with USEPIPE support
 # FIXME # Include here all the encoders we can figure out support pipes
 PIPE_lame="-"
 PIPE_bladeenc="-"
 PIPE_oggenc="-"
+PIPE_flac="-"
 
 # Figure out if we can use pipes with the ripper/encoder combination
 # exit otherwise
 if [ "$USEPIPES" = "y" ]; then
-       PIPERIPPERSVARCHECK="PIPE_${CDROMREADER}"
+       PIPERIPPERSVARCHECK="PIPERIPPER_${CDROMREADERSYNTAX}"
        case "$OUTPUT" in
                mp3)
                        PIPEENCODERSVARCHECK="PIPE_$MP3ENCODERSYNTAX" ;;
@@ -3009,16 +3247,20 @@ if [ "$USEPIPES" = "y" ]; then
                mpc)
                        PIPEENCODERSVARCHECK="PIPE_$MPPENCODER" ;;
        esac
-       if [ ! -n "$( eval echo "\$$PIPERIPPERSVARCHECK" )" ] ; then
-               echo "abcde error: no support for pipes with given ripper" >&2
-               echo "read the USEPIPES file from the source tarball to get help." >&2
-               echo "On a Debian system, it is under /usr/share/doc/abcde/USEPIPES.gz" >&2
+       decho "PIPERIPPERSVARCHECK: $( eval echo "\$$PIPERIPPERSVARCHECK" )"
+       if [ "$( eval echo "\$$PIPERIPPERSVARCHECK" )" = "$" ] || \
+          [ "$( eval echo "\$$PIPERIPPERSVARCHECK" )" = "" ] ; then
+               log error "no support for pipes with given ripper"
+               log error "read the USEPIPES file from the source tarball to get help."
+               log error "On a Debian system, it is under /usr/share/doc/abcde/USEPIPES.gz"
                exit 1;
        fi
-       if [ ! -n "$( eval echo "\$$PIPEENCODERSVARCHECK" )" ] ; then
-               echo "abcde error: no support for pipes with given encoder" >&2
-               echo "read the USEPIPES file from the source tarball to help" >&2
-               echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
+       decho "PIPEENCODERSVARCHECK: $( eval echo "\$$PIPEENCODERSVARCHECK" )"
+       if [ "$( eval echo "\$$PIPEENCODERSVARCHECK" )" = "$" ] || \
+          [ "$( eval echo "\$$PIPEENCODERSVARCHECK" )" = "" ] ; then
+               log error "no support for pipes with given encoder"
+               log error "read the USEPIPES file from the source tarball to help"
+               log error "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz"
                exit 1;
        fi
 fi
@@ -3030,60 +3272,81 @@ for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
        ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
        ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
        ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
-       ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDCUEREADER+$CUEREADER} \
+       ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMP3GAIN+$MP3GAIN} \
+       ${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
-               echo "abcde error: $X is not in your path." >&2
-               exit 1
-       elif [ ! -x $(which $X) ]; then
-               echo "abcde 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
 if [ -x $(which $DIFF) ]; then :; else
-       vecho "[WAR] Disabling diff since we cannot find it in the \$PATH..."
+       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 3306 ;)
 
 # 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
+               ;;
+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
@@ -3111,11 +3374,20 @@ 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 in a previous run
+       if CUEFILE=$(checkstatus cuefile); then
+               IMPORTCUESHEET=y
+       fi
+fi
+
 # Create playlist if needed (backgroundable) and start reading in tracks
 
 (
 
-if [ "$ONETRACK" = "y" ]; then
+if [ "$ONETRACK" = "y" ]; then
        if [ "$DOPLAYLIST" = "y" ]; then
                echo Creating playlist... >&2
                do_playlist
@@ -3130,8 +3402,14 @@ fi
 
 if [ "$ONETRACK" = "y" ]; then 
        TRACKS="$FIRSTTRACK"
-       if checkstatus readtrack-$FIRSTTRACK; then :; else
-               do_cdread onetrack $FIRSTTRACK $LASTTRACK
+       if [ "$USEPIPES" = "y" ]; then
+               if checkstatus readencodetrack-$FIRSTTRACK; then :; else
+                       do_cdread onetrack $FIRSTTRACK $LASTTRACK | do_encode $FIRSTTRACK %local0% > /dev/null 2>&1
+               fi
+       else
+               if checkstatus readtrack-$FIRSTTRACK; then :; else
+                       do_cdread onetrack $FIRSTTRACK $LASTTRACK
+               fi
        fi
 else
        for UTRACKNUM in $TRACKQUEUE
@@ -3157,6 +3435,11 @@ else
                if [ "$NOGAP" = "y" ] || [ "$BATCHNORM" = "y" ]; then
                    :
                else
+                       # If we are not reading, set the encode output to loud already, so
+                       # that we can see the output of the first track.
+                       if [ "$MAXPROCS" = "1" ] && [ ! "$DOREAD" = "y" ]; then
+                               echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
+                       fi
                        echo NEXTTRACK # Get the encoder machine churning again
                        if [ "$DOREAD" = "y" ]; then
                                if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
@@ -3256,10 +3539,9 @@ if [ "$BATCHNORM" = "y" ] || [ "$NOGAP" = "y" ]; then
                                                if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
                                        fi
                                done
-                       else
-                               if checkstatus encodetrack-$LASTTRACK; then :; else do_nogap_encode; fi
-                               if checkerrors nogap-encode; then exit 1; fi
                        fi
+                       if checkstatus encodetrack-$LASTTRACK; then :; else do_nogap_encode; fi
+                       if checkerrors nogap-encode; then exit 1; fi
                fi
        fi
 fi
@@ -3333,10 +3615,8 @@ 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
                        splitvarious
                fi
@@ -3408,12 +3688,13 @@ if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
 fi
 # If the above didn't catch the stragglers, this will
 wait
-if [ "$REPLAYGAIN" = "y" ]; then
+if [ "$DOREPLAYGAIN" = "y" ]; then
        do_replaygain
 fi
+
 # Check to see if run_command logged any errors
 if [ -f "$ABCDETEMPDIR/errors" ]; then
-       echo "The following commands failed to run:"
+       log error "The following commands failed to run:"
        cat "$ABCDETEMPDIR/errors"
        # Don't clean up
        DOCLEAN=n
@@ -3426,11 +3707,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
-               echo "Not all encoded formats have been requested to be moved."
-               echo "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