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