Adding musicbrainz support. First bits.
[abcde.git] / abcde
diff --git a/abcde b/abcde
index 97168a2..b03d2b1 100755 (executable)
--- a/abcde
+++ b/abcde
@@ -1,6 +1,6 @@
-#!/bin/sh
+#!/bin/bash
 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
-# Copyright (c) 2003-2004 Jesus Climent <jesus.climent@hispalinux.es>
+# Copyright (c) 2003-2005 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.
 #
 #
 # Copyright for this work is to expire January 1, 2010, after which it
 # shall be public domain.
+#
+# $Id$
 
-VERSION="2.2pre3"
+VERSION='2.3.99-$Revision$'
 
 usage ()
 {
 echo "This is abcde v$VERSION."
 echo "Usage: abcde [options] [tracks]"
 echo "Options:"
-echo "-1    Encode the whole CD in a single file"
-echo "-a    Actions to perform (cddb,read,normalize,encode,tag,move,playlist,clean)"
-echo "-A    Experimental actions (retag, transcode)"
-echo "-b    Batch mode: enable album normalization and nogap encoding"
-echo "-c    Specify a configuration file (overrides system and user config files)"
-echo "-C    Specify discid to resume from (only needed if you no longer have the cd)"
-echo "-d    Specify CDROM device to grab"
-echo "-D    Debugging mode (equivalent to sh -x abcde)"
-#echo "-f    Force the use of a local CDDB entry. Otherwise use an empty template"
-echo "-h    This help information"
+echo "-1     Encode the whole CD in a single file"
+echo "-a <action1[,action2]...>"
+echo "       Actions to perform:"
+echo "       cddb,musicbrainz,read,normalize,encode,tag,move,replaygain,playlist,clean"
+#echo "-A     Experimental actions (retag, transcode)"
+echo "-b     Enable batch normalization"
+#echo "-B     Disable batch replaygain (do file by file)"
+echo "-c <file>"
+echo "       Specify a configuration file (overrides system and user config files)"
+echo "-C <discid#>"
+echo "       Specify discid to resume from (only needed if you no longer have the cd)"
+echo "-d <device>"
+echo "       Specify CDROM device to grab (flac uses a single-track flac file)"
+echo "-D     Debugging mode (equivalent to sh -x abcde)"
+echo "-e     Erase encoded track information from status file"
+echo "-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"
-echo "-k    Keep the wav tracks for later use"
-echo "-l    Use low disk space algorithm"
-echo "-L    Use local CDDB storage directory"
-echo "-n    No lookup. Don't query CDDB, just create and use template"
-echo "-N    Noninteractive. Never prompt for anything"
-echo "-m    Modify playlist to include CRLF endings, to comply with some players"
-echo "-o    Output file type(s) (ogg,mp3,flac,spx,mpc). Defaults to ogg"
-echo "-p    Pad track numbers with 0's (if less than 10 tracks)"
-echo "-r    [host1,host2...] Also encode on these remote hosts"
-echo "-R    Add replaygain values to the tag info (ogg,flac)"
-echo "-s    Start the track numbering at a given number"
-echo "-S    Set the CD speed"
-#echo "-t    File types to preprocess (wav)"
-#echo "-T    Set postprocessing options"
-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 "-j <#> Number of encoder processes to run at once (localhost)"
+echo "-k     Keep the wav tracks for later use"
+echo "-l     Use low disk space algorithm"
+echo "-L     Use local CDDB storage directory"
+echo "-n     No lookup. Don't query CDDB, just create and use template"
+echo "-N     Noninteractive. Never prompt for anything"
+echo "-m     Modify playlist to include CRLF endings, to comply with some players"
+echo "-M     Create a CUE file"
+echo "-o <type1[,type2]...>"
+echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc,wav). 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,mp3)"
+echo "-s <field>"
+echo "       Show dielfs from the CDDB info (year,genre)"
+echo "-S <#> Set the CD speed"
+echo "-t <#> Start the track numbering at a given number"
+echo "-T <#> Same as -t but modifies tag numbering"
+echo "-u     Use UNICODE tags and comments"
+echo "-v     Show version number and exit"
+echo "-V     Be a bit more verbose about what is happening behind the scenes"
+echo "-x     Eject CD after all tracks are read"
+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."
+echo "Ranges specified with hyphens are allowed (i.e., 1-5)."
+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.
@@ -65,12 +107,42 @@ f_seq_row ()
 f_seq_line ()
 {
        i=$1
-       while [ $i -ne `expr $2 + 1` ]
-       do
-               printf $i" "
-               i=`expr $i + 1`
+       if echo i | grep -q "[[:digit:]]" ; then
+               while [ $i -ne `expr $2 + 1` ]
+               do
+                       printf $i" "
+                       i=`expr $i + 1`
+               done
+               echo
+       else
+               log error "syntax error while processing track numbers"
+               exit 1
+       fi
+}
+
+# Functions to replace the need of awk {print $1} and {print $NF}
+get_first()
+{
+if [ X"$1" = "X" ]; then
+       for first in `cat`; do
+               break
+       done
+else
+       first=$1
+fi
+echo $first
+}
+
+get_last()
+{
+if [ X"$1" = "X" ]; then
+       for stdin in `cat`; do
+               last=$stdin
        done
-       echo
+else
+       for last in $@ ; do :; done
+fi
+echo $last
 }
 
 # checkstatus [blurb]
@@ -96,6 +168,29 @@ checkstatus ()
        fi
 }
 
+# chechwarnings [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).
@@ -108,7 +203,7 @@ checkerrors ()
        fi
        # Take the last line in the status file if there's multiple matches
        PATTERN="^$1(:.*)?$"
-       BLURB="$(egrep $PATTERN $ABCDETEMPDIR/errors | tail -n 1)"
+       BLURB="$(egrep $PATTERN "$ABCDETEMPDIR/errors" | tail -n 1)"
 
        if [ -z "$BLURB" ]; then
                # negative, we did not have a negative...
@@ -119,6 +214,31 @@ checkerrors ()
        fi
 }
 
+# page [file]
+# Finds the right pager in the system to display a file
+page ()
+{
+       PAGEFILE="$1"
+       # Use the debian sensible-pager wrapper to pick the pager
+       # user has requested via their $PAGER environment variable
+       if [ -x "/usr/bin/sensible-pager" ]; then
+               /usr/bin/sensible-pager "$PAGEFILE"
+       elif [ -x "$PAGER" ]; then
+               # That failed, try to load the preferred editor, starting
+               # with their PAGER variable
+               $PAGER "$PAGEFILE"
+               # If that fails, check for less
+       elif [ -x /usr/bin/less ]; then
+               /usr/bin/less -f "$PAGEFILE"
+               # more should be on all UNIX systems
+       elif [ -x /bin/more ]; then
+               /bin/more "$PAGEFILE"
+       else
+               # No bananas, just cat the thing
+               cat "$PAGEFILE" >&2
+       fi
+}
+
 # run_command [blurb] [command...]
 # Runs a command, silently if necessary, and updates the status file
 run_command ()
@@ -141,7 +261,7 @@ run_command ()
                fi
        fi
        case "$1" in
-       normalize)
+       normalize|normalize-audio)
                if [ "$RETURN" = "2" ]; then
                        # File was already normalized.
                        RETURN=0
@@ -207,11 +327,94 @@ relpath ()
                        FR="$(echo "$FR" | cut -d/ -f2-)"
                        TO="../$TO"
                done
+               ;;
        esac
 
        echo $TO
 }
 
+# do_getcddbinfo
+# Finds an specific field from cddbinfo
+do_getcddbinfo()
+{
+       case $1 in
+       TRACKNAME1)
+               TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
+               ;;
+       TRACKNAME)
+               TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
+               ;;
+       esac
+}
+
+# do_gettracknum
+# Get the track number we are going to use for different actions
+do_gettracknum()
+{
+       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_replaygain()
+{
+       if checkstatus replaygain; then :; else
+               run_command "" echo "Adding replygain information..."
+               for OUTPUT in $( echo $OUTPUTTYPE | tr , \ )
+               do
+                       case $OUTPUT in
+                               vorbis|ogg)
+                                       OUTPUT=$OGGOUTPUTCONTAINER
+                                       ;;
+                               flac)
+                                       OUTPUT=$FLACOUTPUTCONTAINER
+                                       ;;
+                       esac
+                       OUTPUTFILES=""
+                       REPLAYINDEX=0
+                       for UTRACKNUM in $TRACKQUEUE
+                       do
+                               CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
+                               do_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)"
+                               fi
+                               OUTPUTFILES[$REPLAYINDEX]="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
+                               (( REPLAYINDEX = $REPLAYINDEX + 1 ))
+                       done
+                       case "$OUTPUT" in
+                               flac)
+                                       run_command replaygain-flac $METAFLAC --add-replay-gain "${OUTPUTFILES[@]}"
+                                       ;;
+                               vorbis|ogg)
+                                       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
+                       run_command replaygain true
+               fi
+       fi
+}
+
 # This code splits the a Various Artist track name from one of the following
 # forms:
 #
@@ -229,43 +432,202 @@ splitvarious ()
        if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
                case "$VARIOUSARTISTSTYLE" in
                forward)
-                       DTITLEARTIST="$(echo $TRACKNAME | sed 's- / -~-g')"
-                       TRACKARTIST="$(echo $DTITLEARTIST | cut -f1 -d~)"
-                       TRACKNAME="$(echo $DTITLEARTIST | cut -f2 -d~)"
+                       DTITLEARTIST="$(echo "$TRACKNAME" | sed 's- / -~-g')"
+                       TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
+                       TRACKNAME="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
                        ;;
                forward-dash)
-                       DTITLEARTIST="$(echo $TRACKNAME | sed 's, - ,~,g')"
-                       TRACKARTIST="$(echo $DTITLEARTIST | cut -f1 -d~)"
-                       TRACKNAME="$(echo $DTITLEARTIST | cut -f2 -d~)"
+                       DTITLEARTIST="$(echo "$TRACKNAME" | sed 's, - ,~,g')"
+                       TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
+                       TRACKNAME="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
                        ;;
                reverse)
-                       DTITLEARTIST="$(echo $TRACKNAME | sed 's- / -~-g')"
-                       TRACKARTIST="$(echo $DTITLEARTIST | cut -f2 -d~)"
-                       TRACKNAME="$(echo $DTITLEARTIST | cut -f1 -d~)"
+                       DTITLEARTIST="$(echo "$TRACKNAME" | sed 's- / -~-g')"
+                       TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
+                       TRACKNAME="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
                        ;;
                reverse-dash)
-                       DTITLEARTIST="$(echo $TRACKNAME | sed 's, - ,~,g')"
-                       TRACKARTIST="$(echo $DTITLEARTIST | cut -f2 -d~)"
-                       TRACKNAME="$(echo $DTITLEARTIST | cut -f1 -d~)"
+                       DTITLEARTIST="$(echo "$TRACKNAME" | sed 's, - ,~,g')"
+                       TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
+                       TRACKNAME="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
                        ;;
                colon)
