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