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