* Re-fix speex tagging. (Closes issue 19).
[clinton/abcde.git] / abcde
diff --git a/abcde b/abcde
index 139b353..50ef599 100755 (executable)
--- a/abcde
+++ b/abcde
@@ -1,19 +1,19 @@
 #!/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-$Revision$'
+VERSION='2.5.2'
 
 usage ()
 {
@@ -46,26 +46,29 @@ 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,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 "       Show fields 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"
 echo "-w <comment>"
 echo "       Add a comment to the CD tracks"
-echo "-W <#> Contatenate CDs: -T #01 -w \"CD #\"" 
+echo "-W <#> Concatenate CDs: -T #01 -w \"CD #\""
 echo "-z     Use debug CDROMREADERSYNTAX option (needs cdparanoia)"
 echo ""
 echo "Tracks is a space-delimited list of tracks to grab."
@@ -80,7 +83,7 @@ addstatus ()
 }
 
 # log [level] [message]
-# 
+#
 # log outputs the right message in a common format
 log ()
 {
@@ -107,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" "
@@ -115,7 +118,7 @@ f_seq_line ()
                done
                echo
        else
-               log error "syntax error while processing track numbers"
+               log error "syntax error while processing track numbers ($i)"
                exit 1
        fi
 }
@@ -153,7 +156,7 @@ checkstatus ()
 {
        # Take the last line in the status file if there's multiple matches
        PATTERN="^$1(=.*)?$"
-       BLURB=$(egrep $PATTERN "$ABCDETEMPDIR/status" | tail -n 1)
+       BLURB=$(grep -E $PATTERN "$ABCDETEMPDIR/status" | tail -n 1)
 
        if [ -z "$BLURB" ]; then
                # No matches found
@@ -168,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.
@@ -180,7 +183,7 @@ checkwarnings ()
        fi
        # Take the last line in the status file if there's multiple matches
        PATTERN="^$1(:.*)?$"
-       BLURB="$(egrep $PATTERN "$ABCDETEMPDIR/warnings" | tail -n 1)"
+       BLURB="$(grep -E $PATTERN "$ABCDETEMPDIR/warnings" | tail -n 1)"
 
        if [ -z "$BLURB" ]; then
                # negative, we did not have a negative...
@@ -203,7 +206,7 @@ checkerrors ()
        fi
        # Take the last line in the status file if there's multiple matches
        PATTERN="^$1(:.*)?$"
-       BLURB="$(egrep $PATTERN "$ABCDETEMPDIR/errors" | tail -n 1)"
+       BLURB="$(grep -E $PATTERN "$ABCDETEMPDIR/errors" | tail -n 1)"
 
        if [ -z "$BLURB" ]; then
                # negative, we did not have a negative...
@@ -243,6 +246,7 @@ page ()
 # Runs a command, silently if necessary, and updates the status file
 run_command ()
 {
+       vvecho "$@"
        BLURB="$1"
        shift
        # See if this is supposed to be silent
@@ -333,9 +337,82 @@ relpath ()
        echo $TO
 }
 
-# do_getcddbinfo
+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|flac)      MISSING_PACKAGE=$X ;;
+                               esac
+                               log info "Hint: apt-get install $MISSING_PACKAGE" >&2
+                       fi
+                       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 comma-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
+}
+
+# getcddbinfo
 # Finds an specific field from cddbinfo
-do_getcddbinfo()
+getcddbinfo()
 {
        case $1 in
        TRACKNAME1)
@@ -344,12 +421,15 @@ do_getcddbinfo()
        TRACKNAME)
                TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
                ;;
+       TRACK-INFO)
+               grep ^EXTT$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\\n/\n/g'
+               ;;
        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
@@ -360,51 +440,129 @@ 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)))
+
+       case "$CDDBMETHOD" in
+               cddb)
+                       printf -v DISCID "%08lx" $(( ($CDDBCKSUM % 0xff) << 24 | $TOTALTIME << 8 | $TRACKS))
+                       ;;
+               musicbrainz)
+                       # FIXME: don't assume the first track is 1
+                       echo "dasd: 1 $TRACKS $LEADIN $LEADOUT $OFFSETS "
+                       DISCID=$($MUSICBRAINZ --command calcid --discinfo 1 $TRACKS $LEADIN $LEADOUT $OFFSETS)
+                       ;;
+       esac
+
+       TRACKINFO="${DISCID} $((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 , \ )
+               run_command "" echo "Adding replaygain information..."
+               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)"
+                               GENRE="$(mungegenre "$GENRE")"
+                               YEAR=${CDYEAR:-$CDYEAR}
+                               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[$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 $FLACGAINOPTS "${OUTPUTFILES[@]}"
+                                       #run_command replaygain-flac true
                                        ;;
                                vorbis|ogg)
-                                       run_command replaygain-vorbis $VORBISGAIN --album "${OUTPUTFILES[@]}"
+                                       run_command replaygain-vorbis nice $ENCNICE $VORBISGAIN $VORBISGAINOPTS "${OUTPUTFILES[@]}"
                                        ;;
                                mp3)
-                                       run_command replaygain-mp3 $MP3GAIN -a "${OUTPUTFILES[@]}"
+                                       run_command replaygain-mp3 nice $ENCNICE $MP3GAIN $MP3GAINOPTS "${OUTPUTFILES[@]}"
                                        ;;
                                mpc)
-                                       run_command replaygain-mpc $MPPGAIN --auto "${OUTPUTFILES[@]}"
+                                       run_command replaygain-mpc nice $ENCNICE $MPPGAIN --auto "${OUTPUTFILES[@]}"
                                        ;;
                                *);;
                        esac
@@ -631,17 +789,22 @@ return 0
 # do_tag [tracknumber]
 # id3 tags a filename
 # variables used:
-# TRACKS, TRACKNAME, TRACKARTIST, TAGGER, TAGGEROPTS, VORBISCOMMENT, METAFLAC, 
-# COMMENT, DALBUM, DARTIST, CDYEAR, CDGENRE (and temporarily) ID3TAGV
+# TRACKS, TRACKNAME, TRACKARTIST, TAGGER, TAGGEROPTS, VORBISCOMMENT, METAFLAC, ATOMICPARSLEY
+# COMMENT, DALBUM, DARTIST, CDYEAR, CDGENRE
 do_tag ()
 {
        COMMENTOUTPUT="$(eval echo ${COMMENT})"
-       CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
+       if [ -z "$COMMENTOUTPUT" ]; then
+               COMMENTOUTPUT="$(getcddbinfo TRACK-INFO)"
+       fi
+       if [ "$CDDBMETHOD" = "cddb" ]; then
+               CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
+       fi
        run_command '' echo "Tagging track $1 of $TRACKS: $TRACKNAME..."
        # 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
@@ -649,22 +812,43 @@ do_tag ()
                mp3)
                        # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
                        GENREID=$(do_getgenreid "${CDGENRE}")
