Documentation update noted in the changelog
[abcde.git] / abcde
diff --git a/abcde b/abcde
index 09938a3..1ad68b6 100755 (executable)
--- a/abcde
+++ b/abcde
@@ -1,17 +1,19 @@
-#!/bin/sh
+#!/bin/bash
 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
-# Copyright (c) 2003-2005 Jesus Climent <jesus.climent@hispalinux.es>
+# Copyright (c) 2003-2006 Jesus Climent <jesus.climent@hispalinux.es>
 # This code is hereby licensed for public consumption under either the
 # GNU GPL v2 or greater, or Larry Wall's Artistic license - your choice.
 #
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 #
 # Copyright for this work is to expire January 1, 2010, after which it
 # shall be public domain.
+#
+# $Id$
 
-VERSION="2.3.99-$Id$"
+VERSION='2.3.99-$Revision$'
 
 usage ()
 {
@@ -20,18 +22,21 @@ echo "Usage: abcde [options] [tracks]"
 echo "Options:"
 echo "-1     Encode the whole CD in a single file"
 echo "-a <action1[,action2]...>"
-echo "       Actions to perform (cddb,read,normalize,encode,tag,move,playlist,clean)"
+echo "       Actions to perform:"
+echo "       cddb,read,normalize,encode,tag,move,replaygain,playlist,clean"
 #echo "-A     Experimental actions (retag, transcode)"
-echo "-b     Batch mode: enable album normalization and nogap encoding"
+echo "-b     Enable batch normalization"
+#echo "-B     Disable batch replaygain (do file by file)"
 echo "-c <file>"
 echo "       Specify a configuration file (overrides system and user config files)"
 echo "-C <discid#>"
 echo "       Specify discid to resume from (only needed if you no longer have the cd)"
 echo "-d <device>"
-echo "       Specify CDROM device to grab"
+echo "       Specify CDROM device to grab (flac uses a single-track flac file)"
 echo "-D     Debugging mode (equivalent to sh -x abcde)"
 echo "-e     Erase encoded track information from status file"
-#echo "-E     Set the encoding information for the tags"
+echo "-f     Force operations that otherwise are considered harmful. Read \"man abcde\""
+echo "-g     Use \"lame --nogap\" for MP3 encoding. Disables low disk and pipes flags"
 echo "-h     This help information"
 #echo "-i    Tag files while encoding, when possible (local only) -NWY-"
 echo "-j <#> Number of encoder processes to run at once (localhost)"
@@ -43,25 +48,26 @@ echo "-N     Noninteractive. Never prompt for anything"
 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
 echo "-M     Create a CUE file"
 echo "-o <type1[,type2]...>"
-echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc). Defaults to vorbis"
+echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc,wav,m4a). Defaults to vorbis"
 echo "-p     Pad track numbers with 0's (if less than 10 tracks)"
 echo "-P     Use UNIX pipes to read+encode without wav files"
 echo "-r <host1[,host2]...>"
 echo "       Also encode on these remote hosts"
-echo "-R     Add replaygain values to the tag info (only for vorbis,flac)"
+echo "-R     Use local CDDB in recursive mode"
 echo "-s <field>"
 echo "       Show dielfs from the CDDB info (year,genre)"
 echo "-S <#> Set the CD speed"
-#echo "-t    File types to preprocess (wav)"
-#echo "-T    Set postprocessing options"
 echo "-t <#> Start the track numbering at a given number"
 echo "-T <#> Same as -t but modifies tag numbering"
+echo "-u     Use UNICODE (UTF8) 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 "-z     Use debug CDROMREADERSYNTAX option (needs cdparanoia)"
 echo ""
 echo "Tracks is a space-delimited list of tracks to grab."
 echo "Ranges specified with hyphens are allowed (i.e., 1-5)."
@@ -69,6 +75,25 @@ echo ""
 #echo "Double hyphens are used to concatenate tracks"
 }
 
+addstatus ()
+{
+       echo "$@" >> "$ABCDETEMPDIR/status"
+}
+
+# log [level] [message]
+# 
+# log outputs the right message in a common format
+log ()
+{
+       BLURB="$1"
+       shift
+       case $BLURB in
+               error)   echo "[ERROR] abcde: $@" >&2 ;;
+               warning) echo "[WARNING] $@" >&2 ;;
+               info)    echo "[INFO] $@" ;;
+       esac
+}
+
 # Funtions to replace the need of seq, which is too distribution dependant.
 f_seq_row ()
 {
@@ -83,7 +108,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" "
@@ -91,7 +116,7 @@ f_seq_line ()
                done
                echo
        else
-               echo "abcde: syntax error while processing track numbers" >&2
+               log error "syntax error while processing track numbers"
                exit 1
        fi
 }
@@ -144,6 +169,29 @@ checkstatus ()
        fi
 }
 
+# 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.
+# Otherwise, returns "".
+checkwarnings ()
+{
+       if [ -e "$ABCDETEMPDIR/warnings" ]; then :; else
+               return 1
+       fi
+       # Take the last line in the status file if there's multiple matches
+       PATTERN="^$1(:.*)?$"
+       BLURB="$(egrep $PATTERN "$ABCDETEMPDIR/warnings" | tail -n 1)"
+
+       if [ -z "$BLURB" ]; then
+               # negative, we did not have a negative...
+               return 1
+       else
+               # affirmative, we had a negative...
+               return 0
+       fi
+}
+
 # checkerrors [blurb]
 # Returns "0" if the blurb was found (meaning there was an error),
 # returns 1 if it wasn't (yes this is a little backwards).
@@ -286,14 +334,73 @@ relpath ()
        echo $TO
 }
 
-# do_getcddbinfo
-# Finds an specific field from cddbinfo
-# 
-#      TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
-#      TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
-#      TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
+new_checkexec ()
+{
+       if [ ! "$@" = "" ]; then
+               # Cut off any command-line option we added in
+               X=$(echo $@ | cut -d' ' -f2)
+               if [ "$(which $X)" = "" ]; then
+                       return 1
+               elif [ ! -x $(which $X) ]; then
+                       return 2
+               fi
+       fi
+       return 0
+}
+
+checkexec ()
+{
+       if [ ! "$@" = "" ]; then
+               # Cut off any command-line option we added in
+               X=$(echo $@ | cut -d' ' -f2)
+               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
+                       exit 1
+               elif [ ! -x "$(which $X)" ]; then
+                       log error "$X is not executable." >&2
+                       exit 1
+               fi
+       fi
+}
+
+# diffentries <filename> <max_value> <entry1>,<entry2>
+# max_value: the range of entries goes from 1 to <max_value>
+diffentries ()
+{
+       FILENAME=$1
+       shift
+       local CDDBDIFFCHOICES=$1
+       shift
+       local CDDBDIFFCHOICE="$@"
+       if [ ! X"$DIFF" = "X" ]; then
+               PARSECHOICE1=$(echo $CDDBDIFFCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
+               PARSECHOICE2=$(echo $CDDBDIFFCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
+               if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBDIFFCHOICES ] || \
+                  [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBDIFFCHOICES ] || \
+                  [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
+                       echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBDIFFCHOICES" >&2
+               else
+                       # We parse the 2 choices to diff, store them in temporary files and diff them.
+                       for PARSECHOICE in $(echo $CDDBDIFFCHOICE | tr , \ ); do
+                               do_cddbparse "$ABCDETEMPDIR/$FILENAME.$PARSECHOICE" > "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE"
+                       done
+                       echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/$FILENAME.diff"
+                       $DIFF $DIFFOPTS "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/$FILENAME.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/$FILENAME.diff"
+                       if [ $(cat "$ABCDETEMPDIR/$FILENAME.diff" | wc -l) -ge 24 ]; then
+                               page "$ABCDETEMPDIR/$FILENAME.diff"
+                       else
+                               cat "$ABCDETEMPDIR/$FILENAME.diff" >&2
+                       fi
+               fi
+       else
+               echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBDIFFCHOICES." >&2
+       fi
+}
 
-do_getcddbinfo()
+# getcddbinfo
+# Finds an specific field from cddbinfo
+getcddbinfo()
 {
        case $1 in
        TRACKNAME1)
@@ -305,9 +412,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
@@ -318,49 +425,121 @@ 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 reply-gain information..."
-               for OUTPUT in $( echo $OUTPUTTYPE | tr , \ )
-               # THE OUTPUT NEEDS TO BE CORRECTED WITH THE CONTAINER?
+               run_command "" echo "Adding replygain 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)
+                               gettracknum
+                               if [ "$ONETRACK" = "y" ]; then 
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
+                                       fi
+                               else    
+                                       if [ "$VARIOUSARTISTS" = "y" ]; then
+                                               OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
+                                       else
+                                               OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
+                                       fi
                                fi
-                               OUTPUTFILES="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT $OUTPUTFILES"
+                               OUTPUTFILES[$REPLAYINDEX]="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
+                               (( REPLAYINDEX = $REPLAYINDEX + 1 ))
                        done
                        case "$OUTPUT" in
                                flac)
-                                       run_command replaygain-flac $METAFLAC --add-replay-gain $OUTPUTFILES
+                                       run_command replaygain-flac $METAFLAC --add-replay-gain "${OUTPUTFILES[@]}"
                                        ;;
                                vorbis|ogg)
