bd8ead59dbb5aad354148b9510910f228efddb65
[abcde.git] / abcde
1 #!/bin/sh
2 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
3 # Copyright (c) 2003-2004 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.2.0"
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 "-h     This help information"
34 #echo "-i    Tag files while encoding, when possible (local only) -NWY-"
35 echo "-j <#> Number of encoder processes to run at once (localhost)"
36 echo "-k     Keep the wav tracks for later use"
37 echo "-l     Use low disk space algorithm"
38 echo "-L     Use local CDDB storage directory"
39 echo "-n     No lookup. Don't query CDDB, just create and use template"
40 echo "-N     Noninteractive. Never prompt for anything"
41 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
42 echo "-o <type1[,type2]...>"
43 echo "       Output file type(s) (ogg,mp3,flac,spx,mpc). Defaults to ogg"
44 echo "-p     Pad track numbers with 0's (if less than 10 tracks)"
45 #echo "-P    Use UNIX pipes to read+encode without wav files"
46 echo "-r <host1[,host2]...>"
47 echo "       Also encode on these remote hosts"
48 echo "-R     Add replaygain values to the tag info (only for ogg,flac)"
49 echo "-S <#> Set the CD speed"
50 #echo "-t    File types to preprocess (wav)"
51 #echo "-T    Set postprocessing options"
52 echo "-t <#> Start the track numbering at a given number"
53 echo "-T <#> Same as -t but modifies tag numbering"
54 echo "-v     Show version number and exit"
55 echo "-V     Be a bit more verbose about what is happening behind the scenes"
56 echo "-x     Eject CD after all tracks are read"
57 echo "-w <comment>"
58 echo "       Add a comment to the CD tracks"
59 echo "-W <#> Contatenate CDs: -T #01 -w \"CD #\"" 
60 echo ""
61 echo "Tracks is a space-delimited list of tracks to grab."
62 echo "Ranges specified with hyphens are allowed."
63 }
64
65 # Funtions to replace the need of seq, which is too distribution dependant.
66 f_seq_row ()
67 {
68         i=$1
69         while [ $i -ne `expr $2 + 1` ]
70         do
71                 echo $i
72                 i=`expr $i + 1`
73         done
74 }
75
76 f_seq_line ()
77 {
78         i=$1
79         while [ $i -ne `expr $2 + 1` ]
80         do
81                 printf $i" "
82                 i=`expr $i + 1`
83         done
84         echo
85 }
86
87 # checkstatus [blurb]
88 # Returns "0" if the blurb was found, returns 1 if it wasn't
89 # Puts the blurb content, if available, on stdout.
90 # Otherwise, returns "".
91 checkstatus ()
92 {
93         # Take the last line in the status file if there's multiple matches
94         PATTERN="^$1(=.*)?$"
95         BLURB=$(egrep $PATTERN "$ABCDETEMPDIR/status" | tail -n 1)
96
97         if [ -z "$BLURB" ]; then
98                 # No matches found
99                 return 1
100         else
101                 # Matches found
102                 # See if there's a = in it
103                 if [ "$(echo $BLURB | grep -c =)" != "0" ]; then
104                         echo "$(echo $BLURB | cut -f2- -d=)"
105                 fi
106                 return 0
107         fi
108 }
109
110 # checkerrors [blurb]
111 # Returns "0" if the blurb was found (meaning there was an error),
112 # returns 1 if it wasn't (yes this is a little backwards).
113 # Does not print the blurb on stdout.
114 # Otherwise, returns "".
115 checkerrors ()
116 {
117         if [ -e "$ABCDETEMPDIR/errors" ]; then :; else
118                 return 1
119         fi
120         # Take the last line in the status file if there's multiple matches
121         PATTERN="^$1(:.*)?$"
122         BLURB="$(egrep $PATTERN $ABCDETEMPDIR/errors | tail -n 1)"
123
124         if [ -z "$BLURB" ]; then
125                 # negative, we did not have a negative...
126                 return 1
127         else
128                 # affirmative, we had a negative...
129                 return 0
130         fi
131 }
132
133 # run_command [blurb] [command...]
134 # Runs a command, silently if necessary, and updates the status file
135 run_command ()
136 {
137         BLURB="$1"
138         shift
139         # See if this is supposed to be silent
140         if [ "$(checkstatus encode-output)" = "loud" ]; then
141                 "$@" >&2
142                 RETURN=$?
143         else
144                 # Special case for SMP, since
145                 # encoder output is never displayed, don't mute echos
146                 if [ -z "$BLURB" -a "$MAXPROCS" != "1" ]; then
147                         "$@" >&2
148                         RETURN=$?
149                 else
150                         "$@" >/dev/null 2>&1
151                         RETURN=$?
152                 fi
153         fi
154         case "$1" in
155         normalize)
156                 if [ "$RETURN" = "2" ]; then
157                         # File was already normalized.
158                         RETURN=0
159                 fi
160                 ;;
161         esac
162         if [ "$RETURN" != "0" ]; then
163                 # Put an error in the errors file. For various reasons we
164                 # can't capture a copy of the program's output but we can
165                 # log what we attempted to execute and the error code
166                 # returned by the program.
167                 if [ "$BLURB" ]; then
168                         TWEAK="$BLURB: "
169                 fi
170                 echo "${TWEAK}returned code $RETURN: $@" >> "$ABCDETEMPDIR/errors"
171                 return $RETURN # Do not pass go, do not update the status file
172         fi
173         if [ "$BLURB" ]; then
174                 echo $BLURB >> "$ABCDETEMPDIR/status"
175         fi
176 }
177
178 # relpath() and slash() are Copyright (c) 1999 Stuart Ballard and
179 # distributed under the terms of the GNU GPL v2 or later, at your option
180
181 # Function to determine if a word contains a slash.
182 slash ()
183 {
184         case "$1" in
185         */*) return 0;;
186         *) return 1;;
187         esac
188 }
189
190 # Function to give the relative path from one file to another.
191 # Usage: relpath fromfile tofile
192 # eg relpath music/Artist/Album.m3u music/Artist/Album/Song.mp3
193 # (the result would be Album/Song.mp3)
194 # Output is relative path to $2 from $1 on stdout
195
196 # This code has the following restrictions:
197 # Multiple ////s are not collapsed into single /s, with strange effects.
198 # Absolute paths and ../s are handled wrong in FR (but they work in TO)
199 # If FR is a directory it must have a trailing /
200
201 relpath ()
202 {
203         FR="$1"
204         TO="$2"
205
206         case "$TO" in
207         /*) ;; # No processing is needed for absolute paths
208         *)
209                 # Loop through common prefixes, ignoring them.
210                 while slash "$FR" && [ "$(echo "$FR" | cut -d/ -f1)" = "$(echo "$TO" | cut -d/ -f1)" ]
211                 do
212                         FR="$(echo "$FR" | cut -d/ -f2-)"
213                         TO="$(echo "$TO" | cut -d/ -f2-)"
214                 done
215                 # Loop through directory portions left in FR, adding appropriate ../s.
216                 while slash "$FR"
217                 do
218                         FR="$(echo "$FR" | cut -d/ -f2-)"
219                         TO="../$TO"
220                 done
221         esac
222
223         echo $TO
224 }
225
226 # This code splits the a Various Artist track name from one of the following
227 # forms:
228 #
229 #  forward:        Artist / Track
230 #  forward-dash:   Artist - Track
231 #  reverse:        Track / Artist
232 #  reverse-dash:   Track - Artist
233 #  colon:          Artist: Track
234 #  trailing-paren: Artist (Track)
235 #
236 # variables used:
237 # VARIOUSARTISTS, VARIOUSARTISTSTYLE, TRACKNAME, TRACKARTIST
238 splitvarious ()
239 {
240         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
241                 case "$VARIOUSARTISTSTYLE" in
242                 forward)
243                         DTITLEARTIST="$(echo $TRACKNAME | sed 's- / -~-g')"
244                         TRACKARTIST="$(echo $DTITLEARTIST | cut -f1 -d~)"
245                         TRACKNAME="$(echo $DTITLEARTIST | cut -f2 -d~)"
246                         ;;
247                 forward-dash)
248                         DTITLEARTIST="$(echo $TRACKNAME | sed 's, - ,~,g')"
249                         TRACKARTIST="$(echo $DTITLEARTIST | cut -f1 -d~)"
250                         TRACKNAME="$(echo $DTITLEARTIST | cut -f2 -d~)"
251                         ;;
252                 reverse)
253                         DTITLEARTIST="$(echo $TRACKNAME | sed 's- / -~-g')"
254                         TRACKARTIST="$(echo $DTITLEARTIST | cut -f2 -d~)"
255                         TRACKNAME="$(echo $DTITLEARTIST | cut -f1 -d~)"
256                         ;;
257                 reverse-dash)
258                         DTITLEARTIST="$(echo $TRACKNAME | sed 's, - ,~,g')"
259                         TRACKARTIST="$(echo $DTITLEARTIST | cut -f2 -d~)"
260                         TRACKNAME="$(echo $DTITLEARTIST | cut -f1 -d~)"
261                         ;;
262                 colon)
263                         DTITLEARTIST="$(echo $TRACKNAME | sed 's-: -~-g')"
264                         TRACKARTIST="$(echo $DTITLEARTIST | cut -f1 -d~)"
265                         TRACKNAME="$(echo $DTITLEARTIST | cut -f2 -d~)"
266                         ;;
267                 trailing-paren)
268                         DTITLEARTIST="$(echo $TRACKNAME | sed 's,^\(.*\) (\(.*\)),\1~\2,')"
269                         TRACKARTIST="$(echo $DTITLEARTIST | cut -f2 -d~)"
270                         TRACKNAME="$(echo $DTITLEARTIST | cut -f1 -d~)"
271                         ;;
272                 esac
273         elif [ "$ONETRACK" = "y" ]; then
274                 TRACKARTIST="Various"
275         else
276                 TRACKARTIST=$DARTIST
277         fi
278 }
279
280 # do_tag [tracknumber]
281 # id3 tags a filename
282 # variables used:
283 # TRACKS, TRACKNAME, TRACKARTIST, TAGGER, TAGGEROPTS, VORBISCOMMENT, METAFLAC, 
284 # COMMENT, DALBUM, DARTIST, CDYEAR, CDGENRE (and temporarily) ID3TAGV
285 do_tag ()
286 {
287         COMMENTOUTPUT="$(eval echo ${COMMENT})"
288         run_command '' echo "Tagging track $1 of $TRACKS: $TRACKNAME..."
289         # If we want to start the tracks with a given number, we need to modify the
290         # TRACKNUM value before evaluation
291         if [ -n "$STARTTRACKNUMBER" -a -n "$STARTTRACKNUMBERTAG" ] ; then
292                 # Get the trackpadding from the current track
293                 CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
294                 TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - 1 ))
295         fi
296         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
297         do
298         case "$OUTPUT" in
299         mp3)
300                 # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
301                 run_command tagtrack-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
302                         -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
303                         -g "$CDGENRE" -T "$1/$TRACKS" "$ABCDETEMPDIR/track$1.$OUTPUT"
304                 ;;
305         ogg)
306                 case "$OGGENCODERSYNTAX" in
307                         vorbize|oggenc)
308                                 # vorbiscomment can't do in-place modification, mv the file first
309                                 if [ -f "$ABCDETEMPDIR/track$1.$OUTPUT" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" ]; then
310                                         mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT"
311                                 fi
312                                 (
313                                 # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
314                                 echo ARTIST=$TRACKARTIST
315                                 echo ALBUM="$DALBUM"
316                                 echo TITLE=$TRACKNAME
317                                 if [ -n "$CDYEAR" ]; then
318                                         echo DATE="$CDYEAR"
319                                 fi
320                                 if [ -n "$CDGENRE" ]; then
321                                         echo GENRE="$CDGENRE"
322                                 fi      
323                                 echo TRACKNUMBER=$1
324                                 echo CDDB=$CDDBDISCID
325                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
326                                         case "$COMMENTOUTPUT" in
327                                                 *=*) echo "$COMMENTOUTPUT";;
328                                                 *)   echo COMMENT="$COMMENTOUTPUT";;
329                                         esac    
330                                 fi
331                                 ) | run_command tagtrack-$1 $VORBISCOMMENT -w \
332                                         "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" "$ABCDETEMPDIR/track$1.$OUTPUT"
333                                 # Doublecheck that the commented file was created successfully before wiping the original
334                                 if [ -f "$ABCDETEMPDIR/track$1.$OUTPUT" ]; then
335                                         rm -f "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT"
336                                 else
337                                         mv "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" "$ABCDETEMPDIR/track$1.$OUTPUT"
338                                 fi
339                                 ;;
340                 esac
341                 ;;
342         flac)
343                 (
344                 echo ARTIST="$TRACKARTIST"
345                 echo ALBUM="$DALBUM"
346                 echo TITLE="$TRACKNAME"
347                 if [ -n "$CDYEAR" ]; then
348                         echo DATE="$CDYEAR"
349                 fi
350                 if [ -n "$CDGENRE" ]; then
351                         echo GENRE="$CDGENRE"
352                 fi      
353                 echo TRACKNUMBER=${TRACKNUM:-$1}
354                 echo CDDB=$CDDBDISCID
355                 if [ "$(eval echo ${COMMENT})" != "" ]; then
356                         case "$COMMENTOUTPUT" in
357                                 *=*) echo "$COMMENTOUTPUT";;
358                                 *)   echo COMMENT="$COMMENTOUTPUT";;
359                         esac    
360                 fi
361                 ) | run_command tagtrack-$1 $METAFLAC --import-vc-from=- --no-utf8-convert "$ABCDETEMPDIR/track$1.$OUTPUT"
362                 ;;
363         spx)
364                 run_command tagtrack-$1 true
365                 ;;
366         mpc)
367                 run_command tagtrack-$1 true
368                 ;;
369         esac
370         done
371 }
372
373 # do_batch_encode
374 # variables used:
375 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
376 do_batch_encode ()
377 {
378         # The commands here don't go through run_command because they're never supposed to be silenced
379         echo "Batch encoding tracks: $TRACKQUEUE"
380         OUTPUT=$(echo $OUTPUTTYPE | grep "mp3" )
381         case "$OUTPUT" in
382         mp3)
383                 case "$MP3ENCODERSYNTAX" in
384                 lame)
385                         (
386                         cd "$ABCDETEMPDIR"
387                         TRACKFILES=
388                         for UTRACKNUM in $TRACKQUEUE
389                         do
390                                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
391                         done
392                         nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
393                         RETURN=$?
394                         if [ "$RETURN" != "0" ]; then
395                                 echo "batch-encode: $ENCODER returned code $RETURN" >> errors
396                         else
397                                 for UTRACKNUM in $TRACKQUEUE
398                                 do
399                                         echo encodetrack-$UTRACKNUM >> status
400                                 done
401                         fi
402                         )
403                         ;;
404                 esac
405                 ;;
406         esac
407         # Other encoders fall through to normal encoding as the tracks
408         # have not been entered in the status file.
409 }
410
411 # do_encode [tracknumber] [hostname]
412 # If no hostname is specified, encode locally
413 # variables used:
414 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
415 do_encode ()
416 {
417         IN="$ABCDETEMPDIR/track$1.wav"
418         # We need IN to proceed.
419         if [ -s "$IN" ] ; then
420                 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
421                 do
422                         OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
423                         run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
424                         case "$OUTPUT" in
425                         mp3)
426                                 case "$2" in
427                                 %local*%)
428                                         case "$MP3ENCODERSYNTAX" in
429                                         lame|gogo) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
430                                         bladeenc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
431                                         l3enc|xingmp3enc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
432                                         mp3enc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
433                                         esac
434                                         ;;
435                                 *)
436                                         run_command encodetrack-$OUTPUT-$1 nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
437                                         ;;
438                                 esac
439                                 ;;
440                         ogg)
441                                 case "$2" in
442                                 %local*%)
443                                         case "$OGGENCODERSYNTAX" in
444                                         vorbize) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
445                                         oggenc) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
446                                         esac
447                                         ;;
448                                 *)
449                                         run_command encodetrack-$OUTPUT-$1 nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
450                                         ;;
451                                 esac
452                                 ;;
453                         flac)
454                                 case "$2" in
455                                 %local*%)
456                                         case "$FLACENCODERSYNTAX" in
457                                         flac) run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $FLACENCODER  $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
458                                         esac
459                                         ;;
460         
461                                 *)
462                                         echo -n "DISTMP3:"
463                                         echo "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
464                                         run_command encodetrack-$OUTPUT-$1 nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
465                                         ;;
466                                 esac
467                                 ;;
468                         spx)
469                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
470                                         case "$COMMENT" in
471                                                 *=*) ;;
472                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
473                                         esac    
474                                         COMMENT="--comment \"$COMMENT\""
475                                 fi
476                                 # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
477                                 if [ ! "$DOTAG" = "y" ]; then
478                                         run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
479                                 else
480                                         run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
481                                 fi
482                                 ;;
483                         mpc)    
484                                 # MPP/MP+(Musepack) format (.mpc) is done locally, with inline
485                                 # tagging.
486                                 # I tried compiling the mppenc from corecodecs.org and got some
487                                 # errors, so I have not tried it myself.
488                                 ## FIXME ## Needs some cleanup to determine if an empty tag sent
489                                 ## FIXME ## to the encoder ends up empty.
490                                 run_command encodetrack-$OUTPUT-$1 nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
491                                 ;;
492                         esac
493                 done
494                 # Only remove .wav if the encoding succeeded
495                 if checkerrors "encodetrack-(.{3,4})-$1"; then 
496                         run_command encodetrack-$1 false
497                 else
498                         run_command encodetrack-$1 true
499                         if [ ! "$KEEPWAVS" = "y" ] ; then
500                                 rm -f "$IN"
501                         fi
502                 fi
503         else
504                 if [ "$(checkstatus encode-output)" = "loud" ]; then
505                         echo "HEH! The file we were about to encode disappeared:"
506                         echo ">> $IN"
507                 fi
508                 run_command encodetrack-$1 false
509         fi
510 }
511
512 # do_preprocess [tracknumber]
513 # variables used:
514 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
515 #do_preprocess ()
516 #{
517 #       IN="$ABCDETEMPDIR/track$1.wav"
518 #       # We need IN to proceed.
519 #       if [ -s "$IN" ] ; then
520 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
521 #               do
522 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
523 #                       run_command '' echo "Pre-processing track $1 of $TRACKS..."
524 #                       case "$POSTPROCESSFORMAT" in
525 #                       all|wav*)
526 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
527 #                       mp3)
528 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
529 #                       ogg)
530 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
531 #                       flac)
532 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
533 #                       spx)
534 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
535 #                       esac
536 #               done
537 #               # Only remove .wav if the encoding succeeded
538 #               if checkerrors "preprocess-(.{3,4})-$1"; then 
539 #                       run_command preprocess-$1 false
540 #               else
541 #                       run_command preprocess-$1 true
542 #               fi
543 #       else
544 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
545 #                       echo "HEH! The file we were about to pre-process disappeared:"
546 #                       echo ">> $IN"
547 #               fi
548 #               run_command preprocess-$1 false
549 #       fi
550 #}
551
552
553 # do_postprocess [tracknumber]
554 # variables used:
555 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
556 #do_postprocess ()
557 #{
558 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
559 #       do
560 #               IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
561 #               # We need IN to proceed.
562 #               if [ -s "$IN" ] ; then
563 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
564 #                       run_command '' echo "Post-processing track $1 of $TRACKS..."
565 #                       case "$POSTPROCESSFORMAT" in
566 #                               mp3)
567 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
568 #                               ogg)
569 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
570 #                               flac)
571 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
572 #                               spx)
573 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
574 #                       esac
575 #                       # Only remove .wav if the encoding succeeded
576 #                       if checkerrors "postprocess-(.{3,4})-$1"; then 
577 #                               run_command postprocess-$1 false
578 #                       else
579 #                               run_command postprocess-$1 true
580 #                       fi
581 #               else
582 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
583 #                               echo "HEH! The file we were about to post-process disappeared:"
584 #                               echo ">> $IN"
585 #                       fi
586 #                       run_command postprocess-$1 false
587 #               fi
588 #       done
589 #}
590
591 # do_batch_gain
592 # variables used:
593 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
594 do_batch_gain ()
595 {
596         # The commands here don't go through run_command because they're never supposed to be silenced
597         echo "Batch analizing gain in tracks: $TRACKQUEUE"
598         (
599         cd "$ABCDETEMPDIR"
600         BLURB=
601         TRACKFILES=
602         for UTRACKNUM in $TRACKQUEUE
603         do
604                 MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
605         done
606         # XXX: Hard-coded batch option!
607         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
608         RETURN=$?
609         if [ "$RETURN" != "0" ]; then
610                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
611         else
612                 for UTRACKNUM in $TRACKQUEUE
613                 do
614                         echo normalizetrack-$UTRACKNUM >> status
615                 done
616         fi
617         )
618 }
619
620 # do_batch_normalize
621 # variables used:
622 # NORMALIZER, NORMALIZEROPTS
623 do_batch_normalize ()
624 {
625         # The commands here don't go through run_command because they're never supposed to be silenced
626         echo "Batch normalizing tracks: $TRACKQUEUE"
627         (
628         cd "$ABCDETEMPDIR"
629         BLURB=
630         TRACKFILES=
631         for UTRACKNUM in $TRACKQUEUE
632         do
633                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
634         done
635         # XXX: Hard-coded batch option!
636         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
637         RETURN=$?
638         if [ "$RETURN" != "0" ]; then
639                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
640         else
641                 for UTRACKNUM in $TRACKQUEUE
642                 do
643                         echo normalizetrack-$UTRACKNUM >> status
644                 done
645         fi
646         )
647 }
648
649 # do_normalize [tracknumber]
650 # variables used:
651 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
652 do_normalize ()
653 {
654         IN="$ABCDETEMPDIR/track$1.wav"
655         if [ -e "$IN" ] ; then
656                 run_command '' echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
657                 run_command normalizetrack-$1 $NORMALIZER $NORMALIZEROPTS "$IN"
658         else
659                 if [ "$(checkstatus encode-output)" = "loud" ]; then
660                         echo "HEH! The file we were about to normalize disappeared:"
661                         echo ">> $IN"
662                 fi
663                 run_command normalizetrack-$1 false "File $IN was not found"
664         fi
665 }
666
667 # do_move [tracknumber]
668 # Deduces the outfile from environment variables
669 # Creates directory if necessary
670 # variables used:
671 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
672 do_move ()
673 {
674         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
675         do
676                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
677                 # Munge filenames as follows:
678                 # ' ' -> '_'
679                 # '/' -> '_'
680                 # ''' -> ''
681                 # '?' -> ''
682                 # Eat control characters
683                 ALBUMFILE=$(mungefilename "$DALBUM")
684                 ARTISTFILE=$(mungefilename "$TRACKARTIST")
685                 TRACKFILE=$(mungefilename "$TRACKNAME")
686                 GENRE=$(mungegenre "$GENRE")
687                 YEAR=$(echo $CDYEAR)
688                 # If we want to start the tracks with a given number, we need to modify the
689                 # TRACKNUM value before evaluation
690                 if [ -n "$STARTTRACKNUMBER" ] ; then
691                         # Get the trackpadding from the current track
692                         CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
693                         TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - 1 ))
694                 else
695                         TRACKNUM=${UTRACKNUM}
696                 fi
697                 # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
698                 # TRACKFILE, and TRACKNUM.
699                 if [ "$VARIOUSARTISTS" = "y" ]; then
700                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
701                         else
702                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
703                 fi
704                 # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
705                 OUTPUTFILEDIR=$(dirname "$OUTPUTDIR/$OUTPUTFILE")
706                 # mkdir -p shouldn't return an error if the directory already exists
707                 mkdir -p "$OUTPUTFILEDIR"
708                 run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
709         done
710 }
711
712 # do_playlist
713 # Create the playlist if wanted
714 # Variables used:
715 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
716 # VARIOUSARTISTS, OUTPUTDIR
717 do_playlist ()
718 {
719         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
720         do
721                 # Create a playlist file for the playlist data to go into.
722                 # We used to wipe it out if it existed. Now we request permision if interactive.
723                 for LASTTRACK in $TRACKQUEUE; do :; done
724                 ALBUMFILE=$(mungefilename "$DALBUM")
725                 ARTISTFILE=$(mungefilename "$DARTIST")
726                 GENRE=$(mungegenre "$GENRE")
727                 if [ "$VARIOUSARTISTS" = "y" ] ; then
728                         PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
729                 else
730                         PLAYLISTFILE=$(eval echo $PLAYLISTFORMAT)
731                 fi
732                 FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
733                 mkdir -p "$FINALPLAYLISTDIR"
734                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
735                         #echo -n "Erase any existing playlist file? [y/n] (y): " >&2
736                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
737                         if [ "$INTERACTIVE" = "y" ]; then
738                                 while [ "$DONE" != "y" ]; do
739                                         read ERASEPLAYLIST
740                                         case $ERASEPLAYLIST in
741                                                 e|E|a|A|k|K) DONE=y ;;
742                                                 *) ;;
743                                         esac
744                                 done
745                         else
746                                 echo e >&2
747                                 ERASEPLAYLIST=e
748                         fi
749                         # Once we erase the playlist, we use append to create the new one.
750                         [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
751                 else
752                         # The playlist does not exist, so we can safelly use append to create the new list
753                         ERASEPLAYLIST=a
754                 fi
755                 if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
756                         touch "$OUTPUTDIR/$PLAYLISTFILE"
757                         for UTRACKNUM in $TRACKQUEUE
758                         do
759                                 # Shares some code with do_move since the filenames have to match
760                                 CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
761                                 TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
762                                 splitvarious
763                                 TRACKFILE=$(mungefilename "$TRACKNAME")
764                                 ARTISTFILE=$(mungefilename "$TRACKARTIST")
765                                 # If we want to start the tracks with a given number, we need to modify the
766                                 # TRACKNUM value before evaluation
767                                 if [ -n $STARTTRACKNUMBER ] ; then
768                                         # Get the trackpadding from the current track
769                                         CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
770                                         TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - 1 ))
771                                 else
772                                         TRACKNUM=${UTRACKNUM}
773                                 fi
774                                 if [ "$VARIOUSARTISTS" = "y" ]; then
775                                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
776                                 else
777                                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
778                                 fi
779                                 if [ "$VARIOUSARTISTS" = "y" ]; then
780                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
781                                                 echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
782                                         else
783                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
784                                         fi
785                                 else
786                                         if [ "$PLAYLISTDATAPREFIX" ]; then
787                                                 echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
788                                         else
789                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
790                                         fi
791                                 fi
792                         done
793                 fi
794                 ## this will convert the playlist to have CRLF line-endings, if specified
795                 ## (some hardware players insist on CRLF endings)
796                 if [ "$DOSPLAYLIST" = "y" ]; then
797                         awk '{substr("\r",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
798 #                       mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
799                         cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
800                 fi
801                 echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
802         done
803 }
804
805 # do_discid
806 # This essentially the start of things
807 do_discid ()
808 {
809         # Query the CD to get the track info, unless the user specified -C
810         # or we are using some actions which do not need the CDDB data at all
811         #if [ ! X"$EXPACTIONS" = "X" ]; then
812         #       :
813         #elif [ -z "$DISCID" ]; then
814         if [ -z "$DISCID" ]; then
815                 vecho -n "Getting CD track info... "
816                 TRACKINFO=$($CDDISCID $CDROM)
817                 # Make sure there's a CD in there by checking cd-discid's return code
818                 if [ "$?" = "1" ]; then
819                         echo "abcde error: CD could not be read. Perhaps there's no CD in the drive?" >&2
820                         exit 1
821                 fi
822                 WEHAVEACD=y
823         else
824                 TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
825         fi
826
827         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
828         # This needs to be done now because a section of the resuming code will need
829         # it later.
830
831         # get the number of digits to pad TRACKNUM with - we'll use this later
832         # a CD can only hold 99 tracks, but since we support a feature for starting
833         # numbering the tracks from a given number, we might need to set it as a
834         # variable for the user to define... or obtain it somehow.
835         if [ "$PADTRACKS" = "y" ] ; then
836                 TRACKNUMPADDING=2
837         fi
838
839         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
840         if [ -z "$TRACKQUEUE" ]; then
841                 if [ ! "$STRIPDATATRACKS" = "y" ]; then
842                         case "$CDROMREADERSYNTAX" in
843                                 cdparanoia|debug)
844                                         if [ "$WEHAVEACD" = "y" ]; then
845                                                 vecho "Querying the CD for audio tracks..."
846                                                 TRACKS=$( $CDROMREADER -Q 2>&1 | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 |  awk '{print $1}' | tr -d "." | tr '\n' ' ' )
847                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
848                                         else
849                                                 if [ -f "$ABCDETEMPDIR/status" ] && checkstatus cdparanoia-audio-tracks ; then
850                                                         TRACKS=$( cat $ABCDETEMPDIR/cdparanoia-audio-tracks )
851                                                 else
852                                                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
853                                                 fi
854                                         fi
855                                         ;;
856                                 *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
857                         esac
858                 else
859                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
860                 fi
861                 echo -n "Grabbing entire CD - tracks: "
862                 if [ ! "$PADTRACKS" = "y" ] ; then
863                         TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
864                 fi
865                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
866                 X=0
867                 while [ "$X" -ne "$TRACKS" ]
868                 do
869                         X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
870                         TRACKQUEUE=$(echo "$TRACKQUEUE" $X)
871                 done
872                 echo $TRACKQUEUE
873         else
874                 TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
875                 # User-supplied track queue.
876                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
877                 TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
878                 # Once cleaned, obtain the highest value in the trackqueue for number padding
879                 for LASTTRACK in $TRACKQUEUE; do :; done
880                 if [ ! "$PADTRACKS" = "y" ] ; then
881                         TRACKNUMPADDING=$(echo -n $LASTTRACK | wc -c | tr -d ' ')
882                 fi
883                 # Now we normalize the trackqueue
884                 for TRACK in $TRACKQUEUE ; do
885                         TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
886                         PADTRACKQUEUE=$(echo $PADTRACKQUEUE $TRACKNUM)
887                 done
888                 TRACKQUEUE=$PADTRACKQUEUE
889                 echo Grabbing tracks: "$TRACKQUEUE"
890         fi
891
892 #       for LASTTRACK in $TRACKQUEUE; do :; done
893
894         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
895
896         # We have the discid, create a temp directory after it to store all the temp
897         # info
898
899         if [ -e "$ABCDETEMPDIR" ]; then
900                 echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
901                 # It already exists, see if it's a directory
902                 if [ ! -d "$ABCDETEMPDIR" ]; then
903                         # This is a file/socket/fifo/device/etc, not a directory
904                         # Complain and exit
905                         echo >&2
906                         echo "abcde: file $ABCDETEMPDIR already exists and does not belong to abcde." >&2
907                         echo "Please investigate, remove it, and rerun abcde." >&2
908                         exit 1
909                 fi
910                 echo -n .
911                 # It's a directory, let's see if it's owned by us
912                 if [ ! -O "$ABCDETEMPDIR" ]; then
913                         # Nope, complain and exit
914                         echo >&2
915                         echo "abcde: directory $ABCDETEMPDIR already exists and is not owned by you." >&2
916                         echo "Please investigate, remove it, and rerun abcde." >&2
917                         exit 1
918                 fi
919                 echo .
920                 # See if it's populated
921                 if [ ! -f "$ABCDETEMPDIR/discid" ]; then
922                         # Wipe and start fresh
923                         echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
924                         echo -n "this directory to continue. Continue? [y/n] (n)" >&2
925                         if [ "$INTERACTIVE" = "y" ]; then
926                                 read ANSWER
927                         else
928                                 echo y >&2
929                                 ANSWER=y
930                         fi
931                         if [ "$ANSWER" != "y" ]; then
932                                 exit 1
933                         fi
934                         rm -rf "$ABCDETEMPDIR" || exit 1
935                         mkdir "$ABCDETEMPDIR"
936                         if [ "$?" -gt "0" ]; then
937                                 # Directory already exists or could not be created
938                                 echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
939                                 exit 1
940                         fi
941                 else
942                         # Everything is fine. Check for ^encodetracklocation-
943                         # and encode-output entries in the status file and
944                         # remove them. These are not relevant across sessions.
945                         if [ -f "$ABCDETEMPDIR/status" ]; then
946                                 mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
947                                 grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
948                                         | grep -v ^encode-output > "$ABCDETEMPDIR/status"
949                         fi
950                         # Remove old error messages
951                         if [ -f "$ABCDETEMPDIR/errors" ]; then
952                                 rm -f "$ABCDETEMPDIR/errors"
953                         fi
954                 fi
955         else
956                 # We are starting from scratch
957                 mkdir "$ABCDETEMPDIR"
958                 if [ "$?" -gt "0" ]; then
959                         # Directory already exists or could not be created
960                         echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
961                         exit 1
962                 fi
963                 cat /dev/null > "$ABCDETEMPDIR/status"
964         fi
965         
966         # If we got the CDPARANOIA status and it is not recorded, save it now
967         ## FIXME ## ! is non-portable
968         if [ -n "$CDPARANOIAAUDIOTRACKS" ] && ! checkstatus cdparanoia-audio-tracks; then
969                 if echo "$CDPARANOIAAUDIOTRACKS" >> "$ABCDETEMPDIR/cdparanoia-audio-tracks"; then
970                         echo "cdparanoia-audio-tracks" >> "$ABCDETEMPDIR/status"
971                 fi
972         fi
973         
974         # Create the discid file
975         echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
976 }
977
978 # do_cddbparse
979 # Parses a CDDB file and outputs the title and the track names.
980 # Variables: CDDBFILE
981 do_cddbparse ()
982 {
983         CDDBPARSEFILE="$1"
984         # List out disc title/author and contents
985         if [ "$ONETRACK" = "y" ]; then
986                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
987         fi
988         echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
989         if [ ! "$ONETRACK" = "y" ]; then
990                 for TRACK in $(f_seq_row 1 $TRACKS)
991                 do
992                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
993                 done
994         fi
995 }
996
997 # do_localcddb
998 # Check for a local CDDB file, and report success
999 do_localcddb ()
1000 {
1001         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
1002         
1003                 CDDBLOCALSUCCESS="n"
1004                 CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1005                 CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1006                 USELOCALRESP="y"
1007                 
1008                 # If the user has selected to check a local CDDB repo, we proceed with it
1009                 if [ -r "${CDDBLOCALFILE}" ]; then
1010                         # List out disc title/author and contents
1011                         do_cddbparse "${CDDBLOCALFILE}"
1012                         echo -n "Locally cached CDDB entry found, use it? [y/n] (y): "
1013                         if [ "$INTERACTIVE" = "y" ]; then
1014                                 read USELOCALRESP
1015                                 while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
1016                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1017                                         read USELOCALRESP
1018                                 done
1019                                 [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
1020                         else
1021                                 echo "y" >&2
1022                         fi
1023                         if [ "$USELOCALRESP" = "y" ]; then
1024                         #echo "Using local copy of CDDB data"
1025                                 cp "${CDDBLOCALFILE}" "$ABCDETEMPDIR/cddbread.1"
1026                                 echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
1027                                 echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
1028                                 do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
1029                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1030                                 CDDBLOCALSUCCESS="y"
1031                         else
1032                                 #echo "Not using local copy of CDDB data"
1033                                 CDDBLOCALSUCCESS="n"
1034                         fi
1035                         CDDBLOCALSUCCESS="y"
1036                 else
1037                         CDDBLOCALSUCCESS="n"
1038                 fi
1039         fi
1040 }
1041
1042 # do_cddbstat
1043 do_cddbstat ()
1044 {
1045         # Perform CDDB protocol version check if it hasn't already been done
1046         if checkstatus cddb-statcomplete; then :; else
1047                 if [ "$CDDBAVAIL" = "n" ]; then
1048                         ERRORCODE=no_query
1049                         echo 503 > "$ABCDETEMPDIR/cddbstat"
1050                 else
1051                         rc=1
1052                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1053                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1054                         while test $rc -eq 1 -a $CDDBPROTO -ge 3; do
1055                                 vecho "Checking CDDB server status..."
1056                                 $CDDBTOOL stat $CDDBURL $CDDBUSER $CDDBHOST $CDDBPROTO > "$ABCDETEMPDIR/cddbstat"
1057                                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
1058                                 case "$RESPONSECODE" in
1059                                 210)    # 210 OK, status information follows (until terminating `.')
1060                                         rc=0;
1061                                         ;;
1062                                 501|*)  # 501 Illegal CDDB protocol level: <n>. 
1063                                         CDDBPROTO=`expr $CDDBPROTO - 1`
1064                                         ;;
1065                                 esac 
1066                         done
1067                         if test $rc -eq 1; then
1068                                 CDDBAVAIL="n" 
1069                         fi
1070                 fi
1071                 echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
1072         fi
1073 }
1074
1075
1076 # do_cddbquery
1077 do_cddbquery ()
1078 {
1079         CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1080         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1081         
1082         # Perform CDDB query if it hasn't already been done
1083         if checkstatus cddb-querycomplete; then :; else
1084                 if [ "$CDDBAVAIL" = "n" ]; then
1085                         ERRORCODE=no_query
1086                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1087                 # The default CDDBLOCALSUCCESS is "n"
1088                 # This part will be triggered if the user CDDB repo does not 
1089                 # contain the entry, or if we are not trying to use the repo.
1090                 else
1091                         vecho "Querying the CDDB server..."
1092                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1093                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1094                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $TRACKINFO > "$ABCDETEMPDIR/cddbquery"
1095                         ERRORCODE=$?
1096                         case $ERRORCODE in
1097                                 0)  # success
1098                                 ;;
1099                                 12|13|14)
1100                                         # no match found in database,
1101                                         # wget/fetch error, or user requested not to use CDDB
1102                                         # Make up an error code (503) that abcde
1103                                         # will recognize in do_cddbread
1104                                         # and compensate by making a template
1105                                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1106                                 ;;
1107                                 *) # strange and unknown error
1108                                         echo ERRORCODE=$ERRORCODE
1109                                         echo "abcde: $CDDBTOOL returned unknown error code"
1110                                 ;;
1111                         esac
1112                 fi
1113                 echo cddb-querycomplete >> "$ABCDETEMPDIR/status"
1114         fi
1115 }
1116
1117 # do_cddbread
1118 do_cddbread ()
1119 {
1120         # If it's not to be used, generate a template.
1121         # Then, display it (or them) and let the user choose/edit it
1122         if checkstatus cddb-readcomplete; then :; else
1123                 vecho "Obtaining CDDB results..."
1124                 # If CDDB is to be used, interpret the query results and read all
1125                 # the available entries.
1126                 rm -f "$ABCDETEMPDIR/cddbchoices"
1127                 CDDBCHOICES=1 # Overridden by multiple matches
1128                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbquery" | cut -f1 -d' ')
1129                 case "$RESPONSECODE" in
1130                 200)
1131                         # One exact match, retrieve it
1132                         # 200 [section] [discid] [artist] / [title]
1133                         if checkstatus cddb-read-1-complete; then :; else
1134                                 echo -n "Retrieving 1 CDDB match..." >> "$ABCDETEMPDIR/cddbchoices"
1135                                 $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(cut -f2,3 -d' ' "$ABCDETEMPDIR/cddbquery") > "$ABCDETEMPDIR/cddbread.1"
1136                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
1137                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1138                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1139                         fi
1140                         # List out disc title/author and contents
1141                         echo ---- "$(cut '-d ' -f4- "$ABCDETEMPDIR/cddbquery")" ---- >> "$ABCDETEMPDIR/cddbchoices"
1142                         for TRACK in $(f_seq_row 1 $TRACKS)
1143                         do
1144                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1145                         done
1146                         echo >> "$ABCDETEMPDIR/cddbchoices"
1147                         ;;
1148                 202|403|409|503)
1149                         # No match
1150                         case "$RESPONSECODE" in
1151                         202) echo "No CDDB match." >> "$ABCDETEMPDIR/cddbchoices" ;;
1152                         403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
1153                         503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
1154                         esac
1155                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
1156                         # List out disc title/author and contents of template
1157                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
1158                         UNKNOWNDISK=y
1159                         for TRACK in $(f_seq_row 1 $TRACKS)
1160                         do
1161                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1162                         done
1163                         echo >> "$ABCDETEMPDIR/cddbchoices"
1164                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
1165                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
1166                         ;;
1167                 210|211)
1168                         # Multiple exact, (possibly multiple) inexact matches
1169                         IN=
1170                         if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
1171                         if [ "$(wc -l < $ABCDETEMPDIR/cddbquery | tr -d ' ')" -eq 3 ]; then
1172                                 echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
1173                                 tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
1174                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1175                         else
1176                                 echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
1177                         fi
1178                         vecho -n "Retrieving multiple matches... "
1179                         grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
1180                         read DISCINFO # eat top line
1181                         while read DISCINFO
1182                         do
1183                                 X=$(expr $X + 1)
1184                                 if checkstatus cddb-read-$X-complete; then :; else
1185                                         $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(echo $DISCINFO | cut -f1,2 -d' ') > "$ABCDETEMPDIR/cddbread.$X"
1186                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
1187                                 fi
1188                                 # List out disc title/author and contents
1189                                 echo \#$X: ---- "$DISCINFO" ---- >> "$ABCDETEMPDIR/cddbchoices"
1190                                 for TRACK in $(f_seq_row 1 $TRACKS)
1191                                 do
1192                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1193                                 done
1194                                 echo >> "$ABCDETEMPDIR/cddbchoices"
1195                         done )
1196                         vecho "done."
1197                         CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1198                         ;;
1199                 999)
1200                         # Using local copy.
1201                         for TRACK in $(f_seq_row 1 $TRACKS)
1202                         do
1203                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1204                         done
1205                         echo >> "$ABCDETEMPDIR/cddbchoices"
1206                         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1207                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1208                         ;;
1209                 esac    
1210                 echo "cddb-readcomplete" >> "$ABCDETEMPDIR/status"
1211         fi
1212 }
1213
1214 # do_cddbedit
1215 do_cddbedit ()
1216 {
1217         if checkstatus cddb-edit >/dev/null; then
1218                 CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1219                 VARIOUSARTISTS="$(checkstatus variousartists)"
1220                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
1221                 return 0
1222         fi
1223         if [ "$INTERACTIVE" = "y" ]; then
1224                 # We should show the CDDB results both when we are not using the local CDDB repo
1225                 # or when we are using it but we could not find a proper match
1226                 if [ "$CDDBUSELOCAL" = "y" ] && [ ! "$CDDBLOCALSUCCESS" = "y" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1227                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1228                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1229                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1230                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1231                                 CHOICE=$(checkstatus cddb-choice)
1232                                 if [ -n "$CHOICE" ] ; then
1233                                         case $CDDBCHOICES in
1234                                                 1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1235                                                 *)
1236                                                 echo "Selected: #$CHOICE"
1237                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1238                                                 ;;
1239                                         esac
1240                                 else
1241                                         # The user has a choice to make, display the info in a pager if necessary
1242                                         if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
1243                                                 # Use the debian sensible-pager wrapper to pick the pager
1244                                                 # user has requested via their $PAGER environment variable
1245                                                 if [ -x "/usr/bin/sensible-pager" ]; then
1246                                                         /usr/bin/sensible-pager "$ABCDETEMPDIR/cddbchoices"
1247                                                 elif [ -x "$PAGER" ]; then
1248                                                         # That failed, try to load the preferred editor, starting
1249                                                         # with their PAGER variable
1250                                                         $PAGER "$ABCDETEMPDIR/cddbchoices"
1251                                                         # If that fails, check for less
1252                                                 elif [ -x /usr/bin/less ]; then
1253                                                         /usr/bin/less -f "$ABCDETEMPDIR/cddbchoices"
1254                                                         # more should be on all UNIX systems
1255                                                 elif [ -x /bin/more ]; then
1256                                                         /bin/more "$ABCDETEMPDIR/cddbchoices"
1257                                                 else
1258                                                         # No bananas, just cat the thing
1259                                                         cat "$ABCDETEMPDIR/cddbchoices" >&2
1260                                                 fi
1261                                         else
1262                                                 # It's all going to fit in one page, cat it
1263                                                 cat "$ABCDETEMPDIR/cddbchoices" >&2
1264                                         fi
1265                                         
1266                                         # I'll take CDDB read #3 for $400, Alex
1267                                         echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
1268                                         read CDDBCHOICE
1269                                         # Make sure we get a valid choice
1270                                         CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1271                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
1272                                                 echo "Invalid selection. Please choose a number between 1 and $CDDBCHOICES." >&2
1273                                                 echo -n "Selection [0-$CDDBCHOICES]: " >&2
1274                                                 read CDDBCHOICE
1275                                                 CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1276                                         done
1277                                         if [ "$CDCHOICENUM" = "0" ]; then
1278                                                 vecho "Creating empty CDDB template..."
1279                                                 UNKNOWNDISK=y
1280                                                 $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > $ABCDETEMPDIR/cddbread.0
1281                                         else
1282                                                 echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
1283                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
1284                                         fi
1285                                         echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1286                                 fi
1287                         fi
1288                 else
1289                         # We need some code to show the selected option when local repository is selected and we have found a match
1290                         vecho "Using cached CDDB match..." >&2
1291                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1292                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1293                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1294                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1295                                 CHOICE=$(checkstatus cddb-choice)
1296                                 if [ "$USELOCALRESP" = "y" ]; then :; else
1297                                         if [ -n "$CHOICE" ] ; then
1298                                                 case $CDDBCHOICES in
1299                                                         0) 
1300                                                         UNKNOWNDISK=y
1301                                                         echo "Selected template."
1302                                                         ;;
1303                                                         1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1304                                                         *)
1305                                                         echo "Selected: #$CHOICE"
1306                                                         do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1307                                                         ;;
1308                                                 esac
1309                                         fi
1310                                 fi
1311                         fi
1312                 fi
1313         else
1314                 # We're noninteractive - pick the first choice.
1315                 # But in case we run a previous instance and selected a choice, use it.
1316                 if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1317                         # Show the choice if we are not using the locally stored one
1318                         # or when the local search failed to find a match.
1319                         PREVIOUSCHOICE=$(checkstatus cddb-choice)
1320                         if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSUCCESS" = "n" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1321                                 #if [ "$PREVIOUSCHOICE" ]; then
1322                                         cat "$ABCDETEMPDIR/cddbchoices"
1323                                 #fi
1324                         fi
1325                         if [ ! -z "$PREVIOUSCHOICE" ] ; then
1326                                 CDCHOICENUM=$PREVIOUSCHOICE
1327                         else
1328                                 CDCHOICENUM=1
1329                                 echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1330                         fi
1331                         echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
1332                 fi
1333         fi
1334
1335         # sanity check
1336         if checkstatus cddb-choice >/dev/null; then :; else
1337                 echo "abcde: internal error: cddb-choice not recorded." >&2
1338                 exit 1
1339         fi
1340         CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1341         echo -n "Edit selected CDDB data? [y/n] (" >&2
1342         if [ "$INTERACTIVE" = "y" ]; then
1343                 if [ "$UNKNOWNDISK" = "y" ]; then
1344                         echo -n "y): " >&2
1345                         read EDITCDDB
1346                         [ "$EDITCDDB" != "n" ] && EDITCDDB=y
1347                 else
1348                         echo -n "n): " >&2
1349                         read EDITCDDB
1350                 fi
1351         else
1352                 echo "n): n" >&2
1353                 EDITCDDB=n
1354         fi
1355         if [ "$EDITCDDB" = "y" ]; then
1356                 CDDBDATAMD5SUM=$($MD5SUM "$CDDBDATA" | cut -d " " -f 1);
1357                 
1358                 # Use the debian sensible-editor wrapper to pick the editor that the
1359                 # user has requested via their $EDITOR environment variable
1360                 if [ -x "/usr/bin/sensible-editor" ]; then
1361                         /usr/bin/sensible-editor "$CDDBDATA"
1362                 elif [ -n "$EDITOR" ]; then
1363                         if [ -x $(which "${EDITOR%%\ *}") ]; then
1364                                 # That failed, try to load the preferred editor, starting
1365                                 # with their EDITOR variable
1366                                 eval $(echo "$EDITOR") "$CDDBDATA"
1367                         fi
1368                 # If that fails, check for a vi
1369                 elif [ -x /usr/bin/vi ]; then
1370                         /usr/bin/vi "$CDDBDATA"
1371                 # nano should be on all (modern, i.e., sarge) debian systems
1372                 elif [ -x /usr/bin/nano ]; then
1373                         /usr/bin/nano "$CDDBDATA"
1374                 # mg should be on all OpenBSD systems
1375                 elif [ -x /usr/bin/mg ]; then
1376                         /usr/bin/mg "$CDDBDATA"
1377                 # bomb out
1378                 else
1379                         echo "No editor available. Check your EDITOR environment variable." >&2
1380                 fi
1381                 # delete editor backup file if it exists
1382                 if [ -w "$CDDBDATA~" ]; then
1383                         rm -f "$CDDBDATA~"
1384                 fi
1385         fi
1386
1387         # Some heuristics first. Look at Disc Title, and if it starts with
1388         # "Various", then we'll assume Various Artists
1389         if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2 -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
1390                 echo "Looks like a Multi-Artist CD" >&2
1391                 VARIOUSARTISTS=y
1392         else
1393                 echo -n "Is the CD multi-artist? [y/n] (n): " >&2
1394                 if [ "$INTERACTIVE" = "y" ]; then
1395                         read VARIOUSARTISTS
1396                 else
1397                         echo n >&2
1398                         VARIOUSARTISTS=n
1399                 fi
1400         fi
1401         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
1402                 # Set a default
1403                 DEFAULTSTYLE=1
1404                 # Need NUMTRACKS before cddb-tool will return it:
1405                 NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
1406                 if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1407                         # More than 1/2 tracks contain a "/", so guess forward
1408                         DEFAULTSTYLE=1
1409                 elif [ "$(grep -c "^TTITLE.*\-" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1410                         # More than 1/2 contain a "-", so guess forward-dash
1411                         DEFAULTSTYLE=2
1412                 elif [ "$(grep -c "^TTITLE.*(.*)" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1413                         # More than 1/2 contain something in parens, so guess trailing-paren
1414                         DEFAULTSTYLE=6
1415                 fi
1416
1417                 echo "1) Artist / Title" >&2
1418                 echo "2) Artist - Title" >&2
1419                 echo "3) Title / Artist" >&2
1420                 echo "4) Title - Artist" >&2
1421                 echo "5) Artist: Title" >&2
1422                 echo "6) Title (Artist)" >&2
1423                 echo "7) This is a single-artist CD" >&2
1424                 echo -n "Which style of multiple artist entries is it? [1-7] ($DEFAULTSTYLE): " >&2
1425                 if [ "$INTERACTIVE" = "y" ]; then
1426                         read VARIOUSARTISTSTYLE
1427                 else
1428                         echo $DEFAULTSTYLE >&2
1429                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1430                 fi
1431                 VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1432                 # If they press Enter, then the default style (0) was chosen
1433                 while [ $VARIOUSARTISTSTYLE -lt 0 ] || [ $VARIOUSARTISTSTYLE -gt 7 ]; do
1434                         echo "Invalid selection. Please choose a number between 1 and 7."
1435                         echo -n "Selection [1-7]: "
1436                         read VARIOUSARTISTSTYLE
1437                         VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1438                 done
1439                 if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
1440                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1441                 fi
1442                 vecho "Selected: $VARIOUSARTISTSTYLE"
1443                 case "$VARIOUSARTISTSTYLE" in
1444                 1) # Artist / Title
1445                         VARIOUSARTISTSTYLE=forward
1446                         ;;
1447                 2) # Artist - Title
1448                         VARIOUSARTISTSTYLE=forward-dash
1449                         ;;
1450                 3) # Title / Artist
1451                         VARIOUSARTISTSTYLE=reverse
1452                         ;;
1453                 4) # Title - Artist
1454                         VARIOUSARTISTSTYLE=reverse-dash
1455                         ;;
1456                 5) # Artist: Title
1457                         VARIOUSARTISTSTYLE=colon
1458                         ;;
1459                 6) # Title (Artist)
1460                         VARIOUSARTISTSTYLE=trailing-paren
1461                         ;;
1462                 7) # Single Artist
1463                         VARIOUSARTISTS=n
1464                         ;;
1465                 esac
1466         fi
1467
1468         echo "variousartists=$VARIOUSARTISTS" >> "$ABCDETEMPDIR/status"
1469         echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
1470
1471         if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
1472                 if [ $CDDBDATAMD5SUM != "" ]  && [ $CDDBDATAMD5SUM != $($MD5SUM "$CDDBDATA" | cut -d " " -f 1) ]; then
1473                         # This works but does not have the necessary error checking
1474                         # yet. If you are familiar with the CDDB spec
1475                         # (see http://www.freedb.org/src/latest/DBFORMAT) 
1476                         # and can create an error-free entry on your own, then put
1477                         # UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE=y in your
1478                         # abcde.conf to enable it. Put CDDBSUBMIT=email@address in
1479                         # your abcde.conf to change the email address submissions are
1480                         # sent to.
1481
1482                         # submit the modified file, if they want
1483                         if [ "$NOSUBMIT" != "y" ]; then
1484                                 echo -n "Do you want to submit this entry to $CDDBSUBMIT? [y/n] (n): "
1485                                 read YESNO
1486                                 while [ "$YESNO" != "y" ] && [ "$YESNO" != "n" ] && [ "$YESNO" != "Y" ] && \
1487                                         [ "$YESNO" != "N" ] && [ "$YESNO" != "" ]
1488                                 do
1489                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1490                                         read YESNO
1491                                 done
1492                                 if [ "$YESNO" = "y" ] || [ "$YESNO" = "Y" ]; then
1493                                         echo -n "Sending..."
1494                                         $CDDBTOOL send "$CDDBDATA" $CDDBSUBMIT
1495                                         echo "done."
1496                                 fi
1497                         fi
1498                 fi
1499         fi
1500         # Make sure the cache directory exists
1501         mkdir -p $CDDBLOCALDIR
1502         # Cache edited CDDB entry in the user's cddb dir
1503         if [ "$CDDBCOPYLOCAL" = "y" ] || [ "$COPYCDDBLOCAL" = "Y" ]; then
1504                 cat "$CDDBDATA" | tail -n $(expr $(cat "$CDDBDATA" | wc -l ) - 1 ) > ${CDDBLOCALDIR}/$(echo "$TRACKINFO" | cut -d' ' -f1)
1505         fi
1506
1507         echo "cddb-edit" >> "$ABCDETEMPDIR/status"
1508 }
1509
1510 # do_cdread_one [lasttrack] [firsttrack]
1511
1512 # Reads the CD in a single track. Live performances, concerts, mixes,... benefit from this.
1513 do_cdread_one ()
1514 {
1515         # The commands here don't go through run_command because they're never supposed to be silenced
1516         # return codes need to be doublechecked anyway, however
1517         LASTTRACKNUMBER=$1
1518         FIRSTTRACKNUMBER=$2
1519         WAVDATA="$ABCDETEMPDIR/track$FIRSTTRACKNUMBER.wav"
1520         echo "Grabbing the CD to a single track..." >&2
1521         case "$CDROMREADERSYNTAX" in
1522                 cdparanoia) nice $READNICE $CDROMREADER -d $CDROM "1-" "$WAVDATA" >&2 ;;
1523                 cdda2wav)
1524                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1525                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1526                                 disktool -u ${CDROM#/dev/} 0
1527                                 # Also, in OSX the cdrom device for cdda2wav changes...
1528                                 CDDA2WAVCDROM="IODVDServices"
1529                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1530                                 CDDA2WAVCDROM="$CDROMID"
1531                         else
1532                                 if [ "$CDROMID" = "" ]; then
1533                                         CDDA2WAVCDROM="$CDROM"
1534                                 else
1535                                         CDDA2WAVCDROM="$CDROMID"
1536                                 fi
1537                         fi
1538                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t 1+$LASTTRACKNUM "$WAVDATA" >&2 
1539                         ;;
1540                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
1541                 cddafs)
1542                         # Find the track's mounted path
1543                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1544                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1545                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
1546                         # If the file exists, copy it
1547                         if [ -e "$FILEPATH" ] ; then
1548                                 nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
1549                         else
1550                                 false
1551                         fi ;;
1552                 debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
1553         esac
1554         RETURN=$?
1555         if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; then
1556                 # Thank goodness errors is only machine-parseable up to the
1557                 # first colon, otherwise this woulda sucked
1558                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
1559                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
1560                 fi
1561                 echo "readtrack-$FIRSTTRACKNUMBER: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1562                 return $RETURN
1563         else
1564                 echo readtrack-$FIRSTTRACKNUMBER >> "$ABCDETEMPDIR/status"
1565         fi
1566 }
1567
1568 # do_cdread [tracknumber]
1569
1570 do_cdread ()
1571 {
1572         # The commands here don't go through run_command because they're never supposed to be silenced
1573         # return codes need to be doublechecked anyway, however
1574         UTRACKNUM=$1
1575         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1576         WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
1577         OUTDATA="$ABCDETEMPDIR/track$UTRACKNUM.$OUTPUTTYPE"
1578         if [ -r "$CDDBDATA" ]; then
1579                 TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
1580                 echo "Grabbing track $UTRACKNUM: $TRACKNAME..." >&2
1581         else
1582                 echo "Grabbing track $UTRACKNUM..." >&2
1583         fi
1584         case "$CDROMREADERSYNTAX" in
1585                 cdparanoia) nice $READNICE $CDROMREADER -d $CDROM $UTRACKNUM "$WAVDATA" >&2 ;;
1586                 cdda2wav)
1587                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1588                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1589                                 disktool -u ${CDROM#/dev/} 0
1590                                 # Also, in OSX the cdrom device for cdda2wav changes...
1591                                 CDDA2WAVCDROM="IODVDServices"
1592                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1593                                 CDDA2WAVCDROM="$CDROMID"
1594                         else
1595                                 if [ "$CDROMID" = "" ]; then
1596                                         CDDA2WAVCDROM="$CDROM"
1597                                 else
1598                                         CDDA2WAVCDROM="$CDROMID"
1599                                 fi
1600                         fi
1601                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t $UTRACKNUM "$WAVDATA" >&2 
1602                         ;;
1603                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
1604                 cddafs)
1605                         # Find the track's mounted path
1606                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1607                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1608                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
1609                         # If the file exists, copy it
1610                         if [ -e "$FILEPATH" ] ; then
1611                                 nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
1612                         else
1613                                 false
1614                         fi ;;
1615                 debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
1616         esac
1617         RETURN=$?
1618         if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; then
1619                 # Thank goodness errors is only machine-parseable up to the
1620                 # first colon, otherwise this woulda sucked
1621                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
1622                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
1623                 fi
1624                 echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1625                 return $RETURN
1626         else
1627                 echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
1628         fi
1629 }
1630
1631 # do_cdspeed
1632 # No values accepted, only uses env variables
1633 do_cdspeed () 
1634 {
1635         if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
1636                 vecho "Setting CD speed to ${CDSPEEDVALUE}x"
1637         else
1638                 echo "abcde: unable to set the device speed" >&2
1639         fi
1640 }
1641
1642 # vecho [message]
1643 #
1644 # vecho outputs a message if EXTRAVERBOSE is selected
1645 vecho ()
1646 {
1647 if [ x"$EXTRAVERBOSE" != "x" ]; then
1648         echo $@
1649 fi
1650 }
1651
1652 # User-redefinable functions
1653 # Custom filename munging:
1654 mungefilename ()
1655 {
1656         echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
1657 }
1658
1659 # Custom genre munging:
1660 mungegenre ()
1661 {
1662         echo $CDGENRE | tr "[:upper:]" "[:lower:]"
1663 }
1664
1665 # pre_read
1666 # Empty pre_read function, to be defined in the configuration file.
1667 pre_read ()
1668 {
1669 :
1670 }
1671
1672 ###############################################################################
1673 # End of functions
1674 #
1675 # Start of execution
1676 ###############################################################################
1677
1678 # Builtin defaults
1679 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
1680 CDDBSUBMIT=freedb-submit@freedb.org
1681 CDDBPROTO=5
1682 HELLOINFO="$(whoami)@$(hostname)"
1683 INTERACTIVE=y
1684 CDROMREADERSYNTAX=cdparanoia
1685 OUTPUTTYPE=ogg
1686 ENCODERSYNTAX=default
1687
1688 MP3ENCODERSYNTAX=default
1689 OGGENCODERSYNTAX=default
1690 FLACENCODERSYNTAX=default
1691 SPEEXENCODERSYNTAX=default
1692 MPPENCODERSYNTAX=default
1693 NORMALIZERSYNTAX=default
1694
1695 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
1696 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
1697 #VAOUTPUTFORMAT=${OUTPUTFORMAT}
1698 VAOUTPUTFORMAT='Various-${ALBUMFILE}/${TRACKNUM}.${ARTISTFILE}-${TRACKFILE}'
1699 ONETRACKOUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${ALBUMFILE}'
1700 VAONETRACKOUTPUTFORMAT='Various-${ALBUMFILE}/${ALBUMFILE}'
1701 PLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1702 PLAYLISTDATAPREFIX=''
1703 VAPLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1704 VAPLAYLISTDATAPREFIX=''
1705 DOSPLAYLIST=n
1706 COMMENT=''
1707 ID3TAGV=2
1708 ENCNICE=10
1709 READNICE=10
1710 DISTMP3NICE=10
1711 VARIOUSARTISTS=n
1712 VARIOUSARTISTSTYLE=forward
1713 KEEPWAVS=n
1714 PADTRACKS=n
1715 CDDBCOPYLOCAL="n"
1716 CDDBLOCALDIR="$HOME/.cddb"
1717 CDDBUSELOCAL="n"
1718
1719 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
1720 # i.e. CDROMID="1,0,0"
1721 CDROMID=""
1722
1723 # program paths - defaults to checking your $PATH
1724 # mp3
1725 LAME=lame
1726 GOGO=gogo
1727 BLADEENC=bladeenc
1728 L3ENC=l3enc
1729 XINGMP3ENC=xingmp3enc
1730 MP3ENC=mp3enc
1731 # ogg
1732 VORBIZE=vorbize
1733 OGGENC=oggenc
1734 # flac
1735 FLAC=flac
1736 # speex
1737 SPEEXENC=speexenc
1738 # mpp (Musepack)
1739 MPPENC=mppenc
1740
1741 ID3=id3
1742 ID3V2=id3v2
1743 CDPARANOIA=cdparanoia
1744 CDDA2WAV=cdda2wav
1745 DAGRAB=dagrab
1746 CDDAFS=cp
1747 CDDISCID=cd-discid
1748 CDDBTOOL=cddb-tool
1749 EJECT=eject
1750 MD5SUM=md5sum
1751 DISTMP3=distmp3
1752 VORBISCOMMENT=vorbiscomment
1753 METAFLAC=metaflac
1754 NORMALIZE=normalize-audio
1755 CDSPEED=eject
1756 VORBISGAIN=vorbisgain
1757
1758 # Options for programs called from abcde
1759 # mp3
1760 LAMEOPTS=
1761 GOGOOPTS=
1762 BLADEENCOPTS=
1763 L3ENCOPTS=
1764 XINGMP3ENCOPTS=
1765 MP3ENCOPTS=
1766 # ogg
1767 VORBIZEOPTS=
1768 OGGENCOPTS=
1769 # flac
1770 FLACOPTS=
1771 # speex
1772 SPEEXENCOPTS=
1773 # mpc
1774 MPPENCOPTS=
1775
1776 ID3OPTS=
1777 ID3V2OPTS=
1778 CDPARANOIAOPTS=
1779 CDDA2WAVOPTS=
1780 DAGRABOPTS=
1781 CDDAFSOPTS="-f"
1782 CDDBTOOLOPTS=
1783 EJECTOPTS=
1784 DISTMP3OPTS=
1785 NORMALIZEOPTS=
1786 CDSPEEDOPTS="-x"
1787 CDSPEEDVALUE=
1788
1789 # Default to one process if -j isn't specified
1790 MAXPROCS=1
1791
1792 # List of actions to perform - by default, run to completion
1793 ACTIONS=cddb,read,encode,tag,move,clean
1794
1795 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
1796 # Let's use these checkings to determine the OS flavour, which will be used later
1797 if [ X$(uname) = "XFreeBSD" ] ; then
1798         HTTPGET=fetch
1799         NEEDCDROMID=y
1800         OSFLAVOUR=FBSD
1801 elif [ X$(uname) = "XDarwin" ] ; then
1802         HTTPGET=curl
1803         OSFLAVOUR=OSX
1804         # We should have disktool in OSX, but let's be sure...
1805         NEEDDISKTOOL=y
1806 elif [ X$(uname) = "XOpenBSD" ] ; then
1807         HTTPGET=wget
1808         MD5SUM=md5
1809 else
1810         HTTPGET=wget
1811 fi
1812
1813 # If CDDBAVAIL is set to n, no CDDB read is done
1814 # If USEID3 is set to n, no ID3 tagging is done
1815 CDDBAVAIL=y
1816 USEID3=y
1817
1818 if [ -z "$OUTPUTDIR" ]; then
1819         OUTPUTDIR=$(pwd)
1820 fi
1821
1822 if [ -z "$WAVOUTPUTDIR" ]; then
1823         WAVOUTPUTDIR="$OUTPUTDIR"
1824 fi
1825
1826 # Load system defaults
1827 if [ -r /etc/abcde.conf ]; then
1828         . /etc/abcde.conf
1829 fi
1830 # Load user preference defaults
1831 if [ -r $HOME/.abcde.conf ]; then
1832         . $HOME/.abcde.conf
1833 fi
1834
1835 # By this time, we need some HTTPGETOPTS already defined.
1836 # If the user has defined a non-default HTTPGET method, we should not be empty.
1837
1838 if [ "$HTTPGETOPTS" = "" ] ; then
1839         case $HTTPGET in
1840                 wget) HTTPGETOPTS="-q -O -";;
1841                 curl) HTTPGETOPTS="-f -s";;
1842                 fetch)HTTPGETOPTS="-q -o -";;
1843                 *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
1844         esac
1845 fi
1846
1847 # If the CDROM has not been set yet, find a suitable one.
1848 # If this is a devfs system, default to /dev/cdroms/cdrom0
1849 # instead of /dev/cdrom
1850 if [ "$CDROM" = "" ] ; then
1851         if [ -e /dev/cdroms/cdrom0 ]; then
1852                 CDROM=/dev/cdroms/cdrom0
1853         elif [ -e /dev/cdrom ]; then
1854                 CDROM=/dev/cdrom
1855         elif [ -e /dev/cd0c ]; then
1856                 CDROM=/dev/cd0c
1857         elif [ -e /dev/acd0c ]; then
1858                 CDROM=/dev/acd0c
1859         elif [ -e /dev/disk1 ]; then
1860                 CDROM=/dev/disk1
1861         fi
1862 fi
1863
1864 # Parse command line options
1865 #while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:t:T:vVx opt ; do
1866 while getopts 1a:A:bc:C:d:Dhj:klLnNo:pr:Rs:S:t:T:vVxw:W: opt ; do
1867         case "$opt" in
1868                 1) ONETRACK=y ;;
1869                 a) ACTIONS="$OPTARG" ;;
1870                 A) EXPACTIONS="$OPTARG";;
1871                 b) BATCH=y ;;
1872                 c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
1873                 C) DISCID="${OPTARG#abcde.}" ;;
1874                 d) CDROM="$OPTARG" ;;
1875                 D) set -x ;;
1876                 h) usage; exit ;;
1877 #               f) FORCECDDBUSELOCAL=y ;;
1878                 i) INLINETAG=y ;;
1879                 j) MAXPROCS="$OPTARG" ;;
1880                 k) KEEPWAVS=y ;;
1881                 l) LOWDISK=y ;;
1882                 L) CDDBUSELOCAL=y ;;
1883                 n) CDDBAVAIL=n ;;
1884                 N) INTERACTIVE=n ;;
1885                 m) DOSPLAYLIST=y ;;
1886                 o) OUTPUTTYPE="$OPTARG" ;;
1887                 p) PADTRACKS=y ;;
1888                 P) USEPIPES=y ;;
1889                 r) REMOTEHOSTS="$OPTARG" ;;
1890                 R) REPLAYGAIN=y ;;
1891                 s) STARTTRACKNUMBER="$OPTARG" ;;
1892                 S) CDSPEEDVALUE="$OPTARG" ;;
1893 #               t) PREPROCESSFORMATS="$OPTARG"
1894 #                  PREPROCESS=y ;;
1895 #               T) POSTPROCESSFORMATS="$OPTARG" ;;
1896                 t) STARTTRACKNUMBER="$OPTARG" ;;
1897                 T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
1898                 v) 
1899                    echo "This is abcde v$VERSION."
1900                    echo "Usage: abcde [options] [tracks]"
1901                    echo "abcde -h for extra help"
1902                    exit
1903                    ;;
1904                 V) EXTRAVERBOSE="y" ;;
1905                 x) EJECTCD="y" ;;
1906                 w) COMMENT="$OPTARG" ;;
1907                 W) STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}" ;;
1908                 ?) usage; exit ;;
1909         esac
1910 done
1911
1912 shift $(($OPTIND - 1))
1913
1914 # Decide if we can continue. TO_REMOVE as soon as we find out about dagrab
1915 if [ "$ONETRACK" = "y" ] ; then 
1916         case "$CDROMREADERSYNTAX" in
1917                 dagrab|debug) echo "abcde error: ONETRACK reading is not suported with "$CDROMREADERSYNTAX" yet"
1918                               exit 1 ;;
1919         esac
1920         if [ "$BATCH" = "y" ]; then
1921                 echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
1922         fi
1923         # It does not matter how many tracks we want. In ONETRACK mode we grab them all
1924         if [ $# -gt 0 ]; then
1925                 vecho "ONETRACK mode selected: grabbing all tracks..."
1926         fi
1927 else
1928         while [ $# -gt 0 ]; do
1929                 # Range parsing code courtesy of Vincent Ho
1930                 RSTART=$(echo $1 | cut -f1 -d-)
1931                 REND=$(echo $1 | cut -f2 -d-)
1932                 if [ "$RSTART" = "$REND" ]; then
1933                         NEWTRACKS="$RSTART"
1934                 else
1935                         NEWTRACKS=$(f_seq_line $RSTART $REND)
1936                 fi
1937                 TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
1938                 shift
1939         done
1940 fi
1941
1942 # List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
1943 # List of experimental actions: retag,transcode
1944
1945 # Determine what actions are to be done from $ACTIONS and set the
1946 # following environment variables for them:
1947 DOCDDB=n
1948 DOREAD=n
1949 DONORMALIZE=n
1950 DOPREPROCESS=n
1951 DOENCODE=n
1952 DOPOSTPROCESS=n
1953 DOTAG=n
1954 DOMOVE=n
1955 DOPLAYLIST=n
1956 DOCLEAN=n
1957
1958 for ACTION in $(echo $ACTIONS | tr , \ )
1959 do
1960         case $ACTION in
1961         cddb) DOCDDB=y;;
1962         read) DOREAD=y;;
1963         normalize) DONORMALIZE=y; DOREAD=y;;
1964 #       preprocess) DOPREPROCESS=y; DOREAD=y;;
1965         encode) DOENCODE=y; DOREAD=y;;
1966 #       postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
1967         tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
1968         move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
1969         playlist) DOCDDB=y; DOPLAYLIST=y;;
1970         clean) DOCLEAN=y;;
1971         esac
1972 done
1973
1974 # Sanity checks:
1975
1976 # At this point a CDROM has to be defined, so we check it exists.
1977 if [ "$CDROM" != "" ] ; then 
1978         if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
1979                 if [ "$OSFLAVOUR" = "FBSD" ]; then
1980                         if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
1981                                 echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
1982                                 echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
1983                                 exit 1
1984                         fi
1985                 fi
1986         elif [ ! -e $CDROM ] ; then
1987                 echo "abcde error: CDROM device cannot be found." >&2
1988                 exit 1
1989         fi
1990 else
1991         echo "abcde error: CDROM has not been defined or cannot be found" >&2
1992         exit 1
1993 fi
1994
1995 # Decide which CDROM reader we're gonna use
1996 case "$CDROMREADERSYNTAX" in
1997         cdparanoia|debug)
1998                 CDROMREADER="$CDPARANOIA"
1999                 CDROMREADEROPTS="$CDPARANOIAOPTS"
2000                 ;;
2001         cdda2wav)
2002                 CDROMREADER="$CDDA2WAV"
2003                 CDROMREADEROPTS="$CDDA2WAVOPTS"
2004                 ;;
2005         dagrab)
2006                 CDROMREADER="$DAGRAB"
2007                 CDROMREADEROPTS="$DAGRABOPTS"
2008                 ;;
2009         cddafs)
2010                 CDROMREADER="$CDDAFS"
2011                 CDROMREADEROPTS="$CDDAFSOPTS"
2012                 ;;
2013 esac
2014
2015 # There's only one normalize...
2016 case "$NORMALIZERSYNTAX" in
2017         default|normalize)
2018                 NORMALIZER="$NORMALIZE"
2019                 NORMALIZEROPTS="$NORMALIZEOPTS"
2020                 ;;
2021 esac
2022
2023 # 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
2024
2025 # Getting ready for multiple output changes
2026 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
2027 do
2028         case $OUTPUT in
2029                 ogg)  [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
2030                       [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
2031                       [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
2032                         ;;
2033                 mp3)  [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
2034                       [ "$DOTAG" = "y" ] && NEEDTAGGER=y
2035                         ;;
2036                 flac) [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
2037                       [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
2038                         ;;
2039                 spx) [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc ;;
2040                 mpc) [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc ;;
2041                 *) echo "abcde error: Invalid OUTPUTTYPE defined" >&2
2042                    exit 1
2043                    ;;
2044         esac
2045 done
2046
2047 # decide which encoder
2048 case "$MP3ENCODERSYNTAX" in
2049         lame)
2050                 MP3ENCODEROPTS="$LAMEOPTS"
2051                 MP3ENCODER="$LAME"
2052                 ;;
2053         gogo)
2054                 MP3ENCODEROPTS="$GOGOOPTS"
2055                 MP3ENCODER="$GOGO"
2056                 ;;
2057         bladeenc)
2058                 MP3ENCODEROPTS="$BLADEENCOPTS"
2059                 MP3ENCODER="$BLADEENC"
2060                 ;;
2061         l3enc)
2062                 MP3ENCODEROPTS="$L3ENCOPTS"
2063                 MP3ENCODER="$L3ENC"
2064                 ;;
2065         xingmp3enc)
2066                 MP3ENCODEROPTS="$XINGMP3ENCOPTS"
2067                 MP3ENCODER="$XINGMP3ENC"
2068                 ;;
2069         mp3enc)
2070                 MP3ENCODEROPTS="$MP3ENCOPTS"
2071                 MP3ENCODER="$MP3ENC"
2072                 ;;
2073 esac
2074 case "$OGGENCODERSYNTAX" in
2075         vorbize)
2076                 OGGENCODEROPTS="$VORBIZEOPTS"
2077                 OGGENCODER="$VORBIZE"
2078                 ;;
2079         oggenc)
2080                 OGGENCODEROPTS="$OGGENCOPTS"
2081                 OGGENCODER="$OGGENC"
2082                 ;;
2083 esac
2084 case "$FLACENCODERSYNTAX" in
2085         flac)
2086                 FLACENCODEROPTS="$FLACOPTS"
2087                 FLACENCODER="$FLAC"
2088                 ;;
2089 esac
2090 case "$SPEEXENCODERSYNTAX" in
2091         speexenc)
2092                 SPEEXENCODEROPTS="$SPEEXENCOPTS"
2093                 SPEEXENCODER="$SPEEXENC"
2094                 ;;
2095 esac
2096 case "$MPPENCODERSYNTAX" in
2097         mppenc)
2098                 MPPENCODEROPTS="$MPPENCOPTS"
2099                 MPPENCODER="$MPPENC"
2100                 ;;
2101 esac
2102
2103 # and which tagger
2104
2105 if [ "$ID3TAGV" = "1" ]; then
2106         TAGGER="$ID3"
2107         TAGGEROPTS="$ID3OPTS"
2108 else
2109         TAGGER="$ID3V2"
2110         TAGGEROPTS="$ID3V2OPTS"
2111 fi
2112
2113 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
2114
2115 if [ "$ENCNICE" ]; then
2116         ENCNICE="-n $ENCNICE"
2117 fi
2118 if [ "$READNICE" ]; then
2119         READNICE="-n $READNICE"
2120 fi
2121 if [ "$DISTMP3NICE" ]; then
2122         DISTMP3NICE="-n $DISTMP3NICE"
2123 fi
2124
2125 # Don't check for stuff if it's not needed
2126 if [ "$REMOTEHOSTS" ]; then NEEDDISTMP3=y; fi
2127 [ "$DONORMALIZE" = "y" ] && NEEDNORMALIZER=y
2128 [ "$EJECTCD" = "y" ] && NEEDEJECT=y
2129 [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ] && NEEDHTTPGET=y
2130
2131 if [ X"$CDSPEEDVALUE" != "X" ]; then
2132         case "$CDROMREADERSYNTAX" in
2133                 cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
2134                 *) NEEDCDSPEED=y ;;
2135         esac
2136 fi
2137
2138
2139 # Make sure a buncha things exist
2140 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
2141         $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
2142         ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
2143         ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
2144         ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
2145         ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
2146         ${NEEDVORBISGAIN+$VORBISGAIN}
2147 do
2148         # Cut off the command-line options we just added in
2149         X=$(echo $X | cut -d' ' -f2)
2150         if [ "$(which $X)" = "" ]; then
2151                 echo "abcde error: $X is not in your path." >&2
2152                 exit 1
2153         elif [ ! -x $(which $X) ]; then
2154                 echo "abcde error: $X is not executable." >&2
2155                 exit 1
2156         fi
2157 done
2158
2159 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
2160 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
2161 HTTPGET="$HTTPGET $HTTPGETOPTS"
2162
2163 # Here it used to say:
2164 # One thousand lines in, we can start doing stuff with things
2165 # Well, right now we are at line 2157 ;)
2166
2167 # Export needed things so they can be read in this subshell
2168 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
2169 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
2170
2171 # User-definable function to set some things. Use it for
2172 #  - closing the CD tray with eject -t
2173 #  - set the CD speed value with eject -x
2174 vecho -n "Executing customizable pre-read function... "
2175
2176 pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
2177
2178 vecho "done."
2179
2180 do_discid # Get ABCDETEMPDIR created and status file initialized
2181
2182 if [ "$DOCDDB" = "y" ]; then
2183         if [ $CDDBUSELOCAL = "y" ]; then
2184                 do_localcddb
2185         fi
2186         if checkstatus cddb-choice > /dev/null; then
2187                 :
2188         else 
2189                 if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
2190                         do_cddbstat
2191                         do_cddbquery
2192                         do_cddbread
2193                 fi
2194         fi
2195         do_cddbedit
2196
2197         eval $($CDDBTOOL parse "$CDDBDATA")
2198 fi
2199
2200 # Before reading tracks, we set the speed of the device
2201
2202 if [ X"$CDSPEEDVALUE" != "X" ]; then
2203         case "$CDROMREADERSYNTAX" in
2204                 cdparanoia|debug) : ;;
2205                 *) do_cdspeed ;;
2206         esac
2207 fi
2208
2209 if [ "$STRIPDATATRACKS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
2210         case "$CDROMREADERSYNTAX" in
2211                 cdparanoia|debug) 
2212                         # cdparanoia can query the CD, so let's process the TRACKQUEUE list with the results.
2213                         if checkstatus cdparanoia-audio-tracks; then
2214                                 CDTRACKQUEUE=$( cat $ABCDETEMPDIR/cdparanoia-audio-tracks )
2215                         else
2216                                 ## FIXME ##
2217                                 vecho "Querying the CD to obtain a list of valid audio tracks..."
2218                                 $CDROMREADER -Q > $ABCDETEMPDIR/cdparanoia-query 2>&1
2219                                 # Obtain a list of valid audio tracks from the results of the query
2220                                 CDTRACKQUEUE=$( cat $ABCDETEMPDIR/cdparanoia-query | egrep '^[[:space:]]+[[:digit:]]' | awk '{print $1}' | tr -d "." | tr '\n' ' ' )
2221                         fi
2222                         # Obtain the track padding value from the before-processing list and pad the CD list
2223                         TRACKNUMPADDING=$( echo $TRACKQUEUE | awk '{print $1}' | tr -d " \n" | wc -c )
2224                         for TRACK in $CDTRACKQUEUE ; do
2225                                 TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
2226                                 PADNEWTRACKQUEUE=$(echo $PADNEWTRACKQUEUE $TRACKNUM)
2227                         done
2228                         CDTRACKQUEUE=$PADNEWTRACKQUEUE
2229                         # Now, compare if the values in the list are valid tracks in the CD
2230                         for TRACK in $TRACKQUEUE; do
2231                                 if echo $CDTRACKQUEUE | grep $TRACK >/dev/null ; then
2232                                         NEWTRACKQUEUE="$NEWTRACKQUEUE $TRACK"
2233                                 fi
2234                         done
2235                         TRACKQUEUE="$NEWTRACKQUEUE"
2236                 ;;
2237         esac
2238 fi
2239
2240 # Create playlist if needed (backgroundable) and start reading in tracks
2241
2242 (
2243
2244 if [ "$ONETRACK" = "y" ]; then :; else
2245         if [ "$DOPLAYLIST" = "y" ]; then
2246                 echo Creating playlist... >&2
2247                 do_playlist
2248         fi
2249 fi
2250
2251 # For the lowdisk option, only one program is running at once so the encoder
2252 # can be unsilenced right away.
2253 if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
2254         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2255 fi
2256
2257 if [ "$ONETRACK" = "y" ]; then 
2258         FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}' )
2259         TRACKS="$FIRSTTRACK"
2260         for UTRACKNUM in $TRACKQUEUE; do :;done
2261         if checkstatus readtrack-$FIRSTTRACK; then :; else
2262                 do_cdread_one $UTRACKNUM $FIRSTTRACK
2263         fi
2264 else
2265         for UTRACKNUM in $TRACKQUEUE
2266         do
2267                 if [ "$DOREAD" = "y" ]; then
2268                         if checkstatus readtrack-$UTRACKNUM; then :; else
2269                                 do_cdread $UTRACKNUM
2270                                 if [ "$?" != "0" ]; then
2271                                         # CD read failed - don't give the goahead to
2272                                         # the encoder
2273                                         echo NO
2274                                         exit
2275                                 fi
2276                         fi
2277                 fi
2278                 if [ "$BATCH" = "y" ]; then
2279                     :
2280                 else
2281                         echo NEXTTRACK # Get the encoder machine churning again
2282                         if [ "$DOREAD" = "y" ]; then
2283                                 if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
2284                                         until checkstatus encodetrack-$UTRACKNUM
2285                                         do
2286                                                 if checkerrors encodetrack-$UTRACKNUM; then
2287                                                         break
2288                                                 fi
2289                                                 sleep 2
2290                                         done
2291                                 fi
2292                         fi
2293                 fi
2294         done
2295 fi
2296
2297 # Now that we're done the encoding can be loud again -
2298 # if we're not using SMP.
2299 if [ "$MAXPROCS" = "1" ]; then
2300         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2301 fi
2302
2303 # All tracks read, start encoding.
2304 if [ "$BATCH" = "y" ] || [ "$ONETRACK" = "y" ]; then
2305         echo NEXTTRACK
2306 fi
2307
2308 # We are now finished with the cdrom - it can be safely ejected. Note that
2309 # abcde will not have completed yet.
2310 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
2311         # We check if the disk we are processing is actually the disk inside the 
2312         # CD tray. If not, we do not eject the CD, since it might be so that the
2313         # user ejected it manually.
2314         #CURRENTTRACKINFO=$($CDDISCID $CDROM)
2315         #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
2316         # More FreeBSD bits.
2317         if [ X"$(uname)" = X"FreeBSD" ] ; then
2318                 # FreeBSD eject uses the EJECT environment variable to name the CDROM
2319                 # but in this script EJECT is in the envionment and names the program
2320                 eject=$EJECT
2321                 unset EJECT
2322                 # The FreeBSD eject needs "adc0" not "/dev/adc0c"
2323                 cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
2324                 $eject $EJECTOPTS $cd
2325         elif [ X"$(uname)" = X"Darwin" ] ; then
2326                 disktool -e ${CDROM#/dev/} 0
2327         else
2328                 $EJECT $EJECTOPTS $CDROM
2329         fi
2330         #fi
2331 fi
2332
2333 ) | (
2334
2335 ## Do we need to pre-process 
2336 #if [ x"$PREPROCESS" = "x" ] ; then
2337 #       cat
2338 #else
2339 #       for PRETRACKNUM in $TRACKQUEUE
2340 #       do
2341 #               read GOAHEAD
2342 #               if [ "$GOAHEAD" = "NO" ]; then break; fi
2343 #               PREPROCEED=
2344 #               until [ $PREPROCEED ]
2345 #               do
2346 #                       if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
2347 #                       # all locations are working, wait and try again later
2348 #                       if [ ! $PREPROCEED ]; then sleep 3; fi
2349 #               done
2350 #               ( do_preprocess $PRETRACKNUM 
2351 #               echo "NEXTTRACK"
2352 #               ) &
2353 #       done
2354 #fi
2355 #
2356 #) | (
2357
2358 # In batch mode, we want all tracks to be read first.
2359 if [ "$BATCH" = "y" ]; then
2360         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2361         if [ "$GOAHEAD" = "NO" ]; then break; fi
2362         for LASTTRACK in $TRACKQUEUE; do :; done
2363         if checkstatus readtrack-$LASTTRACK; then
2364                 if [ "$DONORMALIZE" = "y" ]; then
2365                         if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
2366                         if checkerrors batch-normalize; then exit; fi
2367                 fi
2368                 if [ "$DOENCODE" = "y" ]; then
2369                         if checkstatus encodetrack-$LASTTRACK; then :; else do_batch_encode; fi
2370                         if checkerrors batch-encode; then exit; fi
2371                 fi
2372         fi
2373 fi
2374
2375 # If we are using ONETRACK, we can proceed with the normal encoding using just the $FIRSTTRACK as TRACKQUEUE
2376 if [ "$ONETRACK" = "y" ] ; then
2377         FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}')
2378         TRACKQUEUE=$FIRSTTRACK
2379         TRACKS="$FIRSTTRACK"
2380 fi
2381
2382 # Do the encoding, including parallelization of remote encoding
2383 # Figure out where each track is going to be encoded
2384 ENCODELOCATIONS="$(echo $REMOTEHOSTS | tr , ' ')"
2385 if [ "$MAXPROCS" != "0" ]; then
2386         for NUM in $(f_seq_row 1 "$MAXPROCS")
2387         do
2388                 ENCODELOCATIONS="$ENCODELOCATIONS %local$NUM%"
2389         done
2390 fi
2391 # Strip whitespace
2392 ENCODELOCATIONS=$(echo $ENCODELOCATIONS)
2393 for UTRACKNUM in $TRACKQUEUE
2394 do
2395         # Wait for our cue
2396         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2397         if [ "$GOAHEAD" = "NO" ]; then break; fi
2398         # find out where this track is to be encoded
2399         if [ "$DOENCODE" = "y" ]; then
2400                 # Make sure we have a place to encode this, if not, exit stage right
2401                 if [ -z "$ENCODELOCATIONS" ]; then
2402                         continue
2403                 fi
2404                 PROCEED=
2405                 until [ $PROCEED ]
2406                 do
2407                         for LOCATION in $ENCODELOCATIONS
2408                         do
2409                                 PREVIOUSTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2410                                 # check first if a track has ever been assigned to this location
2411                                 if [ -z "$PREVIOUSTRACK" ]; then PROCEED=y; break; fi
2412                                 # If it errored out, rebuild $ENCODELOCATIONS without this location in it
2413                                 if checkerrors encodetrack-$PREVIOUSTRACK; then
2414                                         for TEMPLOCATION in $ENCODELOCATIONS
2415                                         do
2416                                                 if [ "$TEMPLOCATION" != "$LOCATION" ]; then
2417                                                         TEMPENCODELOCATIONS="$TEMPENCODELOCATIONS $TEMPLOCATION"
2418                                                 fi
2419                                         done
2420                                         ENCODELOCATIONS=$(echo $TEMPENCODELOCATIONS)
2421                                         ABORT=y
2422                                         PROCEED=y
2423                                         break
2424                                 fi
2425                                 # We're still here, this location must have been previously assigned,
2426                                 # and last completed without error - check if it's done with the
2427                                 # previous track yet
2428                                 if checkstatus encodetrack-$PREVIOUSTRACK; then PROCEED=y; break; fi
2429                         done
2430                         # all locations are working, wait and try again later
2431                         if [ ! $PROCEED ]; then sleep 3; fi
2432                 done
2433                 # Record the location we're about to encode the next track at
2434                 echo "encodetracklocation-$LOCATION=$UTRACKNUM" >> "$ABCDETEMPDIR/status"
2435         fi
2436         # Don't proceed with the rest of the loop if we can't encode
2437         if [ "$ABORT" ]; then continue; fi
2438         # Set TRACKNUM, TRACKNAME
2439         if [ -e "$CDDBDATA" ]; then
2440                 if [ "$ONETRACK" = "y" ]; then 
2441                         TRACKNAME="$DALBUM"
2442                         TRACKNUM="$FIRSTTRACK"
2443                         splitvarious
2444                 else
2445 #                       TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
2446                         TRACKNUM=$UTRACKNUM
2447                         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
2448                         TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
2449                         splitvarious
2450                 fi
2451         fi
2452         # You can't encode a file which needs to be normalized before finishing
2453         # You can't tag a file before it's finished encoding -
2454         # thus all of this is backgrounded together
2455         (
2456         if [ "$DONORMALIZE" = "y" ]; then
2457                 if checkstatus readtrack-$UTRACKNUM; then
2458                         if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
2459                 fi
2460         fi
2461         if [ "$DOENCODE" = "y" ]; then
2462                 if checkstatus readtrack-$UTRACKNUM; then
2463                         #if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION; fi
2464                         if [ "$DONORMALIZE" = "y" ]; then
2465                                 if checkstatus normalizetrack-$UTRACKNUM; then
2466                                         if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2467                                 fi
2468                         else
2469                                 if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2470                         fi
2471                 fi
2472         fi
2473         if [ "$DOTAG" = "y" ]; then
2474                 if checkstatus encodetrack-$UTRACKNUM; then
2475                         if checkstatus tagtrack-$UTRACKNUM; then :; else do_tag $UTRACKNUM; fi
2476                 fi
2477         fi
2478         if [ "$DOMOVE" = "y" ]; then
2479                 if checkstatus tagtrack-$UTRACKNUM; then
2480                         if checkstatus movetrack-$UTRACKNUM; then :; else do_move $UTRACKNUM; fi
2481                 fi
2482         fi
2483         ) &
2484 done
2485 # Go through it again and make sure there's no distmp3 stragglers, otherwise
2486 # we'll delete the files they're working on
2487 if [ "$DOENCODE" = "y" ]; then
2488         PROCEED=
2489         until [ $PROCEED ]
2490         do
2491                 PROCEED=y
2492                 for LOCATION in $ENCODELOCATIONS
2493                 do
2494                         CHECKTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2495                         # "How can he give us a status update, if he's DEAD?"
2496                         if checkstatus encodetrack-$CHECKTRACK; then
2497                                 continue
2498                         fi
2499                         # Nothing to see here please go quietly back to your homes
2500                         if [ -z "$CHECKTRACK" ]; then continue; fi
2501                         # You're still here? Maybe there is something...
2502                         if checkstatus encodetrack-$CHECKTRACK; then :; else PROCEED= ; break; fi
2503                 done
2504                 # hold up
2505                 if [ ! $PROCEED ]; then sleep 5; fi
2506         done
2507 fi
2508 # If the above didn't catch the stragglers, this will
2509 wait
2510 # Check to see if run_command logged any errors
2511 if [ -f "$ABCDETEMPDIR/errors" ]; then
2512         echo "The following commands failed to run:"
2513         cat "$ABCDETEMPDIR/errors"
2514         # Don't clean up
2515         DOCLEAN=n
2516 fi
2517 if [ "$KEEPWAVS" = "y" ];then
2518         # Don't clean up
2519         DOCLEAN=n
2520 fi
2521 if [ "$DOCLEAN" = "y" ]; then
2522         # Wipe all the evidence
2523         # Gimme gimme gimme some more time!
2524         sleep 5
2525         rm -rf "$ABCDETEMPDIR"
2526         echo "Finished."
2527 else
2528         echo "Finished. Not cleaning $ABCDETEMPDIR."
2529 fi
2530 )
2531 exit 0