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