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