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