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