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