-                                       run_command replaygain-vorbis $VORBISGAIN --album $OUTPUTFILES
+                                       run_command replaygain-vorbis $VORBISGAIN --album "${OUTPUTFILES[@]}"
+                                       ;;
+                               mp3)
+                                       run_command replaygain-mp3 $MP3GAIN -a "${OUTPUTFILES[@]}"
+                                       ;;
+                               mpc)
+                                       run_command replaygain-mpc $MPPGAIN --auto "${OUTPUTFILES[@]}"
                                        ;;
                                *);;
                        esac
                done
-               if checkerrors replaygain-.{3,6}; then :; else
+               if checkerrors "replaygain-.{3,6}"; then :; else
                        run_command replaygain true
                fi
        fi
@@ -587,16 +766,12 @@ return 0
 do_tag ()
 {
        COMMENTOUTPUT="$(eval echo ${COMMENT})"
+       CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
        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 "$STARTTRACKNUMBER" -a -n "$STARTTRACKNUMBERTAG" ] ; then
-#              # Get the trackpadding from the current track
-#              CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
-#              TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
-#      fi
        if [ -n "$STARTTRACKNUMBERTAG" ] ; then
-               do_gettracknum
+               gettracknum
        fi
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
@@ -608,15 +783,25 @@ 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" \
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot
+                                       # happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS \
+                                               --comment=::"$COMMENTOUTPUT" -A "$DALBUM" \
+                                               -a "$TRACKARTIST" -t "$TRACKNAME" -Y "$CDYEAR" \
                                                -G "$GENREID" -n "${TRACKNUM:-$1}" "${TRACKNUM:+-N $TRACKS}" \
-                                               "${ENCODING:+--set-encoding=$ENCODING}"
+                                               "${ENCODING:+--set-encoding=$ENCODING}" \
+                                               "$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       ;;
+                               # FIXME # Still not activated...
+                               id3ed)
+                                       run_command tagtrack-$OUTPUT-$1 $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
+                                       # 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}" \
@@ -680,7 +865,7 @@ do_tag ()
                                        *)   echo COMMENT="$COMMENTOUTPUT";;
                                esac    
                        fi
-                       ) | run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                       ) | run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
                        ;;
                spx)
                        run_command tagtrack-$OUTPUT-$1 true
@@ -688,6 +873,12 @@ do_tag ()
                mpc)
                        run_command tagtrack-$OUTPUT-$1 true
                        ;;
+               m4a)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
+               wav)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
                esac
        done
        if checkerrors "tagtrack-(.{3,6})-$1"; then :; else
@@ -696,40 +887,50 @@ do_tag ()
 
 }
 
-# do_batch_encode
+# do_nogap_encode
 # variables used:
 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
-do_batch_encode ()
+do_nogap_encode ()
 {
        # The commands here don't go through run_command because they're never supposed to be silenced
-       echo "Batch encoding tracks: $TRACKQUEUE"
-       OUTPUT=$(echo $OUTPUTTYPE | grep "mp3" )
-       case "$OUTPUT" in
-       mp3)
-               case "$MP3ENCODERSYNTAX" in
-               lame)
-                       (
-                       cd "$ABCDETEMPDIR"
-                       TRACKFILES=
-                       for UTRACKNUM in $TRACKQUEUE
-                       do
-                               TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
-                       done
-                       nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS `[ "$MP3ENCODER" = "lame" ] && echo "--nogap"` $TRACKFILES
-                       RETURN=$?
-                       if [ "$RETURN" != "0" ]; then
-                               echo "batch-encode: $ENCODER returned code $RETURN" >> errors
-                       else
+       echo "Encoding gapless MP3 tracks: $TRACKQUEUE"
+       for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+       do
+               case "$OUTPUT" in
+               mp3)
+                       case "$MP3ENCODERSYNTAX" in
+                       lame)
+                               (
+                               cd "$ABCDETEMPDIR"
+                               TRACKFILES=
                                for UTRACKNUM in $TRACKQUEUE
                                do
-                                       run_command encodetrack-$UTRACKNUM true
+                                       TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
                                done
-                       fi
-                       )
+                               nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
+                               RETURN=$?
+                               if [ "$RETURN" != "0" ]; then
+                                       echo "nogap-encode: $ENCODER returned code $RETURN" >> errors
+                               else
+                                       for UTRACKNUM in $TRACKQUEUE
+                                       do
+                                               run_command encodetrack-$OUTPUT-$UTRACKNUM true
+                                               #run_command encodetrack-$UTRACKNUM true
+                                       done
+                               fi
+                               )
+                               ;;
+                       esac
                        ;;
                esac
-               ;;
-       esac
+       done            
+       if checkerrors "nogap-encode"; then :; else
+               if [ ! "$KEEPWAVS" = "y" ] ; then
+                       if [ ! "$KEEPWAVS" = "move" ] ; then
+                               rm -f "$IN"
+                       fi
+               fi
+       fi
        # Other encoders fall through to normal encoding as the tracks
        # have not been entered in the status file.
 }
@@ -757,6 +958,9 @@ do_encode ()
                        mpc)
                                TEMPARG="PIPE_$MPPENCODER"
                                ;;
+                       m4a)
+                               TEMPARG="PIPE_$MPPENCODER"
+                               ;;
                esac
                IN="$( eval echo "\$$TEMPARG" )"
        else
@@ -765,6 +969,7 @@ do_encode ()
                        mp3)
                                case "$MP3ENCODERSYNTAX" in
                                        # FIXME # check if mp3enc needs -if for pipes
+                                       # FIXME # I have not been able to find a working mp3enc binary
                                        mp3enc)
                                                FILEARG="-if $IN"
                                                ;;
@@ -780,21 +985,27 @@ 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
                        if [ X"$USEPIPES" = "Xy" ]; then
                                RUN_COMMAND=""
+                               # We need a way to store the creation of the files when using PIPES
+                               RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
                        else
                                run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
                                RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
@@ -831,16 +1042,15 @@ do_encode ()
                                ;;
                        flac)
                                case "$2" in
-                               %local*%)
+                               %local*%)
                                        case "$FLACENCODERSYNTAX" in
-                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
+                                       flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
                                        esac
-                                       ;;
-       
-                               *)
-                                       echo -n "DISTMP3:"
-                                       echo "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
-                                       $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
+                                               ;;
+                                       *)
+                                               vecho -n "DISTMP3:"
+                                               vecho "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
+                                               $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
                                        ;;
                                esac
                                ;;
@@ -868,13 +1078,28 @@ do_encode ()
                                ## FIXME ## to the encoder ends up empty.
                                $RUN_COMMAND nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
                                ;;
+                       m4a)
+                               # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
+                               if [ ! "$DOTAG" = "y" ]; then
+                                       $RUN_COMMAND nice $ENCNICE $AACENCODER $AACENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" -o "$OUT" "$IN"
+                                       
+                               else
+                                       $RUN_COMMAND nice $ENCNICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
+                               fi
+                               ;;
+                       wav)
+                               # In case of wav output we need nothing. Just keep the wavs.
+                               ;;
                        esac
+                       $RUN_COMMAND_PIPES
                done
                # Only remove .wav if the encoding succeeded
                if checkerrors "encodetrack-(.{3,6})-$1"; then :; else
                        run_command encodetrack-$1 true
                        if [ ! "$KEEPWAVS" = "y" ] ; then
-                               rm -f "$IN"
+                               if [ ! "$KEEPWAVS" = "move" ] ; then
+                                       rm -f "$IN"
+                               fi
                        fi
                fi
        else
@@ -973,7 +1198,7 @@ do_single_gain ()
 
 # do_batch_gain
 # variables used:
-# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
+# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPPGAIN, MPPGAINOPTS
 # FIXME #
 do_batch_gain ()
 {
@@ -987,7 +1212,7 @@ do_batch_gain ()
        do
                MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
        done
-       # XXX: Hard-coded batch option!
+       # FIXME # Hard-coded batch option!
        $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
        RETURN=$?
        if [ "$RETURN" != "0" ]; then
@@ -1055,8 +1280,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:
                # ' ' -> '_'
@@ -1068,39 +1297,64 @@ 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
-       #       if [ -n "$STARTTRACKNUMBER" ] ; then
-       #               # Get the trackpadding from the current track
-       #               CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
-       #               TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
-       #       else
-       #               TRACKNUM=${UTRACKNUM}
-       #       fi
-               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")"
-                       # mkdir -p shouldn't return an error if the directory already exists
-                       mkdir -p "$OUTPUTFILEDIR"
-                       run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
+                       case $OUTPUT in
+                               wav)
+                                       if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
+                                               # FIXME # introduce warnings?
+                                               :
+                                       else
+                                               # mkdir -p shouldn't return an error if the directory already exists
+                                               mkdir -p "$OUTPUTFILEDIR"
+                                               run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
+                                               if checkstatus movetrack-output-$OUTPUT; then :; else
+                                                       run_command movetrack-output-$OUTPUT true
+                                               fi
+                                       fi
+                                       ;;
+                               *)
+                                       # mkdir -p shouldn't return an error if the directory already exists
+                                       mkdir -p "$OUTPUTFILEDIR"
+                                       run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
+                                       if checkstatus movetrack-output-$OUTPUT; then :; else
+                                               run_command movetrack-output-$OUTPUT true
+                                       fi
+                                       ;;
+                       esac
                        # Lets move the cue file
                        if CUEFILE=$(checkstatus cuefile) >/dev/null ; then 
                                if [ -r "$ABCDETEMPDIR/$CUEFILE" ]; then