-                       DTITLEARTIST="$(echo $TRACKNAME | sed 's-: -~-g')"
-                       TRACKARTIST="$(echo $DTITLEARTIST | cut -f1 -d~)"
-                       TRACKNAME="$(echo $DTITLEARTIST | cut -f2 -d~)"
+                       DTITLEARTIST="$(echo "$TRACKNAME" | sed 's-: -~-g')"
+                       TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
+                       TRACKNAME="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
                        ;;
                trailing-paren)
-                       DTITLEARTIST="$(echo $TRACKNAME | sed 's,^\(.*\) (\(.*\)),\1~\2,')"
-                       TRACKARTIST="$(echo $DTITLEARTIST | cut -f2 -d~)"
-                       TRACKNAME="$(echo $DTITLEARTIST | cut -f1 -d~)"
+                       DTITLEARTIST="$(echo "$TRACKNAME" | sed 's,^\(.*\) (\(.*\)),\1~\2,')"
+                       TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
+                       TRACKNAME="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
                        ;;
                esac
-       elif [ "$ONETRACK" = "y" ]; then
+       elif [ "$VARIOUSARTISTS" = "y" ] && [ "$ONETRACK" = "y" ]; then
                TRACKARTIST="Various"
        else
-               TRACKARTIST=$DARTIST
+               TRACKARTIST="$DARTIST"
        fi
 }
 
+do_getgenreid () {
+local genre=$(echo "${@}" | tr '[A-Z]' '[a-z]')
+local id=""
+       case ${genre} in
+               "blues")                 id=0 ;;
+               "classic rock")          id=1 ;;
+               "country")               id=2 ;;
+               "dance")                 id=3 ;;
+               "disco")                 id=4 ;;
+               "funk")                  id=5 ;;
+               "grunge")                id=6 ;;
+               "hip-hop")               id=7 ;;
+               "jazz")                  id=8 ;;
+               "metal")                 id=9 ;;
+               "new age")               id=10 ;;
+               "oldies")                id=11 ;;
+               "other")                 id=12 ;;
+               "pop")                   id=13 ;;
+               "r&b")                   id=14 ;;
+               "rap")                   id=15 ;;
+               "reggae")                id=16 ;;
+               "rock")                  id=17 ;;
+               "techno")                id=18 ;;
+               "industrial")            id=19 ;;
+               "alternative")           id=20 ;;
+               "ska")                   id=21 ;;
+               "death metal")           id=22 ;;
+               "pranks")                id=23 ;;
+               "soundtrack")            id=24 ;;
+               "euro-techno")           id=25 ;;
+               "ambient")               id=26 ;;
+               "trip-hop")              id=27 ;;
+               "vocal")                 id=28 ;;
+               "jazz+funk")             id=29 ;;
+               "fusion")                id=30 ;;
+               "trance")                id=31 ;;
+               "classical")             id=32 ;;
+               "instrumental")          id=33 ;;
+               "acid")                  id=34 ;;
+               "house")                 id=35 ;;
+               "game")                  id=36 ;;
+               "sound clip")            id=37 ;;
+               "gospel")                id=38 ;;
+               "noise")                 id=39 ;;
+               "alt. rock")             id=40 ;;
+               "bass")                  id=41 ;;
+               "soul")                  id=42 ;;
+               "punk")                  id=43 ;;
+               "space")                 id=44 ;;
+               "meditative")            id=45 ;;
+               "instrum. pop")          id=46 ;;
+               "instrum. rock")         id=47 ;;
+               "ethnic")                id=48 ;;
+               "gothic")                id=49 ;;
+               "darkwave")              id=50 ;;
+               "techno-indust.")        id=51 ;;
+               "electronic")            id=52 ;;
+               "pop-folk")              id=53 ;;
+               "eurodance")             id=54 ;;
+               "dream")                 id=55 ;;
+               "southern rock")         id=56 ;;
+               "comedy")                id=57 ;;
+               "cult")                  id=58 ;;
+               "gangsta")               id=59 ;;
+               "top 40")                id=60 ;;
+               "christian rap")         id=61 ;;
+               "pop/funk"|"pop / funk") id=62 ;;
+               "jungle")                id=63 ;;
+               "native american")       id=64 ;;
+               "cabaret")               id=65 ;;
+               "new wave")              id=66 ;;
+               "psychadelic")           id=67 ;;
+               "rave")                  id=68 ;;
+               "showtunes")             id=69 ;;
+               "trailer")               id=70 ;;
+               "lo-fi")                 id=71 ;;
+               "tribal")                id=72 ;;
+               "acid punk")             id=73 ;;
+               "acid jazz")             id=74 ;;
+               "polka")                 id=75 ;;
+               "retro")                 id=76 ;;
+               "musical")               id=77 ;;
+               "rock & roll")           id=78 ;;
+               "hard rock")             id=79 ;;
+               "folk")                  id=80 ;;
+               "folk/rock")             id=81 ;;
+               "national folk")         id=82 ;;
+               "swing")                 id=83 ;;
+               "fusion")                id=84 ;;
+               "bebob")                 id=85 ;;
+               "latin")                 id=86 ;;
+               "revival")               id=87 ;;
+               "celtic")                id=88 ;;
+               "bluegrass")             id=89 ;;
+               "avantgarde")            id=90 ;;
+               "gothic rock")           id=91 ;;
+               "progress. rock")        id=92 ;;
+               "psychadel. rock")       id=93 ;;
+               "symphonic rock")        id=94 ;;
+               "slow rock")             id=95 ;;
+               "big band")              id=96 ;;
+               "chorus")                id=97 ;;
+               "easy listening")        id=98 ;;
+               "acoustic")              id=99 ;;
+               "humour")                id=100 ;;
+               "speech")                id=101 ;;
+               "chanson")               id=102 ;;
+               "opera")                 id=103 ;;
+               "chamber music")         id=104 ;;
+               "sonata")                id=105 ;;
+               "symphony")              id=106 ;;
+               "booty bass")            id=107 ;;
+               "primus")                id=108 ;;
+               "porn groove")           id=109 ;;
+               "satire")                id=110 ;;
+               "slow jam")              id=111 ;;
+               "club")                  id=112 ;;
+               "tango")                 id=113 ;;
+               "samba")                 id=114 ;;
+               "folklore")              id=115 ;;
+               "ballad")                id=116 ;;
+               "power ballad")          id=117 ;;
+               "rhythmic soul")         id=118 ;;
+               "freestyle")             id=119 ;;
+               "duet")                  id=120 ;;
+               "punk rock")             id=121 ;;
+               "drum solo")             id=122 ;;
+               "a capella")             id=123 ;;
+               "euro-house")            id=124 ;;
+               "dance hall")            id=125 ;;
+               "goa")                   id=126 ;;
+               "drum & bass")           id=127 ;;
+               "club-house")            id=128 ;;
+               "hardcore")              id=129 ;;
+               "terror")                id=130 ;;
+               "indie")                 id=131 ;;
+               "britpop")               id=132 ;;
+               "negerpunk")             id=133 ;;
+               "polsk punk")            id=134 ;;
+               "beat")                  id=135 ;;
+               "christian gangsta rap") id=136 ;;
+               "heavy metal")           id=137 ;;
+               "black metal")           id=138 ;;
+               "crossover")             id=139 ;;
+               "contemporary christian")id=140 ;;
+               "christian rock")        id=141 ;;
+               "merengue")              id=142 ;;
+               "salsa")                 id=143 ;;
+               "thrash metal")          id=144 ;;
+               "anime")                 id=145 ;;
+               "jpop")                  id=146 ;;
+               "synthpop")              id=147 ;;
+               "rock/pop"|"rock / pop") id=148 ;;
+               *)                       return 1 ;;
+       esac
+echo ${id}
+return 0
+}
+
 # do_tag [tracknumber]
 # id3 tags a filename
 # variables used:
@@ -274,118 +636,158 @@ splitvarious ()
 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 "$STARTTRACKNUMBERTAG" ] ; then
+               do_gettracknum
+       fi
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
-       case "$OUTPUT" in
-       mp3)
-               # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
-               run_command tagtrack-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
-                       -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
-                       -g "$CDGENRE" -T "$1/$TRACKS" "$ABCDETEMPDIR/track$1.$OUTPUT"
-               ;;
-       ogg)
-               case "$OGGENCODERSYNTAX" in
-                       vorbize|oggenc)
-                               # vorbiscomment can't do in-place modification, mv the file first
-                               if [ -f "$ABCDETEMPDIR/track$1.$OUTPUT" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" ]; then
-                                       mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT"
-                               fi
-                               (
-                               # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
-                               echo ARTIST=$TRACKARTIST
-                               echo ALBUM="$DALBUM"
-                               echo TITLE=$TRACKNAME
-                                       if [ -n "$CDYEAR" ]; then
-                                       echo DATE="$CDYEAR"
-                                       fi
-                               if [ -n "$CDGENRE" ]; then
-                                       echo GENRE="$CDGENRE"
-                               fi      
-                               echo TRACKNUMBER=$1
-                               echo CDDB=$CDDBDISCID
-                               if [ "$(eval echo ${COMMENT})" != "" ]; then
-                                       case "$COMMENTOUTPUT" in
-                                               *=*) echo "$COMMENTOUTPUT";;
-                                               *)   echo COMMENT="$COMMENTOUTPUT";;
-                                       esac    
-                               fi
-                               ) | run_command tagtrack-$1 $VORBISCOMMENT -w \
-                                       "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" "$ABCDETEMPDIR/track$1.$OUTPUT"
-                               # Doublecheck that the commented file was created successfully before wiping the original
-                               if [ -f "$ABCDETEMPDIR/track$1.$OUTPUT" ]; then
-                                       rm -f "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT"
-                               else
-                                       mv "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" "$ABCDETEMPDIR/track$1.$OUTPUT"
-                               fi
-                               ;;
+               case "$OUTPUT" in
+               mp3)
+                       # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
+                       GENREID=$(do_getgenreid "${CDGENRE}")
+       
+                       case "$ID3SYNTAX" in
+                               id3);;
+                               eyed3)
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS --commen=::"$COMMENTOUTPUT" \
+                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -Y "$CDYEAR" \
+                                               -G "$GENREID" -n "${TRACKNUM:-$1}" "${TRACKNUM:+-N $TRACKS}" \
+                                               "${ENCODING:+--set-encoding=$ENCODING}"
+                                               "$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       ;;
+                               *)
+                                       # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
+                                       run_command tagtrack-$OUTPUT-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
+                                               -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
+                                               -g "$GENREID" -T "${TRACKNUM:-$1/$TRACKS}" \
+                                               "$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       ;;
+                       esac
+                       ;;
+               vorbis|ogg)
+                       case "$OGGENCODERSYNTAX" in
+                               vorbize|oggenc)
+                                       # vorbiscomment can't do in-place modification, mv the file first
+                                       if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" ]; then
+                                               mv "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
+                                       fi
+                                       (
+                                       # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
+                                       echo ARTIST="$TRACKARTIST"
+                                       echo ALBUM="$DALBUM"
+                                       echo TITLE="$TRACKNAME"
+                                       if [ -n "$CDYEAR" ]; then
+                                               echo DATE="$CDYEAR"
+                                       fi
+                                       if [ -n "$CDGENRE" ]; then
+                                               echo GENRE="$CDGENRE"
+                                       fi      
+                                       echo TRACKNUMBER=${TRACKNUM:-$1}
+                                       echo CDDB=$CDDBDISCID
+                                       if [ "$(eval echo ${COMMENT})" != "" ]; then
+                                               case "$COMMENTOUTPUT" in
+                                                       *=*) echo "$COMMENTOUTPUT";;
+                                                       *)   echo COMMENT="$COMMENTOUTPUT";;
+                                               esac    
+                                       fi
+                                       ) | run_command tagtrack-$OUTPUT-$1 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
+                                               "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
+                                       # Doublecheck that the commented file was created successfully before wiping the original
+                                       if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" ]; then
+                                               rm -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
+                                       else
+                                               mv "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
+                                       fi
+                                       ;;
+                       esac
+                       ;;
+               flac)
+                       (
+                       echo ARTIST="$TRACKARTIST"
+                       echo ALBUM="$DALBUM"
+                       echo TITLE="$TRACKNAME"
+                       if [ -n "$CDYEAR" ]; then
+                               echo DATE="$CDYEAR"
+                       fi
+                       if [ -n "$CDGENRE" ]; then
+                               echo GENRE="$CDGENRE"
+                       fi      
+                       echo TRACKNUMBER="${TRACKNUM:-$1}"
+                       echo CDDB="$CDDBDISCID"
+                       if [ "$(eval echo ${COMMENT})" != "" ]; then
+                               case "$COMMENTOUTPUT" in
+                                       *=*) echo "$COMMENTOUTPUT";;
+                                       *)   echo COMMENT="$COMMENTOUTPUT";;
+                               esac    
+                       fi
+                       ) | run_command tagtrack-$OUTPUT-$1 $METAFLAC $METAFLACOPTS --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                       ;;
+               spx)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
+               mpc)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
+               wav)
+                       run_command tagtrack-$OUTPUT-$1 true
+                       ;;
                esac
