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