Man page wrapping corrected.
[abcde.git] / abcde
diff --git a/abcde b/abcde
index dd9f095..af8c2e5 100755 (executable)
--- a/abcde
+++ b/abcde
@@ -1,12 +1,12 @@
 #!/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.
@@ -46,21 +46,23 @@ echo "-L     Use local CDDB storage directory"
 echo "-n     No lookup. Don't query CDDB, just create and use template"
 echo "-N     Noninteractive. Never prompt for anything"
 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
-echo "-M     Create a CUE file"
+echo "       WARNING: Deprecated. Use \"cue\" action"
+#echo "-M     Create a CUE file"
 echo "-o <type1[,type2]...>"
 echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc,wav,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     Use local CDDB in recursive mode"
-#echo "-R     Add replaygain values to the tag info (only for vorbis,flac,mp3)"
 echo "-s <field>"
 echo "       Show dielfs from the CDDB info (year,genre)"
 echo "-S <#> Set the CD speed"
 echo "-t <#> Start the track numbering at a given number"
 echo "-T <#> Same as -t but modifies tag numbering"
-echo "-u     Use UNICODE tags and comments"
+echo "-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"
@@ -108,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" "
@@ -169,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.
@@ -334,24 +336,82 @@ relpath ()
        echo $TO
 }
 
+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 the command-line options we just added in
+               # Cut off any command-line option we added in
                X=$(echo $@ | cut -d' ' -f2)
+               # Test for built-in abcde.function
+               [ "$X" != "${X#abcde.}" ] && type $X >/dev/null 2>&1 && return
                if [ "$(which $X)" = "" ]; then
                        log error "$X is not in your path." >&2
+                       log info  "Define the full path to the executable if it exists on your system." >&2
+                       if [ -e /etc/debian_release ] ; then
+                               case $X in
+                                       oggenc) MISSING_PACKAGE=vorbis-tools ;;
+                                       lame)   MISSING_PACKAGE=lame ;;
+                                       flac)   MISSING_PACKAGE=flac ;;
+                               esac
+                               log info "Hint: apt-get install $MISSING_PACKAGE" >&2
                        exit 1
-               elif [ ! -x $(which $X) ]; then
+               elif [ ! -x "$(which $X)" ]; then
                        log error "$X is not executable." >&2
                        exit 1
                fi
        fi
 }
 
-# do_getcddbinfo
+# diffentries <filename> <max_value> <entry1>,<entry2>
+# max_value: the range of entries goes from 1 to <max_value>
+diffentries ()
+{
+       FILENAME=$1
+       shift
+       local CDDBDIFFCHOICES=$1
+       shift
+       local CDDBDIFFCHOICE="$@"
+       if [ ! X"$DIFF" = "X" ]; then
+               PARSECHOICE1=$(echo $CDDBDIFFCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
+               PARSECHOICE2=$(echo $CDDBDIFFCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
+               if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBDIFFCHOICES ] || \
+                  [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBDIFFCHOICES ] || \
+                  [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
+                       echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBDIFFCHOICES" >&2
+               else
+                       # We parse the 2 choices to diff, store them in temporary files and diff them.
+                       for PARSECHOICE in $(echo $CDDBDIFFCHOICE | tr , \ ); do
+                               do_cddbparse "$ABCDETEMPDIR/$FILENAME.$PARSECHOICE" > "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE"
+                       done
+                       echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/$FILENAME.diff"
+                       $DIFF $DIFFOPTS "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/$FILENAME.diff"
+                       if [ $(cat "$ABCDETEMPDIR/$FILENAME.diff" | wc -l) -ge 24 ]; then
+                               page "$ABCDETEMPDIR/$FILENAME.diff"
+                       else
+                               cat "$ABCDETEMPDIR/$FILENAME.diff" >&2
+                       fi
+               fi
+       else
+               echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBDIFFCHOICES." >&2
+       fi
+}
+
+# getcddbinfo
 # Finds an specific field from cddbinfo
-do_getcddbinfo()
+getcddbinfo()
 {
        case $1 in
        TRACKNAME1)
@@ -363,9 +423,9 @@ do_getcddbinfo()
        esac
 }
 
-# do_gettracknum
+# gettracknum
 # Get the track number we are going to use for different actions
-do_gettracknum()
+gettracknum()
 {
        if [ -n "$STARTTRACKNUMBER" ] ; then
                # Get the trackpadding from the current track
@@ -376,51 +436,116 @@ do_gettracknum()
        fi
 }
 
+# makeids
+#
+# Calculate cddb disc ids without requiring specialized helper programs.
+# largely copied from cd-discid and musicbrainz examples.  some of the steps
+# don't make sense, but they're necessary to match the ids generated by other
+# programs.
+#
+## FIXME ## Right now, we get 2 frames more than with cue2discid ??
+# data@petit:~$ sh /tmp/cue2discid /home/data/tmp/flac/01.Roisin_Murphy--Ruby_Blue.flac
+# processing offsetimes 00:00:00 04:47:10 08:20:37 11:46:46 17:45:36 21:41:57 27:32:21 32:03:73 35:39:28 38:27:33 43:50:38 44:42:34
+# 980b4b0c 12 150 21685 37687 53146 80061 97782 124071 144448 160603 173208 197438 201334 2895
+# data@petit:~$ metaflac --export-cuesheet-to=- /home/data/tmp/flac/01.Roisin_Murphy--Ruby_Blue.flac| python /home/data/sources/abcde/trunk/examples/cue2discid
+# 980b4b0c 12 150 21685 37687 53146 80061 97782 124071 144448 160603 173208 197438 201334 2893
+#
+# Variables: OFFSETS, TRACKS, LEADOUT, [LEADIN]
+makeids ()
+{
+       if [ X"$LEADOUT" = "X" ]; then
+               log warning "Error trying to calculate disc ids without lead-out information."
+               exit 1
+       fi
+
+       # default to a two second lead-in
+       IDMAGICNUM=150
+       LEADIN=${LEADIN:=150}
+
+       # number of cdframes per second
+       CDFRAMES=75
+
+       # reset cddb checksum for cddb disc-id calululation
+       CDDBCKSUM=0
+
+       COOKEDOFFSETS=""
+       for OFFSET in $(echo $OFFSETS)
+       do
+               COOKEDOFFSETS="${COOKEDOFFSETS} $(($OFFSET + $LEADIN))"
+
+               OFFSETTIME=$(( ($OFFSET + $LEADIN) / $CDFRAMES  ))
+               while [ $OFFSETTIME -gt 0 ]; do
+                       CDDBCKSUM=$(($CDDBCKSUM + $OFFSETTIME % 10))
+                       OFFSETTIME=$(($OFFSETTIME / 10))
+               done
+
+       done
+
+       COOKEDOFFSETS="${COOKEDOFFSETS:1}"  # eat the leading space
+
+       PREGAP=$(($(echo $OFFSETS | cut -f1 -d' ')))
+       TOTALTIME=$(( (($LEADOUT + $LEADIN + $PREGAP) / $CDFRAMES) - (($LEADIN + $PREGAP) / $CDFRAMES)))
+
+       printf -v HEXSUM "%08lx" $(( ($CDDBCKSUM % 0xff) << 24 | $TOTALTIME << 8 | $TRACKS))
+       TRACKINFO="${HEXSUM} $((TRACKS)) ${COOKEDOFFSETS} $((($LEADOUT + $LEADIN + $IDMAGICNUM) / $CDFRAMES))"
+}
+
 do_replaygain()
 {
        if checkstatus replaygain; then :; else
                run_command "" echo "Adding replygain information..."
-               for OUTPUT in $( echo $OUTPUTTYPE | tr , \ )
+               for TMPOUTPUT in $( echo $OUTPUTTYPE | tr , \ )
                do
-                       case $OUTPUT in
+                       case $TMPOUTPUT in
                                vorbis|ogg)
                                        OUTPUT=$OGGOUTPUTCONTAINER
                                        ;;
                                flac)
                                        OUTPUT=$FLACOUTPUTCONTAINER
                                        ;;