-               ;;
-       flac)
-                (
-               echo ARTIST="$TRACKARTIST"
-               echo ALBUM="$DALBUM"
-               echo TITLE="$TRACKNAME"
-                       if [ -n "$CDYEAR" ]; then
-                       echo DATE="$CDYEAR"
-                       fi
-                       if [ -n "$CDGENRE" ]; then
-                       echo GENRE="$CDGENRE"
-                fi     
-               echo TRACKNUMBER=$1
-               echo CDDB=$CDDBDISCID
-               if [ "$(eval echo ${COMMENT})" != "" ]; then
-                       case "$COMMENTOUTPUT" in
-                               *=*) echo "$COMMENTOUTPUT";;
-                               *)   echo COMMENT="$COMMENTOUTPUT";;
-                       esac    
-               fi
-                ) | run_command tagtrack-$1 $METAFLAC --import-vc-from=- --no-utf8-convert "$ABCDETEMPDIR/track$1.$OUTPUT"
-               ;;
-       spx)
-               run_command tagtrack-$1 true
-               ;;
-       mpc)
-               run_command tagtrack-$1 true
-               ;;
-       esac
        done
+       if checkerrors "tagtrack-(.{3,6})-$1"; then :; else
+               run_command tagtrack-$1 true
+       fi
+
 }
 
-# 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 --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
-                                       echo encodetrack-$UTRACKNUM >> status
+                                       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.
 }
@@ -396,54 +798,114 @@ do_batch_encode ()
 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
 do_encode ()
 {
-       IN="$ABCDETEMPDIR/track$1.wav"
-       # We need IN to proceed.
-       if [ -s "$IN" ] ; then
+       if [ "$USEPIPES" = "y" ]; then
+               case "$OUTPUT" in
+                       mp3)
+                               TEMPARG="PIPE_$MP3ENCODERSYNTAX"
+                               ;;
+                       vorbis|ogg)
+                               TEMPARG="PIPE_$OGGENCODERSYNTAX"
+                               ;;
+                       flac)
+                               TEMPARG="PIPE_$FLACENCODERSYNTAX"
+                               ;;
+                       spx)
+                               TEMPARG="PIPE_$SPEEXENCODER"
+                               ;;
+                       mpc)
+                               TEMPARG="PIPE_$MPPENCODER"
+                               ;;
+               esac
+               IN="$( eval echo "\$$TEMPARG" )"
+       else
+               IN="$ABCDETEMPDIR/track$1.wav"
+               case "$OUTPUT" in
+                       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"
+                                               ;;
+                                       *)
+                                               FILEARG="$IN"
+                                               ;;
+                               esac
+                               ;;
+                       *)
+                               FILEARG="$IN"
+                               ;;
+               esac
+       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 , \ )
                do
-                       OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
-                       run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
+                       case "$OUTPUT" in
+                               vorbis|ogg)
+                                       OUT="$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
+                                       OUTPUT=$OGGOUTPUTCONTAINER
+                                       ;;
+                               flac)
+                                       OUT="$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
+                                       OUTPUT=$FLACOUTPUTCONTAINER
+                                       ;;
+                               *)
+                                       OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
+                                       ;;
+                       esac
+                       if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
+                               continue
+                       fi
+                       if [ X"$USEPIPES" = "Xy" ]; then
+                               RUN_COMMAND=""
+                               # We need a way to store the creation of the files when using PIPES
+                               RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
+                       else
+                               run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
+                               RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
+                       fi
                        case "$OUTPUT" in
                        mp3)
                                case "$2" in
                                %local*%)
                                        case "$MP3ENCODERSYNTAX" in
-                                       lame|gogo) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
-                                       bladeenc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
-                                       l3enc|xingmp3enc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
-                                       mp3enc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
+                                       lame|gogo) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
+                                       bladeenc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
+                                       l3enc|xingmp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
+                                       # FIXME # Relates to the previous FIXME since it might need the "-if" removed.
+                                       mp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
                                        esac
                                        ;;
                                *)
-                                       run_command encodetrack-$OUTPUT-$1 nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
+                                       $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
                                        ;;
                                esac
                                ;;
-                       ogg)
+                       vorbis|ogg)
                                case "$2" in
                                %local*%)
                                        case "$OGGENCODERSYNTAX" in
-                                       vorbize) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
-                                       oggenc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
+                                       vorbize) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
+                                       oggenc) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
                                        esac
                                        ;;
                                *)
-                                       run_command encodetrack-$OUTPUT-$1 nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
+                                       $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
                                        ;;
                                esac
                                ;;
                        flac)
                                case "$2" in
-                               %local*%)
+                               %local*%)
                                        case "$FLACENCODERSYNTAX" in
-                                       flac) run_command encodetrack-$OUTPUT-$1 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 encodetrack-$OUTPUT-$1 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
                                ;;
@@ -457,9 +919,9 @@ do_encode ()
                                fi
                                # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
                                if [ ! "$DOTAG" = "y" ]; then
-                                       run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
+                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
                                else
-                                       run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
+                                       $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
                                fi
                                ;;
                        mpc)    
@@ -469,24 +931,26 @@ do_encode ()
                                # errors, so I have not tried it myself.
                                ## FIXME ## Needs some cleanup to determine if an empty tag sent
                                ## FIXME ## to the encoder ends up empty.
-                               run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
+                               $RUN_COMMAND nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
+                               ;;
+                       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,4})-$1"; then 
-                       run_command encodetrack-$1 false
-               else
+               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
-               if [ "$(checkstatus encode-output)" = "loud" ]; then
-                       echo "HEH! The file we were about to encode disappeared:"
-                       echo ">> $IN"
-               fi
+               run_command "" echo "HEH! The file we were about to encode disappeared:"
+               run_command "" echo ">> $IN"
                run_command encodetrack-$1 false
        fi
 }
@@ -570,9 +1034,18 @@ do_encode ()
 #      done
 #}
 
+# do_single_gain
+# variables used:
+# FIXME #
+do_single_gain ()
+{
+:
+}
+
 # do_batch_gain
 # variables used:
-# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
+# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPPGAIN, MPPGAINOPTS
+# FIXME #
 do_batch_gain ()
 {
        # The commands here don't go through run_command because they're never supposed to be silenced
@@ -585,7 +1058,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
@@ -662,32 +1135,89 @@ do_move ()
                # ''' -> ''
                # '?' -> ''
                # Eat control characters
-               ALBUMFILE=$(mungefilename "$DALBUM")
-               ARTISTFILE=$(mungefilename "$TRACKARTIST")
-               TRACKFILE=$(mungefilename "$TRACKNAME")
-               GENRE=$(mungegenre "$GENRE")
-               YEAR=$(echo $CDYEAR)
+               ALBUMFILE="$(mungefilename "$DALBUM")"
+               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} - 1 ))
-               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)
+                       OUTPUTFILE="$(eval echo "$VAOUTPUTFORMAT")"
+               else
+                       OUTPUTFILE="$(eval echo "$OUTPUTFORMAT")"
+               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
+                               vorbis|ogg)
+                                       OUTPUT=$OGGOUTPUTCONTAINER
+                                       ;;
+                               flac)
+                                       OUTPUT=$FLACOUTPUTCONTAINER
+                                       ;;
+                       esac
+                       # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
+                       OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
+                       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
+                                       if checkstatus movecue-$OUTPUT; then :; else
+                                               # Silence the Copying output since it overlaps with encoding processes...
+                                               #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])
+                                                                       run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
+                                                                       ;;
+                                                               *)
+                                                                       run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT.cue"
+                                                                       ;;
+                                                       esac
+                                               else
+                                                       run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTFILEDIR/$CUEFILE"
+                                               fi
+                                               echo movecue-$OUTPUT >> "$ABCDETEMPDIR/status"
+                                       fi
+                               fi
+                       fi
                fi
-               # 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"
        done
 }
 
@@ -700,12 +1230,21 @@ do_playlist ()
 {
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
+               case $OUTPUT in
+                       vorbis|ogg)
+                               OUTPUT=$OGGOUTPUTCONTAINER
+                               ;;
+                       flac)
+                               OUTPUT=$FLACOUTPUTCONTAINER
+                               ;;
+               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")
+               ALBUMFILE="$(mungefilename "$DALBUM")"
+               ARTISTFILE="$(mungefilename "$DARTIST")"
                GENRE=$(mungegenre "$GENRE")