@@ -1109,6 +1363,14 @@ do_move ()
                                                #run_command '' vecho "Copying cue file to its destination directory..."
                                                if checkstatus onetrack >/dev/null ; then
                                                        case $OUTPUT in
+                                                               wav)
+                                                                       if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
+                                                                               # We dont have the dir, since it was not created before.
+                                                                               :
+                                                                       else
+                                                                               run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
+                                                                       fi
+                                                                       ;;
                                                                # NOTE: Creating a cue file with the 3-char-extension files is to comply with
                                                                # http://brianvictor.tripod.com/mp3cue.htm#details
                                                                [a-z0-9][a-z0-9][a-z0-9])
@@ -1136,29 +1398,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
@@ -1186,26 +1451,18 @@ do_playlist ()
                        do
                                # Shares some code with do_move since the filenames have to match
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                               #TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
-                               do_getcddbinfo TRACKNAME
+                               getcddbinfo TRACKNAME
                                splitvarious
                                TRACKFILE="$(mungefilename "$TRACKNAME")"
                                ARTISTFILE="$(mungefilename "$TRACKARTIST")"
                                ALBUMFILE="$(mungefilename "$DALBUM")"
                                # If we want to start the tracks with a given number, we need to modify the
                                # TRACKNUM value before evaluation
-                       #       if [ -n "$STARTTRACKNUMBER" ] ; then
-                       #               # Get the trackpadding from the current track
-                       #               CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
-                       #               TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
-                       #       else
-                       #               TRACKNUM=${UTRACKNUM}
-                       #       fi
-                               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
@@ -1248,17 +1505,78 @@ do_discid ()
                if [ "$OSFLAVOUR" = "OSX" ]; then
                        disktool -u ${CDROM#/dev/}
                fi
-               TRACKINFO=$($CDDISCID $CDROM)
+               case "$CDROMREADERSYNTAX" in
+                       flac)
+                               if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" > /dev/null 2>&1 ; then
+                                       case "$CUE2DISCID" in
+                                               builtin)
+                                                       #vecho "Using builtin cue2discid implementation..."
+                                                       CUESHEET="$(metaflac $METAFLACOPTS --export-cuesheet-to=- "$CDROM")"
+
+                                                       #TRACKS=$(echo $CUESHEET | egrep "TRACK \+[[:digit:]]\+ \+AUDIO" |wc -l)
+                                                       #TRACKS=0
+                                                       OFFSETTIMES=( $(echo "$CUESHEET" | sed -n -e's/\ *INDEX 01\ \+//p' ) )
+                                                       TRACKS=${#OFFSETTIMES[@]}
+                                                       unset OFFSETS
+                                                       #echo "processing offsetimes ${OFFSETTIMES[@]}"
+                                                       for OFFSETTIME in ${OFFSETTIMES[@]}; do
+                                                               OFFSETS="$OFFSETS $(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))"
+                                                               #OFFSETS[${#OFFSETS[*]}]=$(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))
+                                                       done
+
+                                                       LEADOUT=$(( $(echo "$CUESHEET" | grep lead-out | get_last) / 44100 * 75 ))
+                                                       LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) / 44100 * 75 ))
+                                                       makeids
+                                               ;;
+                                               *)
+                                                       #vecho "Using external python cue2discid implementation..."
+                                                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" | $CUE2DISCID)
+                                               ;;
+                                       esac
+                               else
+                                       log error "the input flac file does not contain a cuesheet."
+                                       exit 1
+                               fi
+                               ;;
+#                      cdparanoia|debug)
+#                              CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
+#                              RET=$?
+#                              if [ ! "$RET" = "0" ];then
+#                                      log warning "something went wrong while querying the CD... Maybe a DATA CD?"
+#                              fi
+#
+#                              TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
+#                              CDPARANOIAAUDIOTRACKS="$TRACKS"
+#
+#                              LEADOUT="$(echo "$CDPARANOIAOUTPUT" | egrep -o '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
+#                              OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')" 
+#                              makeids
+#                              ;;
+                       *)
+                               case "$CDDBMETHOD" in
+                                       cddb) TRACKINFO=$($CDDISCID $CDROM) ;;
+                                       # FIXME # musicbrainz needs a cleanup
+                                       musicbrainz) TRACKINFO=$($MUSICBRAINZ -c $CDROM ) ;;
+                               esac
+                               ;;
+               esac
                # Make sure there's a CD in there by checking cd-discid's return code
