- trunk/debian/control
[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.4"
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-tags-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 -d $CDROM -Q --verbose 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 # do_cdread onetrack [firsttrack] [lasttrack]
1571
1572 do_cdread ()
1573 {
1574         # The commands here don't go through run_command because they're never supposed to be silenced
1575         # return codes need to be doublechecked anyway, however
1576         if [ "$1" = "onetrack" ]; then
1577                 # FIXME # Add the possibility of grabbing ranges of tracks in onetrack
1578                 # FIXME # Until then, we grab the whole CD in one track, no matter what the user said
1579                 # We need the first and last track for cdda2wav
1580                 FIRSTTRACK=$2
1581                 LASTTRACK=$3
1582                 case "$CDROMREADERSYNTAX" in
1583                         cdparanoia) UTRACKNUM="1-" ;;
1584                         cdda2wav) UTRACKNUM="1+$LASTRACK" ;;
1585                         *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
1586                            exit 1 ;;
1587                 esac
1588         else
1589                 UTRACKNUM=$1
1590         fi
1591         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1592         WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
1593         OUTDATA="$ABCDETEMPDIR/track$UTRACKNUM.$OUTPUTTYPE"
1594         if [ -r "$CDDBDATA" ]; then
1595                 TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
1596                 echo "Grabbing track $UTRACKNUM: $TRACKNAME..." >&2
1597         else
1598                 echo "Grabbing track $UTRACKNUM..." >&2
1599         fi
1600         case "$CDROMREADERSYNTAX" in
1601                 cdparanoia) nice $READNICE $CDROMREADER -d $CDROM $UTRACKNUM "$WAVDATA" >&2 ;;
1602                 cdda2wav)
1603                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1604                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1605                                 disktool -u ${CDROM#/dev/} 0
1606                                 # Also, in OSX the cdrom device for cdda2wav changes...
1607                                 CDDA2WAVCDROM="IODVDServices"
1608                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1609                                 CDDA2WAVCDROM="$CDROMID"
1610                         else
1611                                 if [ "$CDROMID" = "" ]; then
1612                                         CDDA2WAVCDROM="$CDROM"
1613                                 else
1614                                         CDDA2WAVCDROM="$CDROMID"
1615                                 fi
1616                         fi
1617                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t $UTRACKNUM "$WAVDATA" >&2 
1618                         ;;
1619                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -f $WAVDATA -v $UTRACKNUM >&2 ;;
1620                 cddafs)
1621                         # Find the track's mounted path
1622                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1623                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1624                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
1625                         # If the file exists, copy it
1626                         if [ -e "$FILEPATH" ] ; then
1627                                 nice $READNICE $CDROMREADER "$FILEPATH" "$WAVDATA" >&2
1628                         else
1629                                 false
1630                         fi ;;
1631                 debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] "$WAVDATA" >&2 ;;
1632         esac
1633         RETURN=$?
1634         if [ "$RETURN" != "0" -o ! -s "$WAVDATA" ]; then
1635                 # Thank goodness errors is only machine-parseable up to the
1636                 # first colon, otherwise this woulda sucked
1637                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
1638                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
1639                 fi
1640                 echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1641                 return $RETURN
1642         else
1643                 echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
1644         fi
1645 }
1646
1647 # do_cdspeed
1648 # No values accepted, only uses env variables
1649 do_cdspeed () 
1650 {
1651         if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
1652                 vecho "Setting CD speed to ${CDSPEEDVALUE}x"
1653         else
1654                 echo "abcde: unable to set the device speed" >&2
1655         fi
1656 }
1657
1658 # vecho [message]
1659 #
1660 # vecho outputs a message if EXTRAVERBOSE is selected
1661 vecho ()
1662 {
1663 if [ x"$EXTRAVERBOSE" != "x" ]; then
1664         echo $@
1665 fi
1666 }
1667
1668 # User-redefinable functions
1669 # Custom filename munging:
1670 mungefilename ()
1671 {
1672         echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
1673 }
1674
1675 # Custom genre munging:
1676 mungegenre ()
1677 {
1678         echo $CDGENRE | tr "[:upper:]" "[:lower:]"
1679 }
1680
1681 # pre_read
1682 # Empty pre_read function, to be defined in the configuration file.
1683 pre_read ()
1684 {
1685 :
1686 }
1687
1688 ###############################################################################
1689 # End of functions
1690 #
1691 # Start of execution
1692 ###############################################################################
1693
1694 # Builtin defaults
1695 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
1696 CDDBSUBMIT=freedb-submit@freedb.org
1697 CDDBPROTO=5
1698 HELLOINFO="$(whoami)@$(hostname)"
1699 INTERACTIVE=y
1700 CDROMREADERSYNTAX=cdparanoia
1701 OUTPUTTYPE=ogg
1702 ENCODERSYNTAX=default
1703
1704 MP3ENCODERSYNTAX=default
1705 OGGENCODERSYNTAX=default
1706 FLACENCODERSYNTAX=default
1707 SPEEXENCODERSYNTAX=default
1708 MPPENCODERSYNTAX=default
1709 NORMALIZERSYNTAX=default
1710
1711 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
1712 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
1713 #VAOUTPUTFORMAT=${OUTPUTFORMAT}
1714 VAOUTPUTFORMAT='Various-${ALBUMFILE}/${TRACKNUM}.${ARTISTFILE}-${TRACKFILE}'
1715 ONETRACKOUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${ALBUMFILE}'
1716 VAONETRACKOUTPUTFORMAT='Various-${ALBUMFILE}/${ALBUMFILE}'
1717 PLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1718 PLAYLISTDATAPREFIX=''
1719 VAPLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1720 VAPLAYLISTDATAPREFIX=''
1721 DOSPLAYLIST=n
1722 COMMENT=''
1723 ID3TAGV=2
1724 ENCNICE=10
1725 READNICE=10
1726 DISTMP3NICE=10
1727 VARIOUSARTISTS=n
1728 VARIOUSARTISTSTYLE=forward
1729 KEEPWAVS=n
1730 PADTRACKS=n
1731 CDDBCOPYLOCAL="n"
1732 CDDBLOCALDIR="$HOME/.cddb"
1733 CDDBUSELOCAL="n"
1734
1735 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
1736 # i.e. CDROMID="1,0,0"
1737 CDROMID=""
1738
1739 # program paths - defaults to checking your $PATH
1740 # mp3
1741 LAME=lame
1742 GOGO=gogo
1743 BLADEENC=bladeenc
1744 L3ENC=l3enc
1745 XINGMP3ENC=xingmp3enc
1746 MP3ENC=mp3enc
1747 # ogg
1748 VORBIZE=vorbize
1749 OGGENC=oggenc
1750 # flac
1751 FLAC=flac
1752 # speex
1753 SPEEXENC=speexenc
1754 # mpp (Musepack)
1755 MPPENC=mppenc
1756
1757 ID3=id3
1758 ID3V2=id3v2
1759 CDPARANOIA=cdparanoia
1760 CDDA2WAV=cdda2wav
1761 DAGRAB=dagrab
1762 CDDAFS=cp
1763 CDDISCID=cd-discid
1764 CDDBTOOL=cddb-tool
1765 EJECT=eject
1766 MD5SUM=md5sum
1767 DISTMP3=distmp3
1768 VORBISCOMMENT=vorbiscomment
1769 METAFLAC=metaflac
1770 NORMALIZE=normalize-audio
1771 CDSPEED=eject
1772 VORBISGAIN=vorbisgain
1773
1774 # Options for programs called from abcde
1775 # mp3
1776 LAMEOPTS=
1777 GOGOOPTS=
1778 BLADEENCOPTS=
1779 L3ENCOPTS=
1780 XINGMP3ENCOPTS=
1781 MP3ENCOPTS=
1782 # ogg
1783 VORBIZEOPTS=
1784 OGGENCOPTS=
1785 # flac
1786 FLACOPTS=
1787 # speex
1788 SPEEXENCOPTS=
1789 # mpc
1790 MPPENCOPTS=
1791
1792 ID3OPTS=
1793 ID3V2OPTS=
1794 CDPARANOIAOPTS=
1795 CDDA2WAVOPTS=
1796 DAGRABOPTS=
1797 CDDAFSOPTS="-f"
1798 CDDBTOOLOPTS=
1799 EJECTOPTS=
1800 DISTMP3OPTS=
1801 NORMALIZEOPTS=
1802 CDSPEEDOPTS="-x"
1803 CDSPEEDVALUE=
1804
1805 # Default to one process if -j isn't specified
1806 MAXPROCS=1
1807
1808 # List of actions to perform - by default, run to completion
1809 ACTIONS=cddb,read,encode,tag,move,clean
1810
1811 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
1812 # Let's use these checkings to determine the OS flavour, which will be used later
1813 if [ X$(uname) = "XFreeBSD" ] ; then
1814         HTTPGET=fetch
1815         NEEDCDROMID=y
1816         OSFLAVOUR=FBSD
1817 elif [ X$(uname) = "XDarwin" ] ; then
1818         HTTPGET=curl
1819         OSFLAVOUR=OSX
1820         # We should have disktool in OSX, but let's be sure...
1821         NEEDDISKTOOL=y
1822 elif [ X$(uname) = "XOpenBSD" ] ; then
1823         HTTPGET=wget
1824         MD5SUM=md5
1825 else
1826         HTTPGET=wget
1827 fi
1828
1829 # If CDDBAVAIL is set to n, no CDDB read is done
1830 # If USEID3 is set to n, no ID3 tagging is done
1831 CDDBAVAIL=y
1832 USEID3=y
1833
1834 if [ -z "$OUTPUTDIR" ]; then
1835         OUTPUTDIR=$(pwd)
1836 fi
1837
1838 if [ -z "$WAVOUTPUTDIR" ]; then
1839         WAVOUTPUTDIR="$OUTPUTDIR"
1840 fi
1841
1842 # Load system defaults
1843 if [ -r /etc/abcde.conf ]; then
1844         . /etc/abcde.conf
1845 fi
1846 # Load user preference defaults
1847 if [ -r $HOME/.abcde.conf ]; then
1848         . $HOME/.abcde.conf
1849 fi
1850
1851 # By this time, we need some HTTPGETOPTS already defined.
1852 # If the user has defined a non-default HTTPGET method, we should not be empty.
1853
1854 if [ "$HTTPGETOPTS" = "" ] ; then
1855         case $HTTPGET in
1856                 wget) HTTPGETOPTS="-q -O -";;
1857                 curl) HTTPGETOPTS="-f -s";;
1858                 fetch)HTTPGETOPTS="-q -o -";;
1859                 *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
1860         esac
1861 fi
1862
1863 # If the CDROM has not been set yet, find a suitable one.
1864 # If this is a devfs system, default to /dev/cdroms/cdrom0
1865 # instead of /dev/cdrom
1866 if [ "$CDROM" = "" ] ; then
1867         if [ -e /dev/cdroms/cdrom0 ]; then
1868                 CDROM=/dev/cdroms/cdrom0
1869         elif [ -e /dev/cdrom ]; then
1870                 CDROM=/dev/cdrom
1871         elif [ -e /dev/cd0c ]; then
1872                 CDROM=/dev/cd0c
1873         elif [ -e /dev/acd0c ]; then
1874                 CDROM=/dev/acd0c
1875         elif [ -e /dev/disk1 ]; then
1876                 CDROM=/dev/disk1
1877         fi
1878 fi
1879
1880 # Parse command line options
1881 #while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:t:T:vVx opt ; do
1882 while getopts 1a:A:bc:C:d:Dhj:klLnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
1883         case "$opt" in
1884                 1) ONETRACK=y ;;
1885                 a) ACTIONS="$OPTARG" ;;
1886                 A) EXPACTIONS="$OPTARG";;
1887                 b) BATCH=y ;;
1888                 c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
1889                 C) DISCID="${OPTARG#abcde.}" ;;
1890                 d) CDROM="$OPTARG" ;;
1891                 D) set -x ;;
1892                 h) usage; exit ;;
1893 #               f) FORCECDDBUSELOCAL=y ;;
1894                 i) INLINETAG=y ;;
1895                 j) MAXPROCS="$OPTARG" ;;
1896                 k) KEEPWAVS=y ;;
1897                 l) LOWDISK=y ;;
1898                 L) CDDBUSELOCAL=y ;;
1899                 n) CDDBAVAIL=n ;;
1900                 N) INTERACTIVE=n ;;
1901                 m) DOSPLAYLIST=y ;;
1902                 o) OUTPUTTYPE="$OPTARG" ;;
1903                 p) PADTRACKS=y ;;
1904                 P) USEPIPES=y ;;
1905                 r) REMOTEHOSTS="$OPTARG" ;;
1906                 R) REPLAYGAIN=y ;;
1907                 s) STARTTRACKNUMBER="$OPTARG" ;;
1908                 S) CDSPEEDVALUE="$OPTARG" ;;
1909 #               t) PREPROCESSFORMATS="$OPTARG"
1910 #                  PREPROCESS=y ;;
1911 #               T) POSTPROCESSFORMATS="$OPTARG" ;;
1912                 t) STARTTRACKNUMBER="$OPTARG" ;;
1913                 T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
1914                 v) 
1915                    echo "This is abcde v$VERSION."
1916                    echo "Usage: abcde [options] [tracks]"
1917                    echo "abcde -h for extra help"
1918                    exit
1919                    ;;
1920                 V) EXTRAVERBOSE="y" ;;
1921                 x) EJECTCD="y" ;;
1922                 w) COMMENT="$OPTARG" ;;
1923                 W) STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}" ;;
1924                 ?) usage; exit ;;
1925         esac
1926 done
1927
1928 shift $(($OPTIND - 1))
1929
1930 # Decide if we can continue.
1931 if [ "$ONETRACK" = "y" ]; then 
1932         # FIXME # remove check as soon as we find out about the other readers
1933         case "$CDROMREADERSYNTAX" in
1934                 dagrab|cddafs|debug) echo "abcde error: ONETRACK reading is not suported with "$CDROMREADERSYNTAX" yet"
1935                                          exit 1 ;;
1936         esac
1937         if [ "$BATCH" = "y" ]; then
1938                 echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
1939                 BATCH=n
1940         fi
1941         # It does not matter how many tracks we want. In ONETRACK mode we grab them all
1942         # FIXME # allow ranges of tracks to be selected for onetrack ripping
1943         if [ $# -gt 0 ]; then
1944                 vecho "abcde warning: ONETRACK mode selected, grabbing all tracks..."
1945         fi
1946 else
1947         while [ $# -gt 0 ]; do
1948                 # Range parsing code courtesy of Vincent Ho
1949                 RSTART=$(echo $1 | cut -f1 -d-)
1950                 REND=$(echo $1 | cut -f2 -d-)
1951                 if [ "$RSTART" = "$REND" ]; then
1952                         NEWTRACKS="$RSTART"
1953                 else
1954                         NEWTRACKS=$(f_seq_line $RSTART $REND)
1955                 fi
1956                 TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
1957                 shift
1958         done
1959 fi
1960
1961 # List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
1962 # List of experimental actions: retag,transcode
1963
1964 # Determine what actions are to be done from $ACTIONS and set the
1965 # following environment variables for them:
1966 DOCDDB=n
1967 DOREAD=n
1968 DONORMALIZE=n
1969 DOPREPROCESS=n
1970 DOENCODE=n
1971 DOPOSTPROCESS=n
1972 DOTAG=n
1973 DOMOVE=n
1974 DOPLAYLIST=n
1975 DOCLEAN=n
1976
1977 for ACTION in $(echo $ACTIONS | tr , \ )
1978 do
1979         case $ACTION in
1980         cddb) DOCDDB=y;;
1981         read) DOREAD=y;;
1982         normalize) DONORMALIZE=y; DOREAD=y;;
1983 #       preprocess) DOPREPROCESS=y; DOREAD=y;;
1984         encode) DOENCODE=y; DOREAD=y;;
1985 #       postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
1986         tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
1987         move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
1988         playlist) DOCDDB=y; DOPLAYLIST=y;;
1989         clean) DOCLEAN=y;;
1990         esac
1991 done
1992
1993 # Sanity checks:
1994
1995 # At this point a CDROM has to be defined, so we check it exists.
1996 if [ "$CDROM" != "" ] ; then 
1997         if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
1998                 if [ "$OSFLAVOUR" = "FBSD" ]; then
1999                         if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
2000                                 echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
2001                                 echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
2002                                 exit 1
2003                         fi
2004                 fi
2005         elif [ ! -e $CDROM ] ; then
2006                 echo "abcde error: CDROM device cannot be found." >&2
2007                 exit 1
2008         fi
2009 else
2010         echo "abcde error: CDROM has not been defined or cannot be found" >&2
2011         exit 1
2012 fi
2013
2014 # USEPIPES is not compatible with:
2015 # - multiple outputs
2016 # - normalize
2017 # - anything else?
2018 if [ "$USEPIPES" = "y" ]; then
2019         if [ $(echo $OUTPUTTYPE | tr , \  | wc -w ) -gt 1 ]; then
2020                 echo "abcde error: Unix pipes not compatible with multiple outputs"
2021                 exit 1
2022         fi
2023         if [ "$DONORMALIZE" = "y" ]; then
2024                 echo "abcde error: Unix pipes not compatible with normalizer"
2025                 # FIXME # Do we need to exit or shall we just disable the mode?
2026                 exit 1
2027         fi
2028         if [ "$DOENCODE" = "n" ]; then
2029                 vecho "Disabling Unix pipes since we are not encoding!"
2030                 USEPIPES=n
2031         fi
2032 fi
2033
2034 # Decide which CDROM reader we're gonna use
2035 case "$CDROMREADERSYNTAX" in
2036         cdparanoia|debug)
2037                 CDROMREADER="$CDPARANOIA"
2038                 CDROMREADEROPTS="$CDPARANOIAOPTS"
2039                 ;;
2040         cdda2wav)
2041                 CDROMREADER="$CDDA2WAV"
2042                 CDROMREADEROPTS="$CDDA2WAVOPTS"
2043                 ;;
2044         dagrab)
2045                 CDROMREADER="$DAGRAB"
2046                 CDROMREADEROPTS="$DAGRABOPTS"
2047                 ;;
2048         cddafs)
2049                 CDROMREADER="$CDDAFS"
2050                 CDROMREADEROPTS="$CDDAFSOPTS"
2051                 ;;
2052 esac
2053
2054 # There's only one normalize...
2055 case "$NORMALIZERSYNTAX" in
2056         default|normalize)
2057                 NORMALIZER="$NORMALIZE"
2058                 NORMALIZEROPTS="$NORMALIZEOPTS"
2059                 ;;
2060 esac
2061
2062 # 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
2063
2064 # Getting ready for multiple output changes
2065 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
2066 do
2067         case $OUTPUT in
2068                 ogg)  [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
2069                       [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
2070                       [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
2071                         ;;
2072                 mp3)  [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
2073                       [ "$DOTAG" = "y" ] && NEEDTAGGER=y
2074                         ;;
2075                 flac) [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
2076                       [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
2077                         ;;
2078                 spx) [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc ;;
2079                 mpc) [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc ;;
2080                 *) echo "abcde error: Invalid OUTPUTTYPE defined" >&2
2081                    exit 1
2082                    ;;
2083         esac
2084 done
2085
2086 # decide which encoder
2087 case "$MP3ENCODERSYNTAX" in
2088         lame)
2089                 MP3ENCODEROPTS="$LAMEOPTS"
2090                 MP3ENCODER="$LAME"
2091                 ;;
2092         gogo)
2093                 MP3ENCODEROPTS="$GOGOOPTS"
2094                 MP3ENCODER="$GOGO"
2095                 ;;
2096         bladeenc)
2097                 MP3ENCODEROPTS="$BLADEENCOPTS"
2098                 MP3ENCODER="$BLADEENC"
2099                 ;;
2100         l3enc)
2101                 MP3ENCODEROPTS="$L3ENCOPTS"
2102                 MP3ENCODER="$L3ENC"
2103                 ;;
2104         xingmp3enc)
2105                 MP3ENCODEROPTS="$XINGMP3ENCOPTS"
2106                 MP3ENCODER="$XINGMP3ENC"
2107                 ;;
2108         mp3enc)
2109                 MP3ENCODEROPTS="$MP3ENCOPTS"
2110                 MP3ENCODER="$MP3ENC"
2111                 ;;
2112 esac
2113 case "$OGGENCODERSYNTAX" in
2114         vorbize)
2115                 OGGENCODEROPTS="$VORBIZEOPTS"
2116                 OGGENCODER="$VORBIZE"
2117                 ;;
2118         oggenc)
2119                 OGGENCODEROPTS="$OGGENCOPTS"
2120                 OGGENCODER="$OGGENC"
2121                 ;;
2122 esac
2123 case "$FLACENCODERSYNTAX" in
2124         flac)
2125                 FLACENCODEROPTS="$FLACOPTS"
2126                 FLACENCODER="$FLAC"
2127                 ;;
2128 esac
2129 case "$SPEEXENCODERSYNTAX" in
2130         speexenc)
2131                 SPEEXENCODEROPTS="$SPEEXENCOPTS"
2132                 SPEEXENCODER="$SPEEXENC"
2133                 ;;
2134 esac
2135 case "$MPPENCODERSYNTAX" in
2136         mppenc)
2137                 MPPENCODEROPTS="$MPPENCOPTS"
2138                 MPPENCODER="$MPPENC"
2139                 ;;
2140 esac
2141
2142 # and which tagger
2143
2144 if [ "$ID3TAGV" = "1" ]; then
2145         TAGGER="$ID3"
2146         TAGGEROPTS="$ID3OPTS"
2147 else
2148         TAGGER="$ID3V2"
2149         TAGGEROPTS="$ID3V2OPTS"
2150 fi
2151
2152 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
2153
2154 if [ "$ENCNICE" ]; then
2155         ENCNICE="-n $ENCNICE"
2156 fi
2157 if [ "$READNICE" ]; then
2158         READNICE="-n $READNICE"
2159 fi
2160 if [ "$DISTMP3NICE" ]; then
2161         DISTMP3NICE="-n $DISTMP3NICE"
2162 fi
2163
2164 # Don't check for stuff if it's not needed
2165 if [ "$REMOTEHOSTS" ]; then NEEDDISTMP3=y; fi
2166 [ "$DONORMALIZE" = "y" ] && NEEDNORMALIZER=y
2167 [ "$EJECTCD" = "y" ] && NEEDEJECT=y
2168 [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ] && NEEDHTTPGET=y
2169
2170 if [ X"$CDSPEEDVALUE" != "X" ]; then
2171         case "$CDROMREADERSYNTAX" in
2172                 cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
2173                 *) NEEDCDSPEED=y ;;
2174         esac
2175 fi
2176
2177
2178 # Make sure a buncha things exist
2179 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
2180         $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
2181         ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
2182         ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
2183         ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
2184         ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
2185         ${NEEDVORBISGAIN+$VORBISGAIN}
2186 do
2187         # Cut off the command-line options we just added in
2188         X=$(echo $X | cut -d' ' -f2)
2189         if [ "$(which $X)" = "" ]; then
2190                 echo "abcde error: $X is not in your path." >&2
2191                 exit 1
2192         elif [ ! -x $(which $X) ]; then
2193                 echo "abcde error: $X is not executable." >&2
2194                 exit 1
2195         fi
2196 done
2197
2198 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
2199 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
2200 HTTPGET="$HTTPGET $HTTPGETOPTS"
2201
2202 # Here it used to say:
2203 # One thousand lines in, we can start doing stuff with things
2204 # Well, right now we are at line 2157 ;)
2205
2206 # Export needed things so they can be read in this subshell
2207 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
2208 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
2209
2210 # User-definable function to set some things. Use it for
2211 #  - closing the CD tray with eject -t
2212 #  - set the CD speed value with eject -x
2213 vecho -n "Executing customizable pre-read function... "
2214
2215 pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
2216
2217 vecho "done."
2218
2219 do_discid # Get ABCDETEMPDIR created and status file initialized
2220
2221 if [ "$DOCDDB" = "y" ]; then
2222         if [ $CDDBUSELOCAL = "y" ]; then
2223                 do_localcddb
2224         fi
2225         if checkstatus cddb-choice > /dev/null; then
2226                 :
2227         else 
2228                 if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
2229                         do_cddbstat
2230                         do_cddbquery
2231                         do_cddbread
2232                 fi
2233         fi
2234         do_cddbedit
2235
2236         eval $($CDDBTOOL parse "$CDDBDATA")
2237 fi
2238
2239 # Before reading tracks, we set the speed of the device
2240
2241 if [ X"$CDSPEEDVALUE" != "X" ]; then
2242         case "$CDROMREADERSYNTAX" in
2243                 cdparanoia|debug) : ;;
2244                 *) do_cdspeed ;;
2245         esac
2246 fi
2247
2248 # Create playlist if needed (backgroundable) and start reading in tracks
2249
2250 (
2251
2252 if [ ! "$ONETRACK" = "y" ]; then
2253         if [ "$DOPLAYLIST" = "y" ]; then
2254                 echo Creating playlist... >&2
2255                 do_playlist
2256         fi
2257 fi
2258
2259 # For the lowdisk option, only one program is running at once so the encoder
2260 # can be unsilenced right away.
2261 if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
2262         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2263 fi
2264
2265 if [ "$ONETRACK" = "y" ]; then 
2266         FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}' )
2267         TRACKS="$FIRSTTRACK"
2268         for UTRACKNUM in $TRACKQUEUE; do :;done
2269         if checkstatus readtrack-$FIRSTTRACK; then :; else
2270                 do_cdread_one $UTRACKNUM $FIRSTTRACK
2271                 # FIXME # Allow ranges of tracks to be encoded in one track
2272                 # FIXME # do_cdread onetrack $FIRSTTRACK $UTRACKNUM
2273                 # Until we have it we must use:
2274                 #do_cdread onetrack $FIRSTTRACK $UTRACKNUM
2275         fi
2276 else
2277         for UTRACKNUM in $TRACKQUEUE
2278         do
2279                 if [ "$DOREAD" = "y" ]; then
2280                         if checkstatus readtrack-$UTRACKNUM; then :; else
2281                                 do_cdread $UTRACKNUM
2282                                 if [ "$?" != "0" ]; then
2283                                         # CD read failed - don't give the goahead to
2284                                         # the encoder
2285                                         echo NO
2286                                         exit
2287                                 fi
2288                         fi
2289                 fi
2290                 if [ "$BATCH" = "y" ]; then
2291                     :
2292                 else
2293                         echo NEXTTRACK # Get the encoder machine churning again
2294                         if [ "$DOREAD" = "y" ]; then
2295                                 if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
2296                                         until checkstatus encodetrack-$UTRACKNUM
2297                                         do
2298                                                 if checkerrors encodetrack-$UTRACKNUM; then
2299                                                         break
2300                                                 fi
2301                                                 sleep 2
2302                                         done
2303                                 fi
2304                         fi
2305                 fi
2306         done
2307 fi
2308
2309 # Now that we're done the encoding can be loud again -
2310 # if we're not using SMP.
2311 if [ "$MAXPROCS" = "1" ]; then
2312         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2313 fi
2314
2315 # All tracks read, start encoding.
2316 if [ "$BATCH" = "y" ] || [ "$ONETRACK" = "y" ]; then
2317         echo NEXTTRACK
2318 fi
2319
2320 # We are now finished with the cdrom - it can be safely ejected. Note that
2321 # abcde will not have completed yet.
2322 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
2323         # We check if the disk we are processing is actually the disk inside the 
2324         # CD tray. If not, we do not eject the CD, since it might be so that the
2325         # user ejected it manually.
2326         #CURRENTTRACKINFO=$($CDDISCID $CDROM)
2327         #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
2328         # More FreeBSD bits.
2329         if [ X"$(uname)" = X"FreeBSD" ] ; then
2330                 # FreeBSD eject uses the EJECT environment variable to name the CDROM
2331                 # but in this script EJECT is in the envionment and names the program
2332                 eject=$EJECT
2333                 unset EJECT
2334                 # The FreeBSD eject needs "adc0" not "/dev/adc0c"
2335                 cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
2336                 $eject $EJECTOPTS $cd
2337         elif [ X"$(uname)" = X"Darwin" ] ; then
2338                 disktool -e ${CDROM#/dev/} 0
2339         else
2340                 $EJECT $EJECTOPTS $CDROM
2341         fi
2342         #fi
2343 fi
2344
2345 ) | (
2346
2347 ## Do we need to pre-process 
2348 #if [ x"$PREPROCESS" = "x" ] ; then
2349 #       cat
2350 #else
2351 #       for PRETRACKNUM in $TRACKQUEUE
2352 #       do
2353 #               read GOAHEAD
2354 #               if [ "$GOAHEAD" = "NO" ]; then break; fi
2355 #               PREPROCEED=
2356 #               until [ $PREPROCEED ]
2357 #               do
2358 #                       if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
2359 #                       # all locations are working, wait and try again later
2360 #                       if [ ! $PREPROCEED ]; then sleep 3; fi
2361 #               done
2362 #               ( do_preprocess $PRETRACKNUM 
2363 #               echo "NEXTTRACK"
2364 #               ) &
2365 #       done
2366 #fi
2367 #
2368 #) | (
2369
2370 # In batch mode, we want all tracks to be read first.
2371 if [ "$BATCH" = "y" ]; then
2372         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2373         if [ "$GOAHEAD" = "NO" ]; then break; fi
2374         for LASTTRACK in $TRACKQUEUE; do :; done
2375         if checkstatus readtrack-$LASTTRACK; then
2376                 if [ "$DONORMALIZE" = "y" ]; then
2377                         if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
2378                         if checkerrors batch-normalize; then exit; fi
2379                 fi
2380                 if [ "$DOENCODE" = "y" ]; then
2381                         if checkstatus encodetrack-$LASTTRACK; then :; else do_batch_encode; fi
2382                         if checkerrors batch-encode; then exit; fi
2383                 fi
2384         fi
2385 fi
2386
2387 # If we are using ONETRACK, we can proceed with the normal encoding using just the $FIRSTTRACK as TRACKQUEUE
2388 if [ "$ONETRACK" = "y" ] ; then
2389         FIRSTTRACK=$( echo $TRACKQUEUE | awk '{print $1}')
2390         TRACKQUEUE=$FIRSTTRACK
2391         TRACKS="$FIRSTTRACK"
2392 fi
2393
2394 # Do the encoding, including parallelization of remote encoding
2395 # Figure out where each track is going to be encoded
2396 ENCODELOCATIONS="$(echo $REMOTEHOSTS | tr , ' ')"
2397 if [ "$MAXPROCS" != "0" ]; then
2398         for NUM in $(f_seq_row 1 "$MAXPROCS")
2399         do
2400                 ENCODELOCATIONS="$ENCODELOCATIONS %local$NUM%"
2401         done
2402 fi
2403 # Strip whitespace
2404 ENCODELOCATIONS=$(echo $ENCODELOCATIONS)
2405 for UTRACKNUM in $TRACKQUEUE
2406 do
2407         # Wait for our cue
2408         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2409         if [ "$GOAHEAD" = "NO" ]; then break; fi
2410         # find out where this track is to be encoded
2411         if [ "$DOENCODE" = "y" ]; then
2412                 # Make sure we have a place to encode this, if not, exit stage right
2413                 if [ -z "$ENCODELOCATIONS" ]; then
2414                         continue
2415                 fi
2416                 PROCEED=
2417                 until [ $PROCEED ]
2418                 do
2419                         for LOCATION in $ENCODELOCATIONS
2420                         do
2421                                 PREVIOUSTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2422                                 # check first if a track has ever been assigned to this location
2423                                 if [ -z "$PREVIOUSTRACK" ]; then PROCEED=y; break; fi
2424                                 # If it errored out, rebuild $ENCODELOCATIONS without this location in it
2425                                 if checkerrors encodetrack-$PREVIOUSTRACK; then
2426                                         for TEMPLOCATION in $ENCODELOCATIONS
2427                                         do
2428                                                 if [ "$TEMPLOCATION" != "$LOCATION" ]; then
2429                                                         TEMPENCODELOCATIONS="$TEMPENCODELOCATIONS $TEMPLOCATION"
2430                                                 fi
2431                                         done
2432                                         ENCODELOCATIONS=$(echo $TEMPENCODELOCATIONS)
2433                                         ABORT=y
2434                                         PROCEED=y
2435                                         break
2436                                 fi
2437                                 # We're still here, this location must have been previously assigned,
2438                                 # and last completed without error - check if it's done with the
2439                                 # previous track yet
2440                                 if checkstatus encodetrack-$PREVIOUSTRACK; then PROCEED=y; break; fi
2441                         done
2442                         # all locations are working, wait and try again later
2443                         if [ ! $PROCEED ]; then sleep 3; fi
2444                 done
2445                 # Record the location we're about to encode the next track at
2446                 echo "encodetracklocation-$LOCATION=$UTRACKNUM" >> "$ABCDETEMPDIR/status"
2447         fi
2448         # Don't proceed with the rest of the loop if we can't encode
2449         if [ "$ABORT" ]; then continue; fi
2450         # Set TRACKNUM, TRACKNAME
2451         if [ -e "$CDDBDATA" ]; then
2452                 if [ "$ONETRACK" = "y" ]; then 
2453                         TRACKNAME="$DALBUM"
2454                         TRACKNUM="$FIRSTTRACK"
2455                         splitvarious
2456                 else
2457 #                       TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
2458                         TRACKNUM=$UTRACKNUM
2459                         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
2460                         TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
2461                         splitvarious
2462                 fi
2463         fi
2464         # You can't encode a file which needs to be normalized before finishing
2465         # You can't tag a file before it's finished encoding -
2466         # thus all of this is backgrounded together
2467         (
2468         if [ "$DONORMALIZE" = "y" ]; then
2469                 if checkstatus readtrack-$UTRACKNUM; then
2470                         if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
2471                 fi
2472         fi
2473         if [ "$DOENCODE" = "y" ]; then
2474                 if checkstatus readtrack-$UTRACKNUM; then
2475                         #if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION; fi
2476                         if [ "$DONORMALIZE" = "y" ]; then
2477                                 if checkstatus normalizetrack-$UTRACKNUM; then
2478                                         if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2479                                 fi
2480                         else
2481                                 if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2482                         fi
2483                 fi
2484         fi
2485         if [ "$DOTAG" = "y" ]; then
2486                 if checkstatus encodetrack-$UTRACKNUM; then
2487                         if checkstatus tagtrack-$UTRACKNUM; then :; else do_tag $UTRACKNUM; fi
2488                 fi
2489         fi
2490         if [ "$DOMOVE" = "y" ]; then
2491                 if checkstatus tagtrack-$UTRACKNUM; then
2492                         if checkstatus movetrack-$UTRACKNUM; then :; else do_move $UTRACKNUM; fi
2493                 fi
2494         fi
2495         ) &
2496 done
2497 # Go through it again and make sure there's no distmp3 stragglers, otherwise
2498 # we'll delete the files they're working on
2499 if [ "$DOENCODE" = "y" ]; then
2500         PROCEED=
2501         until [ $PROCEED ]
2502         do
2503                 PROCEED=y
2504                 for LOCATION in $ENCODELOCATIONS
2505                 do
2506                         CHECKTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2507                         # "How can he give us a status update, if he's DEAD?"
2508                         if checkstatus encodetrack-$CHECKTRACK; then
2509                                 continue
2510                         fi
2511                         # Nothing to see here please go quietly back to your homes
2512                         if [ -z "$CHECKTRACK" ]; then continue; fi
2513                         # You're still here? Maybe there is something...
2514                         if checkstatus encodetrack-$CHECKTRACK; then :; else PROCEED= ; break; fi
2515                 done
2516                 # hold up
2517                 if [ ! $PROCEED ]; then sleep 5; fi
2518         done
2519 fi
2520 # If the above didn't catch the stragglers, this will
2521 wait
2522 # Check to see if run_command logged any errors
2523 if [ -f "$ABCDETEMPDIR/errors" ]; then
2524         echo "The following commands failed to run:"
2525         cat "$ABCDETEMPDIR/errors"
2526         # Don't clean up
2527         DOCLEAN=n
2528 fi
2529 if [ "$KEEPWAVS" = "y" ];then
2530         # Don't clean up
2531         DOCLEAN=n
2532 fi
2533 if [ "$DOCLEAN" = "y" ]; then
2534         # Wipe all the evidence
2535         # Gimme gimme gimme some more time!
2536         sleep 5
2537         rm -rf "$ABCDETEMPDIR"
2538         echo "Finished."
2539 else
2540         echo "Finished. Not cleaning $ABCDETEMPDIR."
2541 fi
2542 )
2543 exit 0
2544
2545 # b:is_bash
2546 # vim:tabstop=4