+               YEAR=${CDYEAR:-$CDYEAR}
                if [ "$VARIOUSARTISTS" = "y" ] ; then
                        PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
                else
@@ -714,7 +1253,6 @@ do_playlist ()
                FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
                mkdir -p "$FINALPLAYLISTDIR"
                if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
-                       #echo -n "Erase any existing playlist file? [y/n] (y): " >&2
                        echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
                        if [ "$INTERACTIVE" = "y" ]; then
                                while [ "$DONE" != "y" ]; do
@@ -740,19 +1278,14 @@ do_playlist ()
                        do
                                # Shares some code with do_move since the filenames have to match
                                CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-                               TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
+                               do_getcddbinfo TRACKNAME
                                splitvarious
-                               TRACKFILE=$(mungefilename "$TRACKNAME")
-                               ARTISTFILE=$(mungefilename "$TRACKARTIST")
+                               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} - 1 ))
-                               else
-                                       TRACKNUM=${UTRACKNUM}
-                               fi
+                               do_gettracknum
                                if [ "$VARIOUSARTISTS" = "y" ]; then
                                        OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
                                else
@@ -795,13 +1328,32 @@ do_discid ()
        #elif [ -z "$DISCID" ]; then
        if [ -z "$DISCID" ]; then
                vecho -n "Getting CD track info... "
-               TRACKINFO=$($CDDISCID $CDROM)
+               # In OSX, unmount the disc before a query
+               if [ "$OSFLAVOUR" = "OSX" ]; then
+                       disktool -u ${CDROM#/dev/}
+               fi
+               if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
+                       TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
+               else
+                       TRACKINFO=$($CDDISCID $CDROM)
+               fi
                # 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
@@ -825,12 +1377,20 @@ do_discid ()
                                cdparanoia|debug)
                                        if [ "$WEHAVEACD" = "y" ]; then
                                                vecho "Querying the CD for audio tracks..."
-                                               TRACKS=$( $CDROMREADER -Q 2>&1 | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 |  awk '{print $1}' | tr -d "." | tr '\n' ' ' )
+                                               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"
                                        else
-                                               if [ -f "$ABCDETEMPDIR/status" ] && checkstatus cdparanoia-audio-tracks ; then
-                                                       TRACKS=$( cat $ABCDETEMPDIR/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
@@ -840,6 +1400,10 @@ do_discid ()
                else
                        TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
                fi
+               if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
+                       log info "The disc does not contain any tracks. Giving up..."
+                       exit 0
+               fi
                echo -n "Grabbing entire CD - tracks: "
                if [ ! "$PADTRACKS" = "y" ] ; then
                        TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
@@ -849,7 +1413,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
@@ -871,8 +1435,6 @@ do_discid ()
                echo Grabbing tracks: "$TRACKQUEUE"
        fi
 
-#      for LASTTRACK in $TRACKQUEUE; do :; done
-
        QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
 
        # We have the discid, create a temp directory after it to store all the temp
@@ -943,47 +1505,61 @@ do_discid ()
                        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
+                               log warning "reading the CUE sheet with mkcue is still considered experimental"
+                               log warning "and there was a problem with the CD reading. abcde will continue,"
+                               log warning "but consider reporting the problem to the abcde author"
+                       fi
+               fi
        fi
-       
        # If we got the CDPARANOIA status and it is not recorded, save it now
-       ## FIXME ## ! is non-portable
-       if [ -n "$CDPARANOIAAUDIOTRACKS" ] && ! checkstatus cdparanoia-audio-tracks; then
-               if echo "$CDPARANOIAAUDIOTRACKS" >> "$ABCDETEMPDIR/cdparanoia-audio-tracks"; then
-                       echo "cdparanoia-audio-tracks" >> "$ABCDETEMPDIR/status"
+       if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
+               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"
+}
 
-       # Determine what actions are to be done from $ACTIONS and set the
-       # following environment variables for them:
-       DOCDDB=n
-       DOREAD=n
-       DONORMALIZE=n
-       DOPREPROCESS=n
-       DOENCODE=n
-       DOPOSTPROCESS=n
-       DOTAG=n
-       DOMOVE=n
-       DOPLAYLIST=n
-       DOCLEAN=n
-
-       for ACTION in $(echo $ACTIONS | tr , \ )
-       do
-               case $ACTION in
-               cddb) DOCDDB=y;;
-               read) DOREAD=y;;
-               normalize) DONORMALIZE=y; DOREAD=y;;
-               preprocess) DOPREPROCESS=y; DOREAD=y;;
-               encode) DOENCODE=y; DOREAD=y;;
-               postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
-               tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
-               move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
-               playlist) DOCDDB=y; DOPLAYLIST=y;;
-               clean) DOCLEAN=y;;
-               esac
-       done
+# do_cleancue
+# Create a proper CUE file based on the CUE file we created before.
+do_cleancue()
+{
+       if CUEFILE_IN="$ABCDETEMPDIR"/$(checkstatus cuefile); then
+               CUEFILE_OUT=$CUEFILE_IN.out
+               ### FIXME ### checkstatus cddb
+               if [ -e "$CDDBDATA" ]; then
+                       vecho "Adding metadata to the cue file..."
+                       # FIXME It doesn't preserve spaces! Why?
+                       # FIXME parse $track into PERFORMER and TITLE - abcde already has code for this?
+                       n=1
+                       echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
+                       echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
+                       cat "$CUEFILE_IN" | while read line
+                       do
+                               if echo "$line" | grep -q "INDEX"
+                               then
+                                       eval track="\$TRACK$n"
+                                       n=$(expr $n + 1)
+                                       echo "TITLE \"$track\"" >> "$CUEFILE_OUT"
+                               fi
+                               echo "$line" >> "$CUEFILE_OUT"
+                       done
+                       mv "$CUEFILE_OUT" "$CUEFILE_IN"
+                       echo "cleancuefile" >> "$ABCDETEMPDIR/status"
+               fi
+       fi
 }
 
 # do_cddbparse
@@ -997,6 +1573,18 @@ do_cddbparse ()
                vecho "ONETRACK mode selected: displaying only the title of the CD..."
        fi
        echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
+       if [ X"$SHOWCDDBYEAR" = "Xy" ]; then
+               PARSEDYEAR=$(grep DYEAR "${CDDBPARSEFILE}" | cut '-d=' -f2-)
+               if [ ! X"$PARSEDYEAR" = "X" ]; then
+                       echo "Year: $PARSEDYEAR"
+               fi
+       fi
+       if [ X"$SHOWCDDBGENRE" = "Xy" ]; then
+               PARSEDGENRE=$(grep DGENRE "${CDDBPARSEFILE}" | cut '-d=' -f2-)
+               if [ ! X"$PARSEDGENRE" = "X" ]; then
+                       echo "Genre: $PARSEDGENRE"
+               fi
+       fi
        if [ ! "$ONETRACK" = "y" ]; then
                for TRACK in $(f_seq_row 1 $TRACKS)
                do
@@ -1017,36 +1605,35 @@ do_localcddb ()
                USELOCALRESP="y"
                
                # If the user has selected to check a local CDDB repo, we proceed with it
-               if [ "$CDDBUSELOCAL" = "y" ]; then
-                       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
+               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
-                                       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
+                               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"
-                               else
-                                       #echo "Not using local copy of CDDB data"
-                                       CDDBLOCALSUCCESS="n"
-                               fi
+                               echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
+                               cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
+                               echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
+                               echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
+                               do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
+                               echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                               CDDBLOCALSUCCESS="y"
                        else
+                               #echo "Not using local copy of CDDB data"
                                CDDBLOCALSUCCESS="n"
                        fi
+               else
+                       CDDBLOCALSUCCESS="n"
                fi
        fi
 }
@@ -1180,7 +1767,7 @@ do_cddbread ()
                        # Multiple exact, (possibly multiple) inexact matches
                        IN=
                        if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
-                       if [ "$(wc -l < $ABCDETEMPDIR/cddbquery | tr -d ' ')" -eq 3 ]; then
+                       if [ "$(wc -l < "$ABCDETEMPDIR/cddbquery" | tr -d ' ')" -eq 3 ]; then
                                echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
                                tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
                                echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
@@ -1252,46 +1839,58 @@ do_cddbedit ()
                                else
                                        # The user has a choice to make, display the info in a pager if necessary
                                        if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
-                                               # Use the debian sensible-pager wrapper to pick the pager
-                                               # user has requested via their $PAGER environment variable
-                                               if [ -x "/usr/bin/sensible-pager" ]; then
-                                                       /usr/bin/sensible-pager "$ABCDETEMPDIR/cddbchoices"
-                                               elif [ -x "$PAGER" ]; then
-                                                       # That failed, try to load the preferred editor, starting
-                                                       # with their PAGER variable
-                                                       $PAGER "$ABCDETEMPDIR/cddbchoices"
-                                                       # If that fails, check for less
-                                               elif [ -x /usr/bin/less ]; then
-                                                       /usr/bin/less -f "$ABCDETEMPDIR/cddbchoices"
-                                                       # more should be on all UNIX systems
-                                               elif [ -x /bin/more ]; then
-                                                       /bin/more "$ABCDETEMPDIR/cddbchoices"
-                                               else
-                                                       # No bananas, just cat the thing
-                                                       cat "$ABCDETEMPDIR/cddbchoices" >&2
-                                               fi
+                                               page "$ABCDETEMPDIR/cddbchoices"
                                        else
                                                # It's all going to fit in one page, cat it
                                                cat "$ABCDETEMPDIR/cddbchoices" >&2
                                        fi
                                        
+                                       CDDBCHOICENUM=""
+                                       # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
+                                       CDCHOICENUM=-1
                                        # I'll take CDDB read #3 for $400, Alex
-                                       echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
-                                       read CDDBCHOICE
-                                       # Make sure we get a valid choice
-                                       CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
-                                       while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
-                                               echo "Invalid selection. Please choose a number between 1 and $CDDBCHOICES." >&2
-                                               echo -n "Selection [0-$CDDBCHOICES]: " >&2
+                                       while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
+                                               echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
                                                read CDDBCHOICE