-               if [ "$?" = "1" ]; then
-                       echo "abcde error: CD could not be read. Perhaps there's no CD in the drive?" >&2
-                       exit 1
+               if [ ! "$?" = "0" ]; then
+                       if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
+                               log error "cuesheet information from the flac file could not be read."
+                               log error "Perhaps the flac file does not contain a cuesheet?."
+                               exit 1
+                       else
+                               log error "CD could not be read. Perhaps there's no CD in the drive?"
+                               exit 1
+                       fi
                fi
                # In OSX, remount the disc again
                if [ "$OSFLAVOUR" = "OSX" ]; then
                        disktool -m ${CDROM#/dev/}
                fi
                WEHAVEACD=y
+               DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
        else
                TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
        fi
@@ -1277,7 +1595,7 @@ 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
@@ -1285,14 +1603,17 @@ do_discid ()
                                                CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
                                                RET=$?
                                                if [ ! "$RET" = "0" ];then
-                                                       echo "Warning: Something went wrong while querying the CD... Maybe a DATA CD?"
+                                                       log warning "something went wrong while querying the CD... Maybe a DATA CD?"
                                                fi
                                                TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
                                                CDPARANOIAAUDIOTRACKS="$TRACKS"
                                        else
-                                               if [ -f "$ABCDETEMPDIR/status" ] && checkstatus cdparanoia-audio-tracks ; then
-                                                       TRACKS=$(checkstatus cdparanoia-audio-tracks)
-                                               else
+                                               # Previous versions of abcde would store the tracks on a file, instead of the status record.
+                                               if [ -f "$ABCDETEMPDIR/cdparanoia-audio-tracks" ]; then
+                                                       echo cdparanoia-audio-tracks=$( cat "$ABCDETEMPDIR/cdparanoia-audio-tracks" ) >> "$ABCDETEMPDIR/status"
+                                                       rm -f "$ABCDETEMPDIR/cdparanoia-audio-tracks"
+                                               fi
+                                               if [ -f "$ABCDETEMPDIR/status" ] && TRACKS=$(checkstatus cdparanoia-audio-tracks); then :; else
                                                        TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
                                                fi
                                        fi
@@ -1303,7 +1624,7 @@ do_discid ()
                        TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
                fi
                if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
-                       echo "The disc does not contain any tracks. Giving up..."
+                       log info "The disc does not contain any tracks. Giving up..."
                        exit 0
                fi
                echo -n "Grabbing entire CD - tracks: "
@@ -1315,7 +1636,7 @@ do_discid ()
                while [ "$X" -ne "$TRACKS" ]
                do
                        X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
-                       TRACKQUEUE=$(echo "$TRACKQUEUE" $X)
+                       TRACKQUEUE=$(echo $TRACKQUEUE $X)
                done
                echo $TRACKQUEUE
        else
@@ -1378,7 +1699,7 @@ do_discid ()
                                exit 1
                        fi
                        rm -rf "$ABCDETEMPDIR" || exit 1
-                       mkdir "$ABCDETEMPDIR"
+                       mkdir -p "$ABCDETEMPDIR"
                        if [ "$?" -gt "0" ]; then
                                # Directory already exists or could not be created
                                echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
@@ -1400,43 +1721,56 @@ do_discid ()
                fi
        else
                # We are starting from scratch
-               mkdir "$ABCDETEMPDIR"
+               mkdir -p "$ABCDETEMPDIR"
                if [ "$?" -gt "0" ]; then
                        # Directory already exists or could not be created
                        echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
                        exit 1
                fi
                cat /dev/null > "$ABCDETEMPDIR/status"
+               # Store the abcde version in the status file.
+               echo "abcde-version=$VERSION" >> "$ABCDETEMPDIR/status"
        fi
        if [ X"$MAKECUEFILE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
                if checkstatus cuefile > /dev/null 2>&1 ; then :; else
                        CUEFILE=cue-$(echo "$TRACKINFO" | cut -f1 -d' ').txt
                        vecho "Creating cue file..."
-                       if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
-                               echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
-                       else
-                               echo "abcde: reading the CUE sheet with mkcue is still considered experimental"
-                               echo "abcde: and there was a problem with the CD reading. abcde will continue,"
-                               echo "abcde: but consider reporting the problem to the abcde author"
-                       fi
+                       case $CDROMREADERSYNTAX in
+                               flac)
+                                       if $METAFLAC --export-cuesheet-to=- $CDROM > "$ABCDETEMPDIR/$CUEFILE"; then :; 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
        if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
-               if checkstatus cdparanoia-audio-tracks; then :; else
+               if checkstatus cdparanoia-audio-tracks > /dev/null 2>&1; then :; else
                        echo cdparanoia-audio-tracks=$CDPARANOIAAUDIOTRACKS >> "$ABCDETEMPDIR/status"
                fi
        fi
        
        # Create the discid file
        echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
+       if checkstatus cddbmethod > /dev/null 2>&1 ; then :; else
+               echo "cddbmethod=$CDDBMETHOD" >> "$ABCDETEMPDIR/status"
+       fi
 }
 
 # do_cleancue
 # Create a proper CUE file based on the CUE file we created before.
 do_cleancue()
 {
-       # FIXME # we can get the name of the cuefile from the status file
        if CUEFILE_IN="$ABCDETEMPDIR"/$(checkstatus cuefile); then
                CUEFILE_OUT=$CUEFILE_IN.out
                ### FIXME ### checkstatus cddb
@@ -1449,8 +1783,7 @@ do_cleancue()
                        echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
                        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
                                        eval track="\$TRACK$n"
                                        n=$(expr $n + 1)
                                        echo "TITLE \"$track\"" >> "$CUEFILE_OUT"
@@ -1500,44 +1833,141 @@ 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"
-                               cp "${CDDBLOCALFILE}" "$ABCDETEMPDIR/cddbread.1"
-                               echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
-                               echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
-                               do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
-                               echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
-                               CDDBLOCALSUCCESS="y"
+
+               if [ "$CDDBLOCALRECURSIVE" = "y" ]; then
+                       CDDBLOCALRESULTS="$(find ${CDDBLOCALDIR} -name "${CDDBDISCID}" -type f 2> /dev/null)"
+                       if [ ! "${CDDBLOCALRESULTS}" = "" ]; then
+                               if   (( $(echo "${CDDBLOCALRESULTS}" | wc -l) == 1 )); then
+                                       CDDBLOCALFILE="${CDDBLOCALRESULTS}"
+                                       CDDBLOCALMATCH=single
+                               elif (( $(echo "${CDDBLOCALRESULTS}" | wc -l) > 1 )); then
+                                       CDDBLOCALMATCH=multiple
+                               fi
                        else
-                               #echo "Not using local copy of CDDB data"
-                               CDDBLOCALSUCCESS="n"
+                               CDDBLOCALMATCH=none
                        fi
+               elif [ "$CDDBLOCALMATCH" = "none" ] && [ -r "${CDDBLOCALDIR}/${CDDBDISCID}" ]; then
+                       CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
+                       CDDBLOCALMATCH=single
                else
-                       CDDBLOCALSUCCESS="n"
+                       CDDBLOCALMATCH=none
                fi
+               
+               # If the user has selected to check a local CDDB repo, we proceed with it
+               case $CDDBLOCALMATCH in
+                       multiple)
+                               echo "Processing multiple matching CDDB entries..." > "$ABCDETEMPDIR/cddblocalchoices"
+                               X=0
+                               echo "$CDDBLOCALRESULTS" | while read RESULT ; do
+                                       X=$(expr $X + 1)
+                                       # List out disc title/author and contents
+                                       CDDBLOCALREAD="$ABCDETEMPDIR/cddblocalread.$X"
+                                       cat "$RESULT" > "${CDDBLOCALREAD}"
+                                       {       
+                                               echo -n "#$X: "
+                                               do_cddbparse "${CDDBLOCALREAD}" 
+                                               echo ""
+                                               ##FIXME## QUICK HACK !!!!
+                                               if [ ! "$INTERACTIVE" = "y" ]; then break ; fi
+                                       } >> "$ABCDETEMPDIR/cddblocalchoices"
+                               done
+                               if [ $(cat "$ABCDETEMPDIR/cddblocalchoices" | wc -l) -ge 24 ] && [ "$INTERACTIVE" = "y" ]; then
+                                       page "$ABCDETEMPDIR/cddblocalchoices"
+                               else
+                                       # It's all going to fit in one page, cat it
+                                       cat "$ABCDETEMPDIR/cddblocalchoices" >&2
+                               fi
+                               CDDBLOCALCHOICES=$( echo "$CDDBLOCALRESULTS" | wc -l )
+                               # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
+                               CDDBLOCALCHOICENUM=-1
+                               if [ "$INTERACTIVE" = "y" ]; then
+                                       while [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; do
+                                               echo -n "Locally cached CDDB entries found. Which one would you like to use (0 for none)? [0-$CDDBLOCALCHOICES]: " >&2
+                                               read CDDBLOCALCHOICE
+                                               [ x"$CDDBLOCALCHOICE" = "x" ] && CDDBLOCALCHOICE="1"
+                                               # FIXME # Introduce diff's
+                                               if echo $CDDBLOCALCHOICE | egrep "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
+                                               elif echo $CDDBLOCALCHOICE | egrep "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       # Make sure we get a valid choice
+                                                       CDDBLOCALCHOICENUM=$(echo $CDDBLOCALCHOICE | xargs printf %d 2>/dev/null)
+                                                       if [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; then
+                                                               echo "Invalid selection. Please choose a number between 0 and $CDDBLOCALCHOICES." >&2
+                                                       fi
+                                               fi
+                                       done
+                               else
+                                       ### FIXME ###
+                                       #echo "Selected ..."
+                                       CDDBLOCALRESP=y
+                                       CDDBLOCALCHOICENUM=1
+                               fi
+                               if [ ! "$CDDBLOCALCHOICENUM" = "0" ]; then
+                                       #echo "Using local copy of CDDB data"
+                                       echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
+                                       cat "$ABCDETEMPDIR/cddblocalread.$CDDBLOCALCHOICENUM" >> "$ABCDETEMPDIR/cddbread.1"
+                                       echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
+                                       echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
+                                       do_cddbparse "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbchoices"
+                                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                                       CDDBLOCALSTATUS="found"
+                               else
+                                       #echo "Not using local copy of CDDB data"
+                                       CDDBLOCALSTATUS="notfound"
+                               fi
+                               ;;
+                       single)
+                               # List out disc title/author and contents
+                               do_cddbparse "${CDDBLOCALFILE}"
+                               #if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
+                               #       echo -n "Embedded cuesheet entry found, use it? [y/n] (y): " >&2
+                               #else
+                                       echo -n "Locally cached CDDB entry found, use it? [y/n] (y): " >&2
+                               #fi
+                               if [ "$INTERACTIVE" = "y" ]; then
+                                       read USELOCALRESP
+                                       while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
+                                               echo -n 'Invalid selection. Please answer "y" or "n": ' >&2
+                                               read USELOCALRESP
+                                       done
+                                       [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
+                               else
+                                       echo "y" >&2
+                               fi
+                               if [ "$USELOCALRESP" = "y" ]; then
+                                       #echo "Using local copy of CDDB data"
+                                       echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
+                                       cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
+                                       echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
+                                       echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
+                                       do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
+                                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                                       CDDBLOCALSTATUS="single"
+                               else
+                                       #echo "Not using local copy of CDDB data"
+                                       CDDBLOCALSTATUS="notfound"
+                               fi
+                               ;;
+                       none)
+                               CDDBLOCALSTATUS="notfound"
+                               ;;
+               esac
        fi
 }
 
+do_musicbrainzstat ()
+{
+       :
+}
+
+do_musicbrainz ()
+{
+       :
+}
+
 # do_cddbstat
 do_cddbstat ()
 {
@@ -1583,7 +2013,7 @@ do_cddbquery ()
                if [ "$CDDBAVAIL" = "n" ]; then
                        ERRORCODE=no_query
                        echo 503 > "$ABCDETEMPDIR/cddbquery"
-               # The default CDDBLOCALSUCCESS is "n"
+               # The default CDDBLOCALSTATUS is "notfound"
                # This part will be triggered if the user CDDB repo does not 
                # contain the entry, or if we are not trying to use the repo.
                else
@@ -1722,7 +2152,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
@@ -1730,6 +2160,13 @@ do_cddbedit ()
                                CHOICE=$(checkstatus cddb-choice)
                                if [ -n "$CHOICE" ] ; then
                                        case $CDDBCHOICES in
+                                               -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep "^$" > /dev/null 2>&1 ; then
+                                                               log error "CDDB query failed!" 
+                                                               exit 1
+                                                       else
+                                                               cat "$ABCDETEMPDIR/cddbchoices"
+                                                       fi
+                                                       ;;
                                                1) cat "$ABCDETEMPDIR/cddbchoices" ;;
                                                *)
                                                echo "Selected: #$CHOICE"
