r12@keebo: data | 2005-01-24T21:38:49.651783Z
[abcde.git] / abcde
diff --git a/abcde b/abcde
index 7287760..4a28dda 100755 (executable)
--- a/abcde
+++ b/abcde
 # Copyright for this work is to expire January 1, 2010, after which it
 # shall be public domain.
 
-VERSION=2.1.20
+VERSION="2.2.4"
 
 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 "-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 (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 <file>"
+echo "       Specify a configuration file (overrides system and user config files)"
+echo "-C <discid#>"
+echo "       Specify discid to resume from (only needed if you no longer have the cd)"
+echo "-d <device>"
+echo "       Specify CDROM device to grab"
+echo "-D     Debugging mode (equivalent to sh -x abcde)"
+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). 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 "-s    Start the track numbering at a given number -NWY-"
-echo "-S    Set the CD speed (if possible)"
+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 "-o <type1[,type2]...>"
+echo "       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 "-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 ogg,flac)"
+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 "-t <#> Start the track numbering at a given number"
+echo "-T <#> Same as -t but modifies tag numbering"
+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 ""
 echo "Tracks is a space-delimited list of tracks to grab."
 echo "Ranges specified with hyphens are allowed."
 }
@@ -101,7 +114,7 @@ checkstatus ()
 # Otherwise, returns "".
 checkerrors ()
 {
-       if [ ! -e "$ABCDETEMPDIR/errors" ]; then
+       if [ -e "$ABCDETEMPDIR/errors" ]; then :; else
                return 1
        fi
        # Take the last line in the status file if there's multiple matches
@@ -273,6 +286,13 @@ do_tag ()
 {
        COMMENTOUTPUT="$(eval echo ${COMMENT})"
        run_command '' echo "Tagging track $1 of $TRACKS: $TRACKNAME..."
+       # If we want to start the tracks with a given number, we need to modify the
+       # TRACKNUM value before evaluation
+       if [ -n "$STARTTRACKNUMBER" -a -n "$STARTTRACKNUMBERTAG" ] ; then
+               # Get the trackpadding from the current track
+               CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
+               TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - 1 ))
+       fi
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
        do
        case "$OUTPUT" in
@@ -291,9 +311,9 @@ do_tag ()
                                fi
                                (
                                # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
-                               echo ARTIST="$TRACKARTIST"
+                               echo ARTIST=$TRACKARTIST
                                echo ALBUM="$DALBUM"
-                               echo TITLE="$TRACKNAME"
+                               echo TITLE=$TRACKNAME
                                        if [ -n "$CDYEAR" ]; then
                                        echo DATE="$CDYEAR"
                                        fi
@@ -301,6 +321,7 @@ do_tag ()
                                        echo GENRE="$CDGENRE"
                                fi      
                                echo TRACKNUMBER=$1
+                               echo CDDB=$CDDBDISCID
                                if [ "$(eval echo ${COMMENT})" != "" ]; then
                                        case "$COMMENTOUTPUT" in
                                                *=*) echo "$COMMENTOUTPUT";;
@@ -329,18 +350,22 @@ do_tag ()
                        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
-               echo TRACKNUMBER=$1
-                ) | run_command tagtrack-$1 $METAFLAC --import-vc-from=- --no-utf8-convert "$ABCDETEMPDIR/track$1.$OUTPUT"
+                ) | run_command tagtrack-$1 $METAFLAC --import-tags-from=- --no-utf8-convert "$ABCDETEMPDIR/track$1.$OUTPUT"
                ;;
        spx)
                run_command tagtrack-$1 true
                ;;
+       mpc)
+               run_command tagtrack-$1 true
+               ;;
        esac
        done
 }
@@ -426,7 +451,6 @@ do_encode ()
                                esac
                                ;;
                        flac)
-       
                                case "$2" in
                                %local*%)
                                        case "$FLACENCODERSYNTAX" in
@@ -456,6 +480,15 @@ do_encode ()
                                        run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
                                fi
                                ;;
