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