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