-                                               CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
+                                               [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
+                                               if echo $CDDBCHOICE | egrep -q "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" ; then
+                                                       if [ ! X"$DIFF" = "X" ]; then
+                                                               PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
+                                                               PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
+                                                               if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBCHOICES ] || \
+                                                                  [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBCHOICES ] || \
+                                                                  [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
+                                                                       echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBCHOICES" >&2
+                                                               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"
+                                                                       done
+                                                                       echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/cddbread.diff"
+                                                                       $DIFF $DIFFOPTS "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/cddbread.diff"
+                                                                       if [ $(cat "$ABCDETEMPDIR/cddbread.diff" | wc -l) -ge 24 ]; then
+                                                                               page "$ABCDETEMPDIR/cddbread.diff"
+                                                                       else
+                                                                               cat "$ABCDETEMPDIR/cddbread.diff" >&2
+                                                                       fi
+                                                               fi
+                                                       else
+                                                               echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
+                                                       fi
+                                               elif echo $CDDBCHOICE | egrep -q "[[:space:]]*[[:digit:]]+[[:space:]]*" ; then
+                                                       # Make sure we get a valid choice
+                                                       CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
+                                                       if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
+                                                               echo "Invalid selection. Please choose a number between 0 and $CDDBCHOICES." >&2
+                                                       fi
+                                               fi
                                        done
                                        if [ "$CDCHOICENUM" = "0" ]; then
                                                vecho "Creating empty CDDB template..."
                                                UNKNOWNDISK=y
-                                               $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > $ABCDETEMPDIR/cddbread.0
+                                               $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
                                        else
-                                               echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
+                                               echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
                                                do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
                                        fi
                                        echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
@@ -1308,6 +1907,10 @@ do_cddbedit ()
                                if [ "$USELOCALRESP" = "y" ]; then :; else
                                        if [ -n "$CHOICE" ] ; then
                                                case $CDDBCHOICES in
+                                                       0) 
+                                                       UNKNOWNDISK=y
+                                                       echo "Selected template."
+                                                       ;;
                                                        1) cat "$ABCDETEMPDIR/cddbchoices" ;;
                                                        *)
                                                        echo "Selected: #$CHOICE"
@@ -1336,7 +1939,7 @@ do_cddbedit ()
                                CDCHOICENUM=1
                                echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
                        fi
-                       echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
+                       echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
                fi
        fi
 
@@ -1371,20 +1974,30 @@ do_cddbedit ()
                        if [ -x $(which "${EDITOR%%\ *}") ]; then
                                # That failed, try to load the preferred editor, starting
                                # with their EDITOR variable
-                               eval $(echo "$EDITOR") "$CDDBDATA"
+                               eval $(echo "$EDITOR") \"$CDDBDATA\"
                        fi
                # If that fails, check for a vi
+               elif which vi >/dev/null 2>&1; then
+                       vi "$CDDBDATA"
+               elif [ -x /usr/bin/vim ]; then
+                       /usr/bin/vim "$CDDBDATA"
                elif [ -x /usr/bin/vi ]; then
                        /usr/bin/vi "$CDDBDATA"
+               elif [ -x /bin/vi ]; then
+                       /bin/vi "$CDDBDATA"
                # nano should be on all (modern, i.e., sarge) debian systems
+               elif which nano >/dev/null 2>&1 ; then
+                       nano "$CDDBDATA"
                elif [ -x /usr/bin/nano ]; then
                        /usr/bin/nano "$CDDBDATA"
                # mg should be on all OpenBSD systems
+               elif which mg >/dev/null 2>&1 ; then
+                       mg "$CDDBDATA"
                elif [ -x /usr/bin/mg ]; then
                        /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
@@ -1394,7 +2007,7 @@ do_cddbedit ()
 
        # Some heuristics first. Look at Disc Title, and if it starts with
        # "Various", then we'll assume Various Artists
-       if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2 -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
+       if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
                echo "Looks like a Multi-Artist CD" >&2
                VARIOUSARTISTS=y
        else
@@ -1477,7 +2090,7 @@ do_cddbedit ()
        echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
 
        if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
-               if [ $CDDBDATAMD5SUM != "" ]  && [ $CDDBDATAMD5SUM != $($MD5SUM "$CDDBDATA" | cut -d " " -f 1) ]; then
+               if [ "$CDDBDATAMD5SUM" != "" ]  && [ "$CDDBDATAMD5SUM" != "$($MD5SUM "$CDDBDATA" | cut -d " " -f 1)" ]; then
                        # This works but does not have the necessary error checking
                        # yet. If you are familiar with the CDDB spec
                        # (see http://www.freedb.org/src/latest/DBFORMAT) 
@@ -1515,79 +2128,63 @@ do_cddbedit ()
        echo "cddb-edit" >> "$ABCDETEMPDIR/status"
 }
 
-# do_cdread_one [lasttrack] [firsttrack]
-# 
-# Reads the CD in a single track. Live performances, concerts, mixes,... benefit from this.
-do_cdread_one ()
-{
-       # The commands here don't go through run_command because they're never supposed to be silenced
-       # return codes need to be doublechecked anyway, however
-       LASTTRACKNUMBER=$1
-       FIRSTTRACKNUMBER=$2
-       WAVDATA="$ABCDETEMPDIR/track$FIRSTTRACKNUMBER.wav"
-       echo "Grabbing the CD to a single track..." >&2
-       case "$CDROMREADERSYNTAX" in
-               cdparanoia) nice $READNICE $CDROMREADER -d $CDROM "1-" "$WAVDATA" >&2 ;;
-               cdda2wav)
-                       if [ "$OSFLAVOUR" = "OSX" ] ; then
-                               # Hei, we have to unmount the device before running anything like cdda2wav in OSX
-                               disktool -u ${CDROM#/dev/} 0
-                               # Also, in OSX the cdrom device for cdda2wav changes...
-                               CDDA2WAVCDROM="IODVDServices"
-                       elif [ "$OSFLAVOUR" = "FBSD" ] ; then
-                               CDDA2WAVCDROM="$CDROMID"
-                       else
-                               if [ "$CDROMID" = "" ]; then
-                                       CDDA2WAVCDROM="$CDROM"
-                               else
-                                       CDDA2WAVCDROM="$CDROMID"
-                               fi
-                       fi
-                       nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t 1+$LASTTRACKNUM "$WAVDATA" >&2 
-                       ;;
-               dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
-               cddafs)
-                       # Find the track's mounted path
-                       REALTRACKNUM=$(expr $UTRACKNUM + 0)
-                       FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
-                       FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
-                       # If the file exists, copy it
-                       if [ -e "$FILEPATH" ] ; then
-                               nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
-                       else
-                               false
-                       fi ;;
-               debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
-       esac
-       RETURN=$?
-       if [ "$RETURN" != "0" ]; then
-               # Thank goodness errors is only machine-parseable up to the
-               # first colon, otherwise this woulda sucked
-                echo "readtrack-$FIRSTTRACKNUMBER: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
-               return $RETURN
-       else
-               echo readtrack-$FIRSTTRACKNUMBER >> "$ABCDETEMPDIR/status"
-       fi
-}
-
 # do_cdread [tracknumber]
+# do_cdread onetrack [firsttrack] [lasttrack]
 # 
 do_cdread ()
 {
        # The commands here don't go through run_command because they're never supposed to be silenced
        # return codes need to be doublechecked anyway, however
-       UTRACKNUM=$1
+       if [ "$1" = "onetrack" ]; then
+               # FIXME # Add the possibility of grabbing ranges of tracks in onetrack
+               # FIXME # Until then, we grab the whole CD in one track, no matter what
+               # the user said
+               # We need the first and last track for cdda2wav
+               FIRSTTRACK=$2
+               LASTTRACK=$3
+               UTRACKNUM=$FIRSTTRACK
+       else
+               UTRACKNUM=$1
+       fi
        CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
-       WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
-       OUTDATA="$ABCDETEMPDIR/track$UTRACKNUM.$OUTPUTTYPE"
-       if [ -r "$CDDBDATA" ]; then
-               TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
-               echo "Grabbing track $UTRACKNUM: $TRACKNAME..." >&2
+       if [ "$USEPIPES" = "y" ]; then
+               TEMPARG="PIPERIPPER_$CDROMREADERSYNTAX"
+               FILEARG="$( eval echo "\$$TEMPARG" )"
+               REDIR=""
+               PIPE_MESSAGE="and encoding "
+       else
+               WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
+               case "$CDROMREADERSYNTAX" in
+               ## FIXME ## Find the cases for dagrab and flac, to avoid exceptions
+                       flac)
+                               FILEARG="--output-name=$WAVDATA"
+                               ;;
+                       dagrab)
+                               FILEARG="-f $WAVDATA"
+                               ;;
+                       *)
+                               FILEARG="$WAVDATA"
+                               ;;
+               esac
+               REDIR=">&2"
+       fi
+       if [ "$1" = "onetrack" ]; then
+               echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK as one track ..." >&2
        else
-               echo "Grabbing track $UTRACKNUM..." >&2
+               if [ -r "$CDDBDATA" ]; then
+                       do_getcddbinfo TRACKNAME
+                       echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
+               else
+                       echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
+               fi
        fi
        case "$CDROMREADERSYNTAX" in
-               cdparanoia) nice $READNICE $CDROMREADER -d $CDROM $UTRACKNUM "$WAVDATA" >&2 ;;
+               ### FIXME ### use an exception for flac, since it uses -o
+               ### FIXME ### Shall we just use -o $FILEARG ??
+               flac)
+                       nice $READNICE $FLAC -d --cue=${READTRACKNUMS:-$UTRACKNUM.1-$(($UTRACKNUM + 1)).0} "$FILEARG" "$CDROM" ;;
+               cdparanoia) 
+                       nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
                cdda2wav)
                        if [ "$OSFLAVOUR" = "OSX" ] ; then
                                # Hei, we have to unmount the device before running anything like cdda2wav in OSX
@@ -1603,30 +2200,50 @@ do_cdread ()
                                        CDDA2WAVCDROM="$CDROMID"
                                fi
                        fi
-                       nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t $UTRACKNUM "$WAVDATA" >&2 
+                       nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR
+                       ;;
+               ## FIXME ## We have an exception for dagrab, since it uses -f
+               ## FIXME ## Shall we just use -f $FILEARG ??
+               dagrab) nice $READNICE $CDROMREADER -d $CDROM -v $UTRACKNUM "$FILEARG" $REDIR
                        ;;
-               dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
                cddafs)
                        # Find the track's mounted path
                        REALTRACKNUM=$(expr $UTRACKNUM + 0)
-                       FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \([^(]*\) (.*/\1/')
+                       FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
                        FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
                        # If the file exists, copy it
                        if [ -e "$FILEPATH" ] ; then
-                               nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
+                               nice $READNICE $CDROMREADER "$FILEPATH" "$FILEARG" $REDIR
                        else
                                false
                        fi ;;
-               debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
+               debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
+                       ;;
        esac
        RETURN=$?
-       if [ "$RETURN" != "0" ]; then
+       # If we get some error or we get some missing wav 
+       # (as long as we dont use pipes)
+       if [ "$RETURN" != "0" -o \( ! -s "$WAVDATA" -a X"$USEPIPES" != "Xy" \) ]; then
                # Thank goodness errors is only machine-parseable up to the
                # first colon, otherwise this woulda sucked
-                echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
+               if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
+                       RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
+               fi
+               if [ "$USEPIPES" = "y" ]; then
+                       echo "readencodetrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
+               else
+                       echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
+               fi
                return $RETURN
        else
-               echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
+               if [ "$USEPIPES" = "y" ]; then
+                       echo readencodetrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
+               else
+                       echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
+                       if [ "$1" = "onetrack" ]; then
+                               echo onetrack >> "$ABCDETEMPDIR/status"
+                       fi
+               fi
        fi
 }
 
@@ -1647,20 +2264,76 @@ do_cdspeed ()
 vecho ()
 {
 if [ x"$EXTRAVERBOSE" != "x" ]; then
-       echo $@
+       case $1 in
+               warning) 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 -q "^\[" ; then
+               DEBUGECHO=$(echo "$@" | tr -d '[]')
+               echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
+       else
+               echo "[DEBUG] $1"
+       fi
 fi
 }
 