+                               *)
+                                       OUTPUT=$TMPOUTPUT
+                                       ;;
                        esac
                        OUTPUTFILES=""
                        REPLAYINDEX=0
                        for UTRACKNUM in $TRACKQUEUE
                        do
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                               do_getcddbinfo TRACKNAME
+                               getcddbinfo TRACKNAME
                                splitvarious
                                TRACKFILE="$(mungefilename "$TRACKNAME")"
                                ARTISTFILE="$(mungefilename "$TRACKARTIST")"
                                ALBUMFILE="$(mungefilename "$DALBUM")"
-                               do_gettracknum
-                               if [ "$VARIOUSARTISTS" = "y" ]; then
-                                       OUTPUTFILE="$(eval echo $VAOUTPUTFORMAT)"
-                               else
-                                       OUTPUTFILE="$(eval echo $OUTPUTFORMAT)"
+                               gettracknum
+                               if [ "$ONETRACK" = "y" ]; then 
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
+                                       fi
+                               else    
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
+                                       fi
                                fi
                                OUTPUTFILES[$REPLAYINDEX]="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
                                (( REPLAYINDEX = $REPLAYINDEX + 1 ))
                        done
                        case "$OUTPUT" in
                                flac)
-                                       run_command replaygain-flac $METAFLAC --add-replay-gain "${OUTPUTFILES[@]}"
+                                       run_command replaygain-flac nice $ENCNICE $METAFLAC --add-replay-gain "${OUTPUTFILES[@]}"
                                        ;;
                                vorbis|ogg)
-                                       run_command replaygain-vorbis $VORBISGAIN --album "${OUTPUTFILES[@]}"
+                                       run_command replaygain-vorbis nice $ENCNICE $VORBISGAIN --album "${OUTPUTFILES[@]}"
                                        ;;
                                mp3)
-                                       run_command replaygain-mp3 $MP3GAIN -a "${OUTPUTFILES[@]}"
+                                       run_command replaygain-mp3 nice $ENCNICE $MP3GAIN -a "${OUTPUTFILES[@]}"
                                        ;;
                                mpc)
-                                       run_command replaygain-mpc $MPPGAIN --auto "${OUTPUTFILES[@]}"
+                                       run_command replaygain-mpc nice $ENCNICE $MPPGAIN --auto "${OUTPUTFILES[@]}"
                                        ;;
                                *);;
                        esac
@@ -657,7 +782,7 @@ do_tag ()
        # If we want to start the tracks with a given number, we need to modify the
        # TRACKNUM value before evaluation
        if [ -n "$STARTTRACKNUMBERTAG" ] ; then
-               do_gettracknum
+               gettracknum
        fi
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
@@ -669,18 +794,32 @@ do_tag ()
                        case "$ID3SYNTAX" in
                                id3);;
                                eyed3)
-                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
-                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS --commen=::"$COMMENTOUTPUT" \
-                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -Y "$CDYEAR" \
-                                               -G "$GENREID" -n "${TRACKNUM:-$1}" "${TRACKNUM:+-N $TRACKS}" \
-                                               "${ENCODING:+--set-encoding=$ENCODING}"
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot
+                                       # happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $TAGGER $TAGGEROPTS \
+                                               --comment=::"$COMMENTOUTPUT" -A "$DALBUM" \
+                                               -a "$TRACKARTIST" -t "$TRACKNAME" -Y "$CDYEAR" \
+                                               -G "$GENREID" -n "${TRACKNUM:-$1}" \
+                                               "${TRACKNUM:+-N $TRACKS}" \
+                                               "${ENCODING:+--set-encoding=$ENCODING}" \
+                                               "$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       ;;
+                               # FIXME # Still not activated...
+                               id3ed)
+                                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
+                                               $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
+                                               -a "$DALBUM" -n "$TRACKARTIST" -s "$TRACKNAME" \
+                                               -y "$CDYEAR" -g "$GENREID" -k "${TRACKNUM:-$1}" \
                                                "$ABCDETEMPDIR/track$1.$OUTPUT"
                                        ;;
                                *)
-                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
-                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
-                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
-                                               -g "$GENREID" -T "${TRACKNUM:-$1/$TRACKS}" \
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot
+                                       # happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
+                                               $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
+                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" \
+                                               -y "$CDYEAR" -g "$GENREID" \
+                                               -T "${TRACKNUM:-$1/$TRACKS}" \
                                                "$ABCDETEMPDIR/track$1.$OUTPUT"
                                        ;;
                        esac
@@ -693,7 +832,9 @@ do_tag ()
                                                mv "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
                                        fi
                                        (
-                                       # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
+                                       # These are from
+                                       # http://www.xiph.org/ogg/vorbis/doc/v-comment.html
+
                                        echo ARTIST="$TRACKARTIST"
                                        echo ALBUM="$DALBUM"
                                        echo TITLE="$TRACKNAME"
@@ -711,9 +852,11 @@ do_tag ()
                                                        *)   echo COMMENT="$COMMENTOUTPUT";;
                                                esac    
                                        fi