+                       mpc)    
+                               # MPP/MP+(Musepack) format (.mpc) is done locally, with inline
+                               # tagging.
+                               # I tried compiling the mppenc from corecodecs.org and got some
+                               # 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"
+                               ;;
                        esac
                done
                # Only remove .wav if the encoding succeeded
@@ -476,6 +509,114 @@ do_encode ()
        fi
 }
 
+# do_preprocess [tracknumber]
+# variables used:
+# TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
+#do_preprocess ()
+#{
+#      IN="$ABCDETEMPDIR/track$1.wav"
+#      # We need IN to proceed.
+#      if [ -s "$IN" ] ; then
+#              for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
+#              do
+#                      #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
+#                      run_command '' echo "Pre-processing track $1 of $TRACKS..."
+#                      case "$POSTPROCESSFORMAT" in
+#                      all|wav*)
+#                              run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
+#                      mp3)
+#                              run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
+#                      ogg)
+#                              run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
+#                      flac)
+#                              run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
+#                      spx)
+#                              run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
+#                      esac
+#              done
+#              # Only remove .wav if the encoding succeeded
+#              if checkerrors "preprocess-(.{3,4})-$1"; then 
+#                      run_command preprocess-$1 false
+#              else
+#                      run_command preprocess-$1 true
+#              fi
+#      else
+#              if [ "$(checkstatus encode-output)" = "loud" ]; then
+#                      echo "HEH! The file we were about to pre-process disappeared:"
+#                      echo ">> $IN"
+#              fi
+#              run_command preprocess-$1 false
+#      fi
+#}
+
+
+# do_postprocess [tracknumber]
+# variables used:
+# TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
+#do_postprocess ()
+#{
+#      for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
+#      do
+#              IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
+#              # We need IN to proceed.
+#              if [ -s "$IN" ] ; then
+#                      #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
+#                      run_command '' echo "Post-processing track $1 of $TRACKS..."
+#                      case "$POSTPROCESSFORMAT" in
+#                              mp3)
+#                                      run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
+#                              ogg)
+#                                      run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
+#                              flac)
+#                                      run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
+#                              spx)
+#                                      run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
+#                      esac
+#                      # Only remove .wav if the encoding succeeded
+#                      if checkerrors "postprocess-(.{3,4})-$1"; then 
+#                              run_command postprocess-$1 false
+#                      else
+#                              run_command postprocess-$1 true
+#                      fi
+#              else
+#                      if [ "$(checkstatus encode-output)" = "loud" ]; then
+#                              echo "HEH! The file we were about to post-process disappeared:"
+#                              echo ">> $IN"
+#                      fi
+#                      run_command postprocess-$1 false
+#              fi
+#      done
+#}
+
+# do_batch_gain
+# variables used:
+# MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
+do_batch_gain ()
+{
+       # The commands here don't go through run_command because they're never supposed to be silenced
+       echo "Batch analizing gain in tracks: $TRACKQUEUE"
+       (
+       cd "$ABCDETEMPDIR"
+       BLURB=
+       TRACKFILES=
+       for UTRACKNUM in $TRACKQUEUE
+       do
+               MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
+       done
+       # XXX: Hard-coded batch option!
+       $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
+       RETURN=$?
+       if [ "$RETURN" != "0" ]; then
+               echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
+       else
+               for UTRACKNUM in $TRACKQUEUE
+               do
+                       echo normalizetrack-$UTRACKNUM >> status
+               done
+       fi
+       )
+}
+
 # do_batch_normalize
 # variables used:
 # NORMALIZER, NORMALIZEROPTS
@@ -527,7 +668,7 @@ do_normalize ()
 # Deduces the outfile from environment variables
 # Creates directory if necessary
 # variables used:
-# TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, OUTPUTDIR
+# TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
 do_move ()
 {
        for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
@@ -542,16 +683,24 @@ do_move ()
                ALBUMFILE=$(mungefilename "$DALBUM")
                ARTISTFILE=$(mungefilename "$TRACKARTIST")
                TRACKFILE=$(mungefilename "$TRACKNAME")
-               GENRE=$(echo $CDGENRE | tr "[:upper:]" "[:lower:]")
-               # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE, TRACKFILE, and TRACKNUM.
+               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
+               # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
+               # TRACKFILE, and TRACKNUM.
                if [ "$VARIOUSARTISTS" = "y" ]; then
                        OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
                        else
                        OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
                fi
-
-               TRACKNUM=${UTRACKNUM}
-       
                # 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
@@ -574,7 +723,7 @@ do_playlist ()
                for LASTTRACK in $TRACKQUEUE; do :; done
                ALBUMFILE=$(mungefilename "$DALBUM")
                ARTISTFILE=$(mungefilename "$DARTIST")
-               GENRE=$(echo $CDGENRE | tr "[:upper:]" "[:lower:]")
+               GENRE=$(mungegenre "$GENRE")
                if [ "$VARIOUSARTISTS" = "y" ] ; then
                        PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
                else
@@ -583,49 +732,71 @@ 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 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
-                               read ERASEPLAYLIST
+                               while [ "$DONE" != "y" ]; do
+                                       read ERASEPLAYLIST
+                                       case $ERASEPLAYLIST in
+                                               e|E|a|A|k|K) DONE=y ;;
+                                               *) ;;
+                                       esac
+                               done
                        else
-                               echo y >&2
-                               ERASEPLAYLIST=y
+                               echo e >&2
+                               ERASEPLAYLIST=e
                        fi
-                       [ "$ERASEPLAYLIST" != "n" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE"
+                       # Once we erase the playlist, we use append to create the new one.
+                       [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
+               else
+                       # The playlist does not exist, so we can safelly use append to create the new list
+                       ERASEPLAYLIST=a
                fi
-               touch "$OUTPUTDIR/$PLAYLISTFILE"
-               for UTRACKNUM in $TRACKQUEUE
-               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:\])
-                       splitvarious
-                       TRACKFILE=$(mungefilename "$TRACKNAME")
-                       ARTISTFILE=$(mungefilename "$TRACKARTIST")
-                       TRACKNUM=${UTRACKNUM}
-                       if [ "$VARIOUSARTISTS" = "y" ]; then
-                               OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
-                       else
-                               OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
-                       fi
-                       if [ "$VARIOUSARTISTS" = "y" ]; then
-                               if [ "$VAPLAYLISTDATAPREFIX" ] ; then
-                                       echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
+               if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
+                       touch "$OUTPUTDIR/$PLAYLISTFILE"
+                       for UTRACKNUM in $TRACKQUEUE
+                       do
+                               # Shares some code with do_move since the filenames have to match
+                               CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
+                               TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
+                               splitvarious
+                               TRACKFILE=$(mungefilename "$TRACKNAME")
+                               ARTISTFILE=$(mungefilename "$TRACKARTIST")
+                               # 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
-                                       relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
+                                       TRACKNUM=${UTRACKNUM}
                                fi
-                       else
-                               if [ "$PLAYLISTDATAPREFIX" ]; then
-                                       echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
+                               if [ "$VARIOUSARTISTS" = "y" ]; then
+                                       OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
                                else
-                                       relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
+                                       OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
                                fi
-                       fi
-               done
+                               if [ "$VARIOUSARTISTS" = "y" ]; then
+                                       if [ "$VAPLAYLISTDATAPREFIX" ] ; then
+                                               echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
+                                       else
+                                               relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
+                                       fi
+                               else
+                                       if [ "$PLAYLISTDATAPREFIX" ]; then
+                                               echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
+                                       else
+                                               relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
+                                       fi
+                               fi
+                       done
+               fi
                ## this will convert the playlist to have CRLF line-endings, if specified
                ## (some hardware players insist on CRLF endings)
                if [ "$DOSPLAYLIST" = "y" ]; then
                        awk '{substr("\r",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
-                       rm "$OUTPUTDIR/$PLAYLISTFILE" && mv "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
+#                      mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
+                       cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
                fi
                echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
        done
