Small fixes in TRACKNAME
[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" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
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                                         [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
1270                                         # Make sure we get a valid choice
1271                                         CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1272                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
1273                                                 echo "Invalid selection. Please choose a number between 1 and $CDDBCHOICES." >&2
1274                                                 echo -n "Selection [0-$CDDBCHOICES]: " >&2
1275                                                 read CDDBCHOICE
1276                                                 CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1277                                         done
1278                                         if [ "$CDCHOICENUM" = "0" ]; then
1279                                                 vecho "Creating empty CDDB template..."
1280                                                 UNKNOWNDISK=y
1281                                                 $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > $ABCDETEMPDIR/cddbread.0
1282                                         else
1283                                                 echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
1284                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
1285                                         fi
1286                                         echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1287                                 fi
1288                         fi
1289                 else
1290                         # We need some code to show the selected option when local repository is selected and we have found a match
1291                         vecho "Using cached CDDB match..." >&2
1292                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1293                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1294                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1295                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1296                                 CHOICE=$(checkstatus cddb-choice)
1297                                 if [ "$USELOCALRESP" = "y" ]; then :; else
1298                                         if [ -n "$CHOICE" ] ; then
1299                                                 case $CDDBCHOICES in
1300                                                         0) 
1301                                                         UNKNOWNDISK=y
1302                                                         echo "Selected template."
1303                                                         ;;
1304                                                         1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1305                                                         *)
1306                                                         echo "Selected: #$CHOICE"
1307                                                         do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1308                                                         ;;
1309                                                 esac
1310                                         fi
1311                                 fi
1312                         fi
1313                 fi
1314         else
1315                 # We're noninteractive - pick the first choice.
1316                 # But in case we run a previous instance and selected a choice, use it.
1317                 if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1318                         # Show the choice if we are not using the locally stored one
1319                         # or when the local search failed to find a match.
1320                         PREVIOUSCHOICE=$(checkstatus cddb-choice)
1321                         if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSUCCESS" = "n" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1322                                 #if [ "$PREVIOUSCHOICE" ]; then
1323                                         cat "$ABCDETEMPDIR/cddbchoices"
1324                                 #fi
1325                         fi
1326                         if [ ! -z "$PREVIOUSCHOICE" ] ; then
1327                                 CDCHOICENUM=$PREVIOUSCHOICE
1328                         else
1329                                 CDCHOICENUM=1
1330                                 echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1331                         fi
1332                         echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
1333                 fi
1334         fi
1335
1336         # sanity check
1337         if checkstatus cddb-choice >/dev/null; then :; else
1338                 echo "abcde: internal error: cddb-choice not recorded." >&2
1339                 exit 1
1340         fi
1341         CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1342         echo -n "Edit selected CDDB data? [y/n] (" >&2
1343         if [ "$INTERACTIVE" = "y" ]; then
1344                 if [ "$UNKNOWNDISK" = "y" ]; then
1345                         echo -n "y): " >&2
1346                         read EDITCDDB
1347                         [ "$EDITCDDB" != "n" ] && EDITCDDB=y
1348                 else
1349                         echo -n "n): " >&2
1350                         read EDITCDDB
1351                 fi
1352         else
1353                 echo "n): n" >&2
1354                 EDITCDDB=n
1355         fi
1356         if [ "$EDITCDDB" = "y" ]; then
1357                 CDDBDATAMD5SUM=$($MD5SUM "$CDDBDATA" | cut -d " " -f 1);
1358                 
1359                 # Use the debian sensible-editor wrapper to pick the editor that the
1360                 # user has requested via their $EDITOR environment variable
1361                 if [ -x "/usr/bin/sensible-editor" ]; then
1362                         /usr/bin/sensible-editor "$CDDBDATA"
1363                 elif [ -n "$EDITOR" ]; then
1364                         if [ -x $(which "${EDITOR%%\ *}") ]; then
1365                                 # That failed, try to load the preferred editor, starting
1366                                 # with their EDITOR variable
1367                                 eval $(echo "$EDITOR") "$CDDBDATA"
1368                         fi
1369                 # If that fails, check for a vi
1370                 elif [ -x /usr/bin/vi ]; then
1371                         /usr/bin/vi "$CDDBDATA"
1372                 # nano should be on all (modern, i.e., sarge) debian systems
1373                 elif [ -x /usr/bin/nano ]; then
1374                         /usr/bin/nano "$CDDBDATA"
1375                 # mg should be on all OpenBSD systems
1376                 elif [ -x /usr/bin/mg ]; then
1377                         /usr/bin/mg "$CDDBDATA"
1378                 # bomb out
1379                 else
1380                         echo "No editor available. Check your EDITOR environment variable." >&2
1381                 fi
1382                 # delete editor backup file if it exists
1383                 if [ -w "$CDDBDATA~" ]; then
1384                         rm -f "$CDDBDATA~"
1385                 fi
1386         fi
1387
1388         # Some heuristics first. Look at Disc Title, and if it starts with
1389         # "Various", then we'll assume Various Artists
1390         if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2 -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
1391                 echo "Looks like a Multi-Artist CD" >&2
1392                 VARIOUSARTISTS=y
1393         else
1394                 echo -n "Is the CD multi-artist? [y/n] (n): " >&2
1395                 if [ "$INTERACTIVE" = "y" ]; then
1396                         read VARIOUSARTISTS
1397                 else
1398                         echo n >&2
1399                         VARIOUSARTISTS=n
1400                 fi
1401         fi
1402         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
1403                 # Set a default
1404                 DEFAULTSTYLE=1
1405                 # Need NUMTRACKS before cddb-tool will return it:
1406                 NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
1407                 if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1408                         # More than 1/2 tracks contain a "/", so guess forward
1409                         DEFAULTSTYLE=1
1410                 elif [ "$(grep -c "^TTITLE.*\-" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1411                         # More than 1/2 contain a "-", so guess forward-dash
1412                         DEFAULTSTYLE=2
1413                 elif [ "$(grep -c "^TTITLE.*(.*)" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1414                         # More than 1/2 contain something in parens, so guess trailing-paren
1415                         DEFAULTSTYLE=6
1416                 fi
1417
1418                 echo "1) Artist / Title" >&2
1419                 echo "2) Artist - Title" >&2
1420                 echo "3) Title / Artist" >&2
1421                 echo "4) Title - Artist" >&2
1422                 echo "5) Artist: Title" >&2
1423                 echo "6) Title (Artist)" >&2
1424                 echo "7) This is a single-artist CD" >&2
1425                 echo -n "Which style of multiple artist entries is it? [1-7] ($DEFAULTSTYLE): " >&2
1426                 if [ "$INTERACTIVE" = "y" ]; then
1427                         read VARIOUSARTISTSTYLE
1428                 else
1429                         echo $DEFAULTSTYLE >&2
1430                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1431                 fi
1432                 VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1433                 # If they press Enter, then the default style (0) was chosen
1434                 while [ $VARIOUSARTISTSTYLE -lt 0 ] || [ $VARIOUSARTISTSTYLE -gt 7 ]; do
1435                         echo "Invalid selection. Please choose a number between 1 and 7."
1436                         echo -n "Selection [1-7]: "
1437                         read VARIOUSARTISTSTYLE
1438                         VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1439                 done
1440                 if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
1441                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1442                 fi
1443                 vecho "Selected: $VARIOUSARTISTSTYLE"
1444                 case "$VARIOUSARTISTSTYLE" in
1445                 1) # Artist / Title
1446                         VARIOUSARTISTSTYLE=forward
1447                         ;;
1448                 2) # Artist - Title
1449                         VARIOUSARTISTSTYLE=forward-dash
1450                         ;;
1451                 3) # Title / Artist
1452                         VARIOUSARTISTSTYLE=reverse
1453                         ;;
1454                 4) # Title - Artist
1455                         VARIOUSARTISTSTYLE=reverse-dash
1456                         ;;
1457                 5) # Artist: Title
1458                         VARIOUSARTISTSTYLE=colon
1459                         ;;
1460                 6) # Title (Artist)
1461                         VARIOUSARTISTSTYLE=trailing-paren
1462                         ;;
1463                 7) # Single Artist
1464                         VARIOUSARTISTS=n
1465                         ;;
1466                 esac
1467         fi
1468
1469         echo "variousartists=$VARIOUSARTISTS" >> "$ABCDETEMPDIR/status"
1470         echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
1471
1472         if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
1473                 if [ $CDDBDATAMD5SUM != "" ]  && [ $CDDBDATAMD5SUM != $($MD5SUM "$CDDBDATA" | cut -d " " -f 1) ]; then
1474                         # This works but does not have the necessary error checking
1475                         # yet. If you are familiar with the CDDB spec
1476                         # (see http://www.freedb.org/src/latest/DBFORMAT) 
1477                         # and can create an error-free entry on your own, then put
1478                         # UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE=y in your
1479                         # abcde.conf to enable it. Put CDDBSUBMIT=email@address in
1480                         # your abcde.conf to change the email address submissions are
1481                         # sent to.
1482
1483                         # submit the modified file, if they want
1484                         if [ "$NOSUBMIT" != "y" ]; then
1485                                 echo -n "Do you want to submit this entry to $CDDBSUBMIT? [y/n] (n): "
1486                                 read YESNO
1487                                 while [ "$YESNO" != "y" ] && [ "$YESNO" != "n" ] && [ "$YESNO" != "Y" ] && \
1488                                         [ "$YESNO" != "N" ] && [ "$YESNO" != "" ]
1489                                 do
1490                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1491                                         read YESNO
1492                                 done
1493                                 if [ "$YESNO" = "y" ] || [ "$YESNO" = "Y" ]; then
1494                                         echo -n "Sending..."
1495                                         $CDDBTOOL send "$CDDBDATA" $CDDBSUBMIT
1496                                         echo "done."
1497                                 fi
1498                         fi
1499                 fi
1500         fi
1501         # Make sure the cache directory exists
1502         mkdir -p $CDDBLOCALDIR
1503         # Cache edited CDDB entry in the user's cddb dir
1504         if [ "$CDDBCOPYLOCAL" = "y" ] || [ "$COPYCDDBLOCAL" = "Y" ]; then
1505                 cat "$CDDBDATA" | tail -n $(expr $(cat "$CDDBDATA" | wc -l ) - 1 ) > ${CDDBLOCALDIR}/$(echo "$TRACKINFO" | cut -d' ' -f1)
1506         fi
1507
1508         echo "cddb-edit" >> "$ABCDETEMPDIR/status"
1509 }
1510
1511 # do_cdread_one [lasttrack] [firsttrack]
1512
1513 # Reads the CD in a single track. Live performances, concerts, mixes,... benefit from this.
1514 do_cdread_one ()
1515 {
1516         # The commands here don't go through run_command because they're never supposed to be silenced
1517         # return codes need to be doublechecked anyway, however
1518         LASTTRACKNUMBER=$1
1519         FIRSTTRACKNUMBER=$2
1520         WAVDATA="$ABCDETEMPDIR/track$FIRSTTRACKNUMBER.wav"
1521         echo "Grabbing the CD to a single track..." >&2
1522         case "$CDROMREADERSYNTAX" in
1523                 cdparanoia) nice $READNICE $CDROMREADER -d $CDROM "1-" "$WAVDATA" >&2 ;;
1524                 cdda2wav)
1525                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1526                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1527                                 disktool -u ${CDROM#/dev/} 0
1528                                 # Also, in OSX the cdrom device for cdda2wav changes...
1529                                 CDDA2WAVCDROM="IODVDServices"
1530                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1531                                 CDDA2WAVCDROM="$CDROMID"
1532                         else
1533                                 if [ "$CDROMID" = "" ]; then
1534                                         CDDA2WAVCDROM="$CDROM"
1535                                 else
1536                                         CDDA2WAVCDROM="$CDROMID"
1537                                 fi
1538                         fi
1539                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t 1+$LASTTRACKNUM "$WAVDATA" >&2 
1540                         ;;
1541                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
1542                 cddafs)
1543                         # Find the track's mounted path
1544                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1545                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1546                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
1547                         # If the file exists, copy it
1548                         if [ -e "$FILEPATH" ] ; then
1549                                 nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
1550                         else
1551                                 false
1552                         fi ;;
1553                 debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
1554         esac
1555         RETURN=$?
1556         if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; then
1557                 # Thank goodness errors is only machine-parseable up to the
1558                 # first colon, otherwise this woulda sucked
1559                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
1560                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
1561                 fi
1562                 echo "readtrack-$FIRSTTRACKNUMBER: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1563                 return $RETURN
1564         else
1565                 echo readtrack-$FIRSTTRACKNUMBER >> "$ABCDETEMPDIR/status"
1566         fi
1567 }
1568
1569 # do_cdread [tracknumber]
1570
1571 do_cdread ()
1572 {
1573         # The commands here don't go through run_command because they're never supposed to be silenced
1574         # return codes need to be doublechecked anyway, however
1575         UTRACKNUM=$1
1576         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1577         WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
1578         OUTDATA="$ABCDETEMPDIR/track$UTRACKNUM.$OUTPUTTYPE"
1579         if [ -r "$CDDBDATA" ]; then
1580                 TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
1581                 echo "Grabbing track $UTRACKNUM: $TRACKNAME..." >&2
1582         else
1583                 echo "Grabbing track $UTRACKNUM..." >&2
1584         fi
1585         case "$CDROMREADERSYNTAX" in
1586                 cdparanoia) nice $READNICE $CDROMREADER -d $CDROM $UTRACKNUM "$WAVDATA" >&2 ;;
1587                 cdda2wav)
1588                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1589                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1590                                 disktool -u ${CDROM#/dev/} 0
1591                                 # Also, in OSX the cdrom device for cdda2wav changes...
1592                                 CDDA2WAVCDROM="IODVDServices"
1593                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1594                                 CDDA2WAVCDROM="$CDROMID"
1595                         else
1596                                 if [ "$CDROMID" = "" ]; then
1597                                         CDDA2WAVCDROM="$CDROM"
1598                                 else
1599                                         CDDA2WAVCDROM="$CDROMID"
1600                                 fi
1601                         fi
1602                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t $UTRACKNUM "$WAVDATA" >&2 
1603                         ;;
1604                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
1605                 cddafs)
1606                         # Find the track's mounted path
1607                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1608                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1609                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
1610                         # If the file exists, copy it
1611                         if [ -e "$FILEPATH" ] ; then
1612                                 nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
1613                         else
1614                                 false
1615                         fi ;;
1616                 debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
1617         esac
1618         RETURN=$?
1619         if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; then
1620                 # Thank goodness errors is only machine-parseable up to the
1621                 # first colon, otherwise this woulda sucked
1622                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
1623                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
1624                 fi
1625                 echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1626                 return $RETURN
1627         else
1628                 echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
1629         fi
1630 }
1631
1632 # do_cdspeed
1633 # No values accepted, only uses env variables
1634 do_cdspeed () 
1635 {
1636         if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
1637                 vecho "Setting CD speed to ${CDSPEEDVALUE}x"
1638         else
1639                 echo "abcde: unable to set the device speed" >&2
1640         fi
1641 }
1642
1643 # vecho [message]
1644 #
1645 # vecho outputs a message if EXTRAVERBOSE is selected
1646 vecho ()
1647 {
1648 if [ x"$EXTRAVERBOSE" != "x" ]; then
1649         echo $@
1650 fi
1651 }
1652
1653 # User-redefinable functions
1654 # Custom filename munging:
1655 mungefilename ()
1656 {
1657         echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
1658 }
1659
1660 # Custom genre munging:
1661 mungegenre ()
1662 {
1663         echo $CDGENRE | tr "[:upper:]" "[:lower:]"
1664 }
1665
1666 # pre_read
1667 # Empty pre_read function, to be defined in the configuration file.
1668 pre_read ()
1669 {
1670 :
1671 }
1672
1673 ###############################################################################
1674 # End of functions
1675 #
1676 # Start of execution
1677 ###############################################################################
1678
1679 # Builtin defaults
1680 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
1681 CDDBSUBMIT=freedb-submit@freedb.org
1682 CDDBPROTO=5
1683 HELLOINFO="$(whoami)@$(hostname)"
1684 INTERACTIVE=y
1685 CDROMREADERSYNTAX=cdparanoia
1686 OUTPUTTYPE=ogg
1687 ENCODERSYNTAX=default
1688
1689 MP3ENCODERSYNTAX=default
1690 OGGENCODERSYNTAX=default
1691 FLACENCODERSYNTAX=default
1692 SPEEXENCODERSYNTAX=default
1693 MPPENCODERSYNTAX=default
1694 NORMALIZERSYNTAX=default
1695
1696 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
1697 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
1698 #VAOUTPUTFORMAT=${OUTPUTFORMAT}
1699 VAOUTPUTFORMAT='Various-${ALBUMFILE}/${TRACKNUM}.${ARTISTFILE}-${TRACKFILE}'
1700 ONETRACKOUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${ALBUMFILE}'
1701 VAONETRACKOUTPUTFORMAT='Various-${ALBUMFILE}/${ALBUMFILE}'
1702 PLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1703 PLAYLISTDATAPREFIX=''
1704 VAPLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1705 VAPLAYLISTDATAPREFIX=''
1706 DOSPLAYLIST=n
1707 COMMENT=''
1708 ID3TAGV=2
1709 ENCNICE=10
1710 READNICE=10
1711 DISTMP3NICE=10
1712 VARIOUSARTISTS=n
1713 VARIOUSARTISTSTYLE=forward
1714 KEEPWAVS=n
1715 PADTRACKS=n
1716 CDDBCOPYLOCAL="n"
1717 CDDBLOCALDIR="$HOME/.cddb"
1718 CDDBUSELOCAL="n"
1719
1720 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
1721 # i.e. CDROMID="1,0,0"
1722 CDROMID=""
1723
1724 # program paths - defaults to checking your $PATH
1725 # mp3
1726 LAME=lame
1727 GOGO=gogo
1728 BLADEENC=bladeenc
1729 L3ENC=l3enc
1730 XINGMP3ENC=xingmp3enc
1731 MP3ENC=mp3enc
1732 # ogg
1733 VORBIZE=vorbize
1734 OGGENC=oggenc
1735 # flac
1736 FLAC=flac
1737 # speex
1738 SPEEXENC=speexenc
1739 # mpp (Musepack)
1740 MPPENC=mppenc
1741
1742 ID3=id3
1743 ID3V2=id3v2
1744 CDPARANOIA=cdparanoia
1745 CDDA2WAV=cdda2wav
1746 DAGRAB=dagrab
1747 CDDAFS=cp
1748 CDDISCID=cd-discid
1749 CDDBTOOL=cddb-tool
1750 EJECT=eject
1751 MD5SUM=md5sum
1752 DISTMP3=distmp3
1753 VORBISCOMMENT=vorbiscomment
1754 METAFLAC=metaflac
1755 NORMALIZE=normalize-audio
1756 CDSPEED=eject
1757 VORBISGAIN=vorbisgain
1758
1759 # Options for programs called from abcde
1760 # mp3
1761 LAMEOPTS=
1762 GOGOOPTS=
1763 BLADEENCOPTS=
1764 L3ENCOPTS=
1765 XINGMP3ENCOPTS=
1766 MP3ENCOPTS=
1767 # ogg
1768 VORBIZEOPTS=
1769 OGGENCOPTS=
1770 # flac
1771 FLACOPTS=
1772 # speex
1773 SPEEXENCOPTS=
1774 # mpc
1775 MPPENCOPTS=
1776
1777 ID3OPTS=
1778 ID3V2OPTS=
1779 CDPARANOIAOPTS=
1780 CDDA2WAVOPTS=
1781 DAGRABOPTS=
1782 CDDAFSOPTS="-f"
1783 CDDBTOOLOPTS=
1784 EJECTOPTS=
1785 DISTMP3OPTS=
1786 NORMALIZEOPTS=
1787 CDSPEEDOPTS="-x"
1788 CDSPEEDVALUE=
1789
1790 # Default to one process if -j isn't specified
1791 MAXPROCS=1
1792
1793 # List of actions to perform - by default, run to completion
1794 ACTIONS=cddb,read,encode,tag,move,clean
1795
1796 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
1797 # Let's use these checkings to determine the OS flavour, which will be used later
1798 if [ X$(uname) = "XFreeBSD" ] ; then
1799         HTTPGET=fetch
1800         NEEDCDROMID=y
1801         OSFLAVOUR=FBSD
1802 elif [ X$(uname) = "XDarwin" ] ; then
1803         HTTPGET=curl
1804         OSFLAVOUR=OSX
1805         # We should have disktool in OSX, but let's be sure...
1806         NEEDDISKTOOL=y
1807 elif [ X$(uname) = "XOpenBSD" ] ; then
1808         HTTPGET=wget
1809         MD5SUM=md5
1810 else
1811         HTTPGET=wget
1812 fi
1813
1814 # If CDDBAVAIL is set to n, no CDDB read is done
1815 # If USEID3 is set to n, no ID3 tagging is done
1816 CDDBAVAIL=y
1817 USEID3=y
1818
1819 if [ -z "$OUTPUTDIR" ]; then
1820         OUTPUTDIR=$(pwd)
1821 fi
1822
1823 if [ -z "$WAVOUTPUTDIR" ]; then
1824         WAVOUTPUTDIR="$OUTPUTDIR"
1825 fi
1826
1827 # Load system defaults
1828 if [ -r /etc/abcde.conf ]; then
1829         . /etc/abcde.conf
1830 fi
1831 # Load user preference defaults
1832 if [ -r $HOME/.abcde.conf ]; then
1833         . $HOME/.abcde.conf
1834 fi
1835
1836 # By this time, we need some HTTPGETOPTS already defined.
1837 # If the user has defined a non-default HTTPGET method, we should not be empty.
1838
1839 if [ "$HTTPGETOPTS" = "" ] ; then
1840         case $HTTPGET in
1841                 wget) HTTPGETOPTS="-q -O -";;
1842                 curl) HTTPGETOPTS="-f -s";;
1843                 fetch)HTTPGETOPTS="-q -o -";;
1844                 *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
1845         esac
1846 fi
1847
1848 # If the CDROM has not been set yet, find a suitable one.
1849 # If this is a devfs system, default to /dev/cdroms/cdrom0
1850 # instead of /dev/cdrom
1851 if [ "$CDROM" = "" ] ; then
1852         if [ -e /dev/cdroms/cdrom0 ]; then
1853                 CDROM=/dev/cdroms/cdrom0
1854         elif [ -e /dev/cdrom ]; then
1855                 CDROM=/dev/cdrom
1856         elif [ -e /dev/cd0c ]; then
1857                 CDROM=/dev/cd0c
1858         elif [ -e /dev/acd0c ]; then
1859                 CDROM=/dev/acd0c
1860         elif [ -e /dev/disk1 ]; then
1861                 CDROM=/dev/disk1
1862         fi
1863 fi
1864
1865 # Parse command line options
1866 #while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:t:T:vVx opt ; do
1867 while getopts 1a:A:bc:C:d:Dhj:klLnNo:pr:Rs:S:t:T:vVxw:W: opt ; do
1868         case "$opt" in
1869                 1) ONETRACK=y ;;
1870                 a) ACTIONS="$OPTARG" ;;
1871                 A) EXPACTIONS="$OPTARG";;
1872                 b) BATCH=y ;;
1873                 c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
1874                 C) DISCID="${OPTARG#abcde.}" ;;
1875                 d) CDROM="$OPTARG" ;;
1876                 D) set -x ;;
1877                 h) usage; exit ;;
1878 #               f) FORCECDDBUSELOCAL=y ;;
1879                 i) INLINETAG=y ;;
1880                 j) MAXPROCS="$OPTARG" ;;
1881                 k) KEEPWAVS=y ;;
1882                 l) LOWDISK=y ;;
1883                 L) CDDBUSELOCAL=y ;;
1884                 n) CDDBAVAIL=n ;;
1885                 N) INTERACTIVE=n ;;
1886                 m) DOSPLAYLIST=y ;;
1887                 o) OUTPUTTYPE="$OPTARG" ;;
1888                 p) PADTRACKS=y ;;
1889                 P) USEPIPES=y ;;
1890                 r) REMOTEHOSTS="$OPTARG" ;;
1891                 R) REPLAYGAIN=y ;;
1892                 s) STARTTRACKNUMBER="$OPTARG" ;;
1893                 S) CDSPEEDVALUE="$OPTARG" ;;
1894 #               t) PREPROCESSFORMATS="$OPTARG"
1895 #                  PREPROCESS=y ;;
1896 #               T) POSTPROCESSFORMATS="$OPTARG" ;;
1897                 t) STARTTRACKNUMBER="$OPTARG" ;;
1898                 T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
1899                 v) 
1900                    echo "This is abcde v$VERSION."
1901                    echo "Usage: abcde [options] [tracks]"
1902                    echo "abcde -h for extra help"
1903                    exit
1904                    ;;
1905                 V) EXTRAVERBOSE="y" ;;
1906                 x) EJECTCD="y" ;;
1907                 w) COMMENT="$OPTARG" ;;
1908                 W) STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}" ;;
1909                 ?) usage; exit ;;
1910         esac
1911 done
1912
1913 shift $(($OPTIND - 1))
1914
1915 # Decide if we can continue. TO_REMOVE as soon as we find out about dagrab
1916 if [ "$ONETRACK" = "y" ] ; then 
1917         case "$CDROMREADERSYNTAX" in
1918                 dagrab|debug) echo "abcde error: ONETRACK reading is not suported with "$CDROMREADERSYNTAX" yet"
1919                               exit 1 ;;
1920         esac
1921         if [ "$BATCH" = "y" ]; then
1922                 echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
1923         fi
1924         # It does not matter how many tracks we want. In ONETRACK mode we grab them all
1925         if [ $# -gt 0 ]; then
1926                 vecho "ONETRACK mode selected: grabbing all tracks..."
1927         fi
1928 else
1929         while [ $# -gt 0 ]; do
1930                 # Range parsing code courtesy of Vincent Ho
1931                 RSTART=$(echo $1 | cut -f1 -d-)
1932                 REND=$(echo $1 | cut -f2 -d-)
1933                 if [ "$RSTART" = "$REND" ]; then
1934                         NEWTRACKS="$RSTART"
1935                 else
1936                         NEWTRACKS=$(f_seq_line $RSTART $REND)
1937                 fi
1938                 TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
1939                 shift
1940         done
1941 fi
1942
1943 # List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
1944 # List of experimental actions: retag,transcode
1945
1946 # Determine what actions are to be done from $ACTIONS and set the
1947 # following environment variables for them:
1948 DOCDDB=n
1949 DOREAD=n
1950 DONORMALIZE=n
1951 DOPREPROCESS=n
1952 DOENCODE=n
1953 DOPOSTPROCESS=n
1954 DOTAG=n
1955 DOMOVE=n
1956 DOPLAYLIST=n
1957 DOCLEAN=n
1958
1959 for ACTION in $(echo $ACTIONS | tr , \ )
1960 do
1961         case $ACTION in
1962         cddb) DOCDDB=y;;
1963         read) DOREAD=y;;
1964         normalize) DONORMALIZE=y; DOREAD=y;;
1965 #       preprocess) DOPREPROCESS=y; DOREAD=y;;
1966         encode) DOENCODE=y; DOREAD=y;;
1967 #       postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
1968         tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
1969         move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
1970         playlist) DOCDDB=y; DOPLAYLIST=y;;
1971         clean) DOCLEAN=y;;
1972         esac
1973 done
1974
1975 # Sanity checks:
1976
1977 # At this point a CDROM has to be defined, so we check it exists.
1978 if [ "$CDROM" != "" ] ; then 
1979         if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
1980                 if [ "$OSFLAVOUR" = "FBSD" ]; then
1981                         if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
1982                                 echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
1983                                 echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
1984                                 exit 1
1985                         fi
1986                 fi
1987         elif [ ! -e $CDROM ] ; then
1988                 echo "abcde error: CDROM device cannot be found." >&2
1989                 exit 1
1990         fi
1991 else
1992         echo "abcde error: CDROM has not been defined or cannot be found" >&2
1993         exit 1
1994 fi
1995
1996 # Decide which CDROM reader we're gonna use
1997 case "$CDROMREADERSYNTAX" in
1998         cdparanoia|debug)
1999                 CDROMREADER="$CDPARANOIA"
2000                 CDROMREADEROPTS="$CDPARANOIAOPTS"
2001                 ;;
2002         cdda2wav)
2003                 CDROMREADER="$CDDA2WAV"
2004                 CDROMREADEROPTS="$CDDA2WAVOPTS"
2005                 ;;
2006         dagrab)
2007                 CDROMREADER="$DAGRAB"
2008                 CDROMREADEROPTS="$DAGRABOPTS"
2009                 ;;
2010         cddafs)
2011                 CDROMREADER="$CDDAFS"
2012                 CDROMREADEROPTS="$CDDAFSOPTS"
2013                 ;;
2014 esac
2015
2016 # There's only one normalize...
2017 case "$NORMALIZERSYNTAX" in
2018         default|normalize)
2019                 NORMALIZER="$NORMALIZE"
2020                 NORMALIZEROPTS="$NORMALIZEOPTS"
2021                 ;;
2022 esac
2023
2024 # 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
2025
2026 # Getting ready for multiple output changes
2027 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
2028 do
2029         case $OUTPUT in
2030                 ogg)  [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
2031                       [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
2032                       [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
2033                         ;;
2034                 mp3)  [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
2035                       [ "$DOTAG" = "y" ] && NEEDTAGGER=y
2036                         ;;
2037                 flac) [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
2038                       [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
2039                         ;;
2040                 spx) [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc ;;
2041                 mpc) [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc ;;
2042                 *) echo "abcde error: Invalid OUTPUTTYPE defined" >&2
2043                    exit 1
2044                    ;;
2045         esac
2046 done
2047
2048 # decide which encoder
2049 case "$MP3ENCODERSYNTAX" in
2050         lame)
2051                 MP3ENCODEROPTS="$LAMEOPTS"
2052                 MP3ENCODER="$LAME"
2053                 ;;
2054         gogo)
2055                 MP3ENCODEROPTS="$GOGOOPTS"
2056                 MP3ENCODER="$GOGO"
2057                 ;;
2058         bladeenc)
2059                 MP3ENCODEROPTS="$BLADEENCOPTS"
2060                 MP3ENCODER="$BLADEENC"
2061                 ;;
2062         l3enc)
2063                 MP3ENCODEROPTS="$L3ENCOPTS"
2064                 MP3ENCODER="$L3ENC"
2065                 ;;
2066         xingmp3enc)
2067                 MP3ENCODEROPTS="$XINGMP3ENCOPTS"
2068                 MP3ENCODER="$XINGMP3ENC"
2069                 ;;
2070         mp3enc)
2071                 MP3ENCODEROPTS="$MP3ENCOPTS"
2072                 MP3ENCODER="$MP3ENC"
2073                 ;;
2074 esac
2075 case "$OGGENCODERSYNTAX" in
2076         vorbize)
2077                 OGGENCODEROPTS="$VORBIZEOPTS"
2078                 OGGENCODER="$VORBIZE"
2079                 ;;
2080         oggenc)
2081                 OGGENCODEROPTS="$OGGENCOPTS"
2082                 OGGENCODER="$OGGENC"
2083                 ;;
2084 esac
2085 case "$FLACENCODERSYNTAX" in
2086         flac)
2087                 FLACENCODEROPTS="$FLACOPTS"
2088                 FLACENCODER="$FLAC"
2089                 ;;
2090 esac
2091 case "$SPEEXENCODERSYNTAX" in
2092         speexenc)
2093                 SPEEXENCODEROPTS="$SPEEXENCOPTS"
2094                 SPEEXENCODER="$SPEEXENC"
2095                 ;;
2096 esac
2097 case "$MPPENCODERSYNTAX" in
2098         mppenc)
2099                 MPPENCODEROPTS="$MPPENCOPTS"
2100                 MPPENCODER="$MPPENC"
2101                 ;;
2102 esac
2103
2104 # and which tagger
2105
2106 if [ "$ID3TAGV" = "1" ]; then
2107         TAGGER="$ID3"
2108         TAGGEROPTS="$ID3OPTS"
2109 else
2110         TAGGER="$ID3V2"
2111         TAGGEROPTS="$ID3V2OPTS"
2112 fi
2113
2114 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
2115
2116 if [ "$ENCNICE" ]; then
2117         ENCNICE="-n $ENCNICE"
2118 fi
2119 if [ "$READNICE" ]; then
2120         READNICE="-n $READNICE"
2121 fi
2122 if [ "$DISTMP3NICE" ]; then
2123         DISTMP3NICE="-n $DISTMP3NICE"
2124 fi
2125
2126 # Don't check for stuff if it's not needed
2127 if [ "$REMOTEHOSTS" ]; then NEEDDISTMP3=y; fi
2128 [ "$DONORMALIZE" = "y" ] && NEEDNORMALIZER=y
2129 [ "$EJECTCD" = "y" ] && NEEDEJECT=y
2130 [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ] && NEEDHTTPGET=y
2131
2132 if [ X"$CDSPEEDVALUE" != "X" ]; then
2133         case "$CDROMREADERSYNTAX" in
2134                 cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
2135                 *) NEEDCDSPEED=y ;;
2136         esac
2137 fi
2138
2139
2140 # Make sure a buncha things exist
2141 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
2142         $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
2143         ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
2144         ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
2145         ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
2146         ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
2147         ${NEEDVORBISGAIN+$VORBISGAIN}
2148 do
2149         # Cut off the command-line options we just added in
2150         X=$(echo $X | cut -d' ' -f2)
2151         if [ "$(which $X)" = "" ]; then
2152                 echo "abcde error: $X is not in your path." >&2
2153                 exit 1
2154         elif [ ! -x $(which $X) ]; then
2155                 echo "abcde error: $X is not executable." >&2
2156                 exit 1
2157         fi
2158 done
2159
2160 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
2161 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
2162 HTTPGET="$HTTPGET $HTTPGETOPTS"
2163
2164 # Here it used to say:
2165 # One thousand lines in, we can start doing stuff with things
2166 # Well, right now we are at line 2157 ;)
2167
2168 # Export needed things so they can be read in this subshell
2169 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
2170 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
2171
2172 # User-definable function to set some things. Use it for
2173 #  - closing the CD tray with eject -t
2174 #  - set the CD speed value with eject -x
2175 vecho -n "Executing customizable pre-read function... "
2176
2177 pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
2178
2179 vecho "done."
2180
2181 do_discid # Get ABCDETEMPDIR created and status file initialized
2182
2183 if [ "$DOCDDB" = "y" ]; then
2184         if [ $CDDBUSELOCAL = "y" ]; then
2185                 do_localcddb
2186         fi
2187         if checkstatus cddb-choice > /dev/null; then
2188                 :
2189         else 
2190                 if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
2191                         do_cddbstat
2192                         do_cddbquery
2193                         do_cddbread
2194                 fi
2195         fi
2196         do_cddbedit
2197
2198         eval $($CDDBTOOL parse "$CDDBDATA")
2199 fi
2200
2201 # Before reading tracks, we set the speed of the device
2202
2203 if [ X"$CDSPEEDVALUE" != "X" ]; then
2204         case "$CDROMREADERSYNTAX" in
2205                 cdparanoia|debug) : ;;
2206                 *) do_cdspeed ;;
2207         esac
2208 fi
2209
2210 if [ "$STRIPDATATRACKS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
2211         case "$CDROMREADERSYNTAX" in
2212                 cdparanoia|debug) 
2213                         # cdparanoia can query the CD, so let's process the TRACKQUEUE list with the results.
2214                         if checkstatus cdparanoia-audio-tracks; then
2215                                 CDTRACKQUEUE=$( cat $ABCDETEMPDIR/cdparanoia-audio-tracks )
2216                         else
2217                                 ## FIXME ##
2218                                 vecho "Querying the CD to obtain a list of valid audio tracks..."
2219                                 $CDROMREADER -Q > $ABCDETEMPDIR/cdparanoia-query 2>&1
2220                                 # Obtain a list of valid audio tracks from the results of the query
2221                                 CDTRACKQUEUE=$( cat $ABCDETEMPDIR/cdparanoia-query | egrep '^[[:space:]]+[[:digit:]]' | awk '{print $1}' | tr -d "." | tr '\n' ' ' )
2222                         fi
2223                         # Obtain the track padding value from the before-processing list and pad the CD list
2224                         TRACKNUMPADDING=$( echo $TRACKQUEUE | awk '{print $1}' | tr -d " \n" | wc -c )
2225                         for TRACK in $CDTRACKQUEUE ; do
2226                                 TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
2227                                 PADNEWTRACKQUEUE=$(echo $PADNEWTRACKQUEUE $TRACKNUM)
2228                         done
2229                         CDTRACKQUEUE=$PADNEWTRACKQUEUE
2230                         # Now, compare if the values in the list are valid tracks in the CD
2231                         for TRACK in $TRACKQUEUE; do
2232                                 if echo $CDTRACKQUEUE | grep $TRACK >/dev/null ; then
2233                                         NEWTRACKQUEUE="$NEWTRACKQUEUE $TRACK"
2234                                 fi
2235                         done
2236                         TRACKQUEUE="$NEWTRACKQUEUE"
2237                 ;;
2238         esac
2239 fi
2240
2241 # Create playlist if needed (backgroundable) and start reading in tracks
2242
2243 (
2244
2245 if [ "$ONETRACK" = "y" ]; then :; else
2246         if [ "$DOPLAYLIST" = "y" ]; then
2247                 echo Creating playlist... >&2
2248                 do_playlist
2249         fi
2250 fi
2251
2252 # For the lowdisk option, only one program is running at once so the encoder
2253 # can be unsilenced right away.
2254 if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
2255         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2256 fi
2257
2258 if [ "$ONETRACK" = "y" ]; then 
2259         FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}' )
2260         TRACKS="$FIRSTTRACK"
2261         for UTRACKNUM in $TRACKQUEUE; do :;done
2262         if checkstatus readtrack-$FIRSTTRACK; then :; else
2263                 do_cdread_one $UTRACKNUM $FIRSTTRACK
2264         fi
2265 else
2266         for UTRACKNUM in $TRACKQUEUE
2267         do
2268                 if [ "$DOREAD" = "y" ]; then
2269                         if checkstatus readtrack-$UTRACKNUM; then :; else
2270                                 do_cdread $UTRACKNUM
2271                                 if [ "$?" != "0" ]; then
2272                                         # CD read failed - don't give the goahead to
2273                                         # the encoder
2274                                         echo NO
2275                                         exit
2276                                 fi
2277                         fi
2278                 fi
2279                 if [ "$BATCH" = "y" ]; then
2280                     :
2281                 else
2282                         echo NEXTTRACK # Get the encoder machine churning again
2283                         if [ "$DOREAD" = "y" ]; then
2284                                 if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
2285                                         until checkstatus encodetrack-$UTRACKNUM
2286                                         do
2287                                                 if checkerrors encodetrack-$UTRACKNUM; then
2288                                                         break
2289                                                 fi
2290                                                 sleep 2
2291                                         done
2292                                 fi
2293                         fi
2294                 fi
2295         done
2296 fi
2297
2298 # Now that we're done the encoding can be loud again -
2299 # if we're not using SMP.
2300 if [ "$MAXPROCS" = "1" ]; then
2301         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2302 fi
2303
2304 # All tracks read, start encoding.
2305 if [ "$BATCH" = "y" ] || [ "$ONETRACK" = "y" ]; then
2306         echo NEXTTRACK
2307 fi
2308
2309 # We are now finished with the cdrom - it can be safely ejected. Note that
2310 # abcde will not have completed yet.
2311 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
2312         # We check if the disk we are processing is actually the disk inside the 
2313         # CD tray. If not, we do not eject the CD, since it might be so that the
2314         # user ejected it manually.
2315         #CURRENTTRACKINFO=$($CDDISCID $CDROM)
2316         #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
2317         # More FreeBSD bits.
2318         if [ X"$(uname)" = X"FreeBSD" ] ; then
2319                 # FreeBSD eject uses the EJECT environment variable to name the CDROM
2320                 # but in this script EJECT is in the envionment and names the program
2321                 eject=$EJECT
2322                 unset EJECT
2323                 # The FreeBSD eject needs "adc0" not "/dev/adc0c"
2324                 cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
2325                 $eject $EJECTOPTS $cd
2326         elif [ X"$(uname)" = X"Darwin" ] ; then
2327                 disktool -e ${CDROM#/dev/} 0
2328         else
2329                 $EJECT $EJECTOPTS $CDROM
2330         fi
2331         #fi
2332 fi
2333
2334 ) | (
2335
2336 ## Do we need to pre-process 
2337 #if [ x"$PREPROCESS" = "x" ] ; then
2338 #       cat
2339 #else
2340 #       for PRETRACKNUM in $TRACKQUEUE
2341 #       do
2342 #               read GOAHEAD
2343 #               if [ "$GOAHEAD" = "NO" ]; then break; fi
2344 #               PREPROCEED=
2345 #               until [ $PREPROCEED ]
2346 #               do
2347 #                       if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
2348 #                       # all locations are working, wait and try again later
2349 #                       if [ ! $PREPROCEED ]; then sleep 3; fi
2350 #               done
2351 #               ( do_preprocess $PRETRACKNUM 
2352 #               echo "NEXTTRACK"
2353 #               ) &
2354 #       done
2355 #fi
2356 #
2357 #) | (
2358
2359 # In batch mode, we want all tracks to be read first.
2360 if [ "$BATCH" = "y" ]; then
2361         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2362         if [ "$GOAHEAD" = "NO" ]; then break; fi
2363         for LASTTRACK in $TRACKQUEUE; do :; done
2364         if checkstatus readtrack-$LASTTRACK; then
2365                 if [ "$DONORMALIZE" = "y" ]; then
2366                         if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
2367                         if checkerrors batch-normalize; then exit; fi
2368                 fi
2369                 if [ "$DOENCODE" = "y" ]; then
2370                         if checkstatus encodetrack-$LASTTRACK; then :; else do_batch_encode; fi
2371                         if checkerrors batch-encode; then exit; fi
2372                 fi
2373         fi
2374 fi
2375
2376 # If we are using ONETRACK, we can proceed with the normal encoding using just the $FIRSTTRACK as TRACKQUEUE
2377 if [ "$ONETRACK" = "y" ] ; then
2378         FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}')
2379         TRACKQUEUE=$FIRSTTRACK
2380         TRACKS="$FIRSTTRACK"
2381 fi
2382
2383 # Do the encoding, including parallelization of remote encoding
2384 # Figure out where each track is going to be encoded
2385 ENCODELOCATIONS="$(echo $REMOTEHOSTS | tr , ' ')"
2386 if [ "$MAXPROCS" != "0" ]; then
2387         for NUM in $(f_seq_row 1 "$MAXPROCS")
2388         do
2389                 ENCODELOCATIONS="$ENCODELOCATIONS %local$NUM%"
2390         done
2391 fi
2392 # Strip whitespace
2393 ENCODELOCATIONS=$(echo $ENCODELOCATIONS)
2394 for UTRACKNUM in $TRACKQUEUE
2395 do
2396         # Wait for our cue
2397         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2398         if [ "$GOAHEAD" = "NO" ]; then break; fi
2399         # find out where this track is to be encoded
2400         if [ "$DOENCODE" = "y" ]; then
2401                 # Make sure we have a place to encode this, if not, exit stage right
2402                 if [ -z "$ENCODELOCATIONS" ]; then
2403                         continue
2404                 fi
2405                 PROCEED=
2406                 until [ $PROCEED ]
2407                 do
2408                         for LOCATION in $ENCODELOCATIONS
2409                         do
2410                                 PREVIOUSTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2411                                 # check first if a track has ever been assigned to this location
2412                                 if [ -z "$PREVIOUSTRACK" ]; then PROCEED=y; break; fi
2413                                 # If it errored out, rebuild $ENCODELOCATIONS without this location in it
2414                                 if checkerrors encodetrack-$PREVIOUSTRACK; then
2415                                         for TEMPLOCATION in $ENCODELOCATIONS
2416                                         do
2417                                                 if [ "$TEMPLOCATION" != "$LOCATION" ]; then
2418                                                         TEMPENCODELOCATIONS="$TEMPENCODELOCATIONS $TEMPLOCATION"
2419                                                 fi
2420                                         done
2421                                         ENCODELOCATIONS=$(echo $TEMPENCODELOCATIONS)
2422                                         ABORT=y
2423                                         PROCEED=y
2424                                         break
2425                                 fi
2426                                 # We're still here, this location must have been previously assigned,
2427                                 # and last completed without error - check if it's done with the
2428                                 # previous track yet
2429                                 if checkstatus encodetrack-$PREVIOUSTRACK; then PROCEED=y; break; fi
2430                         done
2431                         # all locations are working, wait and try again later
2432                         if [ ! $PROCEED ]; then sleep 3; fi
2433                 done
2434                 # Record the location we're about to encode the next track at
2435                 echo "encodetracklocation-$LOCATION=$UTRACKNUM" >> "$ABCDETEMPDIR/status"
2436         fi
2437         # Don't proceed with the rest of the loop if we can't encode
2438         if [ "$ABORT" ]; then continue; fi
2439         # Set TRACKNUM, TRACKNAME
2440         if [ -e "$CDDBDATA" ]; then
2441                 if [ "$ONETRACK" = "y" ]; then 
2442                         TRACKNAME="$DALBUM"
2443                         TRACKNUM="$FIRSTTRACK"
2444                         splitvarious
2445                 else
2446 #                       TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
2447                         TRACKNUM=$UTRACKNUM
2448                         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
2449                         TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
2450                         splitvarious
2451                 fi
2452         fi
2453         # You can't encode a file which needs to be normalized before finishing
2454         # You can't tag a file before it's finished encoding -
2455         # thus all of this is backgrounded together
2456         (
2457         if [ "$DONORMALIZE" = "y" ]; then
2458                 if checkstatus readtrack-$UTRACKNUM; then
2459                         if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
2460                 fi
2461         fi
2462         if [ "$DOENCODE" = "y" ]; then
2463                 if checkstatus readtrack-$UTRACKNUM; then
2464                         #if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION; fi
2465                         if [ "$DONORMALIZE" = "y" ]; then
2466                                 if checkstatus normalizetrack-$UTRACKNUM; then
2467                                         if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2468                                 fi
2469                         else
2470                                 if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2471                         fi
2472                 fi
2473         fi
2474         if [ "$DOTAG" = "y" ]; then
2475                 if checkstatus encodetrack-$UTRACKNUM; then
2476                         if checkstatus tagtrack-$UTRACKNUM; then :; else do_tag $UTRACKNUM; fi
2477                 fi
2478         fi
2479         if [ "$DOMOVE" = "y" ]; then
2480                 if checkstatus tagtrack-$UTRACKNUM; then
2481                         if checkstatus movetrack-$UTRACKNUM; then :; else do_move $UTRACKNUM; fi
2482                 fi
2483         fi
2484         ) &
2485 done
2486 # Go through it again and make sure there's no distmp3 stragglers, otherwise
2487 # we'll delete the files they're working on
2488 if [ "$DOENCODE" = "y" ]; then
2489         PROCEED=
2490         until [ $PROCEED ]
2491         do
2492                 PROCEED=y
2493                 for LOCATION in $ENCODELOCATIONS
2494                 do
2495                         CHECKTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2496                         # "How can he give us a status update, if he's DEAD?"
2497                         if checkstatus encodetrack-$CHECKTRACK; then
2498                                 continue
2499                         fi
2500                         # Nothing to see here please go quietly back to your homes
2501                         if [ -z "$CHECKTRACK" ]; then continue; fi
2502                         # You're still here? Maybe there is something...
2503                         if checkstatus encodetrack-$CHECKTRACK; then :; else PROCEED= ; break; fi
2504                 done
2505                 # hold up
2506                 if [ ! $PROCEED ]; then sleep 5; fi
2507         done
2508 fi
2509 # If the above didn't catch the stragglers, this will
2510 wait
2511 # Check to see if run_command logged any errors
2512 if [ -f "$ABCDETEMPDIR/errors" ]; then
2513         echo "The following commands failed to run:"
2514         cat "$ABCDETEMPDIR/errors"
2515         # Don't clean up
2516         DOCLEAN=n
2517 fi
2518 if [ "$KEEPWAVS" = "y" ];then
2519         # Don't clean up
2520         DOCLEAN=n
2521 fi
2522 if [ "$DOCLEAN" = "y" ]; then
2523         # Wipe all the evidence
2524         # Gimme gimme gimme some more time!
2525         sleep 5
2526         rm -rf "$ABCDETEMPDIR"
2527         echo "Finished."
2528 else
2529         echo "Finished. Not cleaning $ABCDETEMPDIR."
2530 fi
2531 )
2532 exit 0