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