@@ -636,14 +807,19 @@ do_playlist ()
 do_discid ()
 {
        # Query the CD to get the track info, unless the user specified -C
+       # or we are using some actions which do not need the CDDB data at all
+       #if [ ! X"$EXPACTIONS" = "X" ]; then
+       #       :
+       #elif [ -z "$DISCID" ]; then
        if [ -z "$DISCID" ]; then
-               echo -n "Getting CD track info... "
+               vecho -n "Getting CD track info... "
                TRACKINFO=$($CDDISCID $CDROM)
                # 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
                fi
+               WEHAVEACD=y
        else
                TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
        fi
@@ -653,12 +829,35 @@ do_discid ()
        # it later.
 
        # get the number of digits to pad TRACKNUM with - we'll use this later
+       # a CD can only hold 99 tracks, but since we support a feature for starting
+       # numbering the tracks from a given number, we might need to set it as a
+       # variable for the user to define... or obtain it somehow.
        if [ "$PADTRACKS" = "y" ] ; then
                TRACKNUMPADDING=2
        fi
 
-       TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
+       ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
        if [ -z "$TRACKQUEUE" ]; then
+               if [ ! "$STRIPDATATRACKS" = "y" ]; then
+                       case "$CDROMREADERSYNTAX" in
+                               cdparanoia|debug)
+                                       if [ "$WEHAVEACD" = "y" ]; then
+                                               vecho "Querying the CD for audio tracks..."
+                                               TRACKS=$( $CDROMREADER -d $CDROM -Q --verbose 2>&1 | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 |  awk '{print $1}' | tr -d "." | tr '\n' ' ' )
+                                               CDPARANOIAAUDIOTRACKS="$TRACKS"
+                                       else
+                                               if [ -f "$ABCDETEMPDIR/status" ] && checkstatus cdparanoia-audio-tracks ; then
+                                                       TRACKS=$( cat $ABCDETEMPDIR/cdparanoia-audio-tracks )
+                                               else
+                                                       TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
+                                               fi
+                                       fi
+                                       ;;
+                               *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
+                       esac
+               else
+                       TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
+               fi
                echo -n "Grabbing entire CD - tracks: "
                if [ ! "$PADTRACKS" = "y" ] ; then
                        TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
@@ -672,6 +871,7 @@ do_discid ()
                done
                echo $TRACKQUEUE
        else
+               TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
                # User-supplied track queue.
                # Weed out non-numbers, whitespace, then sort and weed out duplicates
                TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
@@ -696,7 +896,6 @@ do_discid ()
        # We have the discid, create a temp directory after it to store all the temp
        # info
 
-       ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
        if [ -e "$ABCDETEMPDIR" ]; then
                echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
                # It already exists, see if it's a directory
@@ -764,37 +963,16 @@ do_discid ()
                cat /dev/null > "$ABCDETEMPDIR/status"
        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"
+               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_cddbparse
@@ -808,7 +986,7 @@ 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 [ ! "$ONETRACK" = "y" ];then
+       if [ ! "$ONETRACK" = "y" ]; then
                for TRACK in $(f_seq_row 1 $TRACKS)
                do
                        echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
@@ -828,36 +1006,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
-                               #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
+                               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
+                       CDDBLOCALSUCCESS="y"
+               else
+                       CDDBLOCALSUCCESS="n"
                fi
        fi
 }
@@ -975,17 +1152,17 @@ do_cddbread ()
                        403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
                        503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
                        esac
-                       $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.1"
+                       $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
                        # List out disc title/author and contents of template
                        echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
                        UNKNOWNDISK=y
                        for TRACK in $(f_seq_row 1 $TRACKS)
                        do
-                               echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
+                               echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
                        done
                        echo >> "$ABCDETEMPDIR/cddbchoices"
-                       echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
-                       echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
+                       echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
+                       echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
                        ;;
                210|211)
                        # Multiple exact, (possibly multiple) inexact matches
@@ -998,7 +1175,7 @@ do_cddbread ()
                        else
                                echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
                        fi
-                       #echo -n "Retrieving multiple matches... "
+                       vecho -n "Retrieving multiple matches... "
                        grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
                        read DISCINFO # eat top line
                        while read DISCINFO
