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