@@ -1753,16 +2190,15 @@ do_cddbedit ()
                                                echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
                                                read CDDBCHOICE
                                                [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
-                                               if echo $CDDBCHOICE | egrep -q "[[:digit:]]+,[[:digit:]]+" ; then
+                                               if echo $CDDBCHOICE | egrep "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
                                                        if [ ! X"$DIFF" = "X" ]; then
-                                                               PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1)
-                                                               PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2)
+                                                               PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
+                                                               PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
                                                                if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBCHOICES ] || \
                                                                   [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBCHOICES ] || \
                                                                   [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
                                                                        echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBCHOICES" >&2
                                                                else
-
                                                                        # We parse the 2 choices to diff, store them in temporary files and diff them.
                                                                        for PARSECHOICE in $(echo $CDDBCHOICE | tr , \ ); do
                                                                                do_cddbparse "$ABCDETEMPDIR/cddbread.$PARSECHOICE" > "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE"
@@ -1778,10 +2214,10 @@ do_cddbedit ()
                                                        else
                                                                echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
                                                        fi
-                                               else
+                                               elif echo $CDDBCHOICE | egrep "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
+                                                       # Make sure we get a valid choice
+                                                       CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
                                                        if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
-                                                               # Make sure we get a valid choice
-                                                               CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
                                                                echo "Invalid selection. Please choose a number between 0 and $CDDBCHOICES." >&2
                                                        fi
                                                fi
@@ -1829,7 +2265,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
@@ -1898,7 +2334,7 @@ do_cddbedit ()
                        /usr/bin/mg "$CDDBDATA"
                # bomb out
                else
-                       echo "No editor available. Check your EDITOR environment variable." >&2
+                       log warning "no editor available. Check your EDITOR environment variable."
                fi
                # delete editor backup file if it exists
                if [ -w "$CDDBDATA~" ]; then
@@ -2019,10 +2455,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
 
@@ -2042,27 +2480,31 @@ 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" ;;
+                       cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTTRACK" ;;
                        *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
-                          exit 1 ;;
+                               exit 1 ;;
                esac
        else
                UTRACKNUM=$1
        fi
        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
        if [ "$USEPIPES" = "y" ]; then
-               TEMPARG="PIPE_$CDROMREADERSYNTAX"
+               TEMPARG="PIPERIPPER_$CDROMREADERSYNTAX"
                FILEARG="$( eval echo "\$$TEMPARG" )"
                REDIR=""
                PIPE_MESSAGE="and encoding "
        else
                WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
                case "$CDROMREADERSYNTAX" in
-               ## FIXME ## Find the case for dagrab, to avoid exceptions
+               ## FIXME ## Find the cases for dagrab and flac, to avoid exceptions
+                       flac)
+                               FILEARG="--output-name=$WAVDATA"
+                               ;;
                        dagrab)
                                FILEARG="-f $WAVDATA"
                                ;;
@@ -2076,14 +2518,19 @@ do_cdread ()
                echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK as one track ..." >&2
        else
                if [ -r "$CDDBDATA" ]; then
-                       #TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
                else
                        echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
                fi
        fi
        case "$CDROMREADERSYNTAX" in
+               ### FIXME ### use an exception for flac, since it uses -o
+               ### FIXME ### Shall we just use -o $FILEARG ??
+               flac)
+                       # Avoid problems wit math expressions by unpadding the given UTRACKNUM
+                       STRIPTRACKNUM=$(expr $UTRACKNUM + 0)
+                       nice $READNICE $FLAC -d -f --cue=${READTRACKNUMS:-$STRIPTRACKNUM.1-$(($STRIPTRACKNUM + 1)).0} "$FILEARG" "$CDROM" ;;
                cdparanoia) 
                        nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
                cdda2wav)
@@ -2141,9 +2588,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
 }
@@ -2165,7 +2612,25 @@ do_cdspeed ()
 vecho ()
 {
 if [ x"$EXTRAVERBOSE" != "x" ]; then
-       echo $@
+       case $1 in
+               warning) shift ; log warning "$@" ;;
+               *) echo "$@" ;;
+       esac
+fi
+}
+
+# decho [message]
+#
+# decho outputs a debug message if DEBUG is selected
+decho ()
+{
+if [ x"$DEBUG" != "x" ]; then
+       if echo $1 | grep "^\[" > /dev/null 2>&1 ; then
+               DEBUGECHO=$(echo "$@" | tr -d '[]')
+               echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
+       else
+               echo "[DEBUG] $1"
+       fi
 fi
 }
 
@@ -2204,11 +2669,17 @@ post_read ()
 ###############################################################################
 
 # Builtin defaults
+
+# CDDB
+# Defaults to FreeDB, but a python musicbrainz can be used
+CDDBMETHOD=cddb
 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
 CDDBSUBMIT=freedb-submit@freedb.org
-CDDBPROTO=5
+CDDBPROTO=6
 HELLOINFO="$(whoami)@$(hostname)"
 CDDBCOPYLOCAL="n"
+CDDBLOCALPOLICY="always"
+CDDBLOCALRECURSIVE="y"
 CDDBLOCALDIR="$HOME/.cddb"
 CDDBUSELOCAL="n"
 
@@ -2216,7 +2687,7 @@ CDDBUSELOCAL="n"
 SHOWCDDBFIELDS="year,genre"
 
 INTERACTIVE=y
-CDROMREADERSYNTAX=cdparanoia
+#CDROMREADERSYNTAX=cdparanoia
 ENCODERSYNTAX=default
 
 MP3ENCODERSYNTAX=default
@@ -2224,6 +2695,7 @@ OGGENCODERSYNTAX=default
 FLACENCODERSYNTAX=default
 SPEEXENCODERSYNTAX=default
 MPPENCODERSYNTAX=default
+AACENCODERSYNTAX=default
 NORMALIZERSYNTAX=default
 CUEREADERSYNTAX=default
 
@@ -2247,6 +2719,8 @@ VARIOUSARTISTS=n
 VARIOUSARTISTSTYLE=forward
 KEEPWAVS=n
 PADTRACKS=n
+NOGAP=n
+BATCHNORM=n
 
 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
 # i.e. CDROMID="1,0,0"
@@ -2258,6 +2732,7 @@ CDPARANOIACDROMBUS="d"
 # program paths - defaults to checking your $PATH
 # mp3
 LAME=lame
+TOOLAME=toolame
 GOGO=gogo
 BLADEENC=bladeenc
 L3ENC=l3enc
@@ -2272,6 +2747,8 @@ FLAC=flac
 SPEEXENC=speexenc
 # mpp (Musepack)
 MPPENC=mppenc
+# m4a
+AACENC=faac
 
 ID3=id3
 ID3V2=id3v2
@@ -2282,6 +2759,7 @@ DAGRAB=dagrab
 CDDAFS=cp
 CDDISCID=cd-discid
 CDDBTOOL=cddb-tool
+MUSICBRAINZ=musicbrainz-get-tracks
 EJECT=eject
 MD5SUM=md5sum
 DISTMP3=distmp3
@@ -2290,13 +2768,17 @@ METAFLAC=metaflac
 NORMALIZE=normalize-audio
 CDSPEED=eject
 VORBISGAIN=vorbisgain
+MP3GAIN=mp3gain
+MPPGAIN=replaygain
 MKCUE=mkcue
 MKTOC=cdrdao
 DIFF=diff
+CUE2DISCID=builtin
 
 # Options for programs called from abcde
 # mp3
 LAMEOPTS=
+TOOLAMEOPTS=
 GOGOOPTS=
 BLADEENCOPTS=
 L3ENCOPTS=
@@ -2306,11 +2788,13 @@ MP3ENCOPTS=
 VORBIZEOPTS=
 OGGENCOPTS=
 # flac
-FLACOPTS="-f"
+FLACOPTS=
 # speex
 SPEEXENCOPTS=
 # mpc
 MPPENCOPTS=
+# m4a
+AACENCOPTS=
 
 ID3OPTS=
 ID3V2OPTS=
@@ -2328,6 +2812,7 @@ MKCUEOPTS=
 MKTOCOPTS=""
 VORBISCOMMENTOPTS="-R"
 METAFLACOPTS="--no-utf8-convert"
+DIFFOPTS=
 
 # Default to one process if -j isn't specified
 MAXPROCS=1
@@ -2335,12 +2820,17 @@ MAXPROCS=1
 # List of actions to perform - by default, run to completion
 ACTIONS=cddb,read,encode,tag,move,clean
 
+# This option is basicaly for Debian package dependencies: 
 # List of prefered outputs - by default, run with whatever we have in the path
-# This option is basicaly for Debian package dependencies
-DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:lame,mp3:bladeenc,spx:speex
+DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:lame,mp3:bladeenc,spx:speex,m4a:faac
 
-# 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 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. 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
@@ -2355,9 +2845,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
@@ -2393,8 +2889,8 @@ if [ "$HTTPGETOPTS" = "" ] ; then
                wget) HTTPGETOPTS="-q -O -";;
                curl) HTTPGETOPTS="-f -s";;
                fetch)HTTPGETOPTS="-q -o -";;
-               ftp)  HTTPGETOPTS="-q -o -";;
-               *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
+               ftp)  HTTPGETOPTS="-a -V -o - ";;
+               *) log warning "HTTPGET in non-standard and HTTPGETOPTS are not defined." ;;
        esac
 fi
 
@@ -2416,22 +2912,23 @@ if [ "$CDROM" = "" ] ; then
 fi
 
 # Parse command line options