@@ -1016,7 +1193,7 @@ do_cddbread ()
                                done
                                echo >> "$ABCDETEMPDIR/cddbchoices"
                        done )
-                       #echo "done."
+                       vecho "done."
                        CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
                        ;;
                999)
@@ -1087,24 +1264,31 @@ do_cddbedit ()
                                        fi
                                        
                                        # I'll take CDDB read #3 for $400, Alex
-                                       echo -n "Which entry would you like abcde to use? [1-$CDDBCHOICES]: " >&2
+                                       echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
                                        read CDDBCHOICE
+                                       [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
                                        # Make sure we get a valid choice
                                        CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
-                                       while [ $CDCHOICENUM -lt 1 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
+                                       while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
                                                echo "Invalid selection. Please choose a number between 1 and $CDDBCHOICES." >&2
-                                               echo -n "Selection [1-$CDDBCHOICES]: " >&2
+                                               echo -n "Selection [0-$CDDBCHOICES]: " >&2
                                                read CDDBCHOICE
                                                CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
                                        done
-                                       echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
-                                       do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
+                                       if [ "$CDCHOICENUM" = "0" ]; then
+                                               vecho "Creating empty CDDB template..."
+                                               UNKNOWNDISK=y
+                                               $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
+                                               do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
+                                       fi
                                        echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
                                fi
                        fi
                else
                        # We need some code to show the selected option when local repository is selected and we have found a match
-                       echo "Using cached CDDB match..."
+                       vecho "Using cached CDDB match..." >&2
                        # Display the $ABCDETEMPDIR/cddbchoices file created above
                        # Pick a pager so that if the tracks overflow the screen the user can still view everything
                        if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
@@ -1113,6 +1297,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"
@@ -1151,7 +1339,7 @@ do_cddbedit ()
                exit 1
        fi
        CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
-       echo -n "Edit selected CDDB data? [y/n] ("
+       echo -n "Edit selected CDDB data? [y/n] (" >&2
        if [ "$INTERACTIVE" = "y" ]; then
                if [ "$UNKNOWNDISK" = "y" ]; then
                        echo -n "y): " >&2
@@ -1215,7 +1403,7 @@ do_cddbedit ()
                # Set a default
                DEFAULTSTYLE=1
                # Need NUMTRACKS before cddb-tool will return it:
-               NUMTRACKS=$(grep -E '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
+               NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
                if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
                        # More than 1/2 tracks contain a "/", so guess forward
                        DEFAULTSTYLE=1
@@ -1252,7 +1440,7 @@ do_cddbedit ()
                if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
                        VARIOUSARTISTSTYLE=$DEFAULTSTYLE
                fi
-               echo "Selected: $VARIOUSARTISTSTYLE"
+               vecho "Selected: $VARIOUSARTISTSTYLE"
                case "$VARIOUSARTISTSTYLE" in
                1) # Artist / Title
                        VARIOUSARTISTSTYLE=forward
@@ -1354,7 +1542,7 @@ do_cdread_one ()
                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
@@ -1365,9 +1553,12 @@ do_cdread_one ()
                debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
        esac
        RETURN=$?
-       if [ "$RETURN" != "0" ]; then
+       if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; then
                # Thank goodness errors is only machine-parseable up to the
                # first colon, otherwise this woulda sucked
+               if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
+                       RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
+               fi
                 echo "readtrack-$FIRSTTRACKNUMBER: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
                return $RETURN
        else
@@ -1376,21 +1567,50 @@ do_cdread_one ()
 }
 
 # 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
+               case "$CDROMREADERSYNTAX" in
+                       cdparanoia) UTRACKNUM="1-" ;;
+                       cdda2wav) UTRACKNUM="1+$LASTRACK" ;;
+                       *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
+                          exit 1 ;;
+               esac
+       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
        else
                echo "Grabbing track $UTRACKNUM..." >&2
        fi
