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