+# User-redefinable functions
+# Custom filename munging:
+mungefilename ()
+{
+       #echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
+       echo "$@" | sed s,:,\ -,g | tr \ / __ | tr -d \'\"\?\[:cntrl:\]
+}
+
+# Custom genre munging:
+mungegenre ()
+{
+       echo $CDGENRE | tr "[:upper:]" "[:lower:]"
+}
+
+# pre_read
+# Empty pre_read function, to be defined in the configuration file.
+pre_read ()
+{
+:
+}
+
+# post_read
+# Empty post_read function, to be defined in the configuration file.
+post_read ()
+{
+:
+}
+
+###############################################################################
+# End of functions
+#
 # Start of execution
+###############################################################################
 
 # Builtin defaults
 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
 CDDBSUBMIT=freedb-submit@freedb.org
 CDDBPROTO=5
 HELLOINFO="$(whoami)@$(hostname)"
+CDDBCOPYLOCAL="n"
+CDDBLOCALDIR="$HOME/.cddb"
+CDDBUSELOCAL="n"
+
+# List of fields we parse and show during the CDDB parsing...
+SHOWCDDBFIELDS="year,genre"
+
 INTERACTIVE=y
 CDROMREADERSYNTAX=cdparanoia
-OUTPUTTYPE=ogg
 ENCODERSYNTAX=default
 
 MP3ENCODERSYNTAX=default
@@ -1668,6 +2341,8 @@ OGGENCODERSYNTAX=default
 FLACENCODERSYNTAX=default
 SPEEXENCODERSYNTAX=default
 MPPENCODERSYNTAX=default
+NORMALIZERSYNTAX=default
+CUEREADERSYNTAX=default
 
 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
@@ -1687,20 +2362,22 @@ READNICE=10
 DISTMP3NICE=10
 VARIOUSARTISTS=n
 VARIOUSARTISTSTYLE=forward
-NORMALIZERSYNTAX=default
 KEEPWAVS=n
 PADTRACKS=n
-CDDBCOPYLOCAL="n"
-CDDBLOCALDIR="$HOME/.cddb"
-CDDBUSELOCAL="n"
+NOGAP=n
+BATCHNORM=n
 
 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
 # i.e. CDROMID="1,0,0"
 CDROMID=""
+# If we are using the IDE bus, we need CDPARANOIACDROMBUS defined as "d"
+# If we are using the ide-scsi emulation layer, we need to define a "g"
+CDPARANOIACDROMBUS="d"
 
 # program paths - defaults to checking your $PATH
 # mp3
 LAME=lame
+TOOLAME=toolame
 GOGO=gogo
 BLADEENC=bladeenc
 L3ENC=l3enc
@@ -1718,6 +2395,7 @@ MPPENC=mppenc
 
 ID3=id3
 ID3V2=id3v2
+EYED3=eyeD3
 CDPARANOIA=cdparanoia
 CDDA2WAV=cdda2wav
 DAGRAB=dagrab
@@ -1729,13 +2407,20 @@ MD5SUM=md5sum
 DISTMP3=distmp3
 VORBISCOMMENT=vorbiscomment
 METAFLAC=metaflac
-NORMALIZE=normalize
+NORMALIZE=normalize-audio
 CDSPEED=eject
 VORBISGAIN=vorbisgain
+MP3GAIN=mp3gain
+MPPGAIN=replaygain
+MKCUE=mkcue
+MKTOC=cdrdao
+DIFF=diff
+CUE2DISCID=cue2discid
 
 # Options for programs called from abcde
 # mp3
 LAMEOPTS=
+TOOLAMEOPTS=
 GOGOOPTS=
 BLADEENCOPTS=
 L3ENCOPTS=
@@ -1763,6 +2448,11 @@ DISTMP3OPTS=
 NORMALIZEOPTS=
 CDSPEEDOPTS="-x"
 CDSPEEDVALUE=
+MKCUEOPTS=
+MKTOCOPTS=""
+VORBISCOMMENTOPTS="-R"
+METAFLACOPTS="--no-utf8-convert"
+DIFFOPTS=
 
 # Default to one process if -j isn't specified
 MAXPROCS=1
@@ -1770,30 +2460,15 @@ MAXPROCS=1
 # List of actions to perform - by default, run to completion
 ACTIONS=cddb,read,encode,tag,move,clean
 
-# User-redefinable functions
-# Custom filename munging:
-mungefilename ()
-{
-       echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
-}
-
-# Custom genre munging:
-mungegenre ()
-{
-       echo $CDGENRE | tr "[:upper:]" "[:lower:]"
-}
-
-# pre_read
-# Empty pre_read function, to be defined in the configuration file.
-pre_read ()
-{
-:
-}
+# 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
 
 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
 # Let's use these checkings to determine the OS flavour, which will be used later
 if [ X$(uname) = "XFreeBSD" ] ; then
        HTTPGET=fetch
+       MD5SUM=md5
        NEEDCDROMID=y
        OSFLAVOUR=FBSD
 elif [ X$(uname) = "XDarwin" ] ; then
@@ -1801,9 +2476,13 @@ elif [ X$(uname) = "XDarwin" ] ; then
        OSFLAVOUR=OSX
        # We should have disktool in OSX, but let's be sure...
        NEEDDISKTOOL=y
+       CDROMREADERSYNTAX=cddafs
 elif [ X$(uname) = "XOpenBSD" ] ; then
        HTTPGET=wget
        MD5SUM=md5
+elif [ X$(uname) = "XNetBSD" ] ; then
+       HTTPGET=ftp
+       MD5SUM=md5
 else
        HTTPGET=wget
 fi
@@ -1812,6 +2491,7 @@ fi
 # If USEID3 is set to n, no ID3 tagging is done
 CDDBAVAIL=y
 USEID3=y
+USEID3V2=y
 
 if [ -z "$OUTPUTDIR" ]; then
        OUTPUTDIR=$(pwd)
@@ -1831,14 +2511,15 @@ if [ -r $HOME/.abcde.conf ]; then
 fi
 
 # By this time, we need some HTTPGETOPTS already defined.
-# If the user has defined its own, we should not be empty.
+# If the user has defined a non-default HTTPGET method, we should not be empty.
 
 if [ "$HTTPGETOPTS" = "" ] ; then
        case $HTTPGET in
                wget) HTTPGETOPTS="-q -O -";;
                curl) HTTPGETOPTS="-f -s";;
                fetch)HTTPGETOPTS="-q -o -";;
-               *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
+               ftp)  HTTPGETOPTS="-q -o -";;
+               *) log warning "HTTPGET in non-standard and HTTPGETOPTS are not defined." ;;
        esac
 fi
 
@@ -1860,36 +2541,43 @@ if [ "$CDROM" = "" ] ; then
 fi
 
 # Parse command line options
-#while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:t:T:vVx opt ; do
-while getopts 1a:A:bc:C:d:Dhj:klLnNo:pr:Rs:S:vVx opt ; do
+#while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
+while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
        case "$opt" in
                1) ONETRACK=y ;;
                a) ACTIONS="$OPTARG" ;;
-               A) EXPACTIONS="$OPTARG";;
-               b) 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.}" ;;
+               A) EXPACTIONS="$OPTARG" ;;
+               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 ;;
-               f) FORCECDDBUSELOCAL=y ;;
+               e) ERASEENCODEDSTATUS=y ;;
+               E) ENCODING="$OPTARG" ;;
+               f) FORCE=y ;;
+               g) NOGAP=y ;;
                i) INLINETAG=y ;;
                j) MAXPROCS="$OPTARG" ;;
                k) KEEPWAVS=y ;;
                l) LOWDISK=y ;;
-               L) CDDBUSELOCAL="y" ;;
-               n) CDDBAVAIL="n" ;;
-               N) INTERACTIVE="n" ;;
+               L) CDDBUSELOCAL=y ;;
+               n) CDDBAVAIL=n ;;
+               N) INTERACTIVE=n ;;
                m) DOSPLAYLIST=y ;;
+               M) MAKECUEFILE=y ;;
                o) OUTPUTTYPE="$OPTARG" ;;
-               p) PADTRACKS="y" ;;
+               p) PADTRACKS=y ;;
+               P) USEPIPES=y ;;
                r) REMOTEHOSTS="$OPTARG" ;;
-               R) REPLAYGAIN=y ;;
-               s) STARTTRACKNUMBER="$OPTARG" ;;
+               R) DOREPLAYGAIN=y ;;
+               s) SHOWCDDBFIELDS="$OPTARG" ;;
                S) CDSPEEDVALUE="$OPTARG" ;;
-               t) PREPROCESSFORMATS="$OPTARG"
-                  PREPROCESS=y ;;
-               T) POSTPROCESSFORMATS="$OPTARG" ;;
+               t) STARTTRACKNUMBER="$OPTARG" ;;
+               T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
+               u) CDDBPROTO=6 ;;
                v) 
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
@@ -1898,24 +2586,56 @@ while getopts 1a:A:bc:C:d:Dhj:klLnNo:pr:Rs:S:vVx opt ; do
                   ;;
                V) EXTRAVERBOSE="y" ;;
                x) EJECTCD="y" ;;
+               w) COMMENT="$OPTARG" ;;
+               W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
+                    STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
+                  else
+                    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))
 
