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