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