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