-                                       ) | run_command tagtrack-$OUTPUT-$1 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
+                                       ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
+                                               $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
                                                "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
-                                       # Doublecheck that the commented file was created successfully before wiping the original
+                                       # Doublecheck that the commented file was created
+                                       # successfully before wiping the original
                                        if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" ]; then
                                                rm -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
                                        else
@@ -741,7 +884,7 @@ do_tag ()
                                        *)   echo COMMENT="$COMMENTOUTPUT";;
                                esac    
                        fi
-                       ) | run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                       ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
                        ;;
                spx)
                        run_command tagtrack-$OUTPUT-$1 true
@@ -768,14 +911,15 @@ do_tag ()
 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
 do_nogap_encode ()
 {
-       # The commands here don't go through run_command because they're never supposed to be silenced
+       # The commands here don't go through run_command because they're never
+       # supposed to be silenced
        echo "Encoding gapless MP3 tracks: $TRACKQUEUE"
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
                case "$OUTPUT" in
                mp3)
                        case "$MP3ENCODERSYNTAX" in
-                       lame)
+                       lame|toolame)
                                (
                                cd "$ABCDETEMPDIR"
                                TRACKFILES=
@@ -807,8 +951,8 @@ do_nogap_encode ()
                        fi
                fi
        fi
-       # Other encoders fall through to normal encoding as the tracks
-       # have not been entered in the status file.
+       # Other encoders fall through to normal encoding as the tracks have not
+       # been entered in the status file.
 }
 
 # do_encode [tracknumber] [hostname]
@@ -861,21 +1005,20 @@ 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
+                       OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
                        if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
                                continue
                        fi
@@ -883,20 +1026,26 @@ do_encode ()
                                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
                                        ;;
                                *)
@@ -908,8 +1057,8 @@ do_encode ()
                                case "$2" in
                                %local*%)
                                        case "$OGGENCODERSYNTAX" in
-                                       vorbize) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
-                                       oggenc) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
+                                       vorbize) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
+                                       oggenc) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
                                        esac
                                        ;;
                                *)
@@ -921,7 +1070,7 @@ do_encode ()
                                case "$2" in
                                %local*%)
                                        case "$FLACENCODERSYNTAX" in
-                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER -f ${IMPORTCUESHEET:+--cuesheet="$ABCDETEMPDIR/$CUEFILE"} $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
+                                       flac) $RUN_COMMAND nice $EFFECTIVE_NICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
                                        esac
                                                ;;
                                        *)
@@ -941,9 +1090,9 @@ do_encode ()
                                fi
                                # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
                                if [ ! "$DOTAG" = "y" ]; then
-                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
                                else
-                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
+                                       $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
                                fi
                                ;;
                        mpc)    
@@ -953,12 +1102,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"
+                                       $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"
@@ -1157,8 +1306,12 @@ do_normalize ()
 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
 do_move ()
 {
-       for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+       for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
+               # For now, set OUTPUT as TMPOUTPUT, and then change it once we have
+               # defined the OUTPUTFILE:
+               OUTPUT="$TMPOUTPUT"
+
                # Create ALBUMFILE, ARTISTFILE, TRACKFILE
                # Munge filenames as follows:
                # ' ' -> '_'
@@ -1170,26 +1323,38 @@ do_move ()
                ARTISTFILE="$(mungefilename "$TRACKARTIST")"
                TRACKFILE="$(mungefilename "$TRACKNAME")"
                GENRE="$(mungegenre "$GENRE")"
-               YEAR="$(echo $CDYEAR)"
-               # If we want to start the tracks with a given number, we need to modify the
-               # TRACKNUM value before evaluation
-               do_gettracknum
-               # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
-               # TRACKFILE, and TRACKNUM.
-               if [ "$VARIOUSARTISTS" = "y" ]; then
-                       OUTPUTFILE="$(eval echo "$VAOUTPUTFORMAT")"
-               else
-                       OUTPUTFILE="$(eval echo "$OUTPUTFORMAT")"
-               fi
+               YEAR=${CDYEAR:-$CDYEAR}
+               # If we want to start the tracks with a given number, we need to modify
+               # the TRACKNUM value before evaluation
+               gettracknum
+               # Supported variables for OUTPUTFORMAT are GENRE, YEAR, ALBUMFILE,
+               # ARTISTFILE, TRACKFILE, and TRACKNUM.
+               if [ "$ONETRACK" = "y" ]; then 
+                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                               OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
+                       else
+                               OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
+                       fi
+               else    
+                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                               OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
+                       else
+                               OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
+                       fi
+               fi
                if checkerrors "tagtrack-$OUTPUT-$1"; then :; else
-                       # Once we know the specific output was successful, we can change the OUTPUT to the value containing the container
-                       case $OUTPUT in
+                       # Once we know the specific output was successful, we can change
+                       # the OUTPUT to the value containing the container
+                       case $TMPOUTPUT in
                                vorbis|ogg)
                                        OUTPUT=$OGGOUTPUTCONTAINER
                                        ;;
                                flac)
                                        OUTPUT=$FLACOUTPUTCONTAINER
                                        ;;
+                               *)
+                                       OUTPUT=$TMPOUTPUT
+                                       ;;
                        esac
                        # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
                        OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
@@ -1259,29 +1424,32 @@ do_move ()
 # VARIOUSARTISTS, OUTPUTDIR
 do_playlist ()
 {
-       for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+       for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
-               case $OUTPUT in
+               case $TMPOUTPUT in
                        vorbis|ogg)
                                OUTPUT=$OGGOUTPUTCONTAINER
                                ;;
                        flac)
                                OUTPUT=$FLACOUTPUTCONTAINER
                                ;;
+                       *)
+                               OUTPUT=$TMPOUTPUT
+                               ;;
                esac
                # Create a playlist file for the playlist data to go into.
                # We used to wipe it out if it existed. Now we request permision if interactive.
                for LASTTRACK in $TRACKQUEUE; do :; done
                ALBUMFILE="$(mungefilename "$DALBUM")"
                ARTISTFILE="$(mungefilename "$DARTIST")"
-               GENRE=$(mungegenre "$GENRE")
+               GENRE="$(mungegenre "$GENRE")"
                YEAR=${CDYEAR:-$CDYEAR}
                if [ "$VARIOUSARTISTS" = "y" ] ; then
