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