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