-                       PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
+                       PLAYLISTFILE="$(eval echo "$VAPLAYLISTFORMAT")"
                else
-                       PLAYLISTFILE=$(eval echo $PLAYLISTFORMAT)
+                       PLAYLISTFILE="$(eval echo "$PLAYLISTFORMAT")"
                fi
-               FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
+               FINALPLAYLISTDIR="$(dirname "$OUTPUTDIR/$PLAYLISTFILE")"
                mkdir -p "$FINALPLAYLISTDIR"
                if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
                        echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
@@ -1290,6 +1458,7 @@ do_playlist ()
                                        read ERASEPLAYLIST
                                        case $ERASEPLAYLIST in
                                                e|E|a|A|k|K) DONE=y ;;
+                                               "") ERASEPLAYLIST=e ; DONE=y ;;
                                                *) ;;
                                        esac
                                done
@@ -1309,18 +1478,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
@@ -1348,6 +1517,156 @@ do_playlist ()
        done
 }
 
+# abcde.cue2discid
+# This function reads a cuefile on stdin and writes an extended
+# cddb query on stdout.  Any PREGAP for track 1 is properly
+# handled, although cue files embedded in FLAC files do not
+# appear to properly store the PREGAP setting. :(
+abcde.cue2discid () {
+
+       cddb_sum () {
+               val=$1
+               ret=0
+               while [ $val -gt 0 ] ; do
+                       ret=$(( $ret + ( $val % 10) ))
+                       val=$(( $val / 10 ))
+               done
+               echo $ret
+       }
+
+       msf2lba () {
+               OIFS="$IFS"
+               IFS=":"
+               set -- $1
+               IFS="$OIFS"
+               local first second third
+               first=$(expr ${1} + 0 )
+               second=$(expr ${2} + 0 )
+               third=$(expr ${3} + 0 )
+
+               echo $(( ((($first * 60) + $second) * 75) + $third ))
+       }
+
+       OFFSET=150
+       PREGAP=0
+       LEADOUT=0
+       LEADIN=88200
+       i=0
+       N=0
+       
+       while read line ; do
+               set -- $line
+               case "$1" in
+               TRACK)  i=$(( i + 1 ))
+                       ;;
+               INDEX)  if [ "$2" -eq 1 ] ; then
+                               LBA=$(msf2lba $3)
+                               START=$(( $LBA + $PREGAP + $OFFSET ))
+                               eval TRACK$i=$START
+                               X=$(cddb_sum $(( $START / 75 )) )
+                               N=$(( $N + $X ))
+                       fi
+                       ;;
+               PREGAP) PREGAP=$(msf2lba $2)
+                       ;;
+               REM)    case "$2" in 
+                       FLAC__lead-out)
+                               LEADOUT=$(( $4 / 588 ))
+                               ;;
+                       FLAC__lead-in)
+                               LEADIN=$(( $3 / 588 ))
+                               ;;
+                       esac
+                       ;;
+               esac
+               
+       done
+       
+       TRACKS=$i
+       LEADOUT=$(( $LEADOUT + $LEADIN ))
+
+       LENGTH=$(( $LEADOUT/75 - $TRACK1/75 ))
+       DISCID=$(( ( $N % 255 ) * 2**24 | $LENGTH * 2**8 | $TRACKS ))
+       printf "%08x %i" $DISCID $TRACKS
+       
+       j=1
+       while [ $j -le $TRACKS ] ; do
+               eval echo -n "\" \$TRACK$j\""
+               j=$((j+1))
+       done
+       echo " $(( $LEADOUT / 75 ))"
+}
+
+# abcde.mkcue
+# abcde.mkcue [--wholedisk]
+# This creates a cuefile directly from the extended discid information
+# The --wholedisk option controls whether we're ripping data from the
+# start of track one or from the start of the disk (usually, but not
+# always the same thing!)
+#
+# Track one leadin/pregap (if any) handeling:
+# --wholedisk specified:
+#   TRACK 01 AUDIO
+#     INDEX 00 00:00:00
+#     INDEX 01 <pregap value>
+#   Remaining track index values unchanged from disc TOC
+#
+# --wholedisk not specified
+#   TRACK 01 AUDIO
+#     PREGAP <pregap value>
+#     INDEX 01 00:00:00
+#   Remaining track index values offset by <pregap value>
+#
+# Variables used:
+# TRACKINFO
+abcde.mkcue () {
+
+       echomsf () {
+               printf "$1%02i:%02i:%02i\n" $(($2/4500)) $((($2/75)%60)) $(($2%75))
+       } 
+
+       local MODE DISCID TRACKS
+       local i OFFSET LBA 
+
+
+    if [ "$1" = --wholedisc ] ; then
+        MODE=INDEX
+    else
+        MODE=PREGAP
+    fi
+
+    set -- $TRACKINFO
+
+    DISCID=$1
+    TRACKS=$2
+    shift 2
+
+    echo REM DISCID $DISCID
+    echo FILE \"dummy.wav\" WAVE
+
+    if [ $1 -ne 150 ] && [ $MODE = "PREGAP"] ; then
+        OFFSET=$1
+    else
+        OFFSET=150
+    fi
+
+    i=1
+    while [ $i -le "$TRACKS" ] ; do
+        LBA=$(( $1 - $OFFSET ))
+        printf "  TRACK %02i AUDIO\n" $i
+        if [ $i -eq 1 -a $1 -ne 150 ] ; then
+            if [ $MODE = PREGAP ] ; then
+                echomsf "    PREGAP " $(($OFFSET-150))
+            else
+                echo    "    INDEX 00 00:00:00"
+            fi
+               fi
+        echomsf "    INDEX 01 " $LBA
+               i=$(($i+1))
+        shift
+    done
+}
+
 # do_discid
 # This essentially the start of things
 do_discid ()
