r121@frost: data | 2005-08-19 00:00:16 +0300
[abcde.git] / abcde
1 #!/bin/sh
2 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
3 # Copyright (c) 2003-2005 Jesus Climent <jesus.climent@hispalinux.es>
4 # This code is hereby licensed for public consumption under either the
5 # GNU GPL v2 or greater, or Larry Wall's Artistic license - your choice.
6 #
7 # You should have received a copy of the GNU General Public License
8 # along with this program; if not, write to the Free Software
9 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
10 #
11 # Copyright for this work is to expire January 1, 2010, after which it
12 # shall be public domain.
13
14 VERSION="2.3.99"
15
16 usage ()
17 {
18 echo "This is abcde v$VERSION."
19 echo "Usage: abcde [options] [tracks]"
20 echo "Options:"
21 echo "-1     Encode the whole CD in a single file"
22 echo "-a <action1[,action2]...>"
23 echo "       Actions to perform (cddb,read,normalize,encode,tag,move,playlist,clean)"
24 #echo "-A     Experimental actions (retag, transcode)"
25 echo "-b     Batch mode: enable album normalization and nogap encoding"
26 echo "-c <file>"
27 echo "       Specify a configuration file (overrides system and user config files)"
28 echo "-C <discid#>"
29 echo "       Specify discid to resume from (only needed if you no longer have the cd)"
30 echo "-d <device>"
31 echo "       Specify CDROM device to grab"
32 echo "-D     Debugging mode (equivalent to sh -x abcde)"
33 echo "-e     Erase encoded track information from status file"
34 echo "-h     This help information"
35 #echo "-i    Tag files while encoding, when possible (local only) -NWY-"
36 echo "-j <#> Number of encoder processes to run at once (localhost)"
37 echo "-k     Keep the wav tracks for later use"
38 echo "-l     Use low disk space algorithm"
39 echo "-L     Use local CDDB storage directory"
40 echo "-n     No lookup. Don't query CDDB, just create and use template"
41 echo "-N     Noninteractive. Never prompt for anything"
42 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
43 echo "-M     Create a CUE file"
44 echo "-o <type1[,type2]...>"
45 echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc). Defaults to vorbis"
46 echo "-p     Pad track numbers with 0's (if less than 10 tracks)"
47 echo "-P     Use UNIX pipes to read+encode without wav files"
48 echo "-r <host1[,host2]...>"
49 echo "       Also encode on these remote hosts"
50 echo "-R     Add replaygain values to the tag info (only for vorbis,flac)"
51 echo "-s <field>"
52 echo "       Show dielfs from the CDDB info (year,genre)"
53 echo "-S <#> Set the CD speed"
54 #echo "-t    File types to preprocess (wav)"
55 #echo "-T    Set postprocessing options"
56 echo "-t <#> Start the track numbering at a given number"
57 echo "-T <#> Same as -t but modifies tag numbering"
58 echo "-v     Show version number and exit"
59 echo "-V     Be a bit more verbose about what is happening behind the scenes"
60 echo "-x     Eject CD after all tracks are read"
61 echo "-w <comment>"
62 echo "       Add a comment to the CD tracks"
63 echo "-W <#> Contatenate CDs: -T #01 -w \"CD #\"" 
64 echo ""
65 echo "Tracks is a space-delimited list of tracks to grab."
66 echo "Ranges specified with hyphens are allowed (i.e., 1-5)."
67 echo ""
68 #echo "Double hyphens are used to concatenate tracks"
69 }
70
71 # Funtions to replace the need of seq, which is too distribution dependant.
72 f_seq_row ()
73 {
74         i=$1
75         while [ $i -ne `expr $2 + 1` ]
76         do
77                 echo $i
78                 i=`expr $i + 1`
79         done
80 }
81
82 f_seq_line ()
83 {
84         i=$1
85         while [ $i -ne `expr $2 + 1` ]
86         do
87                 printf $i" "
88                 i=`expr $i + 1`
89         done
90         echo
91 }
92
93 # Functions to replace the need of awk {print $1} and {print $NF}
94 get_first()
95 {
96 if [ X"$1" = "X" ]; then
97         for first in `cat`; do
98                 break
99         done
100 else
101         first=$1
102 fi
103 echo $first
104 }
105
106 get_last()
107 {
108 if [ X"$1" = "X" ]; then
109         for stdin in `cat`; do
110                 last=$stdin
111         done
112 else
113         for last in $@ ; do :; done
114 fi
115 echo $last
116 }
117
118 # checkstatus [blurb]
119 # Returns "0" if the blurb was found, returns 1 if it wasn't
120 # Puts the blurb content, if available, on stdout.
121 # Otherwise, returns "".
122 checkstatus ()
123 {
124         # Take the last line in the status file if there's multiple matches
125         PATTERN="^$1(=.*)?$"
126         BLURB=$(egrep $PATTERN "$ABCDETEMPDIR/status" | tail -n 1)
127
128         if [ -z "$BLURB" ]; then
129                 # No matches found
130                 return 1
131         else
132                 # Matches found
133                 # See if there's a = in it
134                 if [ "$(echo $BLURB | grep -c =)" != "0" ]; then
135                         echo "$(echo $BLURB | cut -f2- -d=)"
136                 fi
137                 return 0
138         fi
139 }
140
141 # checkerrors [blurb]
142 # Returns "0" if the blurb was found (meaning there was an error),
143 # returns 1 if it wasn't (yes this is a little backwards).
144 # Does not print the blurb on stdout.
145 # Otherwise, returns "".
146 checkerrors ()
147 {
148         if [ -e "$ABCDETEMPDIR/errors" ]; then :; else
149                 return 1
150         fi
151         # Take the last line in the status file if there's multiple matches
152         PATTERN="^$1(:.*)?$"
153         BLURB="$(egrep $PATTERN "$ABCDETEMPDIR/errors" | tail -n 1)"
154
155         if [ -z "$BLURB" ]; then
156                 # negative, we did not have a negative...
157                 return 1
158         else
159                 # affirmative, we had a negative...
160                 return 0
161         fi
162 }
163
164 # page [file]
165 # Finds the right pager in the system to display a file
166 page ()
167 {
168         PAGEFILE="$1"
169         # Use the debian sensible-pager wrapper to pick the pager
170         # user has requested via their $PAGER environment variable
171         if [ -x "/usr/bin/sensible-pager" ]; then
172                 /usr/bin/sensible-pager "$PAGEFILE"
173         elif [ -x "$PAGER" ]; then
174                 # That failed, try to load the preferred editor, starting
175                 # with their PAGER variable
176                 $PAGER "$PAGEFILE"
177                 # If that fails, check for less
178         elif [ -x /usr/bin/less ]; then
179                 /usr/bin/less -f "$PAGEFILE"
180                 # more should be on all UNIX systems
181         elif [ -x /bin/more ]; then
182                 /bin/more "$PAGEFILE"
183         else
184                 # No bananas, just cat the thing
185                 cat "$PAGEFILE" >&2
186         fi
187 }
188
189 # run_command [blurb] [command...]
190 # Runs a command, silently if necessary, and updates the status file
191 run_command ()
192 {
193         BLURB="$1"
194         shift
195         # See if this is supposed to be silent
196         if [ "$(checkstatus encode-output)" = "loud" ]; then
197                 "$@" >&2
198                 RETURN=$?
199         else
200                 # Special case for SMP, since
201                 # encoder output is never displayed, don't mute echos
202                 if [ -z "$BLURB" -a "$MAXPROCS" != "1" ]; then
203                         "$@" >&2
204                         RETURN=$?
205                 else
206                         "$@" >/dev/null 2>&1
207                         RETURN=$?
208                 fi
209         fi
210         case "$1" in
211         normalize)
212                 if [ "$RETURN" = "2" ]; then
213                         # File was already normalized.
214                         RETURN=0
215                 fi
216                 ;;
217         esac
218         if [ "$RETURN" != "0" ]; then
219                 # Put an error in the errors file. For various reasons we
220                 # can't capture a copy of the program's output but we can
221                 # log what we attempted to execute and the error code
222                 # returned by the program.
223                 if [ "$BLURB" ]; then
224                         TWEAK="$BLURB: "
225                 fi
226                 echo "${TWEAK}returned code $RETURN: $@" >> "$ABCDETEMPDIR/errors"
227                 return $RETURN # Do not pass go, do not update the status file
228         fi
229         if [ "$BLURB" ]; then
230                 echo $BLURB >> "$ABCDETEMPDIR/status"
231         fi
232 }
233
234 # relpath() and slash() are Copyright (c) 1999 Stuart Ballard and
235 # distributed under the terms of the GNU GPL v2 or later, at your option
236
237 # Function to determine if a word contains a slash.
238 slash ()
239 {
240         case "$1" in
241         */*) return 0;;
242         *) return 1;;
243         esac
244 }
245
246 # Function to give the relative path from one file to another.
247 # Usage: relpath fromfile tofile
248 # eg relpath music/Artist/Album.m3u music/Artist/Album/Song.mp3
249 # (the result would be Album/Song.mp3)
250 # Output is relative path to $2 from $1 on stdout
251
252 # This code has the following restrictions:
253 # Multiple ////s are not collapsed into single /s, with strange effects.
254 # Absolute paths and ../s are handled wrong in FR (but they work in TO)
255 # If FR is a directory it must have a trailing /
256
257 relpath ()
258 {
259         FR="$1"
260         TO="$2"
261
262         case "$TO" in
263         /*) ;; # No processing is needed for absolute paths
264         *)
265                 # Loop through common prefixes, ignoring them.
266                 while slash "$FR" && [ "$(echo "$FR" | cut -d/ -f1)" = "$(echo "$TO" | cut -d/ -f1)" ]
267                 do
268                         FR="$(echo "$FR" | cut -d/ -f2-)"
269                         TO="$(echo "$TO" | cut -d/ -f2-)"
270                 done
271                 # Loop through directory portions left in FR, adding appropriate ../s.
272                 while slash "$FR"
273                 do
274                         FR="$(echo "$FR" | cut -d/ -f2-)"
275                         TO="../$TO"
276                 done
277                 ;;
278         esac
279
280         echo $TO
281 }
282
283 # This code splits the a Various Artist track name from one of the following
284 # forms:
285 #
286 #  forward:        Artist / Track
287 #  forward-dash:   Artist - Track
288 #  reverse:        Track / Artist
289 #  reverse-dash:   Track - Artist
290 #  colon:          Artist: Track
291 #  trailing-paren: Artist (Track)
292 #
293 # variables used:
294 # VARIOUSARTISTS, VARIOUSARTISTSTYLE, TRACKNAME, TRACKARTIST
295 splitvarious ()
296 {
297         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
298                 case "$VARIOUSARTISTSTYLE" in
299                 forward)
300                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's- / -~-g')
301                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f1 -d~)
302                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f2 -d~)
303                         ;;
304                 forward-dash)
305                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's, - ,~,g')
306                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f1 -d~)
307                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f2 -d~)
308                         ;;
309                 reverse)
310                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's- / -~-g')
311                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f2 -d~)
312                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f1 -d~)
313                         ;;
314                 reverse-dash)
315                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's, - ,~,g')
316                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f2 -d~)
317                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f1 -d~)
318                         ;;
319                 colon)
320                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's-: -~-g')
321                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f1 -d~)
322                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f2 -d~)
323                         ;;
324                 trailing-paren)
325                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's,^\(.*\) (\(.*\)),\1~\2,')
326                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f2 -d~)
327                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f1 -d~)
328                         ;;
329                 esac
330         elif [ "$ONETRACK" = "y" ]; then
331                 TRACKARTIST="Various"
332         else
333                 TRACKARTIST="$DARTIST"
334         fi
335 }
336
337 do_getgenreid () {
338 local genre=$(echo "${@}" | tr '[A-Z]' '[a-z]')
339 local id=""
340         case ${genre} in
341                 "blues")                 id=0 ;;
342                 "classic rock")          id=1 ;;
343                 "country")               id=2 ;;
344                 "dance")                 id=3 ;;
345                 "disco")                 id=4 ;;
346                 "funk")                  id=5 ;;
347                 "grunge")                id=6 ;;
348                 "hip-hop")               id=7 ;;
349                 "jazz")                  id=8 ;;
350                 "metal")                 id=9 ;;
351                 "new age")               id=10 ;;
352                 "oldies")                id=11 ;;
353                 "other")                 id=12 ;;
354                 "pop")                   id=13 ;;
355                 "r&b")                   id=14 ;;
356                 "rap")                   id=15 ;;
357                 "reggae")                id=16 ;;
358                 "rock")                  id=17 ;;
359                 "techno")                id=18 ;;
360                 "industrial")            id=19 ;;
361                 "alternative")           id=20 ;;
362                 "ska")                   id=21 ;;
363                 "death metal")           id=22 ;;
364                 "pranks")                id=23 ;;
365                 "soundtrack")            id=24 ;;
366                 "euro-techno")           id=25 ;;
367                 "ambient")               id=26 ;;
368                 "trip-hop")              id=27 ;;
369                 "vocal")                 id=28 ;;
370                 "jazz+funk")             id=29 ;;
371                 "fusion")                id=30 ;;
372                 "trance")                id=31 ;;
373                 "classical")             id=32 ;;
374                 "instrumental")          id=33 ;;
375                 "acid")                  id=34 ;;
376                 "house")                 id=35 ;;
377                 "game")                  id=36 ;;
378                 "sound clip")            id=37 ;;
379                 "gospel")                id=38 ;;
380                 "noise")                 id=39 ;;
381                 "alt. rock")             id=40 ;;
382                 "bass")                  id=41 ;;
383                 "soul")                  id=42 ;;
384                 "punk")                  id=43 ;;
385                 "space")                 id=44 ;;
386                 "meditative")            id=45 ;;
387                 "instrum. pop")          id=46 ;;
388                 "instrum. rock")         id=47 ;;
389                 "ethnic")                id=48 ;;
390                 "gothic")                id=49 ;;
391                 "darkwave")              id=50 ;;
392                 "techno-indust.")        id=51 ;;
393                 "electronic")            id=52 ;;
394                 "pop-folk")              id=53 ;;
395                 "eurodance")             id=54 ;;
396                 "dream")                 id=55 ;;
397                 "southern rock")         id=56 ;;
398                 "comedy")                id=57 ;;
399                 "cult")                  id=58 ;;
400                 "gangsta")               id=59 ;;
401                 "top 40")                id=60 ;;
402                 "christian rap")         id=61 ;;
403                 "pop/funk")              id=62 ;;
404                 "jungle")                id=63 ;;
405                 "native american")       id=64 ;;
406                 "cabaret")               id=65 ;;
407                 "new wave")              id=66 ;;
408                 "psychadelic")           id=67 ;;
409                 "rave")                  id=68 ;;
410                 "showtunes")             id=69 ;;
411                 "trailer")               id=70 ;;
412                 "lo-fi")                 id=71 ;;
413                 "tribal")                id=72 ;;
414                 "acid punk")             id=73 ;;
415                 "acid jazz")             id=74 ;;
416                 "polka")                 id=75 ;;
417                 "retro")                 id=76 ;;
418                 "musical")               id=77 ;;
419                 "rock & roll")           id=78 ;;
420                 "hard rock")             id=79 ;;
421                 "folk")                  id=80 ;;
422                 "folk/rock")             id=81 ;;
423                 "national folk")         id=82 ;;
424                 "swing")                 id=83 ;;
425                 "fusion")                id=84 ;;
426                 "bebob")                 id=85 ;;
427                 "latin")                 id=86 ;;
428                 "revival")               id=87 ;;
429                 "celtic")                id=88 ;;
430                 "bluegrass")             id=89 ;;
431                 "avantgarde")            id=90 ;;
432                 "gothic rock")           id=91 ;;
433                 "progress. rock")        id=92 ;;
434                 "psychadel. rock")       id=93 ;;
435                 "symphonic rock")        id=94 ;;
436                 "slow rock")             id=95 ;;
437                 "big band")              id=96 ;;
438                 "chorus")                id=97 ;;
439                 "easy listening")        id=98 ;;
440                 "acoustic")              id=99 ;;
441                 "humour")                id=100 ;;
442                 "speech")                id=101 ;;
443                 "chanson")               id=102 ;;
444                 "opera")                 id=103 ;;
445                 "chamber music")         id=104 ;;
446                 "sonata")                id=105 ;;
447                 "symphony")              id=106 ;;
448                 "booty bass")            id=107 ;;
449                 "primus")                id=108 ;;
450                 "porn groove")           id=109 ;;
451                 "satire")                id=110 ;;
452                 "slow jam")              id=111 ;;
453                 "club")                  id=112 ;;
454                 "tango")                 id=113 ;;
455                 "samba")                 id=114 ;;
456                 "folklore")              id=115 ;;
457                 "ballad")                id=116 ;;
458                 "power ballad")          id=117 ;;
459                 "rhythmic soul")         id=118 ;;
460                 "freestyle")             id=119 ;;
461                 "duet")                  id=120 ;;
462                 "punk rock")             id=121 ;;
463                 "drum solo")             id=122 ;;
464                 "a capella")             id=123 ;;
465                 "euro-house")            id=124 ;;
466                 "dance hall")            id=125 ;;
467                 "goa")                   id=126 ;;
468                 "drum & bass")           id=127 ;;
469                 "club-house")            id=128 ;;
470                 "hardcore")              id=129 ;;
471                 "terror")                id=130 ;;
472                 "indie")                 id=131 ;;
473                 "britpop")               id=132 ;;
474                 "negerpunk")             id=133 ;;
475                 "polsk punk")            id=134 ;;
476                 "beat")                  id=135 ;;
477                 "christian gangsta rap") id=136 ;;
478                 "heavy metal")           id=137 ;;
479                 "black metal")           id=138 ;;
480                 "crossover")             id=139 ;;
481                 "contemporary christian")id=140 ;;
482                 "christian rock")        id=141 ;;
483                 "merengue")              id=142 ;;
484                 "salsa")                 id=143 ;;
485                 "thrash metal")          id=144 ;;
486                 "anime")                 id=145 ;;
487                 "jpop")                  id=146 ;;
488                 "synthpop")              id=147 ;;
489                 *)                       return 1 ;;
490         esac
491 echo ${id}
492 return 0
493 }
494
495 # do_tag [tracknumber]
496 # id3 tags a filename
497 # variables used:
498 # TRACKS, TRACKNAME, TRACKARTIST, TAGGER, TAGGEROPTS, VORBISCOMMENT, METAFLAC, 
499 # COMMENT, DALBUM, DARTIST, CDYEAR, CDGENRE (and temporarily) ID3TAGV
500 do_tag ()
501 {
502         COMMENTOUTPUT="$(eval echo ${COMMENT})"
503         run_command '' echo "Tagging track $1 of $TRACKS: $TRACKNAME..."
504         # If we want to start the tracks with a given number, we need to modify the
505         # TRACKNUM value before evaluation
506         if [ -n "$STARTTRACKNUMBER" -a -n "$STARTTRACKNUMBERTAG" ] ; then
507                 # Get the trackpadding from the current track
508                 CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
509                 TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
510         fi
511         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
512         do
513         case "$OUTPUT" in
514         mp3)
515                 # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
516                 GENREID=$(do_getgenreid "${CDGENRE}")
517
518                 # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
519                 run_command tagtrack-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
520                         -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
521                         -g "$GENREID" -T "${TRACKNUM:-$1/$TRACKS}" \
522                         "$ABCDETEMPDIR/track$1.$OUTPUT"
523                 ;;
524         vorbis|ogg)
525                 case "$OGGENCODERSYNTAX" in
526                         vorbize|oggenc)
527                                 # vorbiscomment can't do in-place modification, mv the file first
528                                 if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" ]; then
529                                         mv "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
530                                 fi
531                                 (
532                                 # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
533                                 echo ARTIST="$TRACKARTIST"
534                                 echo ALBUM="$DALBUM"
535                                 echo TITLE="$TRACKNAME"
536                                 if [ -n "$CDYEAR" ]; then
537                                         echo DATE="$CDYEAR"
538                                 fi
539                                 if [ -n "$CDGENRE" ]; then
540                                         echo GENRE="$CDGENRE"
541                                 fi      
542                                 echo TRACKNUMBER=${TRACKNUM:-$1}
543                                 echo CDDB=$CDDBDISCID
544                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
545                                         case "$COMMENTOUTPUT" in
546                                                 *=*) echo "$COMMENTOUTPUT";;
547                                                 *)   echo COMMENT="$COMMENTOUTPUT";;
548                                         esac    
549                                 fi
550                                 ) | run_command tagtrack-$1 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
551                                         "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
552                                 # Doublecheck that the commented file was created successfully before wiping the original
553                                 if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" ]; then
554                                         rm -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
555                                 else
556                                         mv "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
557                                 fi
558                                 ;;
559                 esac
560                 ;;
561         flac)
562                 (
563                 echo ARTIST="$TRACKARTIST"
564                 echo ALBUM="$DALBUM"
565                 echo TITLE="$TRACKNAME"
566                 if [ -n "$CDYEAR" ]; then
567                         echo DATE="$CDYEAR"
568                 fi
569                 if [ -n "$CDGENRE" ]; then
570                         echo GENRE="$CDGENRE"
571                 fi      
572                 echo TRACKNUMBER=${TRACKNUM:-$1}
573                 echo CDDB=$CDDBDISCID
574                 if [ "$(eval echo ${COMMENT})" != "" ]; then
575                         case "$COMMENTOUTPUT" in
576                                 *=*) echo "$COMMENTOUTPUT";;
577                                 *)   echo COMMENT="$COMMENTOUTPUT";;
578                         esac    
579                 fi
580                 ) | run_command tagtrack-$1 $METAFLAC $METAFLACOPTS --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
581                 ;;
582         spx)
583                 run_command tagtrack-$1 true
584                 ;;
585         mpc)
586                 run_command tagtrack-$1 true
587                 ;;
588         esac
589         done
590 }
591
592 # do_batch_encode
593 # variables used:
594 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
595 do_batch_encode ()
596 {
597         # The commands here don't go through run_command because they're never supposed to be silenced
598         echo "Batch encoding tracks: $TRACKQUEUE"
599         OUTPUT=$(echo $OUTPUTTYPE | grep "mp3" )
600         case "$OUTPUT" in
601         mp3)
602                 case "$MP3ENCODERSYNTAX" in
603                 lame)
604                         (
605                         cd "$ABCDETEMPDIR"
606                         TRACKFILES=
607                         for UTRACKNUM in $TRACKQUEUE
608                         do
609                                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
610                         done
611                         nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
612                         RETURN=$?
613                         if [ "$RETURN" != "0" ]; then
614                                 echo "batch-encode: $ENCODER returned code $RETURN" >> errors
615                         else
616                                 for UTRACKNUM in $TRACKQUEUE
617                                 do
618                                         echo encodetrack-$UTRACKNUM >> status
619                                 done
620                         fi
621                         )
622                         ;;
623                 esac
624                 ;;
625         esac
626         # Other encoders fall through to normal encoding as the tracks
627         # have not been entered in the status file.
628 }
629
630 # do_encode [tracknumber] [hostname]
631 # If no hostname is specified, encode locally
632 # variables used:
633 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
634 do_encode ()
635 {
636         if [ "$USEPIPES" = "y" ]; then
637                 case "$OUTPUT" in
638                         mp3)
639                                 TEMPARG="PIPE_$MP3ENCODERSYNTAX"
640                                 ;;
641                         vorbis|ogg)
642                                 TEMPARG="PIPE_$OGGENCODERSYNTAX"
643                                 ;;
644                         flac)
645                                 TEMPARG="PIPE_$FLACENCODERSYNTAX"
646                                 ;;
647                         spx)
648                                 TEMPARG="PIPE_$SPEEXENCODER"
649                                 ;;
650                         mpc)
651                                 TEMPARG="PIPE_$MPPENCODER"
652                                 ;;
653                 esac
654                 IN=${!TEMPARG}
655         else
656                 IN="$ABCDETEMPDIR/track$1.wav"
657                 case "$OUTPUT" in
658                         mp3)
659                                 case "$MP3ENCODERSYNTAX" in
660                                         # FIXME # check if mp3enc needs -if for pipes
661                                         mp3enc)
662                                                 FILEARG="-if $IN"
663                                                 ;;
664                                         *)
665                                                 FILEARG="$IN"
666                                                 ;;
667                                 esac
668                                 ;;
669                         *)
670                                 FILEARG="$IN"
671                                 ;;
672                 esac
673         fi
674         # We need IN to proceed, if we are not using pipes.
675         if [ -s "$IN" -o X"$USEPIPES" = "Xy" ] ; then
676                 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
677                 do
678                         case "$OUTPUT" in
679                                 vorbis|ogg)
680                                         OUT="$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
681                                         ;;
682                                 flac)
683                                         OUT="$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
684                                         ;;
685                                 *)
686                                         OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
687                                         ;;
688                         esac
689                         if [ X"$USEPIPES" = "Xy" ]; then
690                                 RUN_COMMAND=""
691                         else
692                                 run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
693                                 RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
694                         fi
695                         case "$OUTPUT" in
696                         mp3)
697                                 case "$2" in
698                                 %local*%)
699                                         case "$MP3ENCODERSYNTAX" in
700                                         lame|gogo) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
701                                         bladeenc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
702                                         l3enc|xingmp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
703                                         # FIXME # Relates to the previous FIXME since it might need the "-if" removed.
704                                         mp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
705                                         esac
706                                         ;;
707                                 *)
708                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
709                                         ;;
710                                 esac
711                                 ;;
712                         vorbis|ogg)
713                                 case "$2" in
714                                 %local*%)
715                                         case "$OGGENCODERSYNTAX" in
716                                         vorbize) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
717                                         oggenc) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
718                                         esac
719                                         ;;
720                                 *)
721                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
722                                         ;;
723                                 esac
724                                 ;;
725                         flac)
726                                 case "$2" in
727                                 %local*%)
728                                         case "$FLACENCODERSYNTAX" in
729                                         flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
730                                         esac
731                                         ;;
732         
733                                 *)
734                                         echo -n "DISTMP3:"
735                                         echo "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
736                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
737                                         ;;
738                                 esac
739                                 ;;
740                         spx)
741                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
742                                         case "$COMMENT" in
743                                                 *=*) ;;
744                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
745                                         esac    
746                                         COMMENT="--comment \"$COMMENT\""
747                                 fi
748                                 # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
749                                 if [ ! "$DOTAG" = "y" ]; then
750                                         $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
751                                 else
752                                         $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
753                                 fi
754                                 ;;
755                         mpc)    
756                                 # MPP/MP+(Musepack) format (.mpc) is done locally, with inline
757                                 # tagging.
758                                 # I tried compiling the mppenc from corecodecs.org and got some
759                                 # errors, so I have not tried it myself.
760                                 ## FIXME ## Needs some cleanup to determine if an empty tag sent
761                                 ## FIXME ## to the encoder ends up empty.
762                                 $RUN_COMMAND nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
763                                 ;;
764                         esac
765                 done
766                 # Only remove .wav if the encoding succeeded
767                 if checkerrors "encodetrack-(.{3,4})-$1"; then 
768                         run_command encodetrack-$1 false
769                 else
770                         run_command encodetrack-$1 true
771                         if [ ! "$KEEPWAVS" = "y" ] ; then
772                                 rm -f "$IN"
773                         fi
774                 fi
775         else
776                 if [ "$(checkstatus encode-output)" = "loud" ]; then
777                         echo "HEH! The file we were about to encode disappeared:"
778                         echo ">> $IN"
779                 fi
780                 run_command encodetrack-$1 false
781         fi
782 }
783
784 # do_preprocess [tracknumber]
785 # variables used:
786 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
787 #do_preprocess ()
788 #{
789 #       IN="$ABCDETEMPDIR/track$1.wav"
790 #       # We need IN to proceed.
791 #       if [ -s "$IN" ] ; then
792 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
793 #               do
794 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
795 #                       run_command '' echo "Pre-processing track $1 of $TRACKS..."
796 #                       case "$POSTPROCESSFORMAT" in
797 #                       all|wav*)
798 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
799 #                       mp3)
800 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
801 #                       ogg)
802 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
803 #                       flac)
804 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
805 #                       spx)
806 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
807 #                       esac
808 #               done
809 #               # Only remove .wav if the encoding succeeded
810 #               if checkerrors "preprocess-(.{3,4})-$1"; then 
811 #                       run_command preprocess-$1 false
812 #               else
813 #                       run_command preprocess-$1 true
814 #               fi
815 #       else
816 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
817 #                       echo "HEH! The file we were about to pre-process disappeared:"
818 #                       echo ">> $IN"
819 #               fi
820 #               run_command preprocess-$1 false
821 #       fi
822 #}
823
824
825 # do_postprocess [tracknumber]
826 # variables used:
827 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
828 #do_postprocess ()
829 #{
830 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
831 #       do
832 #               IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
833 #               # We need IN to proceed.
834 #               if [ -s "$IN" ] ; then
835 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
836 #                       run_command '' echo "Post-processing track $1 of $TRACKS..."
837 #                       case "$POSTPROCESSFORMAT" in
838 #                               mp3)
839 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
840 #                               ogg)
841 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
842 #                               flac)
843 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
844 #                               spx)
845 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
846 #                       esac
847 #                       # Only remove .wav if the encoding succeeded
848 #                       if checkerrors "postprocess-(.{3,4})-$1"; then 
849 #                               run_command postprocess-$1 false
850 #                       else
851 #                               run_command postprocess-$1 true
852 #                       fi
853 #               else
854 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
855 #                               echo "HEH! The file we were about to post-process disappeared:"
856 #                               echo ">> $IN"
857 #                       fi
858 #                       run_command postprocess-$1 false
859 #               fi
860 #       done
861 #}
862
863 # do_single_gain
864 # variables used:
865 # FIXME #
866 do_single_gain ()
867 {
868 :
869 }
870
871 # do_batch_gain
872 # variables used:
873 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
874 # FIXME #
875 do_batch_gain ()
876 {
877         # The commands here don't go through run_command because they're never supposed to be silenced
878         echo "Batch analizing gain in tracks: $TRACKQUEUE"
879         (
880         cd "$ABCDETEMPDIR"
881         BLURB=
882         TRACKFILES=
883         for UTRACKNUM in $TRACKQUEUE
884         do
885                 MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
886         done
887         # XXX: Hard-coded batch option!
888         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
889         RETURN=$?
890         if [ "$RETURN" != "0" ]; then
891                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
892         else
893                 for UTRACKNUM in $TRACKQUEUE
894                 do
895                         echo normalizetrack-$UTRACKNUM >> status
896                 done
897         fi
898         )
899 }
900
901 # do_batch_normalize
902 # variables used:
903 # NORMALIZER, NORMALIZEROPTS
904 do_batch_normalize ()
905 {
906         # The commands here don't go through run_command because they're never supposed to be silenced
907         echo "Batch normalizing tracks: $TRACKQUEUE"
908         (
909         cd "$ABCDETEMPDIR"
910         BLURB=
911         TRACKFILES=
912         for UTRACKNUM in $TRACKQUEUE
913         do
914                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
915         done
916         # XXX: Hard-coded batch option!
917         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
918         RETURN=$?
919         if [ "$RETURN" != "0" ]; then
920                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
921         else
922                 for UTRACKNUM in $TRACKQUEUE
923                 do
924                         echo normalizetrack-$UTRACKNUM >> status
925                 done
926         fi
927         )
928 }
929
930 # do_normalize [tracknumber]
931 # variables used:
932 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
933 do_normalize ()
934 {
935         IN="$ABCDETEMPDIR/track$1.wav"
936         if [ -e "$IN" ] ; then
937                 run_command '' echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
938                 run_command normalizetrack-$1 $NORMALIZER $NORMALIZEROPTS "$IN"
939         else
940                 if [ "$(checkstatus encode-output)" = "loud" ]; then
941                         echo "HEH! The file we were about to normalize disappeared:"
942                         echo ">> $IN"
943                 fi
944                 run_command normalizetrack-$1 false "File $IN was not found"
945         fi
946 }
947
948 # do_move [tracknumber]
949 # Deduces the outfile from environment variables
950 # Creates directory if necessary
951 # variables used:
952 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
953 do_move ()
954 {
955         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
956         do
957                 case $OUTPUT in
958                         vorbis|ogg)
959                                 OUTPUT=$OGGOUTPUTCONTAINER
960                                 ;;
961                         flac)
962                                 OUTPUT=$FLACOUTPUTCONTAINER
963                                 ;;
964                 esac
965                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
966                 # Munge filenames as follows:
967                 # ' ' -> '_'
968                 # '/' -> '_'
969                 # ''' -> ''
970                 # '?' -> ''
971                 # Eat control characters
972                 ALBUMFILE=$(mungefilename "$DALBUM")
973                 ARTISTFILE=$(mungefilename "$TRACKARTIST")
974                 TRACKFILE=$(mungefilename "$TRACKNAME")
975                 GENRE=$(mungegenre "$GENRE")
976                 YEAR=$(echo $CDYEAR)
977                 # If we want to start the tracks with a given number, we need to modify the
978                 # TRACKNUM value before evaluation
979                 if [ -n "$STARTTRACKNUMBER" ] ; then
980                         # Get the trackpadding from the current track
981                         CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
982                         TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
983                 else
984                         TRACKNUM=${UTRACKNUM}
985                 fi
986                 # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
987                 # TRACKFILE, and TRACKNUM.
988                 if [ "$VARIOUSARTISTS" = "y" ]; then
989                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
990                         else
991                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
992                 fi
993                 # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
994                 OUTPUTFILEDIR=$(dirname "$OUTPUTDIR/$OUTPUTFILE")
995                 # mkdir -p shouldn't return an error if the directory already exists
996                 mkdir -p "$OUTPUTFILEDIR"
997                 # Silence the Moving output since it overlaps with encoding processes...
998                 #run_command '' vecho "Moving track$1.$OUTPUT to $OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
999                 run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1000                 # Lets move the cue file
1001                 if CUEFILE=$(checkstatus cuefile) >/dev/null ; then 
1002                         if [ -r "$ABCDETEMPDIR/$CUEFILE" ]; then
1003                                 if checkstatus movecue-$OUTPUT; then :; else
1004                                         # Silence the Copying output since it overlaps with encoding processes...
1005                                         #run_command '' vecho "Copying cue file to its destination directory..."
1006                                         if checkstatus onetrack >/dev/null ; then
1007                                                 case $OUTPUT in
1008                                                         # NOTE: Creating a cue file with the 3-char-extension files is to comply with
1009                                                         # http://brianvictor.tripod.com/mp3cue.htm#details
1010                                                         [a-z0-9][a-z0-9][a-z0-9])
1011                                                                 run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1012                                                                 ;;
1013                                                         *)
1014                                                                 run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT.cue"
1015                                                                 ;;
1016                                                 esac
1017                                         else
1018                                                 run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTFILEDIR/$CUEFILE"
1019                                         fi
1020                                         echo movecue-$OUTPUT >> "$ABCDETEMPDIR/status"
1021                                 fi
1022                         fi
1023                 fi
1024         done
1025 }
1026
1027 # do_playlist
1028 # Create the playlist if wanted
1029 # Variables used:
1030 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
1031 # VARIOUSARTISTS, OUTPUTDIR
1032 do_playlist ()
1033 {
1034         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1035         do
1036                 # Create a playlist file for the playlist data to go into.
1037                 # We used to wipe it out if it existed. Now we request permision if interactive.
1038                 for LASTTRACK in $TRACKQUEUE; do :; done
1039                 ALBUMFILE=$(mungefilename "$DALBUM")
1040                 ARTISTFILE=$(mungefilename "$DARTIST")
1041                 GENRE=$(mungegenre "$GENRE")
1042                 YEAR=${CDYEAR:-$CDYEAR}
1043                 if [ "$VARIOUSARTISTS" = "y" ] ; then
1044                         PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
1045                 else
1046                         PLAYLISTFILE=$(eval echo $PLAYLISTFORMAT)
1047                 fi
1048                 FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
1049                 mkdir -p "$FINALPLAYLISTDIR"
1050                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
1051                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
1052                         if [ "$INTERACTIVE" = "y" ]; then
1053                                 while [ "$DONE" != "y" ]; do
1054                                         read ERASEPLAYLIST
1055                                         case $ERASEPLAYLIST in
1056                                                 e|E|a|A|k|K) DONE=y ;;
1057                                                 *) ;;
1058                                         esac
1059                                 done
1060                         else
1061                                 echo e >&2
1062                                 ERASEPLAYLIST=e
1063                         fi
1064                         # Once we erase the playlist, we use append to create the new one.
1065                         [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
1066                 else
1067                         # The playlist does not exist, so we can safelly use append to create the new list
1068                         ERASEPLAYLIST=a
1069                 fi
1070                 if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
1071                         touch "$OUTPUTDIR/$PLAYLISTFILE"
1072                         for UTRACKNUM in $TRACKQUEUE
1073                         do
1074                                 # Shares some code with do_move since the filenames have to match
1075                                 CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1076                                 TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
1077                                 splitvarious
1078                                 TRACKFILE=$(mungefilename "$TRACKNAME")
1079                                 ARTISTFILE=$(mungefilename "$TRACKARTIST")
1080                                 # If we want to start the tracks with a given number, we need to modify the
1081                                 # TRACKNUM value before evaluation
1082                                 if [ -n "$STARTTRACKNUMBER" ] ; then
1083                                         # Get the trackpadding from the current track
1084                                         CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
1085                                         TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
1086                                 else
1087                                         TRACKNUM=${UTRACKNUM}
1088                                 fi
1089                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1090                                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
1091                                 else
1092                                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
1093                                 fi
1094                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1095                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
1096                                                 echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1097                                         else
1098                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1099                                         fi
1100                                 else
1101                                         if [ "$PLAYLISTDATAPREFIX" ]; then
1102                                                 echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1103                                         else
1104                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1105                                         fi
1106                                 fi
1107                         done
1108                 fi
1109                 ## this will convert the playlist to have CRLF line-endings, if specified
1110                 ## (some hardware players insist on CRLF endings)
1111                 if [ "$DOSPLAYLIST" = "y" ]; then
1112                         awk '{substr("\r",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
1113 #                       mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
1114                         cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
1115                 fi
1116                 echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
1117         done
1118 }
1119
1120 # do_discid
1121 # This essentially the start of things
1122 do_discid ()
1123 {
1124         # Query the CD to get the track info, unless the user specified -C
1125         # or we are using some actions which do not need the CDDB data at all
1126         #if [ ! X"$EXPACTIONS" = "X" ]; then
1127         #       :
1128         #elif [ -z "$DISCID" ]; then
1129         if [ -z "$DISCID" ]; then
1130                 vecho -n "Getting CD track info... "
1131                 # In OSX, unmount the disc before a query
1132                 if [ "$OSFLAVOUR" = "OSX" ]; then
1133                         disktool -u ${CDROM#/dev/}
1134                 fi
1135                 TRACKINFO=$($CDDISCID $CDROM)
1136                 # Make sure there's a CD in there by checking cd-discid's return code
1137                 if [ "$?" = "1" ]; then
1138                         echo "abcde error: CD could not be read. Perhaps there's no CD in the drive?" >&2
1139                         exit 1
1140                 fi
1141                 # In OSX, remount the disc again
1142                 if [ "$OSFLAVOUR" = "OSX" ]; then
1143                         disktool -m ${CDROM#/dev/}
1144                 fi
1145                 WEHAVEACD=y
1146         else
1147                 TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
1148         fi
1149
1150         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
1151         # This needs to be done now because a section of the resuming code will need
1152         # it later.
1153
1154         # get the number of digits to pad TRACKNUM with - we'll use this later
1155         # a CD can only hold 99 tracks, but since we support a feature for starting
1156         # numbering the tracks from a given number, we might need to set it as a
1157         # variable for the user to define... or obtain it somehow.
1158         if [ "$PADTRACKS" = "y" ] ; then
1159                 TRACKNUMPADDING=2
1160         fi
1161
1162         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
1163         if [ -z "$TRACKQUEUE" ]; then
1164                 if [ ! "$STRIPDATATRACKS" = "y" ]; then
1165                         case "$CDROMREADERSYNTAX" in
1166                                 cdparanoia|debug)
1167                                         if [ "$WEHAVEACD" = "y" ]; then
1168                                                 vecho "Querying the CD for audio tracks..."
1169                                                 CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
1170                                                 RET=$?
1171                                                 if [ ! "$RET" = "0" ];then
1172                                                         echo "Warning: Something went wrong while querying the CD... Maybe a DATA CD?"
1173                                                 fi
1174                                                 TRACKS="$( echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ' )"
1175                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
1176                                         else
1177                                                 if [ -f "$ABCDETEMPDIR/status" ] && checkstatus cdparanoia-audio-tracks ; then
1178                                                         TRACKS=$( cat "$ABCDETEMPDIR/cdparanoia-audio-tracks" )
1179                                                 else
1180                                                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1181                                                 fi
1182                                         fi
1183                                         ;;
1184                                 *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
1185                         esac
1186                 else
1187                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1188                 fi
1189                 if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
1190                         echo "The disc does not contain any tracks. Giving up..."
1191                         exit 0
1192                 fi
1193                 echo -n "Grabbing entire CD - tracks: "
1194                 if [ ! "$PADTRACKS" = "y" ] ; then
1195                         TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
1196                 fi
1197                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
1198                 X=0
1199                 while [ "$X" -ne "$TRACKS" ]
1200                 do
1201                         X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
1202                         TRACKQUEUE=$(echo "$TRACKQUEUE" $X)
1203                 done
1204                 echo $TRACKQUEUE
1205         else
1206                 TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1207                 # User-supplied track queue.
1208                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
1209                 TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
1210                 # Once cleaned, obtain the highest value in the trackqueue for number padding
1211                 for LASTTRACK in $TRACKQUEUE; do :; done
1212                 if [ ! "$PADTRACKS" = "y" ] ; then
1213                         TRACKNUMPADDING=$(echo -n $LASTTRACK | wc -c | tr -d ' ')
1214                 fi
1215                 # Now we normalize the trackqueue
1216                 for TRACK in $TRACKQUEUE ; do
1217                         TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
1218                         PADTRACKQUEUE=$(echo $PADTRACKQUEUE $TRACKNUM)
1219                 done
1220                 TRACKQUEUE=$PADTRACKQUEUE
1221                 echo Grabbing tracks: "$TRACKQUEUE"
1222         fi
1223
1224         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
1225
1226         # We have the discid, create a temp directory after it to store all the temp
1227         # info
1228
1229         if [ -e "$ABCDETEMPDIR" ]; then
1230                 echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
1231                 # It already exists, see if it's a directory
1232                 if [ ! -d "$ABCDETEMPDIR" ]; then
1233                         # This is a file/socket/fifo/device/etc, not a directory
1234                         # Complain and exit
1235                         echo >&2
1236                         echo "abcde: file $ABCDETEMPDIR already exists and does not belong to abcde." >&2
1237                         echo "Please investigate, remove it, and rerun abcde." >&2
1238                         exit 1
1239                 fi
1240                 echo -n .
1241                 # It's a directory, let's see if it's owned by us
1242                 if [ ! -O "$ABCDETEMPDIR" ]; then
1243                         # Nope, complain and exit
1244                         echo >&2
1245                         echo "abcde: directory $ABCDETEMPDIR already exists and is not owned by you." >&2
1246                         echo "Please investigate, remove it, and rerun abcde." >&2
1247                         exit 1
1248                 fi
1249                 echo .
1250                 # See if it's populated
1251                 if [ ! -f "$ABCDETEMPDIR/discid" ]; then
1252                         # Wipe and start fresh
1253                         echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
1254                         echo -n "this directory to continue. Continue? [y/n] (n)" >&2
1255                         if [ "$INTERACTIVE" = "y" ]; then
1256                                 read ANSWER
1257                         else
1258                                 echo y >&2
1259                                 ANSWER=y
1260                         fi
1261                         if [ "$ANSWER" != "y" ]; then
1262                                 exit 1
1263                         fi
1264                         rm -rf "$ABCDETEMPDIR" || exit 1
1265                         mkdir "$ABCDETEMPDIR"
1266                         if [ "$?" -gt "0" ]; then
1267                                 # Directory already exists or could not be created
1268                                 echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
1269                                 exit 1
1270                         fi
1271                 else
1272                         # Everything is fine. Check for ^encodetracklocation-
1273                         # and encode-output entries in the status file and
1274                         # remove them. These are not relevant across sessions.
1275                         if [ -f "$ABCDETEMPDIR/status" ]; then
1276                                 mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
1277                                 grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
1278                                         | grep -v ^encode-output > "$ABCDETEMPDIR/status"
1279                         fi
1280                         # Remove old error messages
1281                         if [ -f "$ABCDETEMPDIR/errors" ]; then
1282                                 rm -f "$ABCDETEMPDIR/errors"
1283                         fi
1284                 fi
1285         else
1286                 # We are starting from scratch
1287                 mkdir "$ABCDETEMPDIR"
1288                 if [ "$?" -gt "0" ]; then
1289                         # Directory already exists or could not be created
1290                         echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
1291                         exit 1
1292                 fi
1293                 cat /dev/null > "$ABCDETEMPDIR/status"
1294         fi
1295         if [ X"$MAKECUEFILE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
1296                 if checkstatus cuefile > /dev/null 2>&1 ; then :; else
1297                         CUEFILE=cue-$(echo "$TRACKINFO" | cut -f1 -d' ').txt
1298                         vecho "Creating cue file..."
1299                         if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
1300                                 echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
1301                         else
1302                                 echo "abcde: reading the CUE sheet with mkcue is still considered experimental"
1303                                 echo "abcde: and there was a problem with the CD reading. abcde will continue,"
1304                                 echo "abcde: but consider reporting the problem to the abcde author"
1305                         fi
1306                 fi
1307         fi
1308         # If we got the CDPARANOIA status and it is not recorded, save it now
1309         if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
1310                 if checkstatus cdparanoia-audio-tracks; then :; else
1311                         if echo "$CDPARANOIAAUDIOTRACKS" >> "$ABCDETEMPDIR/cdparanoia-audio-tracks"; then
1312                                 echo "cdparanoia-audio-tracks" >> "$ABCDETEMPDIR/status"
1313                         fi
1314                 fi
1315         fi
1316         
1317         # Create the discid file
1318         echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
1319 }
1320
1321 # do_cleancue
1322 # Create a proper CUE file based on the CUE file we created before.
1323 do_cleancue()
1324 {
1325         # FIXME # we can get the name of the cuefile from the status file
1326         if CUEFILE_IN="$ABCDETEMPDIR"/$(checkstatus cuefile); then
1327                 CUEFILE_OUT=$CUEFILE_IN.out
1328                 ### FIXME ### checkstatus cddb
1329                 if [ -e "$CDDBDATA" ]; then
1330                         vecho "Adding metadata to the cue file..."
1331                         # FIXME It doesn't preserve spaces! Why?
1332                         # FIXME parse $track into PERFORMER and TITLE - abcde already has code for this?
1333                         n=1
1334                         echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
1335                         echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
1336                         cat "$CUEFILE_IN" | while read line
1337                         do
1338                                 if echo "$line" | grep -q "INDEX"
1339                                 then
1340                                         eval track="\$TRACK$n"
1341                                         n=$(expr $n + 1)
1342                                         echo "TITLE \"$track\"" >> "$CUEFILE_OUT"
1343                                 fi
1344                                 echo "$line" >> "$CUEFILE_OUT"
1345                         done
1346                         mv "$CUEFILE_OUT" "$CUEFILE_IN"
1347                         echo "cleancuefile" >> "$ABCDETEMPDIR/status"
1348                 fi
1349         fi
1350 }
1351
1352 # do_cddbparse
1353 # Parses a CDDB file and outputs the title and the track names.
1354 # Variables: CDDBFILE
1355 do_cddbparse ()
1356 {
1357         CDDBPARSEFILE="$1"
1358         # List out disc title/author and contents
1359         if [ "$ONETRACK" = "y" ]; then
1360                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
1361         fi
1362         echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
1363         if [ X"$SHOWCDDBYEAR" = "Xy" ]; then
1364                 PARSEDYEAR=$(grep DYEAR "${CDDBPARSEFILE}" | cut '-d=' -f2-)
1365                 if [ ! X"$PARSEDYEAR" = "X" ]; then
1366                         echo "Year: $PARSEDYEAR"
1367                 fi
1368         fi
1369         if [ X"$SHOWCDDBGENRE" = "Xy" ]; then
1370                 PARSEDGENRE=$(grep DGENRE "${CDDBPARSEFILE}" | cut '-d=' -f2-)
1371                 if [ ! X"$PARSEDGENRE" = "X" ]; then
1372                         echo "Genre: $PARSEDGENRE"
1373                 fi
1374         fi
1375         if [ ! "$ONETRACK" = "y" ]; then
1376                 for TRACK in $(f_seq_row 1 $TRACKS)
1377                 do
1378                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
1379                 done
1380         fi
1381 }
1382
1383 # do_localcddb
1384 # Check for a local CDDB file, and report success
1385 do_localcddb ()
1386 {
1387         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
1388         
1389                 CDDBLOCALSUCCESS="n"
1390                 CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1391                 CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1392                 USELOCALRESP="y"
1393                 
1394                 # If the user has selected to check a local CDDB repo, we proceed with it
1395                 if [ -r "${CDDBLOCALFILE}" ]; then
1396                         # List out disc title/author and contents
1397                         do_cddbparse "${CDDBLOCALFILE}"
1398                         echo -n "Locally cached CDDB entry found, use it? [y/n] (y): "
1399                         if [ "$INTERACTIVE" = "y" ]; then
1400                                 read USELOCALRESP
1401                                 while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
1402                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1403                                         read USELOCALRESP
1404                                 done
1405                                 [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
1406                         else
1407                                 echo "y" >&2
1408                         fi
1409                         if [ "$USELOCALRESP" = "y" ]; then
1410                                 #echo "Using local copy of CDDB data"
1411                                 cp "${CDDBLOCALFILE}" "$ABCDETEMPDIR/cddbread.1"
1412                                 echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
1413                                 echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
1414                                 do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
1415                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1416                                 CDDBLOCALSUCCESS="y"
1417                         else
1418                                 #echo "Not using local copy of CDDB data"
1419                                 CDDBLOCALSUCCESS="n"
1420                         fi
1421                 else
1422                         CDDBLOCALSUCCESS="n"
1423                 fi
1424         fi
1425 }
1426
1427 # do_cddbstat
1428 do_cddbstat ()
1429 {
1430         # Perform CDDB protocol version check if it hasn't already been done
1431         if checkstatus cddb-statcomplete; then :; else
1432                 if [ "$CDDBAVAIL" = "n" ]; then
1433                         ERRORCODE=no_query
1434                         echo 503 > "$ABCDETEMPDIR/cddbstat"
1435                 else
1436                         rc=1
1437                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1438                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1439                         while test $rc -eq 1 -a $CDDBPROTO -ge 3; do
1440                                 vecho "Checking CDDB server status..."
1441                                 $CDDBTOOL stat $CDDBURL $CDDBUSER $CDDBHOST $CDDBPROTO > "$ABCDETEMPDIR/cddbstat"
1442                                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
1443                                 case "$RESPONSECODE" in
1444                                 210)    # 210 OK, status information follows (until terminating `.')
1445                                         rc=0;
1446                                         ;;
1447                                 501|*)  # 501 Illegal CDDB protocol level: <n>. 
1448                                         CDDBPROTO=`expr $CDDBPROTO - 1`
1449                                         ;;
1450                                 esac 
1451                         done
1452                         if test $rc -eq 1; then
1453                                 CDDBAVAIL="n" 
1454                         fi
1455                 fi
1456                 echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
1457         fi
1458 }
1459
1460
1461 # do_cddbquery
1462 do_cddbquery ()
1463 {
1464         CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1465         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1466         
1467         # Perform CDDB query if it hasn't already been done
1468         if checkstatus cddb-querycomplete; then :; else
1469                 if [ "$CDDBAVAIL" = "n" ]; then
1470                         ERRORCODE=no_query
1471                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1472                 # The default CDDBLOCALSUCCESS is "n"
1473                 # This part will be triggered if the user CDDB repo does not 
1474                 # contain the entry, or if we are not trying to use the repo.
1475                 else
1476                         vecho "Querying the CDDB server..."
1477                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1478                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1479                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $TRACKINFO > "$ABCDETEMPDIR/cddbquery"
1480                         ERRORCODE=$?
1481                         case $ERRORCODE in
1482                                 0)  # success
1483                                 ;;
1484                                 12|13|14)
1485                                         # no match found in database,
1486                                         # wget/fetch error, or user requested not to use CDDB
1487                                         # Make up an error code (503) that abcde
1488                                         # will recognize in do_cddbread
1489                                         # and compensate by making a template
1490                                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1491                                 ;;
1492                                 *) # strange and unknown error
1493                                         echo ERRORCODE=$ERRORCODE
1494                                         echo "abcde: $CDDBTOOL returned unknown error code"
1495                                 ;;
1496                         esac
1497                 fi
1498                 echo cddb-querycomplete >> "$ABCDETEMPDIR/status"
1499         fi
1500 }
1501
1502 # do_cddbread
1503 do_cddbread ()
1504 {
1505         # If it's not to be used, generate a template.
1506         # Then, display it (or them) and let the user choose/edit it
1507         if checkstatus cddb-readcomplete; then :; else
1508                 vecho "Obtaining CDDB results..."
1509                 # If CDDB is to be used, interpret the query results and read all
1510                 # the available entries.
1511                 rm -f "$ABCDETEMPDIR/cddbchoices"
1512                 CDDBCHOICES=1 # Overridden by multiple matches
1513                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbquery" | cut -f1 -d' ')
1514                 case "$RESPONSECODE" in
1515                 200)
1516                         # One exact match, retrieve it
1517                         # 200 [section] [discid] [artist] / [title]
1518                         if checkstatus cddb-read-1-complete; then :; else
1519                                 echo -n "Retrieving 1 CDDB match..." >> "$ABCDETEMPDIR/cddbchoices"
1520                                 $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(cut -f2,3 -d' ' "$ABCDETEMPDIR/cddbquery") > "$ABCDETEMPDIR/cddbread.1"
1521                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
1522                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1523                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1524                         fi
1525                         # List out disc title/author and contents
1526                         echo ---- "$(cut '-d ' -f4- "$ABCDETEMPDIR/cddbquery")" ---- >> "$ABCDETEMPDIR/cddbchoices"
1527                         for TRACK in $(f_seq_row 1 $TRACKS)
1528                         do
1529                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1530                         done
1531                         echo >> "$ABCDETEMPDIR/cddbchoices"
1532                         ;;
1533                 202|403|409|503)
1534                         # No match
1535                         case "$RESPONSECODE" in
1536                         202) echo "No CDDB match." >> "$ABCDETEMPDIR/cddbchoices" ;;
1537                         403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
1538                         503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
1539                         esac
1540                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
1541                         # List out disc title/author and contents of template
1542                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
1543                         UNKNOWNDISK=y
1544                         for TRACK in $(f_seq_row 1 $TRACKS)
1545                         do
1546                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1547                         done
1548                         echo >> "$ABCDETEMPDIR/cddbchoices"
1549                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
1550                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
1551                         ;;
1552                 210|211)
1553                         # Multiple exact, (possibly multiple) inexact matches
1554                         IN=
1555                         if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
1556                         if [ "$(wc -l < "$ABCDETEMPDIR/cddbquery" | tr -d ' ')" -eq 3 ]; then
1557                                 echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
1558                                 tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
1559                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1560                         else
1561                                 echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
1562                         fi
1563                         vecho -n "Retrieving multiple matches... "
1564                         grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
1565                         read DISCINFO # eat top line
1566                         while read DISCINFO
1567                         do
1568                                 X=$(expr $X + 1)
1569                                 if checkstatus cddb-read-$X-complete; then :; else
1570                                         $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(echo $DISCINFO | cut -f1,2 -d' ') > "$ABCDETEMPDIR/cddbread.$X"
1571                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
1572                                 fi
1573                                 # List out disc title/author and contents
1574                                 echo \#$X: ---- "$DISCINFO" ---- >> "$ABCDETEMPDIR/cddbchoices"
1575                                 for TRACK in $(f_seq_row 1 $TRACKS)
1576                                 do
1577                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1578                                 done
1579                                 echo >> "$ABCDETEMPDIR/cddbchoices"
1580                         done )
1581                         vecho "done."
1582                         CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1583                         ;;
1584                 999)
1585                         # Using local copy.
1586                         for TRACK in $(f_seq_row 1 $TRACKS)
1587                         do
1588                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1589                         done
1590                         echo >> "$ABCDETEMPDIR/cddbchoices"
1591                         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1592                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1593                         ;;
1594                 esac    
1595                 echo "cddb-readcomplete" >> "$ABCDETEMPDIR/status"
1596         fi
1597 }
1598
1599 # do_cddbedit
1600 do_cddbedit ()
1601 {
1602         if checkstatus cddb-edit >/dev/null; then
1603                 CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1604                 VARIOUSARTISTS="$(checkstatus variousartists)"
1605                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
1606                 return 0
1607         fi
1608         if [ "$INTERACTIVE" = "y" ]; then
1609                 # We should show the CDDB results both when we are not using the local CDDB repo
1610                 # or when we are using it but we could not find a proper match
1611                 if [ "$CDDBUSELOCAL" = "y" ] && [ ! "$CDDBLOCALSUCCESS" = "y" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1612                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1613                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1614                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1615                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1616                                 CHOICE=$(checkstatus cddb-choice)
1617                                 if [ -n "$CHOICE" ] ; then
1618                                         case $CDDBCHOICES in
1619                                                 1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1620                                                 *)
1621                                                 echo "Selected: #$CHOICE"
1622                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1623                                                 ;;
1624                                         esac
1625                                 else
1626                                         # The user has a choice to make, display the info in a pager if necessary
1627                                         if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
1628                                                 page "$ABCDETEMPDIR/cddbchoices"
1629                                         else
1630                                                 # It's all going to fit in one page, cat it
1631                                                 cat "$ABCDETEMPDIR/cddbchoices" >&2
1632                                         fi
1633                                         
1634                                         CDDBCHOICENUM=""
1635                                         # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
1636                                         CDCHOICENUM=-1
1637                                         # I'll take CDDB read #3 for $400, Alex
1638                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
1639                                                 echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
1640                                                 read CDDBCHOICE
1641                                                 [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
1642                                                 if echo $CDDBCHOICE | egrep -q "[[:digit:]]+,[[:digit:]]+" ; then
1643                                                         if [ ! X"$DIFF" = "X" ]; then
1644                                                                 PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1)
1645                                                                 PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2)
1646                                                                 if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBCHOICES ] || \
1647                                                                    [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBCHOICES ] || \
1648                                                                    [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
1649                                                                         echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBCHOICES" >&2
1650                                                                 else
1651
1652                                                                         # We parse the 2 choices to diff, store them in temporary files and diff them.
1653                                                                         for PARSECHOICE in $(echo $CDDBCHOICE | tr , \ ); do
1654                                                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$PARSECHOICE" > "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE"
1655                                                                         done
1656                                                                         echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/cddbread.diff"
1657                                                                         $DIFF $DIFFOPTS "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/cddbread.diff"
1658                                                                         if [ $(cat "$ABCDETEMPDIR/cddbread.diff" | wc -l) -ge 24 ]; then
1659                                                                                 page "$ABCDETEMPDIR/cddbread.diff"
1660                                                                         else
1661                                                                                 cat "$ABCDETEMPDIR/cddbread.diff" >&2
1662                                                                         fi
1663                                                                 fi
1664                                                         else
1665                                                                 echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
1666                                                         fi
1667                                                 else
1668                                                         if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
1669                                                                 # Make sure we get a valid choice
1670                                                                 CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1671                                                                 echo "Invalid selection. Please choose a number between 0 and $CDDBCHOICES." >&2
1672                                                         fi
1673                                                 fi
1674                                         done
1675                                         if [ "$CDCHOICENUM" = "0" ]; then
1676                                                 vecho "Creating empty CDDB template..."
1677                                                 UNKNOWNDISK=y
1678                                                 $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
1679                                         else
1680                                                 echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
1681                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
1682                                         fi
1683                                         echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1684                                 fi
1685                         fi
1686                 else
1687                         # We need some code to show the selected option when local repository is selected and we have found a match
1688                         vecho "Using cached CDDB match..." >&2
1689                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1690                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1691                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1692                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1693                                 CHOICE=$(checkstatus cddb-choice)
1694                                 if [ "$USELOCALRESP" = "y" ]; then :; else
1695                                         if [ -n "$CHOICE" ] ; then
1696                                                 case $CDDBCHOICES in
1697                                                         0) 
1698                                                         UNKNOWNDISK=y
1699                                                         echo "Selected template."
1700                                                         ;;
1701                                                         1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1702                                                         *)
1703                                                         echo "Selected: #$CHOICE"
1704                                                         do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1705                                                         ;;
1706                                                 esac
1707                                         fi
1708                                 fi
1709                         fi
1710                 fi
1711         else
1712                 # We're noninteractive - pick the first choice.
1713                 # But in case we run a previous instance and selected a choice, use it.
1714                 if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1715                         # Show the choice if we are not using the locally stored one
1716                         # or when the local search failed to find a match.
1717                         PREVIOUSCHOICE=$(checkstatus cddb-choice)
1718                         if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSUCCESS" = "n" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1719                                 #if [ "$PREVIOUSCHOICE" ]; then
1720                                         cat "$ABCDETEMPDIR/cddbchoices"
1721                                 #fi
1722                         fi
1723                         if [ ! -z "$PREVIOUSCHOICE" ] ; then
1724                                 CDCHOICENUM=$PREVIOUSCHOICE
1725                         else
1726                                 CDCHOICENUM=1
1727                                 echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1728                         fi
1729                         echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
1730                 fi
1731         fi
1732
1733         # sanity check
1734         if checkstatus cddb-choice >/dev/null; then :; else
1735                 echo "abcde: internal error: cddb-choice not recorded." >&2
1736                 exit 1
1737         fi
1738         CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1739         echo -n "Edit selected CDDB data? [y/n] (" >&2
1740         if [ "$INTERACTIVE" = "y" ]; then
1741                 if [ "$UNKNOWNDISK" = "y" ]; then
1742                         echo -n "y): " >&2
1743                         read EDITCDDB
1744                         [ "$EDITCDDB" != "n" ] && EDITCDDB=y
1745                 else
1746                         echo -n "n): " >&2
1747                         read EDITCDDB
1748                 fi
1749         else
1750                 echo "n): n" >&2
1751                 EDITCDDB=n
1752         fi
1753         if [ "$EDITCDDB" = "y" ]; then
1754                 CDDBDATAMD5SUM=$($MD5SUM "$CDDBDATA" | cut -d " " -f 1);
1755                 
1756                 # Use the debian sensible-editor wrapper to pick the editor that the
1757                 # user has requested via their $EDITOR environment variable
1758                 if [ -x "/usr/bin/sensible-editor" ]; then
1759                         /usr/bin/sensible-editor "$CDDBDATA"
1760                 elif [ -n "$EDITOR" ]; then
1761                         if [ -x $(which "${EDITOR%%\ *}") ]; then
1762                                 # That failed, try to load the preferred editor, starting
1763                                 # with their EDITOR variable
1764                                 eval $(echo "$EDITOR") \"$CDDBDATA\"
1765                         fi
1766                 # If that fails, check for a vi
1767                 elif which vi >/dev/null 2>&1; then
1768                         vi "$CDDBDATA"
1769                 elif [ -x /usr/bin/vim ]; then
1770                         /usr/bin/vim "$CDDBDATA"
1771                 elif [ -x /usr/bin/vi ]; then
1772                         /usr/bin/vi "$CDDBDATA"
1773                 elif [ -x /bin/vi ]; then
1774                         /bin/vi "$CDDBDATA"
1775                 # nano should be on all (modern, i.e., sarge) debian systems
1776                 elif which nano >/dev/null 2>&1 ; then
1777                         nano "$CDDBDATA"
1778                 elif [ -x /usr/bin/nano ]; then
1779                         /usr/bin/nano "$CDDBDATA"
1780                 # mg should be on all OpenBSD systems
1781                 elif which mg >/dev/null 2>&1 ; then
1782                         mg "$CDDBDATA"
1783                 elif [ -x /usr/bin/mg ]; then
1784                         /usr/bin/mg "$CDDBDATA"
1785                 # bomb out
1786                 else
1787                         echo "No editor available. Check your EDITOR environment variable." >&2
1788                 fi
1789                 # delete editor backup file if it exists
1790                 if [ -w "$CDDBDATA~" ]; then
1791                         rm -f "$CDDBDATA~"
1792                 fi
1793         fi
1794
1795         # Some heuristics first. Look at Disc Title, and if it starts with
1796         # "Various", then we'll assume Various Artists
1797         if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
1798                 echo "Looks like a Multi-Artist CD" >&2
1799                 VARIOUSARTISTS=y
1800         else
1801                 echo -n "Is the CD multi-artist? [y/n] (n): " >&2
1802                 if [ "$INTERACTIVE" = "y" ]; then
1803                         read VARIOUSARTISTS
1804                 else
1805                         echo n >&2
1806                         VARIOUSARTISTS=n
1807                 fi
1808         fi
1809         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
1810                 # Set a default
1811                 DEFAULTSTYLE=1
1812                 # Need NUMTRACKS before cddb-tool will return it:
1813                 NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
1814                 if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1815                         # More than 1/2 tracks contain a "/", so guess forward
1816                         DEFAULTSTYLE=1
1817                 elif [ "$(grep -c "^TTITLE.*\-" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1818                         # More than 1/2 contain a "-", so guess forward-dash
1819                         DEFAULTSTYLE=2
1820                 elif [ "$(grep -c "^TTITLE.*(.*)" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1821                         # More than 1/2 contain something in parens, so guess trailing-paren
1822                         DEFAULTSTYLE=6
1823                 fi
1824
1825                 echo "1) Artist / Title" >&2
1826                 echo "2) Artist - Title" >&2
1827                 echo "3) Title / Artist" >&2
1828                 echo "4) Title - Artist" >&2
1829                 echo "5) Artist: Title" >&2
1830                 echo "6) Title (Artist)" >&2
1831                 echo "7) This is a single-artist CD" >&2
1832                 echo -n "Which style of multiple artist entries is it? [1-7] ($DEFAULTSTYLE): " >&2
1833                 if [ "$INTERACTIVE" = "y" ]; then
1834                         read VARIOUSARTISTSTYLE
1835                 else
1836                         echo $DEFAULTSTYLE >&2
1837                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1838                 fi
1839                 VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1840                 # If they press Enter, then the default style (0) was chosen
1841                 while [ $VARIOUSARTISTSTYLE -lt 0 ] || [ $VARIOUSARTISTSTYLE -gt 7 ]; do
1842                         echo "Invalid selection. Please choose a number between 1 and 7."
1843                         echo -n "Selection [1-7]: "
1844                         read VARIOUSARTISTSTYLE
1845                         VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1846                 done
1847                 if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
1848                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1849                 fi
1850                 vecho "Selected: $VARIOUSARTISTSTYLE"
1851                 case "$VARIOUSARTISTSTYLE" in
1852                 1) # Artist / Title
1853                         VARIOUSARTISTSTYLE=forward
1854                         ;;
1855                 2) # Artist - Title
1856                         VARIOUSARTISTSTYLE=forward-dash
1857                         ;;
1858                 3) # Title / Artist
1859                         VARIOUSARTISTSTYLE=reverse
1860                         ;;
1861                 4) # Title - Artist
1862                         VARIOUSARTISTSTYLE=reverse-dash
1863                         ;;
1864                 5) # Artist: Title
1865                         VARIOUSARTISTSTYLE=colon
1866                         ;;
1867                 6) # Title (Artist)
1868                         VARIOUSARTISTSTYLE=trailing-paren
1869                         ;;
1870                 7) # Single Artist
1871                         VARIOUSARTISTS=n
1872                         ;;
1873                 esac
1874         fi
1875
1876         echo "variousartists=$VARIOUSARTISTS" >> "$ABCDETEMPDIR/status"
1877         echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
1878
1879         if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
1880                 if [ $CDDBDATAMD5SUM != "" ]  && [ $CDDBDATAMD5SUM != $($MD5SUM "$CDDBDATA" | cut -d " " -f 1) ]; then
1881                         # This works but does not have the necessary error checking
1882                         # yet. If you are familiar with the CDDB spec
1883                         # (see http://www.freedb.org/src/latest/DBFORMAT) 
1884                         # and can create an error-free entry on your own, then put
1885                         # UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE=y in your
1886                         # abcde.conf to enable it. Put CDDBSUBMIT=email@address in
1887                         # your abcde.conf to change the email address submissions are
1888                         # sent to.
1889
1890                         # submit the modified file, if they want
1891                         if [ "$NOSUBMIT" != "y" ]; then
1892                                 echo -n "Do you want to submit this entry to $CDDBSUBMIT? [y/n] (n): "
1893                                 read YESNO
1894                                 while [ "$YESNO" != "y" ] && [ "$YESNO" != "n" ] && [ "$YESNO" != "Y" ] && \
1895                                         [ "$YESNO" != "N" ] && [ "$YESNO" != "" ]
1896                                 do
1897                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1898                                         read YESNO
1899                                 done
1900                                 if [ "$YESNO" = "y" ] || [ "$YESNO" = "Y" ]; then
1901                                         echo -n "Sending..."
1902                                         $CDDBTOOL send "$CDDBDATA" $CDDBSUBMIT
1903                                         echo "done."
1904                                 fi
1905                         fi
1906                 fi
1907         fi
1908         # Make sure the cache directory exists
1909         mkdir -p $CDDBLOCALDIR
1910         # Cache edited CDDB entry in the user's cddb dir
1911         if [ "$CDDBCOPYLOCAL" = "y" ] || [ "$COPYCDDBLOCAL" = "Y" ]; then
1912                 cat "$CDDBDATA" | tail -n $(expr $(cat "$CDDBDATA" | wc -l ) - 1 ) > ${CDDBLOCALDIR}/$(echo "$TRACKINFO" | cut -d' ' -f1)
1913         fi
1914
1915         echo "cddb-edit" >> "$ABCDETEMPDIR/status"
1916 }
1917
1918 # do_cdread [tracknumber]
1919 # do_cdread onetrack [firsttrack] [lasttrack]
1920
1921 do_cdread ()
1922 {
1923         # The commands here don't go through run_command because they're never supposed to be silenced
1924         # return codes need to be doublechecked anyway, however
1925         if [ "$1" = "onetrack" ]; then
1926                 # FIXME # Add the possibility of grabbing ranges of tracks in onetrack
1927                 # FIXME # Until then, we grab the whole CD in one track, no matter what
1928                 # the user said
1929                 # We need the first and last track for cdda2wav
1930                 FIRSTTRACK=$2
1931                 LASTTRACK=$3
1932                 UTRACKNUM=$FIRSTTRACK
1933                 case "$CDROMREADERSYNTAX" in
1934                         cdparanoia) READTRACKNUMS="$FIRSTTRACK-$LASTTRACK" ;;
1935                         cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTRACK" ;;
1936                         *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
1937                            exit 1 ;;
1938                 esac
1939         else
1940                 UTRACKNUM=$1
1941         fi
1942         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1943         if [ "$USEPIPES" = "y" ]; then
1944                 TEMPARG="PIPE_$CDROMREADERSYNTAX"
1945                 FILEARG="${!TEMPARG}"
1946                 REDIR=""
1947                 PIPE_MESSAGE="and encoding "
1948         else
1949                 WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
1950                 case "$CDROMREADERSYNTAX" in
1951                 ## FIXME ## Find the case for dagrab, to avoid exceptions
1952                         dagrab)
1953                                 FILEARG="-f $WAVDATA"
1954                                 ;;
1955                         *)
1956                                 FILEARG="$WAVDATA"
1957                                 ;;
1958                 esac
1959                 REDIR=">&2"
1960         fi
1961         if [ "$1" = "onetrack" ]; then
1962                 echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK as one track ..." >&2
1963         else
1964                 if [ -r "$CDDBDATA" ]; then
1965                         TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
1966                         echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
1967                 else
1968                         echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
1969                 fi
1970         fi
1971         case "$CDROMREADERSYNTAX" in
1972                 cdparanoia) 
1973                         nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
1974                 cdda2wav)
1975                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1976                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1977                                 disktool -u ${CDROM#/dev/} 0
1978                                 # Also, in OSX the cdrom device for cdda2wav changes...
1979                                 CDDA2WAVCDROM="IODVDServices"
1980                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1981                                 CDDA2WAVCDROM="$CDROMID"
1982                         else
1983                                 if [ "$CDROMID" = "" ]; then
1984                                         CDDA2WAVCDROM="$CDROM"
1985                                 else
1986                                         CDDA2WAVCDROM="$CDROMID"
1987                                 fi
1988                         fi
1989                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR
1990                         ;;
1991                 ## FIXME ## We have an exception for dagrab, since it uses -f
1992                 ## FIXME ## Shall we just use -f $FILEARG ??
1993                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -v $UTRACKNUM "$FILEARG" $REDIR
1994                         ;;
1995                 cddafs)
1996                         # Find the track's mounted path
1997                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1998                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1999                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
2000                         # If the file exists, copy it
2001                         if [ -e "$FILEPATH" ] ; then
2002                                 nice $READNICE $CDROMREADER "$FILEPATH" "$FILEARG" $REDIR
2003                         else
2004                                 false
2005                         fi ;;
2006                 debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
2007                         ;;
2008         esac
2009         RETURN=$?
2010         # If we get some error or we get some missing wav 
2011         # (as long as we dont use pipes)
2012         if [ "$RETURN" != "0" -o \( ! -s "$WAVDATA" -a X"$USEPIPES" != "Xy" \) ]; then
2013                 # Thank goodness errors is only machine-parseable up to the
2014                 # first colon, otherwise this woulda sucked
2015                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
2016                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
2017                 fi
2018                 if [ "$USEPIPES" = "y" ]; then
2019                         echo "readencodetrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
2020                 else
2021                         echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
2022                 fi
2023                 return $RETURN
2024         else
2025                 if [ "$USEPIPES" = "y" ]; then
2026                         echo readencodetrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
2027                 else
2028                         echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
2029                         if [ "$1" = "onetrack" ]; then
2030                                 echo onetrack >> "$ABCDETEMPDIR/status"
2031                         fi
2032                 fi
2033         fi
2034 }
2035
2036 # do_cdspeed
2037 # No values accepted, only uses env variables
2038 do_cdspeed () 
2039 {
2040         if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
2041                 vecho "Setting CD speed to ${CDSPEEDVALUE}x"
2042         else
2043                 echo "abcde: unable to set the device speed" >&2
2044         fi
2045 }
2046
2047 # vecho [message]
2048 #
2049 # vecho outputs a message if EXTRAVERBOSE is selected
2050 vecho ()
2051 {
2052 if [ x"$EXTRAVERBOSE" != "x" ]; then
2053         echo $@
2054 fi
2055 }
2056
2057 # User-redefinable functions
2058 # Custom filename munging:
2059 mungefilename ()
2060 {
2061         #echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
2062         echo "$@" | sed s,:,\ -,g | tr \ / __ | tr -d \'\"\?\[:cntrl:\]
2063 }
2064
2065 # Custom genre munging:
2066 mungegenre ()
2067 {
2068         echo $CDGENRE | tr "[:upper:]" "[:lower:]"
2069 }
2070
2071 # pre_read
2072 # Empty pre_read function, to be defined in the configuration file.
2073 pre_read ()
2074 {
2075 :
2076 }
2077
2078 # post_read
2079 # Empty post_read function, to be defined in the configuration file.
2080 post_read ()
2081 {
2082 :
2083 }
2084
2085 ###############################################################################
2086 # End of functions
2087 #
2088 # Start of execution
2089 ###############################################################################
2090
2091 # Builtin defaults
2092 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
2093 CDDBSUBMIT=freedb-submit@freedb.org
2094 CDDBPROTO=5
2095 HELLOINFO="$(whoami)@$(hostname)"
2096 CDDBCOPYLOCAL="n"
2097 CDDBLOCALDIR="$HOME/.cddb"
2098 CDDBUSELOCAL="n"
2099
2100 # List of fields we parse and show during the CDDB parsing...
2101 SHOWCDDBFIELDS="year,genre"
2102
2103 INTERACTIVE=y
2104 CDROMREADERSYNTAX=cdparanoia
2105 ENCODERSYNTAX=default
2106
2107 MP3ENCODERSYNTAX=default
2108 OGGENCODERSYNTAX=default
2109 FLACENCODERSYNTAX=default
2110 SPEEXENCODERSYNTAX=default
2111 MPPENCODERSYNTAX=default
2112 NORMALIZERSYNTAX=default
2113 CUEREADERSYNTAX=default
2114
2115 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
2116 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
2117 #VAOUTPUTFORMAT=${OUTPUTFORMAT}
2118 VAOUTPUTFORMAT='Various-${ALBUMFILE}/${TRACKNUM}.${ARTISTFILE}-${TRACKFILE}'
2119 ONETRACKOUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${ALBUMFILE}'
2120 VAONETRACKOUTPUTFORMAT='Various-${ALBUMFILE}/${ALBUMFILE}'
2121 PLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
2122 PLAYLISTDATAPREFIX=''
2123 VAPLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
2124 VAPLAYLISTDATAPREFIX=''
2125 DOSPLAYLIST=n
2126 COMMENT=''
2127 ID3TAGV=2
2128 ENCNICE=10
2129 READNICE=10
2130 DISTMP3NICE=10
2131 VARIOUSARTISTS=n
2132 VARIOUSARTISTSTYLE=forward
2133 KEEPWAVS=n
2134 PADTRACKS=n
2135
2136 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
2137 # i.e. CDROMID="1,0,0"
2138 CDROMID=""
2139 # If we are using the IDE bus, we need CDPARANOIACDROMBUS defined as "d"
2140 # If we are using the ide-scsi emulation layer, we need to define a "g"
2141 CDPARANOIACDROMBUS="d"
2142
2143 # program paths - defaults to checking your $PATH
2144 # mp3
2145 LAME=lame
2146 GOGO=gogo
2147 BLADEENC=bladeenc
2148 L3ENC=l3enc
2149 XINGMP3ENC=xingmp3enc
2150 MP3ENC=mp3enc
2151 # ogg
2152 VORBIZE=vorbize
2153 OGGENC=oggenc
2154 # flac
2155 FLAC=flac
2156 # speex
2157 SPEEXENC=speexenc
2158 # mpp (Musepack)
2159 MPPENC=mppenc
2160
2161 ID3=id3
2162 ID3V2=id3v2
2163 CDPARANOIA=cdparanoia
2164 CDDA2WAV=cdda2wav
2165 DAGRAB=dagrab
2166 CDDAFS=cp
2167 CDDISCID=cd-discid
2168 CDDBTOOL=cddb-tool
2169 EJECT=eject
2170 MD5SUM=md5sum
2171 DISTMP3=distmp3
2172 VORBISCOMMENT=vorbiscomment
2173 METAFLAC=metaflac
2174 NORMALIZE=normalize-audio
2175 CDSPEED=eject
2176 VORBISGAIN=vorbisgain
2177 MKCUE=mkcue
2178 MKTOC=cdrdao
2179 DIFF=diff
2180
2181 # Options for programs called from abcde
2182 # mp3
2183 LAMEOPTS=
2184 GOGOOPTS=
2185 BLADEENCOPTS=
2186 L3ENCOPTS=
2187 XINGMP3ENCOPTS=
2188 MP3ENCOPTS=
2189 # ogg
2190 VORBIZEOPTS=
2191 OGGENCOPTS=
2192 # flac
2193 FLACOPTS="-f"
2194 # speex
2195 SPEEXENCOPTS=
2196 # mpc
2197 MPPENCOPTS=
2198
2199 ID3OPTS=
2200 ID3V2OPTS=
2201 CDPARANOIAOPTS=
2202 CDDA2WAVOPTS=
2203 DAGRABOPTS=
2204 CDDAFSOPTS="-f"
2205 CDDBTOOLOPTS=
2206 EJECTOPTS=
2207 DISTMP3OPTS=
2208 NORMALIZEOPTS=
2209 CDSPEEDOPTS="-x"
2210 CDSPEEDVALUE=
2211 MKCUEOPTS=
2212 MKTOCOPTS=""
2213 VORBISCOMMENTOPTS="-R"
2214 METAFLACOPTS="--no-utf8-convert"
2215
2216 # Default to one process if -j isn't specified
2217 MAXPROCS=1
2218
2219 # List of actions to perform - by default, run to completion
2220 ACTIONS=cddb,read,encode,tag,move,clean
2221
2222 # List of prefered outputs - by default, run with whatever we have in the path
2223 # This option is basicaly for Debian package dependencies
2224 DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:lame,mp3:bladeenc,spx:speex
2225
2226 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
2227 # Let's use these checkings to determine the OS flavour, which will be used later
2228 if [ X$(uname) = "XFreeBSD" ] ; then
2229         HTTPGET=fetch
2230         NEEDCDROMID=y
2231         OSFLAVOUR=FBSD
2232 elif [ X$(uname) = "XDarwin" ] ; then
2233         HTTPGET=curl
2234         OSFLAVOUR=OSX
2235         # We should have disktool in OSX, but let's be sure...
2236         NEEDDISKTOOL=y
2237         CDROMREADERSYNTAX=cddafs
2238 elif [ X$(uname) = "XOpenBSD" ] ; then
2239         HTTPGET=wget
2240         MD5SUM=md5
2241 else
2242         HTTPGET=wget
2243 fi
2244
2245 # If CDDBAVAIL is set to n, no CDDB read is done
2246 # If USEID3 is set to n, no ID3 tagging is done
2247 CDDBAVAIL=y
2248 USEID3=y
2249 USEID3V2=y
2250
2251 if [ -z "$OUTPUTDIR" ]; then
2252         OUTPUTDIR=$(pwd)
2253 fi
2254
2255 if [ -z "$WAVOUTPUTDIR" ]; then
2256         WAVOUTPUTDIR="$OUTPUTDIR"
2257 fi
2258
2259 # Load system defaults
2260 if [ -r /etc/abcde.conf ]; then
2261         . /etc/abcde.conf
2262 fi
2263 # Load user preference defaults
2264 if [ -r $HOME/.abcde.conf ]; then
2265         . $HOME/.abcde.conf
2266 fi
2267
2268 # By this time, we need some HTTPGETOPTS already defined.
2269 # If the user has defined a non-default HTTPGET method, we should not be empty.
2270
2271 if [ "$HTTPGETOPTS" = "" ] ; then
2272         case $HTTPGET in
2273                 wget) HTTPGETOPTS="-q -O -";;
2274                 curl) HTTPGETOPTS="-f -s";;
2275                 fetch)HTTPGETOPTS="-q -o -";;
2276                 *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
2277         esac
2278 fi
2279
2280 # If the CDROM has not been set yet, find a suitable one.
2281 # If this is a devfs system, default to /dev/cdroms/cdrom0
2282 # instead of /dev/cdrom
2283 if [ "$CDROM" = "" ] ; then
2284         if [ -e /dev/cdroms/cdrom0 ]; then
2285                 CDROM=/dev/cdroms/cdrom0
2286         elif [ -e /dev/cdrom ]; then
2287                 CDROM=/dev/cdrom
2288         elif [ -e /dev/cd0c ]; then
2289                 CDROM=/dev/cd0c
2290         elif [ -e /dev/acd0c ]; then
2291                 CDROM=/dev/acd0c
2292         elif [ -e /dev/disk1 ]; then
2293                 CDROM=/dev/disk1
2294         fi
2295 fi
2296
2297 # Parse command line options
2298 #while getopts 1a:A:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
2299 while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
2300         case "$opt" in
2301                 1) ONETRACK=y ;;
2302                 a) ACTIONS="$OPTARG" ;;
2303                 A) EXPACTIONS="$OPTARG";;
2304                 b) BATCH=y ;;
2305                 c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
2306                 C) DISCID="${OPTARG#abcde.}" ;;
2307                 d) CDROM="$OPTARG" ;;
2308                 D) set -x ;;
2309                 e) ERASEENCODEDSTATUS=y ;;
2310                 h) usage; exit ;;
2311                 e) ERASEENCODEDSTATUS=y ;;
2312 #               f) FORCECDDBUSELOCAL=y ;;
2313                 i) INLINETAG=y ;;
2314                 j) MAXPROCS="$OPTARG" ;;
2315                 k) KEEPWAVS=y ;;
2316                 l) LOWDISK=y ;;
2317                 L) CDDBUSELOCAL=y ;;
2318                 n) CDDBAVAIL=n ;;
2319                 N) INTERACTIVE=n ;;
2320                 m) DOSPLAYLIST=y ;;
2321                 M) MAKECUEFILE=y ;;
2322                 o) OUTPUTTYPE="$OPTARG" ;;
2323                 p) PADTRACKS=y ;;
2324                 P) USEPIPES=y ;;
2325                 r) REMOTEHOSTS="$OPTARG" ;;
2326                 R) REPLAYGAIN=y ;;
2327                 s) SHOWCDDBFIELDS="$OPTARG" ;;
2328                 S) CDSPEEDVALUE="$OPTARG" ;;
2329 #               t) PREPROCESSFORMATS="$OPTARG"
2330 #                  PREPROCESS=y ;;
2331 #               T) POSTPROCESSFORMATS="$OPTARG" ;;
2332                 t) STARTTRACKNUMBER="$OPTARG" ;;
2333                 T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
2334                 v) 
2335                    echo "This is abcde v$VERSION."
2336                    echo "Usage: abcde [options] [tracks]"
2337                    echo "abcde -h for extra help"
2338                    exit
2339                    ;;
2340                 V) EXTRAVERBOSE="y" ;;
2341                 x) EJECTCD="y" ;;
2342                 w) COMMENT="$OPTARG" ;;
2343                 W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
2344                      STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
2345                    else
2346                      echo "abcde error: argument of -W must be integer"
2347                          exit 1
2348                    fi
2349                    ;;
2350                 ?) usage; exit ;;
2351         esac
2352 done
2353
2354 shift $(($OPTIND - 1))
2355
2356 # Decide if we can continue.
2357 if [ "$ONETRACK" = "y" ]; then 
2358         # FIXME # remove check as soon as we find out about the other readers
2359         case "$CDROMREADERSYNTAX" in
2360                 cdparanoia) ;;
2361                 cdda2wav) ;;
2362                 *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
2363                    exit 1 ;;
2364         esac
2365         if [ "$BATCH" = "y" ]; then
2366                 echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
2367                 BATCH=n
2368         fi
2369         # It does not matter how many tracks we want. In ONETRACK mode we grab them all
2370         # FIXME # allow ranges of tracks to be selected for onetrack ripping
2371         if [ $# -gt 0 ]; then
2372                 vecho "abcde warning: ONETRACK mode selected, grabbing all tracks..."
2373         fi
2374 else
2375         while [ $# -gt 0 ]; do
2376                 # Range parsing code courtesy of Vincent Ho
2377                 RSTART=$(echo $1 | cut -f1 -d-)
2378                 REND=$(echo $1 | cut -f2 -d-)
2379                 if [ "$RSTART" = "$REND" ]; then
2380                         NEWTRACKS="$RSTART"
2381                 else
2382                         NEWTRACKS=$(f_seq_line $RSTART $REND)
2383                 fi
2384                 TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
2385                 shift
2386         done
2387 fi
2388
2389 # List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
2390 # List of experimental actions: retag,transcode
2391
2392 # Determine what actions are to be done from $ACTIONS and set the
2393 # following environment variables for them:
2394 DOCDDB=n
2395 DOREAD=n
2396 DONORMALIZE=n
2397 DOPREPROCESS=n
2398 DOENCODE=n
2399 DOPOSTPROCESS=n
2400 DOTAG=n
2401 DOMOVE=n
2402 DOPLAYLIST=n
2403 DOCLEAN=n
2404
2405 for ACTION in $(echo $ACTIONS | tr , \ )
2406 do
2407         case $ACTION in
2408                 cddb) DOCDDB=y;;
2409                 read) DOREAD=y;;
2410                 normalize) DONORMALIZE=y; DOREAD=y;;
2411 #               preprocess) DOPREPROCESS=y; DOREAD=y;;
2412                 encode) DOENCODE=y; DOREAD=y;;
2413 #               postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
2414                 tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
2415                 move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
2416                 playlist) DOCDDB=y; DOPLAYLIST=y;;
2417                 clean) DOCLEAN=y;;
2418         esac
2419 done
2420
2421 for SHOWCDDBFIELD in $(echo $SHOWCDDBFIELDS | tr , \ ); do
2422         case $SHOWCDDBFIELD in
2423                 y*|Y*) SHOWCDDBYEAR="y";;
2424                 g*|G*) SHOWCDDBGENRE="y";;
2425                 *) ;;
2426         esac
2427 done
2428
2429 # Sanity checks:
2430
2431 # At this point a CDROM has to be defined, so we check it exists.
2432 if [ X"$CDROM" != "X" ] ; then 
2433         if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
2434                 if [ "$OSFLAVOUR" = "FBSD" ]; then
2435                         if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
2436                                 echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
2437                                 echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
2438                                 exit 1
2439                         fi
2440                 fi
2441         elif [ ! -e "$CDROM" -a X"$DOREAD" = "Xy" ]; then
2442                 echo "abcde error: CDROM device cannot be found." >&2
2443                 exit 1
2444         fi
2445 # avoid processing if we are not going to hit the CDROM.
2446 elif [ X"$DOREAD" = "Xy" ]; then
2447         echo "abcde error: CDROM has not been defined or cannot be found" >&2
2448         exit 1
2449 fi
2450
2451 # USEPIPES pre-tests, before we get into more serious stuff
2452 # Not compatible with:
2453 # - multiple outputs
2454 # - normalize
2455 # - lowdisk algorithm
2456 # - anything else?
2457 if [ X"$USEPIPES" = "Xy" ]; then
2458         if [ $(echo "$OUTPUTTYPE" | tr , \  | wc -w ) -gt 1 ]; then
2459                 echo "abcde error: Unix pipes not compatible with multiple outputs" >&2
2460                 exit 1
2461         fi
2462         if [ X"$DONORMALIZE" = "Xy" ]; then
2463                 echo "abcde error: Unix pipes not compatible with normalizer"
2464                 # FIXME # Do we need to exit or shall we just disable the mode?
2465                 exit 1
2466         fi
2467         if [ X"$DOENCODE" = "Xn" ]; then
2468                 vecho "Disabling Unix pipes since we are not encoding!"
2469                 USEPIPES=n
2470         fi
2471         if [ X"$LOWDISK" = "Xy" ]; then
2472                 vecho "abcde error: Unix pipes not compatible with lowdisk algorithm"
2473                 exit 1
2474         fi
2475 fi
2476
2477 # Check the encoding format from the ones available in the system, if nothing has been configured in the system.
2478 if [ X"$OUTPUTTYPE" = "X" ]; then
2479         for DEFAULT_OUTPUT in $( echo "$DEFAULT_OUTPUT_BINARIES" | tr , \ ); do
2480                 DEFAULT_OUTPUT_FORMAT="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 1)"
2481                 DEFAULT_OUTPUT_BINARY="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 2)"
2482                 if [ -x $(which $DEFAULT_OUTPUT_BINARY) ] ; then
2483                         OUTPUTTYPE=$DEFAULT_OUTPUT_FORMAT
2484                         vecho "No default output type defined. Autoselecting $OUTPUTTYPE..." >&2
2485                         break
2486                 fi
2487         done
2488         if [ X"$OUTPUTTYPE" = "X" ]; then
2489                 echo "abcde error: no encoder found in the PATH" >&2
2490                 echo "hits: are all dependencies installed? has the \$PATH been modified?" >&2
2491                 exit 1
2492         fi
2493 fi
2494
2495 # Decide which CDROM reader we're gonna use
2496 case "$CDROMREADERSYNTAX" in
2497         cdparanoia|debug)
2498                 CDROMREADER="$CDPARANOIA"
2499                 CDROMREADEROPTS="$CDPARANOIAOPTS"
2500                 ;;
2501         cdda2wav)
2502                 CDROMREADER="$CDDA2WAV"
2503                 CDROMREADEROPTS="$CDDA2WAVOPTS"
2504                 ;;
2505         dagrab)
2506                 CDROMREADER="$DAGRAB"
2507                 CDROMREADEROPTS="$DAGRABOPTS"
2508                 ;;
2509         cddafs)
2510                 CDROMREADER="$CDDAFS"
2511                 CDROMREADEROPTS="$CDDAFSOPTS"
2512                 ;;
2513 esac
2514
2515 # There's only one normalize...
2516 case "$NORMALIZERSYNTAX" in
2517         default|normalize)
2518                 NORMALIZER="$NORMALIZE"
2519                 NORMALIZEROPTS="$NORMALIZEOPTS"
2520                 ;;
2521 esac
2522
2523 # Allow -o OUTPUT(1):OPTIONS(1),...,OUTPUT(N):OPTIONS(N) mode of operation
2524 if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
2525         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ ); do
2526                 case "$OUTPUT" in
2527                         vorbis:*|ogg:*) OGGENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2528                         mp3:*)  MP3ENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2529                         flac:*) FLACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2530                         spx:*)  SPEEXENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2531                         mpc:*)  MPPENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2532                 esac
2533         done
2534         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ ); do
2535                 TEMPOUTPUT=$( echo "$OUTPUT" | cut -d: -f1 )
2536                 TEMPOUTPUTTYPE="${TEMPOUTPUTTYPE:+$TEMPOUTPUTTYPE,}$TEMPOUTPUT"
2537         done
2538         OUTPUTTYPE="$TEMPOUTPUTTYPE"
2539 fi
2540
2541 # 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
2542
2543 # Getting ready for multiple output changes
2544 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
2545 do
2546         case $OUTPUT in
2547                 vorbis|ogg)
2548                         [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
2549                         [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
2550                         [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
2551                         OGGOUTPUTCONTAINER=ogg
2552                         ;;
2553                 mp3)
2554                         [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
2555                         [ "$DOTAG" = "y" ] && NEEDTAGGER=y
2556                         ;;
2557                 flac)
2558                         [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
2559                         [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
2560                         ;;
2561                 spx)
2562                         [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
2563                         ;;
2564                 mpc)
2565                         [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc
2566                         ;;
2567                 *)      echo "abcde error: Invalid OUTPUTTYPE defined" >&2
2568                         exit 1
2569                         ;;
2570         esac
2571 done
2572
2573 # decide which encoder
2574 case "$MP3ENCODERSYNTAX" in
2575         lame)
2576                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$LAMEOPTS}"
2577                 MP3ENCODER="$LAME"
2578                 ;;
2579         gogo)
2580                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$GOGOOPTS}"
2581                 MP3ENCODER="$GOGO"
2582                 ;;
2583         bladeenc)
2584                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$BLADEENCOPTS}"
2585                 MP3ENCODER="$BLADEENC"
2586                 ;;
2587         l3enc)
2588                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$L3ENCOPTS}"
2589                 MP3ENCODER="$L3ENC"
2590                 ;;
2591         xingmp3enc)
2592                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$XINGMP3ENCOPTS}"
2593                 MP3ENCODER="$XINGMP3ENC"
2594                 ;;
2595         mp3enc)
2596                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$MP3ENCOPTS}"
2597                 MP3ENCODER="$MP3ENC"
2598                 ;;
2599 esac
2600 case "$OGGENCODERSYNTAX" in
2601         vorbize)
2602                 OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$VORBIZEOPTS}"
2603                 OGGENCODER="$VORBIZE"
2604                 ;;
2605         oggenc)
2606                 OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$OGGENCOPTS}"
2607                 OGGENCODER="$OGGENC"
2608                 ;;
2609 esac
2610 case "$FLACENCODERSYNTAX" in
2611         flac)
2612                 FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
2613                 FLACENCODER="$FLAC"     
2614                 # FLAC streams can be encapsulated on a Ogg transport layer
2615                 if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
2616                         echo "abcde error: FLAC on an Ogg container is not yet supported" >&2
2617                         echo "             due to problem with adding comments to such files" >&2
2618                         exit 1
2619                         FLACOUTPUTCONTAINER=ogg
2620                 else
2621                         FLACOUTPUTCONTAINER=flac
2622                 fi
2623                 ;;
2624 esac
2625 case "$SPEEXENCODERSYNTAX" in
2626         speexenc)
2627                 SPEEXENCODEROPTS="${SPEEXENCODEROPTSCLI:-$SPEEXENCOPTS}"
2628                 SPEEXENCODER="$SPEEXENC"
2629                 ;;
2630 esac
2631 case "$MPPENCODERSYNTAX" in
2632         mppenc)
2633                 MPPENCODEROPTS="${MPPENCODEROPTSCLI:-$MPPENCOPTS}"
2634                 MPPENCODER="$MPPENC"
2635                 ;;
2636 esac
2637                 
2638 # and which tagger
2639
2640 if [ "$ID3TAGV" = "1" ]; then
2641         TAGGER="$ID3"
2642         TAGGEROPTS="$ID3OPTS"
2643 else
2644         TAGGER="$ID3V2"
2645         TAGGEROPTS="$ID3V2OPTS"
2646 fi
2647
2648 # Options for mkcue
2649 case "$CUEREADERSYNTAX" in
2650         default|mkcue)
2651                 CUEREADEROPTS="${CDROM}"
2652                 CUEREADER="$MKCUE"
2653                 ;;
2654 esac
2655
2656 # Check if both OGGEOUTPUTCONTAINER and FLACOUTPUTCONTAINER are the same, and differentiante them
2657 if [ X"$OGGOUTPUTCONTAINER" = "Xogg" ] && [ X"$FLACOUTPUTCONTAINER" = "Xogg" ]; then
2658         echo "abcde error: FLAC on an Ogg container is not yet supported" >&2
2659         echo "             due to problem with adding comments to such files" >&2
2660         exit 1
2661         OGGOUTPUTCONTAINER=ogg.ogg
2662         FLACOUTPUTCONTAINER=flac.ogg
2663         vecho "abcde warning: modified file endings due to conflicting transport layers in Ogg/Vorbis and Ogg/FLAC"
2664 fi
2665
2666 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
2667
2668 if [ "$ENCNICE" ]; then
2669         ENCNICE="-n $ENCNICE"
2670 fi
2671 if [ "$READNICE" ]; then
2672         READNICE="-n $READNICE"
2673 fi
2674 if [ "$DISTMP3NICE" ]; then
2675         DISTMP3NICE="-n $DISTMP3NICE"
2676 fi
2677
2678 # Don't check for stuff if it's not needed
2679 if [ "$REMOTEHOSTS" ]; then 
2680         NEEDDISTMP3=y
2681 fi
2682 if [ "$DONORMALIZE" = "y" ]; then
2683         NEEDNORMALIZER=y
2684 fi
2685 if [ "$EJECTCD" = "y" ]; then
2686         NEEDEJECT=y
2687 fi
2688 if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
2689         NEEDHTTPGET=y
2690 fi
2691 if [ "$MAKECUEFILE" = "y" ]; then
2692         NEEDCUEREADER=y
2693 fi
2694
2695 if [ X"$CDSPEEDVALUE" != "X" ]; then
2696         case "$CDROMREADERSYNTAX" in
2697                 cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
2698                 *) NEEDCDSPEED=y ;;
2699         esac
2700 fi
2701
2702 # Rippers with USEPIPE support
2703 # FIXME # Include here all the rippers we can figure out support pipes
2704 PIPE_cdparanoia="-"
2705
2706 # Encoders with USEPIPE support
2707 # FIXME # Include here all the encoders we can figure out support pipes
2708 PIPE_lame="-"
2709 PIPE_bladeenc="-"
2710 PIPE_oggenc="-"
2711
2712 # Figure out if we can use pipes with the ripper/encoder combination
2713 # exit otherwise
2714 if [ "$USEPIPES" = "y" ]; then
2715         PIPERIPPERSVARCHECK="PIPE_${CDROMREADER}"
2716         case "$OUTPUT" in
2717                 mp3)
2718                         PIPEENCODERSVARCHECK="PIPE_$MP3ENCODERSYNTAX" ;;
2719                 vorbis|ogg)
2720                         PIPEENCODERSVARCHECK="PIPE_$OGGENCODERSYNTAX" ;;
2721                 flac)
2722                         PIPEENCODERSVARCHECK="PIPE_$FLACENCODERSYNTAX" ;;
2723                 spx)
2724                         PIPEENCODERSVARCHECK="PIPE_$SPEEXENCODER" ;;
2725                 mpc)
2726                         PIPEENCODERSVARCHECK="PIPE_$MPPENCODER" ;;
2727         esac
2728         if [ ! -n "${!PIPERIPPERSVARCHECK}" ] ; then
2729                 echo "abcde error: no support for pipes with given ripper" >&2
2730                 echo "read the USEPIPES file from the source tarball to help" >&2
2731                 echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
2732                 exit 1;
2733         fi
2734         if [ ! -n "${!PIPEENCODERSVARCHECK}" ] ; then
2735                 echo "abcde error: no support for pipes with given encoder" >&2
2736                 echo "read the USEPIPES file from the source tarball to help" >&2
2737                 echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
2738                 exit 1;
2739         fi
2740 fi
2741
2742 # Make sure a buncha things exist
2743 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
2744         $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
2745         ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
2746         ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
2747         ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
2748         ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
2749         ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDCUEREADER+$CUEREADER}
2750 do
2751         # Cut off the command-line options we just added in
2752         X=$(echo $X | cut -d' ' -f2)
2753         if [ "$(which $X)" = "" ]; then
2754                 echo "abcde error: $X is not in your path." >&2
2755                 exit 1
2756         elif [ ! -x $(which $X) ]; then
2757                 echo "abcde error: $X is not executable." >&2
2758                 exit 1
2759         fi
2760 done
2761
2762 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
2763 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
2764 HTTPGET="$HTTPGET $HTTPGETOPTS"
2765
2766 # And last but not least, check if we can diff between files
2767 if [ -x $(which $DIFF) ]; then :; else
2768         vecho "[WAR] Disabling diff since we cannot find it in the \$PATH..."
2769         DIFF=""
2770 fi
2771
2772 # Here it used to say:
2773 # One thousand lines in, we can start doing stuff with things
2774 # Well, right now we are at line 2736 ;)
2775
2776 # Export needed things so they can be read in this subshell
2777 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
2778 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
2779
2780 # User-definable function to set some things. Use it for
2781 #  - closing the CD tray with eject -t
2782 #  - set the CD speed value with eject -x
2783 vecho -n "Executing customizable pre-read function... "
2784
2785 pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
2786
2787 vecho "done."
2788
2789 do_discid # Get ABCDETEMPDIR created and status file initialized
2790
2791 if [ "$DOCDDB" = "y" ]; then
2792         if [ $CDDBUSELOCAL = "y" ]; then
2793                 do_localcddb
2794         fi
2795         if checkstatus cddb-choice > /dev/null; then
2796                 :
2797         else 
2798                 if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
2799                         do_cddbstat
2800                         do_cddbquery
2801                         do_cddbread
2802                 fi
2803         fi
2804         do_cddbedit
2805
2806         eval $($CDDBTOOL parse "$CDDBDATA")
2807 fi
2808
2809 # Before reading tracks, we set the speed of the device
2810
2811 if [ X"$CDSPEEDVALUE" != "X" ]; then
2812         case "$CDROMREADERSYNTAX" in
2813                 cdparanoia|debug) : ;;
2814                 *) do_cdspeed ;;
2815         esac
2816 fi
2817
2818 # Define the first and last track, since we might need them later in several places
2819 FIRSTTRACK=$( get_first $TRACKQUEUE )
2820 LASTTRACK=$( get_last $TRACKQUEUE )
2821
2822 if [ -f "$ABCDETEMPDIR/status" ] && [ X"$ERASEENCODEDSTATUS" = "Xy" ]; then
2823         mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
2824         grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
2825                 | grep -v ^encode-output > "$ABCDETEMPDIR/status"
2826 fi
2827
2828 # Create playlist if needed (backgroundable) and start reading in tracks
2829
2830 (
2831
2832 if [ ! "$ONETRACK" = "y" ]; then
2833         if [ "$DOPLAYLIST" = "y" ]; then
2834                 echo Creating playlist... >&2
2835                 do_playlist
2836         fi
2837 fi
2838
2839 # For the lowdisk option, only one program is running at once so the encoder
2840 # can be unsilenced right away.
2841 if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
2842         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2843 fi
2844
2845 if [ "$ONETRACK" = "y" ]; then 
2846         TRACKS="$FIRSTTRACK"
2847         if checkstatus readtrack-$FIRSTTRACK; then :; else
2848                 do_cdread onetrack $FIRSTTRACK $LASTTRACK
2849         fi
2850 else
2851         for UTRACKNUM in $TRACKQUEUE
2852         do
2853                 if [ "$DOREAD" = "y" ]; then
2854                         if [ "$USEPIPES" = "y" ]; then
2855                                 if checkstatus readencodetrack-$UTRACKNUM; then :; else
2856                                         # Read, pipe, shut up!
2857                                         do_cdread $UTRACKNUM | do_encode $UTRACKNUM %local0% > /dev/null 2>&1
2858                                 fi
2859                         else
2860                                 if checkstatus readtrack-$UTRACKNUM; then :; else
2861                                         do_cdread $UTRACKNUM
2862                                 fi
2863                                 if [ "$?" != "0" ]; then
2864                                         # CD read failed - don't give the goahead to
2865                                         # the encoder
2866                                         echo NO
2867                                         exit
2868                                 fi
2869                         fi
2870                 fi
2871                 if [ "$BATCH" = "y" ]; then
2872                     :
2873                 else
2874                         echo NEXTTRACK # Get the encoder machine churning again
2875                         if [ "$DOREAD" = "y" ]; then
2876                                 if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
2877                                         until checkstatus encodetrack-$UTRACKNUM
2878                                         do
2879                                                 if checkerrors encodetrack-$UTRACKNUM; then
2880                                                         break
2881                                                 fi
2882                                                 sleep 2
2883                                         done
2884                                 fi
2885                         fi
2886                 fi
2887         done
2888 fi
2889
2890 # Now that we're done the encoding can be loud again -
2891 # if we're not using SMP.
2892 if [ "$MAXPROCS" = "1" ]; then
2893         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2894 fi
2895
2896 # All tracks read, start encoding.
2897 if [ "$BATCH" = "y" ] || [ "$ONETRACK" = "y" ]; then
2898         echo NEXTTRACK
2899 fi
2900
2901 # Execute the user-defined post_read funtion before ejecting CD
2902 post_read
2903
2904 # We are now finished with the cdrom - it can be safely ejected. Note that
2905 # abcde will not have completed yet.
2906 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
2907         # We check if the disk we are processing is actually the disk inside the 
2908         # CD tray. If not, we do not eject the CD, since it might be so that the
2909         # user ejected it manually.
2910         #CURRENTTRACKINFO=$($CDDISCID $CDROM)
2911         #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
2912         # More FreeBSD bits.
2913         if [ X"$(uname)" = X"FreeBSD" ] ; then
2914                 # FreeBSD eject uses the EJECT environment variable to name the CDROM
2915                 # but in this script EJECT is in the envionment and names the program
2916                 eject=$EJECT
2917                 unset EJECT
2918                 # The FreeBSD eject needs "adc0" not "/dev/adc0c"
2919                 cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
2920                 $eject $EJECTOPTS $cd
2921         elif [ X"$(uname)" = X"Darwin" ] ; then
2922                 disktool -e ${CDROM#/dev/} 0
2923         else
2924                 $EJECT $EJECTOPTS $CDROM
2925         fi
2926         #fi
2927 fi
2928
2929 ) | (
2930
2931 ## Do we need to pre-process 
2932 #if [ x"$PREPROCESS" = "x" ] ; then
2933 #       cat
2934 #else
2935 #       for PRETRACKNUM in $TRACKQUEUE
2936 #       do
2937 #               read GOAHEAD
2938 #               if [ "$GOAHEAD" = "NO" ]; then break; fi
2939 #               PREPROCEED=
2940 #               until [ $PREPROCEED ]
2941 #               do
2942 #                       if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
2943 #                       # all locations are working, wait and try again later
2944 #                       if [ ! $PREPROCEED ]; then sleep 3; fi
2945 #               done
2946 #               ( do_preprocess $PRETRACKNUM 
2947 #               echo "NEXTTRACK"
2948 #               ) &
2949 #       done
2950 #fi
2951 #
2952 #) | (
2953
2954 # In batch mode, we want all tracks to be read first.
2955 if [ "$BATCH" = "y" ]; then
2956         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2957         if [ "$GOAHEAD" = "NO" ]; then break; fi
2958         for LASTTRACK in $TRACKQUEUE; do :; done
2959         if checkstatus readtrack-$LASTTRACK; then
2960                 if [ "$DONORMALIZE" = "y" ]; then
2961                         if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
2962                         if checkerrors batch-normalize; then exit; fi
2963                 fi
2964                 if [ "$DOENCODE" = "y" ]; then
2965                         if checkstatus encodetrack-$LASTTRACK; then :; else do_batch_encode; fi
2966                         if checkerrors batch-encode; then exit; fi
2967                 fi
2968         fi
2969 fi
2970
2971 # If we are using ONETRACK, we can proceed with the normal encoding using just the $FIRSTTRACK as TRACKQUEUE
2972 if [ "$ONETRACK" = "y" ] ; then
2973         TRACKQUEUE="$FIRSTTRACK"
2974         TRACKS="$FIRSTTRACK"
2975 fi
2976
2977 # Do the encoding, including parallelization of remote encoding
2978 # Figure out where each track is going to be encoded
2979 ENCODELOCATIONS="$(echo $REMOTEHOSTS | tr , ' ')"
2980 if [ "$MAXPROCS" != "0" ]; then
2981         for NUM in $(f_seq_row 1 "$MAXPROCS")
2982         do
2983                 ENCODELOCATIONS="$ENCODELOCATIONS %local$NUM%"
2984         done
2985 fi
2986 # Strip whitespace
2987 ENCODELOCATIONS=$(echo $ENCODELOCATIONS)
2988 for UTRACKNUM in $TRACKQUEUE
2989 do
2990         # Wait for our cue
2991         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2992         if [ "$GOAHEAD" = "NO" ]; then break; fi
2993         # find out where this track is to be encoded
2994         if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
2995                 # Make sure we have a place to encode this, if not, exit stage right
2996                 if [ -z "$ENCODELOCATIONS" ]; then
2997                         continue
2998                 fi
2999                 PROCEED=
3000                 until [ $PROCEED ]
3001                 do
3002                         for LOCATION in $ENCODELOCATIONS
3003                         do
3004                                 PREVIOUSTRACK="$(checkstatus encodetracklocation-$LOCATION)"
3005                                 # check first if a track has ever been assigned to this location
3006                                 if [ -z "$PREVIOUSTRACK" ]; then PROCEED=y; break; fi
3007                                 # If it errored out, rebuild $ENCODELOCATIONS without this location in it
3008                                 if checkerrors encodetrack-$PREVIOUSTRACK; then
3009                                         for TEMPLOCATION in $ENCODELOCATIONS
3010                                         do
3011                                                 if [ "$TEMPLOCATION" != "$LOCATION" ]; then
3012                                                         TEMPENCODELOCATIONS="$TEMPENCODELOCATIONS $TEMPLOCATION"
3013                                                 fi
3014                                         done
3015                                         ENCODELOCATIONS=$(echo $TEMPENCODELOCATIONS)
3016                                         ABORT=y
3017                                         PROCEED=y
3018                                         break
3019                                 fi
3020                                 # We're still here, this location must have been previously assigned,
3021                                 # and last completed without error - check if it's done with the
3022                                 # previous track yet
3023                                 if checkstatus encodetrack-$PREVIOUSTRACK; then PROCEED=y; break; fi
3024                         done
3025                         # all locations are working, wait and try again later
3026                         if [ ! $PROCEED ]; then sleep 3; fi
3027                 done
3028                 # Record the location we're about to encode the next track at
3029                 echo "encodetracklocation-$LOCATION=$UTRACKNUM" >> "$ABCDETEMPDIR/status"
3030         fi
3031         # Don't proceed with the rest of the loop if we can't encode
3032         if [ "$ABORT" ]; then continue; fi
3033         # Set TRACKNUM, TRACKNAME
3034         if [ -e "$CDDBDATA" ]; then
3035                 if [ "$ONETRACK" = "y" ]; then 
3036                         TRACKNAME="$DALBUM"
3037                         TRACKNUM="$FIRSTTRACK"
3038                         splitvarious
3039                 else
3040 #                       TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
3041                         TRACKNUM=$UTRACKNUM
3042                         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
3043                         TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
3044                         splitvarious
3045                 fi
3046         fi
3047         # You can't encode a file which needs to be normalized before finishing
3048         # You can't tag a file before it's finished encoding -
3049         # thus all of this is backgrounded together
3050         (
3051         if [ "$DONORMALIZE" = "y" ]; then
3052                 if checkstatus readtrack-$UTRACKNUM; then
3053                         if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
3054                 fi
3055         fi
3056         if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
3057                 if checkstatus readtrack-$UTRACKNUM; then
3058                         #if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION; fi
3059                         if [ "$DONORMALIZE" = "y" ]; then
3060                                 if checkstatus normalizetrack-$UTRACKNUM; then
3061                                         if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
3062                                 fi
3063                         else
3064                                 if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
3065                         fi
3066                 fi
3067         fi
3068         if [ "$DOTAG" = "y" ]; then
3069                 if checkstatus encodetrack-$UTRACKNUM; then
3070                         if checkstatus tagtrack-$UTRACKNUM; then :; else do_tag $UTRACKNUM; fi
3071                 fi
3072                 # Lets tag the cue file
3073                 if checkstatus cleancuefile >/dev/null; then :; else
3074                         if checkstatus cuefile >/dev/null ; then 
3075                                 do_cleancue
3076                         fi
3077                 fi
3078         fi
3079         if [ "$DOMOVE" = "y" ]; then
3080                 if checkstatus tagtrack-$UTRACKNUM; then
3081                         if checkstatus movetrack-$UTRACKNUM; then :; else do_move $UTRACKNUM; fi
3082                 fi
3083         fi
3084         ) &
3085 done
3086
3087
3088 # Go through it again and make sure there's no distmp3 stragglers, otherwise
3089 # we'll delete the files they're working on
3090 ## FIXME ## Check also for files which are encoded using PIPEs.
3091 if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
3092         PROCEED=
3093         until [ $PROCEED ]
3094         do
3095                 PROCEED=y
3096                 for LOCATION in $ENCODELOCATIONS
3097                 do
3098                         CHECKTRACK="$(checkstatus encodetracklocation-$LOCATION)"
3099                         # "How can he give us a status update, if he's DEAD?"
3100                         if checkstatus encodetrack-$CHECKTRACK; then
3101                                 continue
3102                         fi
3103                         # Nothing to see here please go quietly back to your homes
3104                         if [ -z "$CHECKTRACK" ]; then continue; fi
3105                         # You're still here? Maybe there is something...
3106                         if checkstatus encodetrack-$CHECKTRACK; then :; else PROCEED= ; break; fi
3107                 done
3108                 # hold up
3109                 if [ ! $PROCEED ]; then sleep 5; fi
3110         done
3111 fi
3112 # If the above didn't catch the stragglers, this will
3113 wait
3114 # Check to see if run_command logged any errors
3115 if [ -f "$ABCDETEMPDIR/errors" ]; then
3116         echo "The following commands failed to run:"
3117         cat "$ABCDETEMPDIR/errors"
3118         # Don't clean up
3119         DOCLEAN=n
3120 fi
3121 if [ "$KEEPWAVS" = "y" ];then
3122         # Don't clean up
3123         DOCLEAN=n
3124 fi
3125 if [ "$DOCLEAN" = "y" ]; then
3126         # Wipe all the evidence
3127         # Gimme gimme gimme some more time!
3128         sleep 5
3129         rm -rf "$ABCDETEMPDIR"
3130         echo "Finished."
3131 else
3132         echo "Finished. Not cleaning $ABCDETEMPDIR."
3133 fi
3134 )
3135 exit 0
3136
3137 # b:is_bash
3138 # vim:tabstop=4