-# Decide if we can continue. TO_REMOVE as soon as we find out about dagrab
-if [ "$ONETRACK" = "y" ] ; then 
+# If the user specified a flac file, then switch to special flac mode
+if echo $CDROM | grep -i -q '.flac$'; then
+       vecho "abcde: switching to flac CDROMREADERSYNTAX..."
+       CDROMREADERSYNTAX=flac
+       if [ "$EJECTCD" = "y" ];then
+               vecho "abcde: CDROM flac mode, deactivating EJECTCD..."
+               EJECTCD=n
+       fi
+fi
+
+# If the user provided a DISCID, disable eject
+if [ -n "$DISCID" ]; then EJECTCD=n ; 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
-               dagrab|debug) echo "abcde error: ONETRACK reading is not suported with "$CDROMREADERSYNTAX" yet"
-                             exit 1 ;;
+               flac) ;;
+               cdparanoia) ;;
+               cdda2wav) ;;
+               *) 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"
+       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 "ONETRACK mode selected: grabbing all tracks..."
+               log warning "ONETRACK mode selected, grabbing all tracks..."
        fi
 else
        while [ $# -gt 0 ]; do
@@ -1932,25 +2652,151 @@ else
        done
 fi
 
+# List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
+# List of experimental actions: retag,transcode
+
+# Determine what actions are to be done from $ACTIONS and set the
+# following environment variables for them:
+DOCDDB=n
+DOMUSICBRAINZ=n
+DOREAD=n
+DONORMALIZE=n
+DOPREPROCESS=n
+DOENCODE=n
+DOPOSTPROCESS=n
+DOTAG=n
+DOMOVE=n
+DOREPLAYGAIN=n
+DOPLAYLIST=n
+DOCLEAN=n
+
+for ACTION in $(echo $ACTIONS | tr , \ )
+do
+       case $ACTION in
+               cddb) DOCDDB=y;;
+               musicbrainz) DOMUSICBRAINZ=y;;
+               read) DOREAD=y;;
+               normalize) DONORMALIZE=y; DOREAD=y;;
+#              preprocess) DOPREPROCESS=y; DOREAD=y;;
+               encode) DOENCODE=y; DOREAD=y;;
+#              postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
+               tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
+               move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
+               replaygain) DOCDDB=y; DOREAD=y; DOENCODE=y; DOTAG=y; DOMOVE=y; DOREPLAYGAIN=y;;
+               playlist) DOCDDB=y; DOPLAYLIST=y;;
+               clean) DOCLEAN=y;;
+       esac
+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
+       case $SHOWCDDBFIELD in
+               y*|Y*) SHOWCDDBYEAR="y";;
+               g*|G*) SHOWCDDBGENRE="y";;
+               *) ;;
+       esac
+done
+
+# Sanity checks:
+
 # At this point a CDROM has to be defined, so we check it exists.
-if [ "$CDROM" != "" ] ; then 
+if [ X"$CDROM" != "X" ] ; then 
        if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
                if [ "$OSFLAVOUR" = "FBSD" ]; then
                        if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
-                               echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
-                               echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
+                               log error "CDROMID not in the right format for $CDROMREADERSYNTAX"
+                               log error "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
                                exit 1
                        fi
                fi
-       elif [ ! -e $CDROM ] ; then
-               echo "abcde error: CDROM device cannot be found." >&2
+       elif [ ! -e "$CDROM" -a X"$DOREAD" = "Xy" ]; then
+               log error "CDROM device cannot be found."
                exit 1
        fi
-else
-       echo "abcde error: CDROM has not been defined or cannot be found" >&2
+# avoid processing if we are not going to hit the CDROM.
+elif [ X"$DOREAD" = "Xy" ]; then
+       log error "CDROM has not been defined or cannot be found"
        exit 1
 fi
 
+# USEPIPES pre-tests, before we get into more serious stuff
+# Not compatible with:
+# - multiple outputs
+# - normalize
+# - lowdisk algorithm
+# - anything else?
+if [ X"$USEPIPES" = "Xy" ]; then
+       if [ $(echo "$OUTPUTTYPE" | tr , \  | wc -w ) -gt 1 ]; then
+               log error "Unix pipes not compatible with multiple outputs"
+               exit 1
+       fi
+       if [ X"$DONORMALIZE" = "Xy" ]; then
+               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 warning "Disabling Unix pipes since we are not encoding!"
+               USEPIPES=n
+       fi
+       if [ X"$LOWDISK" = "Xy" ]; then
+               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
+               DEFAULT_OUTPUT_FORMAT="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 1)"
+               DEFAULT_OUTPUT_BINARY="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 2)"
+               if [ -x $(which $DEFAULT_OUTPUT_BINARY) ] ; then
+                       OUTPUTTYPE=$DEFAULT_OUTPUT_FORMAT
+                       vecho "No default output type defined. Autoselecting $OUTPUTTYPE..." >&2
+                       break
+               fi
+       done
+       if [ X"$OUTPUTTYPE" = "X" ]; then
+               log error "no encoder found in the PATH"
+               log error "hints: are all dependencies installed? has the \$PATH been modified?"
+               exit 1
+       fi
+fi
+
 # Decide which CDROM reader we're gonna use
 case "$CDROMREADERSYNTAX" in
        cdparanoia|debug)
@@ -1969,6 +2815,10 @@ case "$CDROMREADERSYNTAX" in
                CDROMREADER="$CDDAFS"
                CDROMREADEROPTS="$CDDAFSOPTS"
                ;;
+       flac)
+               CDROMREADER="$FLAC"
+               CDROMREADEROPTS="$FLACOPTS"
+               ;;
 esac
 
 # There's only one normalize...
@@ -1979,86 +2829,135 @@ case "$NORMALIZERSYNTAX" in
                ;;
 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
+               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- )" ;;
+               esac
+       done
+       for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
+               TEMPOUTPUT=$( echo "$OUTPUT" | cut -d: -f1 )
+               TEMPOUTPUTTYPE="${TEMPOUTPUTTYPE:+$TEMPOUTPUTTYPE,}$TEMPOUTPUT"
+       done
+       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
 
 # Getting ready for multiple output changes
 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
 do
        case $OUTPUT in
-               ogg)  [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
-                     echo $ACTIONS | grep tag > /dev/null 2>&1 && NEEDCOMMENTER=y
-                     if [ "$REPLAYGAIN" = "y" ]; then NEEDVORBISGAIN=y; fi
+               vorbis|ogg)
+                       [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
+                       [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
+                       OGGOUTPUTCONTAINER=ogg
                        ;;
-               mp3)  [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
-                     echo $ACTIONS | grep tag > /dev/null 2>&1 && NEEDTAGGER=y
+               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
+                       ;;
+               spx)
+                       [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
+#                      [ "$DOREPLAYGAIN" = "y" ] &&
+                       ;;
+               mpc)
+                       [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc
+                       [ "$DOREPLAYGAIN" = "y" ] && NEEDMPPGAIN=y
+                       ;;
+               wav)
+                       if [ "$KEEPWAVS" = "y" ]; then
+                               vecho "Unsetting the KEEPWAVS option, since the resulting wav files were requested..."
+                       fi
+                       KEEPWAVS=move
+                       ;;
+               *)      log error "Invalid OUTPUTTYPE defined"
+                       exit 1
                        ;;
-               flac) [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
-                     echo $ACTIONS | grep tag > /dev/null 2>&1 && NEEDMETAFLAC=y
-                       ;;
-               spx) [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc ;;
-               mpc) [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc ;;
-               *) echo "abcde error: Invalid OUTPUTTYPE defined" >&2
-                  exit 1
-                  ;;
        esac
 done
 
 # decide which encoder
 case "$MP3ENCODERSYNTAX" in
        lame)
-               MP3ENCODEROPTS="$LAMEOPTS"
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$LAMEOPTS}"
                MP3ENCODER="$LAME"
                ;;
+       toolame)
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$TOOLAMEOPTS}"
+               MP3ENCODER="$TOOLAME"
+               ;;
        gogo)
-               MP3ENCODEROPTS="$GOGOOPTS"
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$GOGOOPTS}"
                MP3ENCODER="$GOGO"
                ;;
        bladeenc)
-               MP3ENCODEROPTS="$BLADEENCOPTS"
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$BLADEENCOPTS}"
                MP3ENCODER="$BLADEENC"
                ;;
        l3enc)
-               MP3ENCODEROPTS="$L3ENCOPTS"
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$L3ENCOPTS}"
                MP3ENCODER="$L3ENC"
                ;;
        xingmp3enc)
-               MP3ENCODEROPTS="$XINGMP3ENCOPTS"
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$XINGMP3ENCOPTS}"
                MP3ENCODER="$XINGMP3ENC"
                ;;
        mp3enc)
-               MP3ENCODEROPTS="$MP3ENCOPTS"
+               MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$MP3ENCOPTS}"
                MP3ENCODER="$MP3ENC"
                ;;
 esac
 case "$OGGENCODERSYNTAX" in
        vorbize)
-               OGGENCODEROPTS="$VORBIZEOPTS"
+               OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$VORBIZEOPTS}"
                OGGENCODER="$VORBIZE"
                ;;
        oggenc)
-               OGGENCODEROPTS="$OGGENCOPTS"
+               OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$OGGENCOPTS}"
                OGGENCODER="$OGGENC"
                ;;
 esac
 case "$FLACENCODERSYNTAX" in
        flac)
-               FLACENCODEROPTS="$FLACOPTS"
-               FLACENCODER="$FLAC"
+               FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
+               FLACENCODER="$FLAC"     
+               # FLAC streams can be encapsulated on a Ogg transport layer
+               if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;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
+                       FLACOUTPUTCONTAINER=flac
+               fi
                ;;
 esac
 case "$SPEEXENCODERSYNTAX" in
        speexenc)
-               SPEEXENCODEROPTS="$SPEEXENCOPTS"
+               SPEEXENCODEROPTS="${SPEEXENCODEROPTSCLI:-$SPEEXENCOPTS}"
                SPEEXENCODER="$SPEEXENC"
                ;;
 esac
 case "$MPPENCODERSYNTAX" in
        mppenc)
-               MPPENCODEROPTS="$MPPENCOPTS"
+               MPPENCODEROPTS="${MPPENCODEROPTSCLI:-$MPPENCOPTS}"
                MPPENCODER="$MPPENC"
                ;;
 esac
-
+               
 # and which tagger
 
 if [ "$ID3TAGV" = "1" ]; then
@@ -2069,6 +2968,30 @@ 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)
+               CUEREADEROPTS="${CDROM}"
+               CUEREADER="$MKCUE"
+               ;;
+esac
+
+# Check if both OGGEOUTPUTCONTAINER and FLACOUTPUTCONTAINER are the same, and differentiante them
+if [ X"$OGGOUTPUTCONTAINER" = "Xogg" ] && [ X"$FLACOUTPUTCONTAINER" = "Xogg" ]; then
+       log error "FLAC on an Ogg container is not yet supported"
+       log error "due to problem with adding comments to such files"
+       exit 1
+       OGGOUTPUTCONTAINER=ogg.ogg
+       FLACOUTPUTCONTAINER=flac.ogg
+       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')
 
 if [ "$ENCNICE" ]; then
@@ -2082,18 +3005,79 @@ if [ "$DISTMP3NICE" ]; then
 fi
 
 # Don't check for stuff if it's not needed