@@ -1363,22 +1682,64 @@ do_discid ()
                if [ "$OSFLAVOUR" = "OSX" ]; then
                        disktool -u ${CDROM#/dev/}
                fi
-               if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
-                       if [ "$TRACKINFO" = "" ]; then
-                               TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
-                       else
-                               if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM > /dev/null 2>&1 ; then :; else
+               case "$CDROMREADERSYNTAX" in
+                       flac)
+                               if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" > /dev/null 2>&1 ; then
+                                       case "$CUE2DISCID" in
+                                               # FIXME # right now we have 2 cue2discid internal
+                                               # implementations: builtin and abcde.cue2discid. Test
+                                               # both of them and decide which one we want to use.
+                                               builtin)
+                                                       #vecho "Using builtin cue2discid implementation..."
+                                                       CUESHEET="$(metaflac $METAFLACOPTS --export-cuesheet-to=- "$CDROM")"
+
+                                                       #TRACKS=$(echo $CUESHEET | egrep "TRACK \+[[:digit:]]\+ \+AUDIO" |wc -l)
+                                                       #TRACKS=0
+                                                       OFFSETTIMES=( $(echo "$CUESHEET" | sed -n -e's/\ *INDEX 01\ \+//p' ) )
+                                                       TRACKS=${#OFFSETTIMES[@]}
+                                                       unset OFFSETS
+                                                       #echo "processing offsetimes ${OFFSETTIMES[@]}"
+                                                       for OFFSETTIME in ${OFFSETTIMES[@]}; do
+                                                               OFFSETS="$OFFSETS $(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))"
+                                                               #OFFSETS[${#OFFSETS[*]}]=$(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))
+                                                       done
+
+                                                       LEADOUT=$(( $(echo "$CUESHEET" | grep lead-out | get_last) / 44100 * 75 ))
+                                                       LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) / 44100 * 75 ))
+                                                       makeids
+                                               ;;
+                                               *)
+                                                       #vecho "Using external python cue2discid implementation..."
+                                                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" | $CUE2DISCID)
+                                               ;;
+                                       esac
+                               else
                                        log error "the input flac file does not contain a cuesheet."
                                        exit 1
                                fi
-                       fi
-               else
-                       case "$CDDBMETHOD" in
-                               cddb) TRACKINFO=$($CDDISCID $CDROM) ;;
-                               # FIXME # musicbrainz needs a cleanup
-                               musicbrainz) TRACKINFO=$($MUSICBRAINZ -c $CDROM ) ;;
-                       esac
-               fi
+                               ;;
+#                      cdparanoia|debug)
+#                              CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
+#                              RET=$?
+#                              if [ ! "$RET" = "0" ];then
+#                                      log warning "something went wrong while querying the CD... Maybe a DATA CD?"
+#                              fi
+#
+#                              TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
+#                              CDPARANOIAAUDIOTRACKS="$TRACKS"
+#
+#                              LEADOUT="$(echo "$CDPARANOIAOUTPUT" | egrep -o '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
+#                              OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')" 
+#                              makeids
+#                              ;;
+                       *)
+                               case "$CDDBMETHOD" in
+                                       cddb) TRACKINFO=$($CDDISCID "$CDROM") ;;
+                                       # FIXME # musicbrainz needs a cleanup
+                                       musicbrainz) TRACKINFO=$($MUSICBRAINZ -c "$CDROM" ) ;;
+                               esac
+                               ;;
+               esac
                # Make sure there's a CD in there by checking cd-discid's return code
                if [ ! "$?" = "0" ]; then
                        if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
@@ -1414,12 +1775,12 @@ do_discid ()
 
        ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
        if [ -z "$TRACKQUEUE" ]; then
-               if [ ! "$STRIPDATATRACKS" = "y" ]; then
+               if [ ! "$STRIPDATATRACKS" = "n" ]; then
                        case "$CDROMREADERSYNTAX" in
                                cdparanoia|debug)
                                        if [ "$WEHAVEACD" = "y" ]; then
                                                vecho "Querying the CD for audio tracks..."
-                                               CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
+                                               CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
                                                RET=$?
                                                if [ ! "$RET" = "0" ];then
                                                        log warning "something went wrong while querying the CD... Maybe a DATA CD?"
@@ -1550,17 +1911,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
@@ -1591,16 +1963,24 @@ do_cleancue()
                        n=1
                        echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
                        echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
+                       # Set IFS to <newline> to prevent read from swallowing spaces and tabs
+                       OIFS="$IFS"
+                       IFS='
+'
                        cat "$CUEFILE_IN" | while read line
                        do
-                               if echo "$line" | grep -q "INDEX"
-                               then
+                               if echo "$line" | grep "INDEX 01" > /dev/null 2>&1 ; then
+# FIXME # Possible patch: remove the line above, uncomment the 2 lines below.
+#                              echo "$line" >> "$CUEFILE_OUT"
+#                              if echo "$line" | grep "^[[:space:]]*TRACK" > /dev/null 2>&1 ; then
                                        eval track="\$TRACK$n"
                                        n=$(expr $n + 1)
-                                       echo "TITLE \"$track\"" >> "$CUEFILE_OUT"
+                                       echo "    TITLE \"$track\"" >> "$CUEFILE_OUT"
                                fi
+# FIXME # If the lines above are uncommented, remove the line below.
                                echo "$line" >> "$CUEFILE_OUT"
                        done
+                       IFS="$OIFS"
                        mv "$CUEFILE_OUT" "$CUEFILE_IN"
                        echo "cleancuefile" >> "$ABCDETEMPDIR/status"
                fi
@@ -1654,8 +2034,6 @@ do_localcddb ()
                                if   (( $(echo "${CDDBLOCALRESULTS}" | wc -l) == 1 )); then
                                        CDDBLOCALFILE="${CDDBLOCALRESULTS}"
                                        CDDBLOCALMATCH=single
-                                       echo "${CDDBLOCALRESULTS}" : $(echo "${CDDBLOCALRESULTS}" | wc -l )
-                                       echo CDDBLOCALMATCH=single
                                elif (( $(echo "${CDDBLOCALRESULTS}" | wc -l) > 1 )); then
                                        CDDBLOCALMATCH=multiple
                                fi
@@ -1672,32 +2050,51 @@ do_localcddb ()
                # 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"
+                               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}"
+                                       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 )
-                               cat "$ABCDETEMPDIR/cddblocalchoices"
+                               # 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 CDDBLOCALCHOICENUM
-                                               [ x"$CDDBLOCALCHOICENUM" = "x" ] && CDDBLOCALCHOICENUM="1"
+                                               read CDDBLOCALCHOICE
+                                               [ x"$CDDBLOCALCHOICE" = "x" ] && CDDBLOCALCHOICE="1"
+                                               # FIXME # Introduce diff's
+                                               if echo $CDDBLOCALCHOICE | egrep "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
+                                               elif echo $CDDBLOCALCHOICE | egrep "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       # Make sure we get a valid choice
+                                                       CDDBLOCALCHOICENUM=$(echo $CDDBLOCALCHOICE | xargs printf %d 2>/dev/null)
+                                                       if [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; then
+                                                               echo "Invalid selection. Please choose a number between 0 and $CDDBLOCALCHOICES." >&2
+                                                       fi
+                                               fi
                                        done
                                else
                                        ### FIXME ###
-                                       echo "Selected ..."
+                                       #echo "Selected ..."
                                        CDDBLOCALRESP=y
+                                       CDDBLOCALCHOICENUM=1
                                fi
                                if [ ! "$CDDBLOCALCHOICENUM" = "0" ]; then
                                        #echo "Using local copy of CDDB data"
@@ -1716,11 +2113,11 @@ do_localcddb ()
                        single)
                                # List out disc title/author and contents
                                do_cddbparse "${CDDBLOCALFILE}"
