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