-if [ "$REMOTEHOSTS" ]; then NEEDDISTMP3=y; fi
-if echo $ACTIONS | grep normalize > /dev/null 2>&1 ; then NEEDNORMALIZER=y; fi
-if [ "$EJECTCD" = "y" ]; then NEEDEJECT=y; fi
-if echo $ACTIONS | grep cddb > /dev/null 2>&1 ; then NEEDHTTPGET=y ; fi
+if [ "$REMOTEHOSTS" ]; then 
+       NEEDDISTMP3=y
+fi
+if [ "$DONORMALIZE" = "y" ]; then
+       NEEDNORMALIZER=y
+fi
+if [ "$EJECTCD" = "y" ]; then
+       NEEDEJECT=y
+fi
+if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
+       NEEDHTTPGET=y
+fi
+if [ "$MAKECUEFILE" = "y" ]; then
+       NEEDCUEREADER=y
+fi
 
 if [ X"$CDSPEEDVALUE" != "X" ]; then
        case "$CDROMREADERSYNTAX" in
                cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
+               ### FIXME ### translate "cue2discid" from python to bash
+               flac) NEEDMETAFLAC=y ; NEEDCUE2DISCID=y ;;
                *) NEEDCDSPEED=y ;;
        esac
 fi
 
+###USEPIPESSUPPORT###
+
+# Rippers with USEPIPE support
+# FIXME # Include here all the rippers we can figure out support pipes
+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="PIPERIPPER_${CDROMREADERSYNTAX}"
+       case "$OUTPUT" in
+               mp3)
+                       PIPEENCODERSVARCHECK="PIPE_$MP3ENCODERSYNTAX" ;;
+               vorbis|ogg)
+                       PIPEENCODERSVARCHECK="PIPE_$OGGENCODERSYNTAX" ;;
+               flac)
+                       PIPEENCODERSVARCHECK="PIPE_$FLACENCODERSYNTAX" ;;
+               spx)
+                       PIPEENCODERSVARCHECK="PIPE_$SPEEXENCODER" ;;
+               mpc)
+                       PIPEENCODERSVARCHECK="PIPE_$MPPENCODER" ;;
+       esac
+       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
+       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
 
 # Make sure a buncha things exist
 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
@@ -2102,15 +3086,17 @@ for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
        ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
        ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
        ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
-       ${NEEDVORBISGAIN+$VORBISGAIN}
+       ${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
+               log error "$X is not in your path." >&2
                exit 1
        elif [ ! -x $(which $X) ]; then
-               echo "abcde error: $X is not executable." >&2
+               log error "$X is not executable." >&2
                exit 1
        fi
 done
@@ -2119,12 +3105,15 @@ CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
 HTTPGET="$HTTPGET $HTTPGETOPTS"
 
+# And last but not least, check if we can diff between files
+if [ -x $(which $DIFF) ]; then :; else
+       vecho warning "Disabling diff since we cannot find it in the \$PATH..."
+       DIFF=""
+fi
+
 # Here it used to say:
 # One thousand lines in, we can start doing stuff with things
-# Well, right now we are at line 2116 ;)
-
-# List of valid actions: cddb,read,normalize,encode,tag,playlist,move,clean
-# List of experimental actions: retag,transcode
+# Well, right now we are at line 2736 ;)
 
 # Export needed things so they can be read in this subshell
 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
@@ -2145,62 +3134,45 @@ if [ "$DOCDDB" = "y" ]; then
        if [ $CDDBUSELOCAL = "y" ]; then
                do_localcddb
        fi
-       ## FIXME ## ! is non-portable
-       if ! checkstatus cddb-choice > /dev/null && [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
-               do_cddbstat
-               do_cddbquery
-               do_cddbread
+       if checkstatus cddb-choice > /dev/null; then
+               :
+       else 
+               if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
+                       do_cddbstat
+                       do_cddbquery
+                       do_cddbread
+               fi
        fi
        do_cddbedit
 
-       eval $($CDDBTOOL parse "$CDDBDATA")
+       eval "$($CDDBTOOL parse "$CDDBDATA")"
 fi
 
 # Before reading tracks, we set the speed of the device
 
 if [ X"$CDSPEEDVALUE" != "X" ]; then
        case "$CDROMREADERSYNTAX" in
-               cdparanoia|debug) : ;;
+               cdparanoia|debug) ;;
+               flac) ;;
                *) do_cdspeed ;;
        esac
 fi
 
-if [ "$STRIPDATATRACKS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
-       case "$CDROMREADERSYNTAX" in
-               cdparanoia|debug) 
-                       # cdparanoia can query the CD, so let's process the TRACKQUEUE list with the results.
-                       if checkstatus cdparanoia-audio-tracks; then
-                               CDTRACKQUEUE=$( cat $ABCDETEMPDIR/cdparanoia-audio-tracks )
-                       else
-                               ## FIXME ##
-                               vecho "Querying the CD to obtain a list of valid audio tracks..."
-                               $CDROMREADER -Q > $ABCDETEMPDIR/cdparanoia-query 2>&1
-                               # Obtain a list of valid audio tracks from the results of the query
-                               CDTRACKQUEUE=$( cat $ABCDETEMODIR/cdparanoia- | egrep '^[[:space:]]+[[:digit:]]' | awk '{print $1}' | tr -d "." | tr '\n' ' ' )
-                       fi
-                       # Obtain the track padding value from the before-processing list and pad the CD list
-                       TRACKNUMPADDING=$( echo $TRACKQUEUE | awk '{print $1}' | tr -d " \n" | wc -c )
-                       for TRACK in $CDTRACKQUEUE ; do
-                               TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
-                               PADNEWTRACKQUEUE=$(echo $PADNEWTRACKQUEUE $TRACKNUM)
-                       done
-                       CDTRACKQUEUE=$PADNEWTRACKQUEUE
-                       # Now, compare if the values in the list are valid tracks in the CD
-                       for TRACK in $TRACKQUEUE; do
-                               if echo $CDTRACKQUEUE | grep $TRACK >/dev/null ; then
-                                       NEWTRACKQUEUE="$NEWTRACKQUEUE $TRACK"
-                               fi
-                       done
-                       TRACKQUEUE="$NEWTRACKQUEUE"
-               ;;
-       esac
+# Define the first and last track, since we might need them later in several places
+FIRSTTRACK=$( get_first $TRACKQUEUE )
+LASTTRACK=$( get_last $TRACKQUEUE )
+
+if [ -f "$ABCDETEMPDIR/status" ] && [ X"$ERASEENCODEDSTATUS" = "Xy" ]; then
+       mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
+       grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
+               | grep -v ^encode-output > "$ABCDETEMPDIR/status"
 fi
 
 # Create playlist if needed (backgroundable) and start reading in tracks
 
 (
 
-if [ "$ONETRACK" = "y" ]; then :; else
+if [ ! "$ONETRACK" = "y" ]; then
        if [ "$DOPLAYLIST" = "y" ]; then
                echo Creating playlist... >&2
                do_playlist
@@ -2214,18 +3186,27 @@ if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
 fi
 
 if [ "$ONETRACK" = "y" ]; then 
-       FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}' )
        TRACKS="$FIRSTTRACK"
-       for UTRACKNUM in $TRACKQUEUE; do :;done
        if checkstatus readtrack-$FIRSTTRACK; then :; else
-               do_cdread_one $UTRACKNUM $FIRSTTRACK
+               if [ "$USEPIPES" = "y" ]; then
+                       do_cdread onetrack $FIRSTTRACK $LASTTRACK | do_encode $FIRSTTRACK %local0% > /dev/null 2>&1
+               else
+                       do_cdread onetrack $FIRSTTRACK $LASTTRACK
+               fi
        fi
 else
        for UTRACKNUM in $TRACKQUEUE
        do
                if [ "$DOREAD" = "y" ]; then
-                       if checkstatus readtrack-$UTRACKNUM; then :; else
-                               do_cdread $UTRACKNUM
+                       if [ "$USEPIPES" = "y" ]; then
+                               if checkstatus readencodetrack-$UTRACKNUM; then :; else
+                                       # Read, pipe, shut up!
+                                       do_cdread $UTRACKNUM | do_encode $UTRACKNUM %local0% > /dev/null 2>&1
+                               fi
+                       else
+                               if checkstatus readtrack-$UTRACKNUM; then :; else
+                                       do_cdread $UTRACKNUM
+                               fi
                                if [ "$?" != "0" ]; then
                                        # CD read failed - don't give the goahead to
                                        # the encoder
@@ -2234,9 +3215,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
@@ -2260,10 +3246,13 @@ 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
 
+# Execute the user-defined post_read funtion before ejecting CD
+post_read
+
 # We are now finished with the cdrom - it can be safely ejected. Note that
 # abcde will not have completed yet.
 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
@@ -2314,27 +3303,35 @@ 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
 
 # If we are using ONETRACK, we can proceed with the normal encoding using just the $FIRSTTRACK as TRACKQUEUE
 if [ "$ONETRACK" = "y" ] ; then
-       FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}')
-       TRACKQUEUE=$FIRSTTRACK
+       TRACKQUEUE="$FIRSTTRACK"
        TRACKS="$FIRSTTRACK"
 fi
 
@@ -2355,7 +3352,7 @@ do
        read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
        if [ "$GOAHEAD" = "NO" ]; then break; fi
        # find out where this track is to be encoded
-       if [ "$DOENCODE" = "y" ]; then
+       if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
                # Make sure we have a place to encode this, if not, exit stage right
                if [ -z "$ENCODELOCATIONS" ]; then
                        continue
@@ -2401,10 +3398,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" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
+                       CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
+                       do_getcddbinfo TRACKNAME
                        splitvarious
                fi
        fi
@@ -2417,7 +3413,7 @@ do
                        if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
                fi
        fi
-       if [ "$DOENCODE" = "y" ]; then
+       if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
                if checkstatus readtrack-$UTRACKNUM; then
                        #if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION; fi
                        if [ "$DONORMALIZE" = "y" ]; then
@@ -2433,6 +3429,12 @@ do
                if checkstatus encodetrack-$UTRACKNUM; then
                        if checkstatus tagtrack-$UTRACKNUM; then :; else do_tag $UTRACKNUM; fi
                fi
+               # Lets tag the cue file
+               if checkstatus cleancuefile >/dev/null; then :; else
+                       if checkstatus cuefile >/dev/null ; then 
+                               do_cleancue
+                       fi
+               fi
        fi
        if [ "$DOMOVE" = "y" ]; then
                if checkstatus tagtrack-$UTRACKNUM; then
@@ -2441,9 +3443,12 @@ do
        fi
        ) &
 done
+
+
 # Go through it again and make sure there's no distmp3 stragglers, otherwise
 # we'll delete the files they're working on
-if [ "$DOENCODE" = "y" ]; then
+## FIXME ## Check also for files which are encoded using PIPEs.
+if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
        PROCEED=
        until [ $PROCEED ]
        do
@@ -2466,9 +3471,13 @@ if [ "$DOENCODE" = "y" ]; then
 fi
 # If the above didn't catch the stragglers, this will
 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
@@ -2477,6 +3486,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!
@@ -2488,3 +3509,6 @@ else
 fi
 )
 exit 0
+
+# b:is_bash
+# vim:tabstop=4