-                               if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
-                                       echo -n "Embedded cuesheet entry found, use ut? [y/n] (y): " >&2
-                               else
+                               #if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
+                               #       echo -n "Embedded cuesheet entry found, use it? [y/n] (y): " >&2
+                               #else
                                        echo -n "Locally cached CDDB entry found, use it? [y/n] (y): " >&2
-                               fi
+                               #fi
                                if [ "$INTERACTIVE" = "y" ]; then
                                        read USELOCALRESP
                                        while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
@@ -1757,8 +2154,9 @@ do_musicbrainzstat ()
        :
 }
 
-do_musizbrainz ()
+do_musicbrainz ()
 {
+# Use MBE_TOCGetCDIndexId on a perl query
        :
 }
 
@@ -1954,7 +2352,7 @@ do_cddbedit ()
                                CHOICE=$(checkstatus cddb-choice)
                                if [ -n "$CHOICE" ] ; then
                                        case $CDDBCHOICES in
-                                               -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep -q "^$" ; then
+                                               -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep "^$" > /dev/null 2>&1 ; then
                                                                log error "CDDB query failed!" 
                                                                exit 1
                                                        else
@@ -1984,7 +2382,7 @@ 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 | egrep "[[: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)
@@ -2008,7 +2406,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 | egrep "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
                                                        # Make sure we get a valid choice
                                                        CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
                                                        if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
@@ -2274,12 +2672,15 @@ do_cdread ()
                # the user said
                # We need the first and last track for cdda2wav
                FIRSTTRACK=$2
-               LASTTRACK=$3
+               LASTTRACK=$(expr $3 + 0)
                UTRACKNUM=$FIRSTTRACK
                case "$CDROMREADERSYNTAX" in
                        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) READTRACKNUMS="$FIRSTTRACK+$LASTTRACK" ;;
                        *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
                                exit 1 ;;
                esac
@@ -2312,7 +2713,7 @@ do_cdread ()
                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
@@ -2326,8 +2727,7 @@ do_cdread ()
                        STRIPTRACKNUM=$(expr $UTRACKNUM + 0)
                        nice $READNICE $FLAC -d -f --cue=${READTRACKNUMS:-$STRIPTRACKNUM.1-$(($STRIPTRACKNUM + 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 ;;
+                       nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
                cdda2wav)
                        if [ "$OSFLAVOUR" = "OSX" ] ; then
                                # Hei, we have to unmount the device before running anything like cdda2wav in OSX
@@ -2347,7 +2747,7 @@ do_cdread ()
                        ;;
                ## FIXME ## We have an exception for dagrab, since it uses -f
                ## FIXME ## Shall we just use -f $FILEARG ??
-               dagrab) nice $READNICE $CDROMREADER -d $CDROM -v $UTRACKNUM "$FILEARG" $REDIR
+               dagrab) nice $READNICE $CDROMREADER -d "$CDROM" -v $UTRACKNUM "$FILEARG" $REDIR
                        ;;
                cddafs)
                        # Find the track's mounted path
@@ -2360,7 +2760,7 @@ do_cdread ()
                        else
                                false
                        fi ;;
-               debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
+               debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
                        ;;
        esac
        RETURN=$?
@@ -2383,9 +2783,9 @@ do_cdread ()
                        echo readencodetrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
                else
                        echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
-                       if [ "$1" = "onetrack" ]; then
-                               echo onetrack >> "$ABCDETEMPDIR/status"
-                       fi
+               fi
+               if [ "$1" = "onetrack" ]; then
+                       echo onetrack >> "$ABCDETEMPDIR/status"
                fi
        fi
 }
@@ -2420,7 +2820,7 @@ fi
 decho ()
 {
 if [ x"$DEBUG" != "x" ]; then
-       if echo $1 | grep -q "^\[" ; then
+       if echo $1 | grep "^\[" > /dev/null 2>&1 ; then
                DEBUGECHO=$(echo "$@" | tr -d '[]')
                echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
        else
@@ -2470,7 +2870,7 @@ post_read ()
 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"
@@ -2516,6 +2916,7 @@ KEEPWAVS=n
 PADTRACKS=n
 NOGAP=n
 BATCHNORM=n
+NOCDDBQUERY=n
 
 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
 # i.e. CDROMID="1,0,0"
@@ -2568,7 +2969,7 @@ MPPGAIN=replaygain
 MKCUE=mkcue
 MKTOC=cdrdao
 DIFF=diff
-CUE2DISCID=cue2discid
+CUE2DISCID=builtin
 
 # Options for programs called from abcde
 # mp3
@@ -2617,13 +3018,21 @@ ACTIONS=cddb,read,encode,tag,move,clean
 
 # This option is basicaly for Debian package dependencies: 
 # List of prefered outputs - by default, run with whatever we have in the path
-DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:lame,mp3:bladeenc,spx:speex
+DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:toolame,mp3:lame,mp3:bladeenc,spx:speex,m4a:faac
 
 # List of prefered cdromreaders - by default, run whichever we have in the path
 DEFAULT_CDROMREADERS="cdparanoia cdda2wav"
 
-# Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
-# Let's use these checkings to determine the OS flavour, which will be used later
+# List of quality levels associated with the encoders:
+DEFAULT_QUALITY_XLO="oggenc:-q -1,lame:-q 9,speex:--quality 1,m4a:"
+DEFAULT_QUALITY_LO="oggenc:-q 1,lame:-q 7,speex:--quality 5,m4a:"
+DEFAULT_QUALITY_HI="oggenc:-q 7,lame:--preset standard,speex:--quality 9,m4a:"
+DEFAULT_QUALITY_XHI="oggenc:-q 10,lame:--preset extreme,speex:--quality 10,m4a:"
+
+# Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for
+# Linux/OpenBSD. ftp is user for NetBSD.
+# Let's use these checkings to determine the OS flavour, which will be used
+# later
 if [ X$(uname) = "XFreeBSD" ] ; then
        HTTPGET=fetch
        MD5SUM=md5
@@ -2638,9 +3047,15 @@ elif [ X$(uname) = "XDarwin" ] ; then
 elif [ X$(uname) = "XOpenBSD" ] ; then
        HTTPGET=wget
        MD5SUM=md5
+       OSFLAVOUR=OBSD
 elif [ X$(uname) = "XNetBSD" ] ; then
        HTTPGET=ftp
        MD5SUM=md5
+       OSFLAVOUR=NBSD
+elif [ X$(uname) = "SunOS" ] ; then
+       HTTPGET=""
+       MD5SUM=md5
+       OSFLAVOUR=SunOS
 else
        HTTPGET=wget
 fi
@@ -2651,6 +3066,12 @@ CDDBAVAIL=y
 USEID3=y
 USEID3V2=y
 
+# There we go..
+# But before we get into business, let us chop off any GREP environmental
+# variables.
+GREP_OPTIONS=""
+GREP_COLOR=""
+
 if [ -z "$OUTPUTDIR" ]; then
        OUTPUTDIR=$(pwd)
 fi
@@ -2673,10 +3094,10 @@ fi
 
 if [ "$HTTPGETOPTS" = "" ] ; then
        case $HTTPGET in
-               wget) HTTPGETOPTS="-q -O -";;
+               wget) HTTPGETOPTS="-q -nv -O -";;
                curl) HTTPGETOPTS="-f -s";;
                fetch)HTTPGETOPTS="-q -o -";;