+       if [ "$USEPIPES" = "y" ]; then
+               TEMPARG="PIPE_$CDROMREADERSYNTAX"
+               FILEARG=${!TEMPARG}
+               REDIR=""
+       else
+               case "$CDROMREADERSYNTAX" in
+                       dagrab)
+                               FILEARG="-f $WAVDATA"
+                               ;;
+                       *)
+                               FILEARG=$WAVDATA
+                               ;;
+               esac
+               REDIR=">&2"
+       fi
        case "$CDROMREADERSYNTAX" in
                cdparanoia) nice $READNICE $CDROMREADER -d $CDROM $UTRACKNUM "$WAVDATA" >&2 ;;
                cdda2wav)
@@ -1414,7 +1634,7 @@ do_cdread ()
                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
@@ -1425,16 +1645,29 @@ do_cdread ()
                debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
        esac
        RETURN=$?
-       if [ "$RETURN" != "0" ]; then
+       if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; 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"
+               fi
        fi
 }
 
+# do_cdspeed
+# No values accepted, only uses env variables
 do_cdspeed () 
 {
        if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
@@ -1454,7 +1687,31 @@ if [ x"$EXTRAVERBOSE" != "x" ]; then
 fi
 }
 
+# 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 ()
+{
+:
+}
+
+###############################################################################
+# End of functions
+#
 # Start of execution
+###############################################################################
 
 # Builtin defaults
 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
@@ -1470,6 +1727,8 @@ MP3ENCODERSYNTAX=default
 OGGENCODERSYNTAX=default
 FLACENCODERSYNTAX=default
 SPEEXENCODERSYNTAX=default
+MPPENCODERSYNTAX=default
+NORMALIZERSYNTAX=default
 
 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
@@ -1489,7 +1748,6 @@ READNICE=10
 DISTMP3NICE=10
 VARIOUSARTISTS=n
 VARIOUSARTISTSTYLE=forward
-NORMALIZERSYNTAX=default
 KEEPWAVS=n
 PADTRACKS=n
 CDDBCOPYLOCAL="n"
@@ -1515,6 +1773,8 @@ OGGENC=oggenc
 FLAC=flac
 # speex
 SPEEXENC=speexenc
+# mpp (Musepack)
+MPPENC=mppenc
 
 ID3=id3
 ID3V2=id3v2
@@ -1529,8 +1789,9 @@ MD5SUM=md5sum
 DISTMP3=distmp3
 VORBISCOMMENT=vorbiscomment
 METAFLAC=metaflac
-NORMALIZE=normalize
+NORMALIZE=normalize-audio
 CDSPEED=eject
+VORBISGAIN=vorbisgain
 
 # Options for programs called from abcde
 # mp3
@@ -1547,6 +1808,8 @@ OGGENCOPTS=
 FLACOPTS=
 # speex
 SPEEXENCOPTS=
+# mpc
+MPPENCOPTS=
 
 ID3OPTS=
 ID3V2OPTS=
@@ -1567,19 +1830,6 @@ 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:\]
-}
-
-# Pre-read execution:
-pre_read ()
-{
-:
-}
-
 # 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
@@ -1621,7 +1871,7 @@ 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
@@ -1651,33 +1901,38 @@ fi
 
 # Parse command line options
 #while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:t:T:vVx opt ; do
-while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:vVx opt ; do
+while getopts 1a:A:bc:C:d:Dhj:klLnNo:pPr:Rs:S:t:T:vVxw:W: 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.}" ;;
                d) CDROM="$OPTARG" ;;
                D) set -x ;;
                h) usage; exit ;;
-               f) FORCECDDBUSELOCAL=y ;;
+#              f) FORCECDDBUSELOCAL=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 ;;
                o) OUTPUTTYPE="$OPTARG" ;;
-               p) PADTRACKS="y" ;;
+               p) PADTRACKS=y ;;
+               P) USEPIPES=y ;;
                r) REMOTEHOSTS="$OPTARG" ;;
+               R) REPLAYGAIN=y ;;
                s) STARTTRACKNUMBER="$OPTARG" ;;
                S) CDSPEEDVALUE="$OPTARG" ;;