+                       # Set TPE2 in case we have a Various Artists rip.
+                       TPE2=""
+                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                               TPE2="Various"
+                       fi
        
                        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}" \
+                                               "${TPE2:+--set-user-text-frame=TPE2:$TPE2}" \
+                                               "$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" \
+                                               ${TPE2:+--TPE2 "$TPE2"} \
                                                "$ABCDETEMPDIR/track$1.$OUTPUT"
                                        ;;
                        esac
@@ -677,7 +861,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"
@@ -688,6 +874,9 @@ do_tag ()
                                                echo GENRE="$CDGENRE"
                                        fi      
                                        echo TRACKNUMBER=${TRACKNUM:-$1}
+                                       if [ -n "$DISCNUMBER" ]; then
+                                               echo DISCNUMBER="$DISCNUMBER"
+                                       fi
                                        echo CDDB=$CDDBDISCID
                                        if [ "$(eval echo ${COMMENT})" != "" ]; then
                                                case "$COMMENTOUTPUT" in
@@ -695,9 +884,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
@@ -718,6 +909,9 @@ do_tag ()
                                echo GENRE="$CDGENRE"
                        fi      
                        echo TRACKNUMBER="${TRACKNUM:-$1}"
+                       if [ -n "$DISCNUMBER" ]; then
+                               echo DISCNUMBER="$DISCNUMBER"
+                       fi
                        echo CDDB="$CDDBDISCID"
                        if [ "$(eval echo ${COMMENT})" != "" ]; then
                                case "$COMMENTOUTPUT" in
@@ -725,7 +919,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
@@ -734,7 +928,20 @@ do_tag ()
                        run_command tagtrack-$OUTPUT-$1 true
                        ;;
                m4a)
-                       run_command tagtrack-$OUTPUT-$1 true
+                       #  Use a temp-file of our choice. --overWrite seems to
+                       #  case core dumps with AtomicParsley 0.9.0
+                       ATOMICTEMPFILE="$ABCDETEMPDIR/track$1.m4a-atomic"
+
+                       VARIOUSBOOL="false"
+                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                               VARIOUSBOOL="true"
+                       fi
+
+                       #It has to be command file opts for AtomicParsley
+                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $ATOMICPARSLEY $ABCDETEMPDIR/track$1.m4a --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --tracknum ${TRACKNUM:-$1} --year "$CDYEAR" --genre "$CDGENRE" --compilation $VARIOUSBOOL --comment "$COMMENTOUTPUT" --output $ATOMICTEMPFILE
+                       if [ -f $ATOMICTEMPFILE ]; then
+                               mv "$ATOMICTEMPFILE" "$ABCDETEMPDIR/track$1.m4a"
+                       fi
                        ;;
                wav)
                        run_command tagtrack-$OUTPUT-$1 true
@@ -752,14 +959,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=
@@ -791,8 +999,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]
@@ -845,42 +1053,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
-                       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
-                       if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
+                       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
                                        ;;
                                *)
@@ -892,8 +1105,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
                                        ;;
                                *)
@@ -905,8 +1118,8 @@ do_encode ()
                                case "$2" in
                                %local*%)
                                        case "$FLACENCODERSYNTAX" in
-                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
-                                       esac
+                                       flac) $RUN_COMMAND nice $EFFECTIVE_NICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;;
+                                               esac
                                                ;;
                                        *)
                                                vecho -n "DISTMP3:"
@@ -921,13 +1134,12 @@ do_encode ()
                                                *=*) ;;
                                                *)   COMMENT="COMMENT=$COMMENT" ;;
                                        esac    
-                                       COMMENT="--comment \"$COMMENT\""
                                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"
+                               # Tag the file at encode time, as it can't be done after encoding.
+                               if [ "$DOTAG" = "y" ]; then
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
                                else
-                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
                                fi
                                ;;
                        mpc)    
@@ -937,12 +1149,12 @@ 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 $ENCNICE $AACENCODER $AACENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" -o "$OUT" "$IN"
+                               # Tag the file at encode time, as it can't be done after encoding.
+                               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"
@@ -996,7 +1208,7 @@ do_encode ()
 #                      esac
 #              done
 #              # Only remove .wav if the encoding succeeded
-#              if checkerrors "preprocess-(.{3,4})-$1"; then 
+#              if checkerrors "preprocess-(.{3,4})-$1"; then
 #                      run_command preprocess-$1 false
 #              else
 #                      run_command preprocess-$1 true
@@ -1034,7 +1246,7 @@ do_encode ()
 #                                      run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
 #                      esac
 #                      # Only remove .wav if the encoding succeeded
-#                      if checkerrors "postprocess-(.{3,4})-$1"; then 
+#                      if checkerrors "postprocess-(.{3,4})-$1"; then
 #                              run_command postprocess-$1 false
 #                      else
 #                              run_command postprocess-$1 true
@@ -1141,8 +1353,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:
                # ' ' -> '_'
@@ -1154,26 +1370,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")"
+               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")"
@@ -1201,7 +1429,7 @@ do_move ()
                                        ;;
                        esac
                        # Lets move the cue file
-                       if CUEFILE=$(checkstatus cuefile) >/dev/null ; then 
+                       if CUEFILE=$(checkstatus cuefile) >/dev/null ; then
                                if [ -r "$ABCDETEMPDIR/$CUEFILE" ]; then
                                        if checkstatus movecue-$OUTPUT; then :; else
                                                # Silence the Copying output since it overlaps with encoding processes...
@@ -1243,29 +1471,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
@@ -1274,6 +1505,7 @@ do_playlist ()
                                        read ERASEPLAYLIST
                                        case $ERASEPLAYLIST in
                                                e|E|a|A|k|K) DONE=y ;;
+                                               "") ERASEPLAYLIST=e ; DONE=y ;;
                                                *) ;;
                                        esac
                                done
@@ -1293,18 +1525,18 @@ do_playlist ()
                        do
                                # Shares some code with do_move since the filenames have to match
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                               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
@@ -1332,6 +1564,171 @@ 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
+       local CUEWAVFILE
+
+       if [ "$1" = --wholedisc ] ; then
+               MODE=INDEX
+       else
+               MODE=PREGAP
+       fi
+
+       vecho "One track is $ONETRACK"
+       TRACKFILE="$(mungefilename "$TRACKNAME")"
+       ARTISTFILE="$(mungefilename "$TRACKARTIST")"
+       ALBUMFILE="$(mungefilename "$DALBUM")"
+       if [ "$ONETRACK" = "y" ]; then
+               if [ "$VARIOUSARTISTS" = "y" ]; then
+                       CUEWAVFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
+               else
+                       CUEWAVFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
+               fi
+               vecho "Cue wav file is $CUEWAVFILE"
+       else
+               CUEWAVFILE="dummy.wav"
+       fi
+
+       set -- $TRACKINFO
+
+       DISCID=$1
+       TRACKS=$2
+       shift 2
+
+       echo REM DISCID $DISCID
+       echo FILE \""$CUEWAVEFILE"\" 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 ()
@@ -1345,17 +1742,65 @@ do_discid ()
                vecho -n "Getting CD track info... "
                # In OSX, unmount the disc before a query
                if [ "$OSFLAVOUR" = "OSX" ]; then
