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