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