-                       disktool -u ${CDROM#/dev/}
-               fi
-               if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
-                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
-               else
-                       case "$CDDBMETHOD" in
-                               cddb) TRACKINFO=$($CDDISCID $CDROM) ;;
-                               # FIXME # musicbrainz needs a cleanup
-                               musicbrainz) TRACKINFO=$($MUSICBRAINZ -c $CDROM ) ;;
-                       esac
+                       diskutil unmount ${CDROM#/dev/}
                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 | grep -E "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) * 75 / 44100 ))
+                                                       LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) * 75 / 44100 ))
+                                                       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" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
+#                              CDPARANOIAAUDIOTRACKS="$TRACKS"
+#
+#                              LEADOUT="$(echo "$CDPARANOIAOUTPUT" | grep -Eo '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
+#                              OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')"
+#                              makeids
+#                              ;;
+                       *)
+                               case "$CDDBMETHOD" in
+                                       cddb) TRACKINFO=$($CDDISCID "$CDROM") ;;
+                                       musicbrainz) TRACKINFO=$($MUSICBRAINZ --command id --device "$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
@@ -1369,7 +1814,7 @@ do_discid ()
                fi
                # In OSX, remount the disc again
                if [ "$OSFLAVOUR" = "OSX" ]; then
-                       disktool -m ${CDROM#/dev/}
+                       diskutil mount ${CDROM#/dev/}
                fi
                WEHAVEACD=y
                DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
@@ -1391,17 +1836,17 @@ 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?"
                                                fi
-                                               TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
+                                               TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[: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.
@@ -1471,11 +1916,11 @@ do_discid ()
                        exit 1
                fi
                echo -n .
-               # It's a directory, let's see if it's owned by us
-               if [ ! -O "$ABCDETEMPDIR" ]; then
+               # It's a directory, let's see if it's writable by us
+               if [ ! -r "$ABCDETEMPDIR" ] || [ ! -w "$ABCDETEMPDIR" ] || [ ! -x "$ABCDETEMPDIR" ]; then
                        # Nope, complain and exit
                        echo >&2
-                       echo "abcde: directory $ABCDETEMPDIR already exists and is not owned by you." >&2
+                       echo "abcde: directory $ABCDETEMPDIR already exists and is not writeable." >&2
                        echo "Please investigate, remove it, and rerun abcde." >&2
                        exit 1
                fi
@@ -1484,7 +1929,7 @@ do_discid ()
                if [ ! -f "$ABCDETEMPDIR/discid" ]; then
                        # Wipe and start fresh
                        echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
-                       echo -n "this directory to continue. Continue? [y/n] (n)" >&2
+                       echo -n "this directory to continue. Continue [y/N]? " >&2
                        if [ "$INTERACTIVE" = "y" ]; then
                                read ANSWER
                        else
@@ -1527,17 +1972,28 @@ do_discid ()
                # 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
@@ -1568,16 +2024,43 @@ 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"
+                               # When making a single-track rip, put the
+                               # actual file name into the file declaration
+                               # in the cue file so that it is usable by
+                               # music players and the like
+                               elif [ "$ONETRACK" = "y" ] &&
+                                               echo "$line" | grep '^FILE "dummy.wav" WAVE' > /dev/null 2>&1 ; then
+
+                                       TRACKFILE="$(mungefilename "$TRACKNAME")"
+                                       ARTISTFILE="$(mungefilename "$TRACKARTIST")"
+                                       ALBUMFILE="$(mungefilename "$DALBUM")"
+
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
+                                       fi
+
+                                       echo "FILE \"$OUTPUTFILE\" WAVE" >> "$CUEFILE_OUT"
+                                       continue
                                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
@@ -1621,53 +2104,254 @@ 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 | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
+                                               elif echo $CDDBLOCALCHOICE | grep -E "[[: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]? " >&2
+                               #else
+                                       echo -n "Locally cached CDDB entry found, use it [Y/n]? " >&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_cdtext
+# Try to read CD-Text from the drive using icedax / cdda2wav
+do_cdtext ()
 {
-       :
+       if new_checkexec icedax; then
+               CDTEXT_READER=icedax
+       elif new_checkexec cdda2wav; then
+               CDTEXT_READER=cdda2wav
+    else
+               # Didn't find either, bail
+               return 0
+       fi
+
+       if [ "$CDROMID" = "" ]; then
+               CDDA2WAVCDROM="$CDROM"
+       else
+               CDDA2WAVCDROM="$CDROMID"
+       fi
+
+       # Do we have CD-Text on the disc (and can the drive read it?)
+       ${CDTEXT_READER} -J -N -D ${CDDA2WAVCDROM} > $ABCDETEMPDIR/cd-text 2>&1
+       grep -q '^CD-Text: detected' $ABCDETEMPDIR/cd-text
+       ERRORCODE=$?
+       if [ $ERRORCODE -ne 0 ]; then
+               # No CD-Text found, bail
+               return 0
+       fi
+
+       rm -f "$ABCDETEMPDIR/cddbchoices"
+       CDDBCHOICES=1
+       # Make an empty template
+       $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.1"
+       echo -n "Retrieved 1 CD-Text match..." >> "$ABCDETEMPDIR/cddbchoices"
+       echo "done." >> "$ABCDETEMPDIR/cddbchoices"
+       echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
+       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+       ATITLE=$(grep -e '^Album title:' ${ABCDETEMPDIR}/cd-text | cut -c14- )
+       echo "200 none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
+       # List out disc title/author and contents
+       echo ---- ${ATITLE} ---- >> "$ABCDETEMPDIR/cddbchoices"
+       for TRACK in $(f_seq_row 1 $TRACKS)
+       do
+               TRACKM1=$(($TRACK - 1))
+               TITLE="$(grep -E ^Track\ +$TRACK: "$ABCDETEMPDIR/cd-text" | tr -d \\r\\n | sed 's~^Track ..: .~~g;'"s~'$~~g")"
+               echo "$TRACK: $TITLE" >> "$ABCDETEMPDIR/cddbchoices"
+               sed -i "s~^TTITLE${TRACKM1}=.*~TTITLE${TRACKM1}=${TITLE}~" $ABCDETEMPDIR/cddbread.1
+       done
+       sed -i "s~^DTITLE=.*~DTITLE=${ATITLE}~" $ABCDETEMPDIR/cddbread.1
+       echo >> "$ABCDETEMPDIR/cddbchoices"
+       echo "cdtext-readcomplete" >> "$ABCDETEMPDIR/status"
 }
 
-do_musizbrainz ()
+# do_musicbrainz
+# Work with the musicbrainz WS API, then transform the results here so
+# they look (very) like the results from CDDB. Maybe not the best way
+# to go, but it Works For Me (TM)
+
+do_musicbrainz ()
 {
-       :
+       if checkstatus musicbrainz-readcomplete; then :; else
+               vecho "Obtaining Musicbrainz results..."
+               # If MB is to be used, interpret the query results and read all
+               # the available entries.
+               rm -f "$ABCDETEMPDIR/cddbchoices"
+               CDDBCHOICES=1 # Overridden by multiple matches
+               MBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
+               ${MUSICBRAINZ} --command data --discid "$MBDISCID" --workdir $ABCDETEMPDIR
+
+               # The helper script will write disc matches out to
+               # cddbread.*. Count how many we have
+               NUM_RESPONSES=$(echo ${ABCDETEMPDIR}/cddbread.* | wc -w)
+               if [ "$NUM_RESPONSES" -eq 1 ] ; then
+                       # One exact match
+                       echo -n "Retrieved 1 Musicbrainz match..." >> "$ABCDETEMPDIR/cddbchoices"
+                       echo "done." >> "$ABCDETEMPDIR/cddbchoices"
+                       echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
+                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                       ATITLE=$(grep -e '^DTITLE=' ${ABCDETEMPDIR}/cddbread.1 | cut -c8- )
+                       echo "200 none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
+                       # List out disc title/author and contents
+                       echo ---- ${ATITLE} ---- >> "$ABCDETEMPDIR/cddbchoices"
+                       for TRACK in $(f_seq_row 1 $TRACKS)
+                       do
+                               echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
+                       done
+                       echo >> "$ABCDETEMPDIR/cddbchoices"
+               elif [ "$NUM_RESPONSES" -eq 0 ] ; then
+                       # No matches. Use the normal cddb template for the user to
+                       # fill in
+                       echo "No Musicbrainz match." >> "$ABCDETEMPDIR/cddbchoices"
+                       $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
+                       # List out disc title/author and contents of template
+                       echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
+                       UNKNOWNDISK=y
+                       for TRACK in $(f_seq_row 1 $TRACKS)
+                       do
+                               echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
+                       done
+                       echo >> "$ABCDETEMPDIR/cddbchoices"
+                       echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
+                       echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
+                       echo 503 > "$ABCDETEMPDIR/cddbquery"
+               else
+                       echo "210 Found exact matches, list follows (until terminating .)" > "$ABCDETEMPDIR/cddbquery"
+                       echo "Multiple Musicbrainz matches:" >> "$ABCDETEMPDIR/cddbchoices"
+                       for file in $ABCDETEMPDIR/cddbread.*
+                       do
+                               X=$(echo $file | sed 's/^.*cddbread\.//g')
+                               echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
+                               ATITLE=$(grep -e '^DTITLE=' ${ABCDETEMPDIR}/cddbread.$X | cut -c8- )
+                               echo "none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
+                               # List out disc title/author and contents
+                               echo "#$X: ---- ${ATITLE} ----" >> "$ABCDETEMPDIR/cddbchoices"
+                               for TRACK in $(f_seq_row 1 $TRACKS)
+                               do
+                                       echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
+                               done
+                               echo >> "$ABCDETEMPDIR/cddbchoices"
+                       done
+                       echo "." >> "$ABCDETEMPDIR/cddbquery"
+               fi
+               echo "musicbrainz-readcomplete" >> "$ABCDETEMPDIR/status"
+       fi
 }
 
 # do_cddbstat
@@ -1688,15 +2372,25 @@ do_cddbstat ()
                                RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
                                case "$RESPONSECODE" in
                                210)    # 210 OK, status information follows (until terminating `.')
-                                       rc=0;
+                                       rc=0
                                        ;;
-                               501|*)  # 501 Illegal CDDB protocol level: <n>. 
+                               501)  # 501 Illegal CDDB protocol level: <n>.
                                        CDDBPROTO=`expr $CDDBPROTO - 1`
                                        ;;
-                               esac 
+                               *)      # Try a cddb query, since freedb2.org doesn't support the stat or ver commands
+                                       # FreeDB TESTCD disc-id is used for query
+                                       $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST 03015501 1 296 344 > "$ABCDETEMPDIR/cddbstat"
+                                       RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
+                                       case "$RESPONSECODE" in
+                                               2??)    # Server responded, everything seems OK
+                                                       rc=0
+                                                       ;;
+                                       esac
+                                       ;;
+                               esac
                        done
                        if test $rc -eq 1; then