-#while getopts 1a:A:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
-while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
+#while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
+while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxX:w:W:z opt ; do
        case "$opt" in
                1) ONETRACK=y ;;
                a) ACTIONS="$OPTARG" ;;
                A) EXPACTIONS="$OPTARG" ;;
-               b) BATCH=y ;;
-               c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
-               C) DISCID="${OPTARG#abcde.}" ;;
+               b) BATCHNORM=y ;;
+               B) NOBATCHREPLAYGAIN=y ;;
+               c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else log error "config file \"$OPTARG\" cannot be found." ; exit 1 ; fi ;;
+               C) DISCID="$( echo ${OPTARG#abcde.} | tr -d /)" ;;
                d) CDROM="$OPTARG" ;;
                D) set -x ;;
-               e) ERASEENCODEDSTATUS=y ;;
                h) usage; exit ;;
                e) ERASEENCODEDSTATUS=y ;;
                E) ENCODING="$OPTARG" ;;
-#              f) FORCECDDBUSELOCAL=y ;;
+               f) FORCE=y ;;
+               g) NOGAP=y ;;
                i) INLINETAG=y ;;
                j) MAXPROCS="$OPTARG" ;;
                k) KEEPWAVS=y ;;
@@ -2445,14 +2942,13 @@ while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
                p) PADTRACKS=y ;;
                P) USEPIPES=y ;;
                r) REMOTEHOSTS="$OPTARG" ;;
-               R) REPLAYGAIN=y ;;
+               R) CDDBLOCALRECURSIVE=y ;;
                s) SHOWCDDBFIELDS="$OPTARG" ;;
                S) CDSPEEDVALUE="$OPTARG" ;;
-#              t) PREPROCESSFORMATS="$OPTARG"
-#                 PREPROCESS=y ;;
-#              T) POSTPROCESSFORMATS="$OPTARG" ;;
                t) STARTTRACKNUMBER="$OPTARG" ;;
                T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
+               u) CDDBPROTO=6 ;;
+               U) CDDBPROTO=5 ;;
                v) 
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
@@ -2461,37 +2957,83 @@ while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: 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
-                    echo "abcde error: argument of -W must be integer"
+                    log error "argument of -W must be integer"
                         exit 1
                   fi
                   ;;
+               z) DEBUG=y ; CDROMREADERSYNTAX=debug ; EJECTCD="n" ;;
                ?) usage; exit ;;
        esac
 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 the user specified a flac file, then switch to special flac mode
+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" ] || [ "$CDROMREADERSYNTAX" = "flac" ]; then EJECTCD=n ; fi
+
+# Check the available cd rippers in the system, from the ones we know.
+if [ "$CDROMREADERSYNTAX" = "" ]; then
+       for DEFAULT_CDROMREADER in $DEFAULT_CDROMREADERS; do
+               if new_checkexec $DEFAULT_CDROMREADER; then
+                       CDROMREADERSYNTAX=$DEFAULT_CDROMREADER
+                       break
+               fi
+       done
+       if [ "$CDROMREADERSYNTAX" = "" ]; then
+               log error "no cdreader found in your PATH"
+               log error "hints: are all dependencies installed? has the \$PATH been modified?"
+               exit 1
+       fi
+fi
+
 # Decide if we can continue.
 if [ "$ONETRACK" = "y" ]; then 
        # FIXME # remove check as soon as we find out about the other readers
        case "$CDROMREADERSYNTAX" in
+               flac) ;;
                cdparanoia) ;;
                cdda2wav) ;;
-               *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
+               *) log error "$CDROMREADERSYNTAX does not support ONETRACK mode"
                   exit 1 ;;
        esac
-       if [ "$BATCH" = "y" ]; then
-               echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
-               BATCH=n
+       if [ "$BATCHNORM" = "y" ]; then
+               log warning "BATCHNORM mode is not compatible with ONETRACK mode. Disabling..."
+               BATCHNORM=n
+       fi
+       if [ "$NOGAP" = "y" ]; then
+               log warning "NOGAP mode is not compatible with ONETRACK mode. Disabling..."
+               NOGAP=n
        fi
        # It does not matter how many tracks we want. In ONETRACK mode we grab them all
        # FIXME # allow ranges of tracks to be selected for onetrack ripping
        if [ $# -gt 0 ]; then
-               vecho "abcde warning: ONETRACK mode selected, grabbing all tracks..."
+               log warning "ONETRACK mode selected, grabbing all tracks..."
        fi
 else
        while [ $# -gt 0 ]; do
@@ -2528,6 +3070,7 @@ DOCLEAN=n
 for ACTION in $(echo $ACTIONS | tr , \ )
 do
        case $ACTION in
+               default) DOCDDB=y; DOREAD=y; DOENCODE=y; DOTAG=y; DOMOVE=y; DOCLEAN=y;;
                cddb) DOCDDB=y;;
                read) DOREAD=y;;
                normalize) DONORMALIZE=y; DOREAD=y;;
@@ -2544,7 +3087,7 @@ done
 
 if [ "$DONORMALIZE" = "y" ] && [ "$DOREPLAYGAIN" = "y" ]; then
        # FIXME # should we abort on error or just inform the user?
-       :
+       log warning "selected both normalize and replaygain actions"
 fi
 
 for SHOWCDDBFIELD in $(echo $SHOWCDDBFIELDS | tr , \ ); do
@@ -2555,25 +3098,23 @@ 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
-                               echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
-                               echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
+                       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
                        fi
                fi
        elif [ ! -e "$CDROM" -a X"$DOREAD" = "Xy" ]; then
-               echo "abcde error: CDROM device cannot be found." >&2
+               log error "CDROM device cannot be found."
                exit 1
        fi
 # avoid processing if we are not going to hit the CDROM.
 elif [ X"$DOREAD" = "Xy" ]; then
-       echo "abcde error: CDROM has not been defined or cannot be found" >&2
+       log error "CDROM has not been defined or cannot be found"
        exit 1
 fi
 
@@ -2585,24 +3126,54 @@ fi
 # - anything else?
 if [ X"$USEPIPES" = "Xy" ]; then
        if [ $(echo "$OUTPUTTYPE" | tr , \  | wc -w ) -gt 1 ]; then
-               echo "abcde error: Unix pipes not compatible with multiple outputs" >&2
+               log error "Unix pipes not compatible with multiple outputs"
                exit 1
        fi
        if [ X"$DONORMALIZE" = "Xy" ]; then
-               echo "abcde error: Unix pipes not compatible with normalizer"
+               log error "Unix pipes not compatible with normalizer"
                # FIXME # Do we need to exit or shall we just disable the mode?
                exit 1
        fi
+       if [ X"$BATCHNORM" = "Xy" ]; then
+               log error "Unix pipes not compatible with BATCHNORM encoding"
+               exit 1
+       fi
+       if [ X"$NOGAP" = "Xy" ]; then
+               log error "Unix pipes not compatible with NOGAP encoding"
+               exit 1
+       fi
        if [ X"$DOENCODE" = "Xn" ]; then
-               vecho "Disabling Unix pipes since we are not encoding!"
+               vecho warning "Disabling Unix pipes since we are not encoding!"
                USEPIPES=n
        fi
        if [ X"$LOWDISK" = "Xy" ]; then
-               vecho "abcde error: Unix pipes not compatible with lowdisk algorithm"
+               log error "Unix pipes not compatible with lowdisk algorithm"
                exit 1
        fi
 fi
 
+# LOWDISK pre-tests, before we get into more problematic stuff
+# Not compatible with anything that needs all the files in the hard disc:
+# - BATCHNORM
+# - NOGAP lame mode
+if [ X"$LOWDISK" = "Xy" ]; then
+       if [ X"$BATCHNORM" = "Xy" ]; then
+               log error "Unix pipes not compatible with BATCHNORM encoding"
+               exit 1
+       fi
+       if [ X"$NOGAP" = "Xy" ]; then
+               log error "Unix pipes not compatible with NOGAP encoding"
+               exit 1
+       fi
+fi
+
+# BATCHNORM pre-tests, before we get into serious problems
+# Not compatible with 
+if [ "$BATCHNORM" = "y" ] && [ "$DONORMALIZE" = "n" ]; then
+       vecho warning "Disabling BATCHNORM since we are not normalizing!"
+       BATCHNORM=n
+fi
+
 # Check the encoding format from the ones available in the system, if nothing has been configured in the system.
 if [ X"$OUTPUTTYPE" = "X" ]; then
        for DEFAULT_OUTPUT in $( echo "$DEFAULT_OUTPUT_BINARIES" | tr , \ ); do
@@ -2615,8 +3186,8 @@ if [ X"$OUTPUTTYPE" = "X" ]; then
                fi
        done
        if [ X"$OUTPUTTYPE" = "X" ]; then
-               echo "abcde error: no encoder found in the PATH" >&2
-               echo "hits: are all dependencies installed? has the \$PATH been modified?" >&2
+               log error "no encoder found in the PATH"
+               log error "hints: are all dependencies installed? has the \$PATH been modified?"
                exit 1
        fi
 fi
@@ -2639,6 +3210,10 @@ case "$CDROMREADERSYNTAX" in
                CDROMREADER="$CDDAFS"
                CDROMREADEROPTS="$CDDAFSOPTS"
                ;;
