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