-                               CDDBAVAIL="n" 
+                               CDDBAVAIL="n"
                        fi
                fi
                echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
@@ -1715,8 +2409,8 @@ do_cddbquery ()
                if [ "$CDDBAVAIL" = "n" ]; then
                        ERRORCODE=no_query
                        echo 503 > "$ABCDETEMPDIR/cddbquery"
-               # The default CDDBLOCALSUCCESS is "n"
-               # This part will be triggered if the user CDDB repo does not 
+               # 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
                        vecho "Querying the CDDB server..."
@@ -1802,7 +2496,7 @@ do_cddbread ()
                        if [ "$(wc -l < "$ABCDETEMPDIR/cddbquery" | tr -d ' ')" -eq 3 ]; then
                                echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
                                tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
-                               echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                                                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
                        else
                                echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
                        fi
@@ -1854,7 +2548,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
@@ -1862,8 +2556,12 @@ do_cddbedit ()
                                CHOICE=$(checkstatus cddb-choice)
                                if [ -n "$CHOICE" ] ; then
                                        case $CDDBCHOICES in
-                                               -1) log error "CDDB query failed!" 
-                                                       exit 1
+                                               -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" ;;
                                                *)
@@ -1888,14 +2586,14 @@ 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 "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" ; then
+                                               if echo $CDDBCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
                                                        if [ ! X"$DIFF" = "X" ]; then
                                                                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
+                                                                  [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then
+                                                                       echo "Invalid diff range. Please select two comma-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
@@ -1912,7 +2610,7 @@ do_cddbedit ()
                                                        else
                                                                echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
                                                        fi
-                                               elif echo $CDDBCHOICE | egrep -q "[[:space:]]*[[:digit:]]+[[:space:]]*" ; then
+                                               elif echo $CDDBCHOICE | grep -E "[[: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
@@ -1942,7 +2640,7 @@ do_cddbedit ()
                                if [ "$USELOCALRESP" = "y" ]; then :; else
                                        if [ -n "$CHOICE" ] ; then
                                                case $CDDBCHOICES in
-                                                       0) 
+                                                       0)
                                                        UNKNOWNDISK=y
                                                        echo "Selected template."
                                                        ;;