-               ftp)  HTTPGETOPTS="-q -o -";;
+               ftp)  HTTPGETOPTS="-a -V -o - ";;
                *) log warning "HTTPGET in non-standard and HTTPGETOPTS are not defined." ;;
        esac
 fi
@@ -2699,8 +3120,8 @@ if [ "$CDROM" = "" ] ; then
 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:pPr:s:S:t:T:UvVxX:w:W:z opt ; do
        case "$opt" in
                1) ONETRACK=y ;;
                a) ACTIONS="$OPTARG" ;;
@@ -2711,7 +3132,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" ;;
@@ -2725,17 +3145,18 @@ while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
                n) CDDBAVAIL=n ;;
                N) INTERACTIVE=n ;;
                m) DOSPLAYLIST=y ;;
-               M) MAKECUEFILE=y ;;
+               M) DOCUE=y ;;
                o) OUTPUTTYPE="$OPTARG" ;;
                p) PADTRACKS=y ;;
                P) USEPIPES=y ;;
+               q) QUALITYLEVEL="$OPTARG" ;;
                r) REMOTEHOSTS="$OPTARG" ;;
-               R) DOREPLAYGAIN=y ;;
+               R) CDDBLOCALRECURSIVE=y ;;
                s) SHOWCDDBFIELDS="$OPTARG" ;;
                S) CDSPEEDVALUE="$OPTARG" ;;
                t) STARTTRACKNUMBER="$OPTARG" ;;
                T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
-               u) CDDBPROTO=6 ;;
+               U) CDDBPROTO=5 ;;
                v) 
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
@@ -2744,8 +3165,9 @@ while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
                   ;;
                V) EXTRAVERBOSE="y" ;;
                x) EJECTCD="y" ;;
+               X) CUE2DISCID="$OPTARG" ;;
                w) COMMENT="$OPTARG" ;;
-               W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
+               W) if echo $OPTARG | grep "[[:digit:]]" > /dev/null 2>&1 ; then 
                     STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
                   else
                     log error "argument of -W must be integer"
@@ -2759,12 +3181,28 @@ 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 warning "abcde: switching to flac CDROMREADERSYNTAX..."
+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
-       # Added a need on CUE2DISCID until we manage to convert the python script to bash.
-       NEEDCUE2DISCID=y
+       # We have a builtin version of cue2discid...
+       case "$CUE2DISCID" in
+               builtin);;
+               *) NEEDCUE2DISCID=y;;
+       esac
        NEEDMETAFLAC=y
        EJECTCD=n
 fi
@@ -2775,7 +3213,7 @@ 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
@@ -2841,10 +3279,14 @@ DOMOVE=n
 DOREPLAYGAIN=n
 DOPLAYLIST=n
 DOCLEAN=n
+## FIXME ## Lets keep compatibility with -M
+[ "$DOCUE" != "y" ] && DOCUE=n
 
 for ACTION in $(echo $ACTIONS | tr , \ )
 do
        case $ACTION in
+               default) DOCDDB=y; DOREAD=y; DOENCODE=y; DOTAG=y; DOMOVE=y; DOCLEAN=y;;
+               cue) DOCUE=y ; MAKECUEFILE=y ;;
                cddb) DOCDDB=y;;
                read) DOREAD=y;;
                normalize) DONORMALIZE=y; DOREAD=y;;
@@ -2872,13 +3314,11 @@ for SHOWCDDBFIELD in $(echo $SHOWCDDBFIELDS | tr , \ ); do
        esac
 done
 
-# Sanity checks:
-
 # At this point a CDROM has to be defined, so we check it exists.
 if [ X"$CDROM" != "X" ] ; then 
        if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
                if [ "$OSFLAVOUR" = "FBSD" ]; then
-                       if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
+                       if echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then :; else
                                log error "CDROMID not in the right format for $CDROMREADERSYNTAX"
                                log error "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
                                exit 1
@@ -2950,7 +3390,7 @@ if [ "$BATCHNORM" = "y" ] && [ "$DONORMALIZE" = "n" ]; then
        BATCHNORM=n
 fi
 
-# Check the encoding format from the ones available in the system, if nothing has been configured in the system.
+# Check the encoding format from the ones available in the system, if nothing has been configured.
 if [ X"$OUTPUTTYPE" = "X" ]; then
        for DEFAULT_OUTPUT in $( echo "$DEFAULT_OUTPUT_BINARIES" | tr , \ ); do
                DEFAULT_OUTPUT_FORMAT="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 1)"