-               t) PREPROCESSFORMATS="$OPTARG"
-                  PREPROCESS=y ;;
-               T) POSTPROCESSFORMATS="$OPTARG" ;;
+#              t) PREPROCESSFORMATS="$OPTARG"
+#                 PREPROCESS=y ;;
+#              T) POSTPROCESSFORMATS="$OPTARG" ;;
+               t) STARTTRACKNUMBER="$OPTARG" ;;
+               T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
                v) 
                   echo "This is abcde v$VERSION."
                   echo "Usage: abcde [options] [tracks]"
@@ -1686,15 +1941,29 @@ while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:vVx opt ; do
                   ;;
                V) EXTRAVERBOSE="y" ;;
                x) EJECTCD="y" ;;
+               w) COMMENT="$OPTARG" ;;
+               W) STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}" ;;
                ?) usage; exit ;;
        esac
 done
 
 shift $(($OPTIND - 1))
 
-if [ "$ONETRACK" = "y" ] ; then 
+# 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|cddafs|debug) echo "abcde error: ONETRACK reading is not suported with "$CDROMREADERSYNTAX" yet"
+                                        exit 1 ;;
+       esac
+       if [ "$BATCH" = "y" ]; then
+               echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
+               BATCH=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..."
+               vecho "abcde warning: ONETRACK mode selected, grabbing all tracks..."
        fi
 else
        while [ $# -gt 0 ]; do
@@ -1707,11 +1976,44 @@ else
                        NEWTRACKS=$(f_seq_line $RSTART $REND)
                fi
                TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
-       
                shift
        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
+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
+
+# Sanity checks:
+
 # At this point a CDROM has to be defined, so we check it exists.
 if [ "$CDROM" != "" ] ; then 
        if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
@@ -1731,14 +2033,23 @@ else
        exit 1
 fi
 
-# Decide if we can continue. TO_REMOVE as soon as we find out about dagrab
-if [ "$ONETRACK" = "y" ]; then
-       case "$CDROMREADERSYNTAX" in
-               dagrab|debug) echo "abcde error: ONETRACK reading is not suported with "$CDROMREADERSYNTAX" yet"
-                             exit 1 ;;
-       esac
-       if [ "$BATCH" = "y" ]; then
-               echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
+# USEPIPES is not compatible with:
+# - multiple outputs
+# - normalize
+# - anything else?
+if [ "$USEPIPES" = "y" ]; then
+       if [ $(echo $OUTPUTTYPE | tr , \  | wc -w ) -gt 1 ]; then
+               echo "abcde error: Unix pipes not compatible with multiple outputs"
+               exit 1
+       fi
+       if [ "$DONORMALIZE" = "y" ]; then
+               echo "abcde error: Unix pipes not compatible with normalizer"
+               # FIXME # Do we need to exit or shall we just disable the mode?
+               exit 1
+       fi
+       if [ "$DOENCODE" = "n" ]; then
+               vecho "Disabling Unix pipes since we are not encoding!"
+               USEPIPES=n
        fi
 fi
 
@@ -1770,22 +2081,24 @@ case "$NORMALIZERSYNTAX" in
                ;;
 esac
 