@@ -1963,7 +2661,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
@@ -2042,11 +2740,11 @@ do_cddbedit ()
 
        # Some heuristics first. Look at Disc Title, and if it starts with
        # "Various", then we'll assume Various Artists
-       if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
+       if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | grep -Eci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
                echo "Looks like a Multi-Artist CD" >&2
                VARIOUSARTISTS=y
        else
-               echo -n "Is the CD multi-artist? [y/n] (n): " >&2
+               echo -n "Is the CD multi-artist [y/N]? " >&2
                if [ "$INTERACTIVE" = "y" ]; then
                        read VARIOUSARTISTS
                else
@@ -2058,7 +2756,7 @@ do_cddbedit ()
                # Set a default
                DEFAULTSTYLE=1
                # Need NUMTRACKS before cddb-tool will return it:
-               NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
+               NUMTRACKS=$(grep -E '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
                if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
                        # More than 1/2 tracks contain a "/", so guess forward
                        DEFAULTSTYLE=1
@@ -2124,11 +2822,11 @@ do_cddbedit ()
        echo "variousartists=$VARIOUSARTISTS" >> "$ABCDETEMPDIR/status"
        echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
 
-       if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
+       if [ "$EDITCDDB" = "y" ] && [ "$CDDBMETHOD" = "cddb" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
                if [ "$CDDBDATAMD5SUM" != "" ]  && [ "$CDDBDATAMD5SUM" != "$($MD5SUM "$CDDBDATA" | cut -d " " -f 1)" ]; then
                        # This works but does not have the necessary error checking
                        # yet. If you are familiar with the CDDB spec
-                       # (see http://www.freedb.org/src/latest/DBFORMAT) 
+                       # (see http://www.freedb.org/src/latest/DBFORMAT)
                        # and can create an error-free entry on your own, then put
                        # UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE=y in your
                        # abcde.conf to enable it. Put CDDBSUBMIT=email@address in
@@ -2137,7 +2835,7 @@ do_cddbedit ()
 
                        # submit the modified file, if they want
                        if [ "$NOSUBMIT" != "y" ]; then
-                               echo -n "Do you want to submit this entry to $CDDBSUBMIT? [y/n] (n): "
+                               echo -n "Do you want to submit this entry to $CDDBSUBMIT [y/N]? "
                                read YESNO
                                while [ "$YESNO" != "y" ] && [ "$YESNO" != "n" ] && [ "$YESNO" != "Y" ] && \
                                        [ "$YESNO" != "N" ] && [ "$YESNO" != "" ]
@@ -2153,10 +2851,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
 
@@ -2165,7 +2865,7 @@ do_cddbedit ()
 
 # do_cdread [tracknumber]
 # do_cdread onetrack [firsttrack] [lasttrack]
-# 
+#
 do_cdread ()
 {
        # The commands here don't go through run_command because they're never supposed to be silenced
@@ -2174,14 +2874,17 @@ do_cdread ()
                # FIXME # Add the possibility of grabbing ranges of tracks in onetrack
                # FIXME # Until then, we grab the whole CD in one track, no matter what
                # the user said
-               # We need the first and last track for cdda2wav
+               # We need the first and last track for cdda2wav/icedax
                FIRSTTRACK=$2
-               LASTTRACK=$3
+               LASTTRACK=$(expr $3 + 0)
                UTRACKNUM=$FIRSTTRACK
                case "$CDROMREADERSYNTAX" in
                        flac) READTRACKNUMS="$FIRSTTRACK.1-$(($LASTTRACK + 1)).0" ;;
-                       cdparanoia) READTRACKNUMS="$FIRSTTRACK-$LASTTRACK" ;;
-                       cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTRACK" ;;
+                       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 | icedax) READTRACKNUMS="$FIRSTTRACK+$LASTTRACK" ;;
                        *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
                                exit 1 ;;
                esac
@@ -2192,7 +2895,7 @@ do_cdread ()
        if [ "$USEPIPES" = "y" ]; then
                TEMPARG="PIPERIPPER_$CDROMREADERSYNTAX"
                FILEARG="$( eval echo "\$$TEMPARG" )"
-               REDIR=""
+               REDIR="y"
                PIPE_MESSAGE="and encoding "
        else
                WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
@@ -2208,13 +2911,13 @@ do_cdread ()
                                FILEARG="$WAVDATA"
                                ;;
                esac
-               REDIR=">&2"
+               REDIR="n"
        fi
        if [ "$1" = "onetrack" ]; then
                echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK as one track ..." >&2
        else
                if [ -r "$CDDBDATA" ]; then
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
                else
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
@@ -2224,15 +2927,21 @@ 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" ;;
-               cdparanoia) 
-                       echo "nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;" > /tmp/log
-                       nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
-               cdda2wav)
+                       # 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)
+                       if [ "$REDIR" = "y" ]; then
+                               nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" >&2
+                       else
+                               nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG"
+                       fi;;
+
+               cdda2wav | icedax)
                        if [ "$OSFLAVOUR" = "OSX" ] ; then
-                               # Hei, we have to unmount the device before running anything like cdda2wav in OSX
-                               disktool -u ${CDROM#/dev/} 0
-                               # Also, in OSX the cdrom device for cdda2wav changes...
+                               # Hei, we have to unmount the device before running anything like cdda2wav/icedax in OSX
+                               diskutil unmount ${CDROM#/dev/} 0
+                               # Also, in OSX the cdrom device for cdda2wav/icedax changes...
                                CDDA2WAVCDROM="IODVDServices"
                        elif [ "$OSFLAVOUR" = "FBSD" ] ; then
                                CDDA2WAVCDROM="$CDROMID"
@@ -2243,12 +2952,19 @@ do_cdread ()
                                        CDDA2WAVCDROM="$CDROMID"
                                fi
                        fi
-                       nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR
-                       ;;
+                       if [ "$REDIR" = "y" ]; then
+                               nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" >&2
+                       else
+                               nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG"
+                       fi ;;
                ## 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)
+               if [ "$REDIR" = "y" ]; then
+                               nice $READNICE $CDROMREADER -d "$CDROM" -v $UTRACKNUM "$FILEARG" >&2
+                       else
+                               nice $READNICE $CDROMREADER -d "$CDROM" -v $UTRACKNUM "$FILEARG"
+                       fi ;;
                cddafs)
                        # Find the track's mounted path
                        REALTRACKNUM=$(expr $UTRACKNUM + 0)
@@ -2256,15 +2972,23 @@ do_cdread ()
                        FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
                        # If the file exists, copy it
                        if [ -e "$FILEPATH" ] ; then
-                               nice $READNICE $CDROMREADER "$FILEPATH" "$FILEARG" $REDIR
+                               if [ "$REDIR" = "y" ]; then
+                                       nice $READNICE $CDROMREADER "$FILEPATH" "$FILEARG" >&2
+                               else
+                                       nice $READNICE $CDROMREADER "$FILEPATH" "$FILEARG"
+                               fi
                        else
                                false
                        fi ;;
-               debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
-                       ;;
+               debug)
+                       if [ "$REDIR" = "y" ]; then
+                               nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -w $UTRACKNUM-[:1] "$FILEARG" >&2
+                       else
+                               nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -w $UTRACKNUM-[:1] "$FILEARG"
+                       fi ;;
        esac
        RETURN=$?