@@ -3002,7 +3442,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- )" ;;
@@ -3041,9 +3481,7 @@ do
                        [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
                        [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
                        [ "$DOREPLAYGAIN" = "y" ] && NEEDMETAFLAC=y
-                       if [ "$ONETRACK" = "y" ]; then
-                               [ "$MAKECUEFILE" = "y" ] && IMPORTCUESHEET=y
-                       fi
+                       [ "$ONETRACK" = "y" ] && [ "$DOCUE" = "y" ] && NEEDMETAFLAC=y 
                        ;;
                spx)
                        [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
@@ -3058,7 +3496,7 @@ do
                        ;;
                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
                        ;;
@@ -3114,7 +3552,7 @@ case "$FLACENCODERSYNTAX" in
                FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
                FLACENCODER="$FLAC"     
                # FLAC streams can be encapsulated on a Ogg transport layer
-               if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
+               if echo "$FLACENCODEROPTS" | egrep -- "(^| )--ogg($| )" > /dev/null 2>&1 ;then
                        log error "FLAC on an Ogg container is not yet supported"
                        log error "due to problem with adding comments to such files"
                        exit 1
@@ -3142,8 +3580,8 @@ case "$AACENCODERSYNTAX" in
                AACENCODER="$AACENC"
                ;;
 esac
-# and which tagger
 
+# and which tagger
 if [ "$ID3TAGV" = "1" ]; then
        TAGGER="$ID3"
        TAGGEROPTS="$ID3OPTS"
@@ -3211,11 +3649,11 @@ if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
                :
        fi
 fi
-if [ "$MAKECUEFILE" = "y" ]; then
+if [ "$DOCUE" = "y" ]; then
        NEEDCUEREADER=y
 fi
 
-if [ X"$CDSPEEDVALUE" != "X" ] && [ "$DOREAD" = "y"]; then
+if [ X"$CDSPEEDVALUE" != "X" ] && [ "$DOREAD" = "y" ]; then
        case "$CDROMREADERSYNTAX" in
                cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
                ### FIXME ### translate "cue2discid" from python to bash
@@ -3276,32 +3714,34 @@ fi
 # Make sure a buncha things exist
 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
        $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
+       $AACENCODER \
        ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
        ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
        ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
        ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
        ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMP3GAIN+$MP3GAIN} \
-       ${NEEDMPPGAIN+$MPPGAIN} \
-       ${NEEDCUEREADER+$CUEREADER}
+       ${NEEDMPPGAIN+$MPPGAIN} ${NEEDCUEREADER+$CUEREADER} \
+       ${NEEDCUE2DISCID+$CUE2DISCID}
 do
        checkexec "$X"
 done
 
-# And last but not least, check if we can diff between files
+# And last but not least, check if we can diff between files. We do not abort,
+# since diffing is not critical...
 if [ -x $(which $DIFF) ]; then :; else
        vecho warning "Disabling diff since we cannot find it in the \$PATH..."
        DIFF=""
 fi
 
-# Now that we have metaflac, check if we need cue2discid
-case $CDROMREADERSYNTAX in
-       flac)
-               TRACKINFO=$($METAFLAC --show-tag=CDDB $CDROM | cut -d"=" -f2 | egrep "[a-f0-9]{8}")
-               if [ "$TRACKINFO" = "" ]; then 
-                       checkexec ${NEEDCUE2DISCID+$CUE2DISCID}
-               fi
-               ;;
-esac
+## Now that we have metaflac, check if we need cue2discid
+#case $CDROMREADERSYNTAX in
+#      flac)
+#              TRACKINFO=$($METAFLAC --show-tag=CDDB $CDROM | cut -d"=" -f2 | egrep "[a-f0-9]{8}")
+#              if [ "$TRACKINFO" = "" ]; then 
+#                      checkexec ${NEEDCUE2DISCID+$CUE2DISCID}
+#              fi
+#              ;;
+#esac
 
 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
@@ -3309,7 +3749,7 @@ 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 3306 ;)
+# 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
@@ -3331,11 +3771,13 @@ case "$CDDBMETHOD" in
                do_discid # Get ABCDETEMPDIR created and status file initialized
                ;;
        musicbrainz)
-               do_musicbrainz
+               do_musicbrainz id
                ;;
 esac
 
 if [ "$DOCDDB" = "y" ]; then
+       # start with a sane default:
+       CDDBLOCALSTATUS=notfound
        if [ $CDDBUSELOCAL = "y" ]; then
                do_localcddb
        fi
@@ -3380,6 +3822,15 @@ if [ -f "$ABCDETEMPDIR/status" ] && [ X"$ERASEENCODEDSTATUS" = "Xy" ]; then
                | grep -v ^encode-output > "$ABCDETEMPDIR/status"
 fi
 
+if checkstatus onetrack ; then ONETRACK=y ; fi
+
+if [ "$ONETRACK" = "y" ]; then 
+       # Reuse the CUEFILE in case we created it (now or in a previous run)
+       if CUEFILE=$(checkstatus cuefile); then
+               IMPORTCUESHEET=y
+       fi
+fi
+
 # Create playlist if needed (backgroundable) and start reading in tracks
 
 (
@@ -3398,15 +3849,13 @@ if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
 fi
 
 if [ "$ONETRACK" = "y" ]; then 
-       # Reuse the CUEFILE in case we created it in a previous run
-       if CUEFILE=$(checkstatus cuefile) >/dev/null ; then
-               IMPORTCUESHEET=y
-       fi
        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
@@ -3489,7 +3938,7 @@ if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
        elif [ X"$(uname)" = X"Darwin" ] ; then
                disktool -e ${CDROM#/dev/} 0
        else
-               $EJECT $EJECTOPTS $CDROM
+               $EJECT $EJECTOPTS "$CDROM"
        fi
        #fi
 fi
@@ -3607,6 +4056,8 @@ do
        fi
        # Don't proceed with the rest of the loop if we can't encode
        if [ "$ABORT" ]; then continue; fi
+       ## FIXME ## Add here 
+       ## run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
        # Set TRACKNUM, TRACKNAME
        if [ -e "$CDDBDATA" ]; then
                if [ "$ONETRACK" = "y" ]; then 
@@ -3616,7 +4067,7 @@ do
                else
                        TRACKNUM=$UTRACKNUM
                        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        splitvarious
                fi
        fi
@@ -3663,8 +4114,9 @@ done
 
 # Go through it again and make sure there's no distmp3 stragglers, otherwise
 # we'll delete the files they're working on
+# Do NOT play ball if there is no ball to play (so ABORT if needed)
 ## FIXME ## Check also for files which are encoded using PIPEs.
-if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
+if [ "$DOENCODE" = "y" ] && [ "$USEPIPES" != "y" ] && [ ! "$ABORT" ]; then
        PROCEED=
        until [ $PROCEED ]
        do