-# If nothing has been specified, use oggenc for oggs and lame for mp3s and flac for flacs and speexenc for speex
+# 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
+                     [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
+                     [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
                        ;;
                mp3)  [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
-                     echo $ACTIONS | grep tag > /dev/null 2>&1 && NEEDTAGGER=y
+                     [ "$DOTAG" = "y" ] && NEEDTAGGER=y
                        ;;
                flac) [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
-                     echo $ACTIONS | grep tag > /dev/null 2>&1 && NEEDMETAFLAC=y
+                     [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
                        ;;
                spx) [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc ;;
+               mpc) [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc ;;
                *) echo "abcde error: Invalid OUTPUTTYPE defined" >&2
                   exit 1
                   ;;
@@ -1841,6 +2154,12 @@ case "$SPEEXENCODERSYNTAX" in
                SPEEXENCODER="$SPEEXENC"
                ;;
 esac
+case "$MPPENCODERSYNTAX" in
+       mppenc)
+               MPPENCODEROPTS="$MPPENCOPTS"
+               MPPENCODER="$MPPENC"
+               ;;
+esac
 
 # and which tagger
 
@@ -1866,9 +2185,9 @@ 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
+[ "$DONORMALIZE" = "y" ] && NEEDNORMALIZER=y
+[ "$EJECTCD" = "y" ] && NEEDEJECT=y
+[ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ] && NEEDHTTPGET=y
 
 if [ X"$CDSPEEDVALUE" != "X" ]; then
        case "$CDROMREADERSYNTAX" in
@@ -1880,11 +2199,12 @@ fi
 
 # Make sure a buncha things exist
 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
-       $OGGENCODER $FLACENCODER $SPEEXENCODER ${NEEDHTTPGET+$HTTPGET} \
-       ${NEEDDISTMP3+$DISTMP3} ${NEEDCOMMENTER+$VORBISCOMMENT} \
-       ${NEEDMETAFLAC+$METAFLAC} ${NEEDNORMALIZER+$NORMALIZER} \
-       ${NEEDEJECT+$EJECT} ${NEEDDISKTOOL+disktool} \
-       ${NEEDCDSPEED+$CDSPEED}
+       $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
+       ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
+       ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
+       ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
+       ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
+       ${NEEDVORBISGAIN+$VORBISGAIN}
 do
        # Cut off the command-line options we just added in
        X=$(echo $X | cut -d' ' -f2)
@@ -1901,9 +2221,9 @@ CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
 HTTPGET="$HTTPGET $HTTPGETOPTS"
 
-# One thousand seven hundred lines in, we can start doing stuff with things
-
-# List of valid actions: cddb,playlist,read,normalize,encode,tag,move
+# Here it used to say:
+# One thousand lines in, we can start doing stuff with things
+# Well, right now we are at line 2157 ;)
 
 # Export needed things so they can be read in this subshell
 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
@@ -1924,10 +2244,14 @@ if [ "$DOCDDB" = "y" ]; then
        if [ $CDDBUSELOCAL = "y" ]; then
                do_localcddb
        fi
-       if [ ! "$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
 
@@ -1946,7 +2270,8 @@ 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
@@ -1965,13 +2290,23 @@ if [ "$ONETRACK" = "y" ]; then
        for UTRACKNUM in $TRACKQUEUE; do :;done
        if checkstatus readtrack-$FIRSTTRACK; then :; else
                do_cdread_one $UTRACKNUM $FIRSTTRACK
+               # FIXME # Allow ranges of tracks to be encoded in one track
+               # FIXME # do_cdread onetrack $FIRSTTRACK $UTRACKNUM
+               # Until we have it we must use:
+               #do_cdread onetrack $FIRSTTRACK $UTRACKNUM
        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
+                                       do_cdread $UTRACKNUM | do_encode $UTRACKNUM %local0%
+                               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
@@ -2037,6 +2372,29 @@ fi
 
 ) | (
 
+## Do we need to pre-process 
+#if [ x"$PREPROCESS" = "x" ] ; then
+#      cat
+#else
+#      for PRETRACKNUM in $TRACKQUEUE
+#      do
+#              read GOAHEAD
+#              if [ "$GOAHEAD" = "NO" ]; then break; fi
+#              PREPROCEED=
+#              until [ $PREPROCEED ]
+#              do
+#                      if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
+#                      # all locations are working, wait and try again later
+#                      if [ ! $PREPROCEED ]; then sleep 3; fi
+#              done
+#              ( do_preprocess $PRETRACKNUM 
+#              echo "NEXTTRACK"
+#              ) &
+#      done
+#fi
+#
+#) | (
+
 # In batch mode, we want all tracks to be read first.
 if [ "$BATCH" = "y" ]; then
        read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
@@ -2078,7 +2436,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
@@ -2127,7 +2485,7 @@ do
 #                      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:\])
+                       TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
                        splitvarious
                fi
        fi
@@ -2211,3 +2569,6 @@ else
 fi
 )
 exit 0
+
+# b:is_bash
+# vim:tabstop=4