-       # If we get some error or we get some missing wav 
+       # If we get some error or we get some missing wav
        # (as long as we dont use pipes)
        if [ "$RETURN" != "0" -o \( ! -s "$WAVDATA" -a X"$USEPIPES" != "Xy" \) ]; then
                # Thank goodness errors is only machine-parseable up to the
@@ -2283,16 +3007,16 @@ 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
 }
 
 # do_cdspeed
 # No values accepted, only uses env variables
-do_cdspeed () 
+do_cdspeed ()
 {
        if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
                vecho "Setting CD speed to ${CDSPEEDVALUE}x"
@@ -2303,12 +3027,25 @@ do_cdspeed ()
 
 # vecho [message]
 #
-# vecho outputs a message if EXTRAVERBOSE is selected
+# vecho outputs a message if EXTRAVERBOSE is 1 or more
 vecho ()
 {
-if [ x"$EXTRAVERBOSE" != "x" ]; then
+if [ x"$EXTRAVERBOSE" != "x" ] && [ $EXTRAVERBOSE -gt 0 ] ; then
        case $1 in
-               warning) log warning "$@" ;;
+               warning) shift ; log warning "$@" ;;
+               *) echo "$@" ;;
+       esac
+fi
+}
+
+# vvecho [message]
+#
+# vvecho outputs a message if EXTRAVERBOSE is 2 or more
+vvecho ()
+{
+if [ x"$EXTRAVERBOSE" != "x" ] && [ $EXTRAVERBOSE -gt 1 ] ; then
+       case $1 in
+               warning) shift ; log warning "$@" ;;
                *) echo "$@" ;;
        esac
 fi
@@ -2320,7 +3057,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
@@ -2357,6 +3094,13 @@ post_read ()
 :
 }
 
+# post_encode
+# Empty post_encode function, to be defined in the configuration file.
+post_encode ()
+{
+:
+}
+
 ###############################################################################
 # End of functions
 #
@@ -2366,13 +3110,15 @@ post_read ()
 # Builtin defaults
 
 # CDDB
-# Defaults to FreeDB, but a python musicbrainz can be used
+# Defaults to FreeDB, but musicbrainz can be used too, via the abcde-musicbrainz-tool script
 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"
 
@@ -2414,8 +3160,9 @@ KEEPWAVS=n
 PADTRACKS=n
 NOGAP=n
 BATCHNORM=n
+NOCDDBQUERY=n
 
-# If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
+# If using scsi devices, cdda2wav/icedax needs a CDROMID, instead of a device node
 # i.e. CDROMID="1,0,0"
 CDROMID=""
 # If we are using the IDE bus, we need CDPARANOIACDROMBUS defined as "d"
@@ -2446,18 +3193,21 @@ AACENC=faac
 ID3=id3
 ID3V2=id3v2
 EYED3=eyeD3
+VORBISCOMMENT=vorbiscomment
+METAFLAC=metaflac
+AACTAG=faac
+ATOMICPARSLEY=AtomicParsley
+
 CDPARANOIA=cdparanoia
-CDDA2WAV=cdda2wav
+CDDA2WAV=icedax
 DAGRAB=dagrab
 CDDAFS=cp
 CDDISCID=cd-discid
 CDDBTOOL=cddb-tool
-MUSICBRAINZ=musicbrainz-get-tracks
+MUSICBRAINZ=abcde-musicbrainz-tool
 EJECT=eject
 MD5SUM=md5sum
 DISTMP3=distmp3
-VORBISCOMMENT=vorbiscomment
-METAFLAC=metaflac
 NORMALIZE=normalize-audio
 CDSPEED=eject
 VORBISGAIN=vorbisgain
@@ -2466,7 +3216,7 @@ MPPGAIN=replaygain
 MKCUE=mkcue
 MKTOC=cdrdao
 DIFF=diff
-CUE2DISCID=cue2discid
+CUE2DISCID=builtin
 
 # Options for programs called from abcde
 # mp3
@@ -2477,11 +3227,14 @@ BLADEENCOPTS=
 L3ENCOPTS=
 XINGMP3ENCOPTS=
 MP3ENCOPTS=
+MP3GAINOPTS="-a -k"
 # ogg
 VORBIZEOPTS=
 OGGENCOPTS=
+VORBISGAINOPTS="--album"
 # flac
 FLACOPTS=
+FLACGAINOPTS="--add-replay-gain"
 # speex
 SPEEXENCOPTS=
 # mpc
@@ -2513,15 +3266,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: 
+# This option is basicaly for Debian package dependencies:
 # List of prefered outputs - by default, run with whatever we have in the path
-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
+DEFAULT_CDROMREADERS="cdparanoia icedax cdda2wav"
+
+# 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
@@ -2530,15 +3291,21 @@ if [ X$(uname) = "XFreeBSD" ] ; then
 elif [ X$(uname) = "XDarwin" ] ; then
        HTTPGET=curl
        OSFLAVOUR=OSX
-       # We should have disktool in OSX, but let's be sure...
-       NEEDDISKTOOL=y
+       # We should have diskutil in OSX, but let's be sure...
+       NEEDDISKUTIL=y
        CDROMREADERSYNTAX=cddafs
 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
@@ -2549,6 +3316,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
@@ -2571,10 +3344,10 @@ fi
 
 if [ "$HTTPGETOPTS" = "" ] ; then
        case $HTTPGET in
-               wget) HTTPGETOPTS="-q -O -";;
+               wget) HTTPGETOPTS="-q -nv -e timestamping=off -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
@@ -2587,18 +3360,32 @@ if [ "$CDROM" = "" ] ; then
                CDROM=/dev/cdroms/cdrom0
        elif [ -e /dev/cdrom ]; then
                CDROM=/dev/cdrom
+       elif [ -e /dev/sr0 ]; then
+               CDROM=/dev/sr0
        elif [ -e /dev/cd0c ]; then
                CDROM=/dev/cd0c
        elif [ -e /dev/acd0c ]; then
                CDROM=/dev/acd0c
        elif [ -e /dev/disk1 ]; then
                CDROM=/dev/disk1
