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