+       flac)
+               CDROMREADER="$FLAC"
+               CDROMREADEROPTS="$FLACOPTS"
+               ;;
 esac
 
 # There's only one normalize...
@@ -2651,13 +3226,14 @@ esac
 
 # Allow -o OUTPUT(1):OPTIONS(1),...,OUTPUT(N):OPTIONS(N) mode of operation
 if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
-       for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
+       for OUTPUT in "$(echo "$OUTPUTTYPE" | tr \  \|| tr , \ | tr \| \ )"; do
                case "$OUTPUT" in
                        vorbis:*|ogg:*) OGGENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        mp3:*)  MP3ENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        flac:*) FLACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        spx:*)  SPEEXENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                        mpc:*)  MPPENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
+                       m4a:*)  AACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
                esac
        done
        for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
@@ -2667,7 +3243,8 @@ if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
        OUTPUTTYPE="$TEMPOUTPUTTYPE"
 fi
 
-# If nothing has been specified, use oggenc for oggs and lame for mp3s and flac for flacs and speexenc for speex and mppenc for mpps
+# If nothing has been specified, use oggenc for oggs and lame for mp3s and flac
+# for flacs and speexenc for speex and mppenc for mpps and faac for m4as
 
 # Getting ready for multiple output changes
 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
@@ -2676,24 +3253,38 @@ do
                vorbis|ogg)
                        [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
                        [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
-                       [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
                        OGGOUTPUTCONTAINER=ogg
                        ;;
                mp3)
                        [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
                        [ "$DOTAG" = "y" ] && NEEDTAGGER=y
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDMP3GAIN=y
                        ;;
                flac)
                        [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
                        [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDMETAFLAC=y
+                       [ "$ONETRACK" = "y" ] && [ "$MAKECUEFILE" = "y" ] && NEEDMETAFLAC=y 
                        ;;
                spx)
                        [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
+#                      [ "$DOREPLAYGAIN" = "y" ] &&
                        ;;
                mpc)
                        [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDMPPGAIN=y
+                       ;;
+               m4a)
+                       [ "$AACENCODERSYNTAX" = "default" ] && AACENCODERSYNTAX=faac
                        ;;
-               *)      echo "abcde error: Invalid OUTPUTTYPE defined" >&2
+               wav)
+                       if [ "$KEEPWAVS" = "y" ]; then
+                               vecho "Setting the KEEPWAVS option, since the resulting wav files were requested..."
+                       fi
+                       KEEPWAVS=move
+                       ;;
+               *)      log error "Invalid OUTPUTTYPE defined"
                        exit 1
                        ;;
        esac
@@ -2705,6 +3296,10 @@ case "$MP3ENCODERSYNTAX" in
                MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$LAMEOPTS}"
                MP3ENCODER="$LAME"
                ;;
+       toolame)
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$TOOLAMEOPTS}"
+               MP3ENCODER="$TOOLAME"
+               ;;
        gogo)
                MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$GOGOOPTS}"
                MP3ENCODER="$GOGO"
@@ -2741,9 +3336,9 @@ 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
-                       echo "abcde error: FLAC on an Ogg container is not yet supported" >&2
-                       echo "             due to problem with adding comments to such files" >&2
+               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
                        FLACOUTPUTCONTAINER=ogg
                else
@@ -2763,9 +3358,14 @@ case "$MPPENCODERSYNTAX" in
                MPPENCODER="$MPPENC"
                ;;
 esac
-               
-# and which tagger
+case "$AACENCODERSYNTAX" in
+       faac)
+               AACENCODEROPTS="${AACENCODEROPTSCLI:-$AACENCOPTS}"
+               AACENCODER="$AACENC"
+               ;;
+esac
 
+# and which tagger
 if [ "$ID3TAGV" = "1" ]; then
        TAGGER="$ID3"
        TAGGEROPTS="$ID3OPTS"
@@ -2774,6 +3374,12 @@ else
        TAGGEROPTS="$ID3V2OPTS"
 fi
 
+# Specific for NOGAP is the use of lame. Another encoder fails...
+if [ "$NOGAP" = "y" ] && [ ! "$MP3ENCODER" = "lame" ]; then
+       log warning "the NOGAP option is specific of lame. Deactivating..."
+       NOGAP=n
+fi
+
 # Options for mkcue
 case "$CUEREADERSYNTAX" in
        default|mkcue)
@@ -2782,14 +3388,20 @@ case "$CUEREADERSYNTAX" in
                ;;
 esac
 
+# which information retrieval tool are we using?
+case "$CDDBTOOL" in
+       cddb) ;;
+       musicbrainz) ;;
+esac
+
 # Check if both OGGEOUTPUTCONTAINER and FLACOUTPUTCONTAINER are the same, and differentiante them
 if [ X"$OGGOUTPUTCONTAINER" = "Xogg" ] && [ X"$FLACOUTPUTCONTAINER" = "Xogg" ]; then
-       echo "abcde error: FLAC on an Ogg container is not yet supported" >&2
-       echo "             due to problem with adding comments to such files" >&2
+       log error "FLAC on an Ogg container is not yet supported"
+       log error "due to problem with adding comments to such files"
        exit 1
        OGGOUTPUTCONTAINER=ogg.ogg
        FLACOUTPUTCONTAINER=flac.ogg
-       vecho "abcde warning: modified file endings due to conflicting transport layers in Ogg/Vorbis and Ogg/FLAC"
+       vecho warning "modified file endings due to conflicting transport layers in Ogg/Vorbis and Ogg/FLAC"
 fi
 
 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
@@ -2815,33 +3427,44 @@ if [ "$EJECTCD" = "y" ]; then
        NEEDEJECT=y
 fi
 if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
-       NEEDHTTPGET=y
+       if [ "$CDDBMETHOD" = "cddb" ]; then
+               NEEDHTTPGET=y
+       elif [ "$CDDBMETHOD" = "musicbrainz" ]; then
+               :
+       fi
 fi
 if [ "$MAKECUEFILE" = "y" ]; then
        NEEDCUEREADER=y
 fi
 
-if [ X"$CDSPEEDVALUE" != "X" ]; then
+if [ X"$CDSPEEDVALUE" != "X" ] && [ "$DOREAD" = "y" ]; then
        case "$CDROMREADERSYNTAX" in
                cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
+               ### FIXME ### translate "cue2discid" from python to bash
+               flac) NEEDMETAFLAC=y ; NEEDCUE2DISCID=y ; CDSPEEDVALUE="" ;;
                *) NEEDCDSPEED=y ;;
        esac
 fi
 
+###USEPIPESSUPPORT###
+
 # Rippers with USEPIPE support
 # FIXME # Include here all the rippers we can figure out support pipes
-PIPE_cdparanoia="-"
+PIPERIPPER_cdparanoia="-"
+PIPERIPPER_debug="-"
+PIPERIPPER_flac="-c "
 
 # Encoders with USEPIPE support
 # FIXME # Include here all the encoders we can figure out support pipes
 PIPE_lame="-"
 PIPE_bladeenc="-"
 PIPE_oggenc="-"
+PIPE_flac="-"
 
 # Figure out if we can use pipes with the ripper/encoder combination
 # exit otherwise
 if [ "$USEPIPES" = "y" ]; then
-       PIPERIPPERSVARCHECK="PIPE_${CDROMREADER}"
+       PIPERIPPERSVARCHECK="PIPERIPPER_${CDROMREADERSYNTAX}"
        case "$OUTPUT" in
                mp3)
                        PIPEENCODERSVARCHECK="PIPE_$MP3ENCODERSYNTAX" ;;
@@ -2854,16 +3477,20 @@ if [ "$USEPIPES" = "y" ]; then
                mpc)
                        PIPEENCODERSVARCHECK="PIPE_$MPPENCODER" ;;
        esac
-       if [ ! -n "$( eval echo "\$$PIPERIPPERSVARCHECK" )" ] ; then
-               echo "abcde error: no support for pipes with given ripper" >&2
-               echo "read the USEPIPES file from the source tarball to help" >&2
-               echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
+       decho "PIPERIPPERSVARCHECK: $( eval echo "\$$PIPERIPPERSVARCHECK" )"
+       if [ "$( eval echo "\$$PIPERIPPERSVARCHECK" )" = "$" ] || \
+          [ "$( eval echo "\$$PIPERIPPERSVARCHECK" )" = "" ] ; then
+               log error "no support for pipes with given ripper"
+               log error "read the USEPIPES file from the source tarball to get help."
+               log error "On a Debian system, it is under /usr/share/doc/abcde/USEPIPES.gz"
                exit 1;
        fi
-       if [ ! -n "$( eval echo "\$$PIPEENCODERSVARCHECK" )" ] ; then
-               echo "abcde error: no support for pipes with given encoder" >&2
-               echo "read the USEPIPES file from the source tarball to help" >&2
-               echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
+       decho "PIPEENCODERSVARCHECK: $( eval echo "\$$PIPEENCODERSVARCHECK" )"
+       if [ "$( eval echo "\$$PIPEENCODERSVARCHECK" )" = "$" ] || \
+          [ "$( eval echo "\$$PIPEENCODERSVARCHECK" )" = "" ] ; then
+               log error "no support for pipes with given encoder"
+               log error "read the USEPIPES file from the source tarball to help"
+               log error "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz"
                exit 1;
        fi
 fi