+       elif [ "$OSFLAVOUR" = "OSX" ] && [[ $(diskutil list) =~ CD_part.*(disk.)$'\n' ]]; then
+               CDROM=/dev/${BASH_REMATCH[1]}
        fi
 fi
 
+# We used to use EXTRAVERBOSE=y to turn on more debug output. Now
+# that's changed to a number to allow for more control. If
+# EXTRAVERBOSE=y, set it to 1 for backwards compatibility.
+if [ "$EXTRAVERBOSE" = "y" ]; then
+       EXTRAVERBOSE=1
+fi
+if [ "$EXTRAVERBOSE" = "n" ]; then
+       EXTRAVERBOSE=0
+fi
+
 # Parse command line options
-#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
+#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:pPq:r:s:S:t:T:UvVxX:w:W:z opt ; do
        case "$opt" in
                1) ONETRACK=y ;;
                a) ACTIONS="$OPTARG" ;;
@@ -2609,7 +3396,6 @@ while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
                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" ;;
@@ -2623,30 +3409,35 @@ 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 ;;
-               v) 
+               U) CDDBPROTO=5 ;;
+               v)
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
                   echo "abcde -h for extra help"
                   exit
                   ;;
-               V) EXTRAVERBOSE="y" ;;
+               V) EXTRAVERBOSE=$(($EXTRAVERBOSE + 1)) ;;
                x) EJECTCD="y" ;;
+               X) CUE2DISCID="$OPTARG" ;;
                w) COMMENT="$OPTARG" ;;
-               W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
-                    STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
+               W) if echo $OPTARG | grep "[[:digit:]]" > /dev/null 2>&1 ; then
+                        STARTTRACKNUMBER="${OPTARG}01"
+                        STARTTRACKNUMBERTAG="y"
+                        COMMENT="CD${OPTARG}"
+                        DISCNUMBER="${OPTARG}"
                   else
-                    log error "argument of -W must be integer"
+                        log error "argument of -W must be integer"
                         exit 1
                   fi
                   ;;
@@ -2657,23 +3448,39 @@ 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 [ -x $( which $DEFAULT_CDROMREADER ) ]; then
+               if new_checkexec $DEFAULT_CDROMREADER; then
                        CDROMREADERSYNTAX=$DEFAULT_CDROMREADER
                        break
                fi
@@ -2686,14 +3493,14 @@ if [ "$CDROMREADERSYNTAX" = "" ]; then
 fi
 
 # Decide if we can continue.
-if [ "$ONETRACK" = "y" ]; then 
+if [ "$ONETRACK" = "y" ]; then
        # FIXME # remove check as soon as we find out about the other readers
        case "$CDROMREADERSYNTAX" in
                flac) ;;
                cdparanoia) ;;
-               cdda2wav) ;;
+               cdda2wav | icedax) ;;
                *) log error "$CDROMREADERSYNTAX does not support ONETRACK mode"
-                  exit 1 ;;
+                       exit 1 ;;
        esac
        if [ "$BATCHNORM" = "y" ]; then
                log warning "BATCHNORM mode is not compatible with ONETRACK mode. Disabling..."
@@ -2711,14 +3518,18 @@ if [ "$ONETRACK" = "y" ]; then
 else
        while [ $# -gt 0 ]; do
                # Range parsing code courtesy of Vincent Ho
-               RSTART=$(echo $1 | cut -f1 -d-)
-               REND=$(echo $1 | cut -f2 -d-)
-               if [ "$RSTART" = "$REND" ]; then
-                       NEWTRACKS="$RSTART"
+               # Cleaned up to use shell built-ins by Charles Steinkuehler
+               if [ "${1#*[^0-9-]}" != "$1" ]; then
+                       log error "syntax error while processing track numbers ($1)"
+                       exit 1
                else
-                       NEWTRACKS=$(f_seq_line $RSTART $REND)
+                       RSTART=${1%%-*}
+                       REND=${1##*-}
+                       while [ ${RSTART:=1} -le ${REND:=0} ] ; do
+                               TRACKQUEUE="$TRACKQUEUE $RSTART"
+                               RSTART=$(( $RSTART + 1 ))
+                       done
                fi
-               TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
                shift
        done
 fi
@@ -2739,10 +3550,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;;
@@ -2770,13 +3585,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 [ X"$CDROM" != "X" ] ; then
+       if ( [ "$CDROMREADERSYNTAX" = "cdda2wav" ] || [ "$CDROMREADERSYNTAX" = "icedax" ] ) && [ "$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
@@ -2842,13 +3655,13 @@ if [ X"$LOWDISK" = "Xy" ]; then
 fi
 
 # BATCHNORM pre-tests, before we get into serious problems
-# Not compatible with 
+# 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.
+# 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)"
@@ -2872,7 +3685,7 @@ case "$CDROMREADERSYNTAX" in
                CDROMREADER="$CDPARANOIA"
                CDROMREADEROPTS="$CDPARANOIAOPTS"
                ;;
-       cdda2wav)
+       cdda2wav | icedax)
                CDROMREADER="$CDDA2WAV"
                CDROMREADEROPTS="$CDDA2WAVOPTS"
                ;;
@@ -2900,7 +3713,7 @@ 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- )" ;;
@@ -2939,6 +3752,7 @@ do
                        [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
                        [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
                        [ "$DOREPLAYGAIN" = "y" ] && NEEDMETAFLAC=y
+                       [ "$ONETRACK" = "y" ] && [ "$DOCUE" = "y" ] && NEEDMETAFLAC=y
                        ;;
                spx)
                        [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
@@ -2950,10 +3764,11 @@ do
                        ;;
                m4a)
                        [ "$AACENCODERSYNTAX" = "default" ] && AACENCODERSYNTAX=faac
+                       [ "$DOTAG" = "y" ] && CHECKATOMICPARSLEY=y
                        ;;
                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
                        ;;
@@ -3008,8 +3823,11 @@ case "$FLACENCODERSYNTAX" in
        flac)
                FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
                FLACENCODER="$FLAC"     
+               if [ "$DOREPLAYGAIN" = "y" ]; then
+                       FLACENCODEROPTS="${FLACENCODEROPTS} --replay-gain"
+               fi
                # FLAC streams can be encapsulated on a Ogg transport layer
-               if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
+               if echo "$FLACENCODEROPTS" | grep -E -- "(^| )--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
@@ -3037,8 +3855,8 @@ case "$AACENCODERSYNTAX" in
                AACENCODER="$AACENC"
                ;;
 esac
-# and which tagger
 
+# and which tagger
 if [ "$ID3TAGV" = "1" ]; then
        TAGGER="$ID3"
        TAGGEROPTS="$ID3OPTS"