@@ -2871,63 +3498,87 @@ fi
 # Make sure a buncha things exist
 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
        $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
+       $AACENCODER \
        ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
        ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
        ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
        ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
-       ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDCUEREADER+$CUEREADER}
+       ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMP3GAIN+$MP3GAIN} \
+       ${NEEDMPPGAIN+$MPPGAIN} ${NEEDCUEREADER+$CUEREADER} \
+       ${NEEDCUE2DISCID+$CUE2DISCID}
 do
-       # Cut off the command-line options we just added in
-       X=$(echo $X | cut -d' ' -f2)
-       if [ "$(which $X)" = "" ]; then
-               echo "abcde error: $X is not in your path." >&2
-               exit 1
-       elif [ ! -x $(which $X) ]; then
-               echo "abcde error: $X is not executable." >&2
-               exit 1
-       fi
+       checkexec "$X"
 done
 
-CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
-CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
-HTTPGET="$HTTPGET $HTTPGETOPTS"
-
-# And last but not least, check if we can diff between files
+# 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 "[WAR] Disabling diff since we cannot find it in the \$PATH..."
+       vecho warning "Disabling diff since we cannot find it in the \$PATH..."
        DIFF=""
 fi
 
+## Now that we have metaflac, check if we need cue2discid
+#case $CDROMREADERSYNTAX in
+#      flac)
+#              TRACKINFO=$($METAFLAC --show-tag=CDDB $CDROM | cut -d"=" -f2 | egrep "[a-f0-9]{8}")
+#              if [ "$TRACKINFO" = "" ]; then 
+#                      checkexec ${NEEDCUE2DISCID+$CUE2DISCID}
+#              fi
+#              ;;
+#esac
+
+CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
+CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
+HTTPGET="$HTTPGET $HTTPGETOPTS"
+
 # Here it used to say:
 # One thousand lines in, we can start doing stuff with things
-# Well, right now we are at line 2736 ;)
+# Well, right now we are at line 3306 ;)
 
 # Export needed things so they can be read in this subshell
 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
 
-# User-definable function to set some things. Use it for
-#  - closing the CD tray with eject -t
-#  - set the CD speed value with eject -x
-vecho -n "Executing customizable pre-read function... "
+if [ "$DOREAD" = "y" ]; then
+       # User-definable function to set some things. Use it for
+       #  - closing the CD tray with eject -t
+       #  - set the CD speed value with eject -x
+       vecho -n "Executing customizable pre-read function... "
 
-pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
+       pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
 
-vecho "done."
+       vecho "done."
+fi
 
-do_discid # Get ABCDETEMPDIR created and status file initialized
+case "$CDDBMETHOD" in
+       cddb)
+               do_discid # Get ABCDETEMPDIR created and status file initialized
+               ;;
+       musicbrainz)
+               do_musicbrainz id
+               ;;
+esac
 
 if [ "$DOCDDB" = "y" ]; then
+       # start with a sane default:
+       CDDBLOCALSTATUS=notfound
        if [ $CDDBUSELOCAL = "y" ]; then
                do_localcddb
        fi
        if checkstatus cddb-choice > /dev/null; then
                :
        else 
-               if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
-                       do_cddbstat
-                       do_cddbquery
-                       do_cddbread
+               if [ "$CDDBLOCALSTATUS" = "notfound" ] ; then
+                       case "$CDDBMETHOD" in
+                               cddb)
+                                       do_cddbstat
+                                       do_cddbquery
+                                       do_cddbread
+                                       ;;
+                               musicbrainz)
+                                       do_musicbrainz
+                                       ;;
+                       esac
                fi
        fi
        do_cddbedit
@@ -2939,7 +3590,8 @@ fi
 
 if [ X"$CDSPEEDVALUE" != "X" ]; then
        case "$CDROMREADERSYNTAX" in
-               cdparanoia|debug) : ;;
+               cdparanoia|debug) ;;
+               flac) ;;
                *) do_cdspeed ;;
        esac
 fi
@@ -2954,6 +3606,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
 
 (
@@ -2973,8 +3634,14 @@ fi
 
 if [ "$ONETRACK" = "y" ]; then 
        TRACKS="$FIRSTTRACK"
-       if checkstatus readtrack-$FIRSTTRACK; then :; else
-               do_cdread onetrack $FIRSTTRACK $LASTTRACK
+       if [ "$USEPIPES" = "y" ]; then
+               if checkstatus readencodetrack-$FIRSTTRACK; then :; else
+                       do_cdread onetrack $FIRSTTRACK $LASTTRACK | do_encode $FIRSTTRACK %local0% > /dev/null 2>&1
+               fi
+       else
+               if checkstatus readtrack-$FIRSTTRACK; then :; else
+                       do_cdread onetrack $FIRSTTRACK $LASTTRACK
+               fi
        fi
 else
        for UTRACKNUM in $TRACKQUEUE
@@ -2997,9 +3664,14 @@ else
                                fi
                        fi
                fi
-               if [ "$BATCH" = "y" ]; then
+               if [ "$NOGAP" = "y" ] || [ "$BATCHNORM" = "y" ]; then
                    :
                else
+                       # If we are not reading, set the encode output to loud already, so
+                       # that we can see the output of the first track.
+                       if [ "$MAXPROCS" = "1" ] && [ ! "$DOREAD" = "y" ]; then
+                               echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
+                       fi
                        echo NEXTTRACK # Get the encoder machine churning again
                        if [ "$DOREAD" = "y" ]; then
                                if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
@@ -3023,7 +3695,7 @@ if [ "$MAXPROCS" = "1" ]; then
 fi
 
 # All tracks read, start encoding.
-if [ "$BATCH" = "y" ] || [ "$ONETRACK" = "y" ]; then
+if [ "$NOGAP" = "y" ] || [ "$BATCHNORM" = "y" ] || [ "$ONETRACK" = "y" ]; then
        echo NEXTTRACK
 fi
 
@@ -3080,19 +3752,28 @@ fi
 #
 #) | (
 
-# In batch mode, we want all tracks to be read first.
-if [ "$BATCH" = "y" ]; then
+# In BATCHNORM and/or NOGAP modes, we want all tracks to be read first.
+#BACK
+if [ "$BATCHNORM" = "y" ] || [ "$NOGAP" = "y" ]; then
        read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
        if [ "$GOAHEAD" = "NO" ]; then break; fi
        for LASTTRACK in $TRACKQUEUE; do :; done
        if checkstatus readtrack-$LASTTRACK; then
-               if [ "$DONORMALIZE" = "y" ]; then
+               if [ "$DONORMALIZE" = "y" ] && [ "$BATCHNORM" = "y" ]; then
                        if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
-                       if checkerrors batch-normalize; then exit; fi
+                       if checkerrors batch-normalize; then exit 1; fi
                fi
-               if [ "$DOENCODE" = "y" ]; then
-                       if checkstatus encodetrack-$LASTTRACK; then :; else do_batch_encode; fi
-                       if checkerrors batch-encode; then exit; fi
+               if [ "$DOENCODE" = "y" ] && [ "$NOGAP" = "y" ]; then
+                       if [ "$DONORMALIZE" = "y" ]; then
+                               for UTRACKNUM in $TRACKQUEUE
+                               do
+                                       if checkstatus readtrack-$UTRACKNUM; then
+                                               if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
+                                       fi
+                               done
+                       fi
+                       if checkstatus encodetrack-$LASTTRACK; then :; else do_nogap_encode; fi
+                       if checkerrors nogap-encode; then exit 1; fi
                fi
        fi
 fi
@@ -3159,6 +3840,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 
@@ -3166,11 +3849,9 @@ do
                        TRACKNUM="$FIRSTTRACK"
                        splitvarious
                else
-#                      TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
                        TRACKNUM=$UTRACKNUM
                        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                       #TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
-                       do_getcddbinfo TRACKNAME
+                       getcddbinfo TRACKNAME
                        splitvarious
                fi
        fi
@@ -3217,8 +3898,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
@@ -3244,9 +3926,10 @@ wait
 if [ "$DOREPLAYGAIN" = "y" ]; then
        do_replaygain
 fi
+
 # Check to see if run_command logged any errors
 if [ -f "$ABCDETEMPDIR/errors" ]; then
-       echo "The following commands failed to run:"
+       log error "The following commands failed to run:"
        cat "$ABCDETEMPDIR/errors"
        # Don't clean up
        DOCLEAN=n
@@ -3255,6 +3938,18 @@ if [ "$KEEPWAVS" = "y" ];then
        # Don't clean up
        DOCLEAN=n
 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' '|')
+       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 "|" " " )"
+               log warning "Formats moved: $( echo $MOVED_FORMATS | tr "|" " " )"
+               log warning "Use \"abcde -a clean -f -C $DISCID\" to force the removal of the remaining data."
+               DOCLEAN=n
+       fi
+fi
 if [ "$DOCLEAN" = "y" ]; then
        # Wipe all the evidence
        # Gimme gimme gimme some more time!