@@ -3047,9 +3865,9 @@ else
        TAGGEROPTS="$ID3V2OPTS"
 fi
 
-# Specific for NOGAP is the use of lame. Another encoder fails...
+# NOGAP is specific to lame. Other encoders fail ...
 if [ "$NOGAP" = "y" ] && [ ! "$MP3ENCODER" = "lame" ]; then
-       log warning "the NOGAP option is specific of lame. Deactivating..."
+       log warning "the NOGAP option is specific to lame. Deactivating..."
        NOGAP=n
 fi
 
@@ -3061,6 +3879,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"
@@ -3084,7 +3908,7 @@ if [ "$DISTMP3NICE" ]; then
 fi
 
 # Don't check for stuff if it's not needed
-if [ "$REMOTEHOSTS" ]; then 
+if [ "$REMOTEHOSTS" ]; then
        NEEDDISTMP3=y
 fi
 if [ "$DONORMALIZE" = "y" ]; then
@@ -3100,15 +3924,15 @@ if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; 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
@@ -3165,69 +3989,81 @@ fi
 # Make sure a buncha things exist
 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
        $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
+       $AACENCODER $CDDBTOOL \
+       ${NEEDATOMICPARSLEY+$ATOMICPARSLEY} \
        ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
        ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
        ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
-       ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
+       ${NEEDDISKUTIL+diskutil} ${NEEDCDSPEED+$CDSPEED} \
        ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMP3GAIN+$MP3GAIN} \
-       ${NEEDMPPGAIN+$MPPGAIN} \
-       ${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"
+if [ "$CHECKATOMICPARSLEY" = "y" ]; then
+       if ! new_checkexec "$ATOMICPARSLEY"; then
+               echo "WARNING: $ATOMICPARSLEY Not Found Not Post-Tagging!"
+               DOTAG='n'
+       else
+               echo "Using $ATOMICPARSLEY To Tag AAC Tracks."
+       fi
+fi
 
-# 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 | grep -E "[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
 
-case "$CDDBMETHOD" in
-       cddb)
-               do_discid # Get ABCDETEMPDIR created and status file initialized
-               ;;
-       musicbrainz)
-               do_musicbrainz
-               ;;
-esac
+# Get ABCDETEMPDIR created and status file initialized
+do_discid
 
 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
+       else
+               if [ "$CDDBLOCALSTATUS" = "notfound" ] ; then
                        case "$CDDBMETHOD" in
                                cddb)
                                        do_cddbstat
@@ -3239,6 +4075,13 @@ if [ "$DOCDDB" = "y" ]; then
                                        ;;
                        esac
                fi
+               CHOICE=$(checkstatus cddb-choice)
+               if [ $CHOICE = 0 ] ; then
+                       # We don't have any information at all; try to fall back
+                       # to CD-Text for basic information
+                       vecho "No CDDB information found, trying cdtext from the CD"
+                       do_cdtext
+               fi
        fi
        do_cddbedit
 
@@ -3265,6 +4108,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
 
 (
@@ -3282,12 +4134,14 @@ if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
        echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
 fi
 
-if [ "$ONETRACK" = "y" ]; then 
+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
@@ -3313,7 +4167,7 @@ else
                        fi
                fi
                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.
@@ -3353,11 +4207,11 @@ post_read
 # We are now finished with the cdrom - it can be safely ejected. Note that
 # abcde will not have completed yet.
 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
-       # We check if the disk we are processing is actually the disk inside the 
+       # We check if the disk we are processing is actually the disk inside the
        # CD tray. If not, we do not eject the CD, since it might be so that the
        # user ejected it manually.
        #CURRENTTRACKINFO=$($CDDISCID $CDROM)
-       #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
+       #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then
        # More FreeBSD bits.
        if [ X"$(uname)" = X"FreeBSD" ] ; then
                # FreeBSD eject uses the EJECT environment variable to name the CDROM
@@ -3368,16 +4222,16 @@ if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
                cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
                $eject $EJECTOPTS $cd
        elif [ X"$(uname)" = X"Darwin" ] ; then
-               disktool -e ${CDROM#/dev/} 0
+               diskutil eject ${CDROM#/dev/} 0
        else
-               $EJECT $EJECTOPTS $CDROM
+               $EJECT $EJECTOPTS "$CDROM"
        fi
        #fi
 fi
 
 ) | (
 
-## Do we need to pre-process 
+## Do we need to pre-process
 #if [ x"$PREPROCESS" = "x" ] ; then
 #      cat
 #else
@@ -3392,7 +4246,7 @@ fi
 #                      # all locations are working, wait and try again later
 #                      if [ ! $PREPROCEED ]; then sleep 3; fi
 #              done
-#              ( do_preprocess $PRETRACKNUM 
+#              ( do_preprocess $PRETRACKNUM
 #              echo "NEXTTRACK"
 #              ) &
 #      done
@@ -3488,16 +4342,18 @@ 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 
+               if [ "$ONETRACK" = "y" ]; then
                        TRACKNAME="$DALBUM"
                        TRACKNUM="$FIRSTTRACK"
                        splitvarious
                else
                        TRACKNUM=$UTRACKNUM
                        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        splitvarious
                fi
        fi
@@ -3528,7 +4384,7 @@ do
                fi
                # Lets tag the cue file
                if checkstatus cleancuefile >/dev/null; then :; else
-                       if checkstatus cuefile >/dev/null ; then 
+                       if checkstatus cuefile >/dev/null ; then
                                do_cleancue
                        fi
                fi
@@ -3544,8 +4400,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
@@ -3572,6 +4429,9 @@ if [ "$DOREPLAYGAIN" = "y" ]; then
        do_replaygain
 fi
 
+# Execute the user-defined post_encode function before cleaning up
+post_encode
+
 # Check to see if run_command logged any errors
 if [ -f "$ABCDETEMPDIR/errors" ]; then
        log error "The following commands failed to run:"
@@ -3585,8 +4445,8 @@ if [ "$KEEPWAVS" = "y" ];then
 fi
 # Check if we have moved all the formats we had previously encoded, if we are not using the FORCE.
 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' '|')
+       ENCODED_FORMATS=$(grep -E "^encodetrack-(.{3,6})-(.{1,2})$" "$ABCDETEMPDIR/status" | cut -d"-" -f2 | sort -u | tr '\n' '|')
+       MOVED_FORMATS=$(grep -E "^movetrack-output-(.{3,6})$" "$ABCDETEMPDIR/status" | cut -d"-" -f3 | sort -u | tr '\n' '|')
        if [ "$ENCODED_FORMATS" != "$MOVED_FORMATS" ]; then
                log warning "The encoded formats does not match with the moved ones"
                log warning "Formats encoded: $( echo $ENCODED_FORMATS | tr "|" " " )"