Rewritten warning information.
[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                         case "$OUTPUT" in
844                                 vorbis|ogg)
845                                         OUT="$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
846                                         OUTPUT=$OGGOUTPUTCONTAINER
847                                         ;;
848                                 flac)
849                                         OUT="$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
850                                         OUTPUT=$FLACOUTPUTCONTAINER
851                                         ;;
852                                 *)
853                                         OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
854                                         ;;
855                         esac
856                         if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then 
857                                 continue
858                         fi
859                         if [ X"$USEPIPES" = "Xy" ]; then
860                                 RUN_COMMAND=""
861                                 # We need a way to store the creation of the files when using PIPES
862                                 RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
863                         else
864                                 run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
865                                 RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
866                         fi
867                         case "$OUTPUT" in
868                         mp3)
869                                 case "$2" in
870                                 %local*%)
871                                         case "$MP3ENCODERSYNTAX" in
872                                         lame|gogo) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
873                                         bladeenc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
874                                         l3enc|xingmp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
875                                         # FIXME # Relates to the previous FIXME since it might need the "-if" removed.
876                                         mp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
877                                         esac
878                                         ;;
879                                 *)
880                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
881                                         ;;
882                                 esac
883                                 ;;
884                         vorbis|ogg)
885                                 case "$2" in
886                                 %local*%)
887                                         case "$OGGENCODERSYNTAX" in
888                                         vorbize) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
889                                         oggenc) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
890                                         esac
891                                         ;;
892                                 *)
893                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
894                                         ;;
895                                 esac
896                                 ;;
897                         flac)
898                                 case "$2" in
899                                 %local*%)
900                                         case "$FLACENCODERSYNTAX" in
901                                         flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
902                                         esac
903                                                 ;;
904                                         *)
905                                                 vecho -n "DISTMP3:"
906                                                 vecho "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
907                                                 $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
908                                         ;;
909                                 esac
910                                 ;;
911                         spx)
912                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
913                                         case "$COMMENT" in
914                                                 *=*) ;;
915                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
916                                         esac    
917                                         COMMENT="--comment \"$COMMENT\""
918                                 fi
919                                 # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
920                                 if [ ! "$DOTAG" = "y" ]; then
921                                         $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
922                                 else
923                                         $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
924                                 fi
925                                 ;;
926                         mpc)    
927                                 # MPP/MP+(Musepack) format (.mpc) is done locally, with inline
928                                 # tagging.
929                                 # I tried compiling the mppenc from corecodecs.org and got some
930                                 # errors, so I have not tried it myself.
931                                 ## FIXME ## Needs some cleanup to determine if an empty tag sent
932                                 ## FIXME ## to the encoder ends up empty.
933                                 $RUN_COMMAND nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
934                                 ;;
935                         wav)
936                                 # In case of wav output we need nothing. Just keep the wavs.
937                                 ;;
938                         esac
939                         $RUN_COMMAND_PIPES
940                 done
941                 # Only remove .wav if the encoding succeeded
942                 if checkerrors "encodetrack-(.{3,6})-$1"; then :; else
943                         run_command encodetrack-$1 true
944                         if [ ! "$KEEPWAVS" = "y" ] ; then
945                                 if [ ! "$KEEPWAVS" = "move" ] ; then
946                                         rm -f "$IN"
947                                 fi
948                         fi
949                 fi
950         else
951                 run_command "" echo "HEH! The file we were about to encode disappeared:"
952                 run_command "" echo ">> $IN"
953                 run_command encodetrack-$1 false
954         fi
955 }
956
957 # do_preprocess [tracknumber]
958 # variables used:
959 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
960 #do_preprocess ()
961 #{
962 #       IN="$ABCDETEMPDIR/track$1.wav"
963 #       # We need IN to proceed.
964 #       if [ -s "$IN" ] ; then
965 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
966 #               do
967 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
968 #                       run_command '' echo "Pre-processing track $1 of $TRACKS..."
969 #                       case "$POSTPROCESSFORMAT" in
970 #                       all|wav*)
971 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
972 #                       mp3)
973 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
974 #                       ogg)
975 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
976 #                       flac)
977 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
978 #                       spx)
979 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
980 #                       esac
981 #               done
982 #               # Only remove .wav if the encoding succeeded
983 #               if checkerrors "preprocess-(.{3,4})-$1"; then 
984 #                       run_command preprocess-$1 false
985 #               else
986 #                       run_command preprocess-$1 true
987 #               fi
988 #       else
989 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
990 #                       echo "HEH! The file we were about to pre-process disappeared:"
991 #                       echo ">> $IN"
992 #               fi
993 #               run_command preprocess-$1 false
994 #       fi
995 #}
996
997
998 # do_postprocess [tracknumber]
999 # variables used:
1000 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1001 #do_postprocess ()
1002 #{
1003 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
1004 #       do
1005 #               IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
1006 #               # We need IN to proceed.
1007 #               if [ -s "$IN" ] ; then
1008 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1009 #                       run_command '' echo "Post-processing track $1 of $TRACKS..."
1010 #                       case "$POSTPROCESSFORMAT" in
1011 #                               mp3)
1012 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
1013 #                               ogg)
1014 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
1015 #                               flac)
1016 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
1017 #                               spx)
1018 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
1019 #                       esac
1020 #                       # Only remove .wav if the encoding succeeded
1021 #                       if checkerrors "postprocess-(.{3,4})-$1"; then 
1022 #                               run_command postprocess-$1 false
1023 #                       else
1024 #                               run_command postprocess-$1 true
1025 #                       fi
1026 #               else
1027 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
1028 #                               echo "HEH! The file we were about to post-process disappeared:"
1029 #                               echo ">> $IN"
1030 #                       fi
1031 #                       run_command postprocess-$1 false
1032 #               fi
1033 #       done
1034 #}
1035
1036 # do_single_gain
1037 # variables used:
1038 # FIXME #
1039 do_single_gain ()
1040 {
1041 :
1042 }
1043
1044 # do_batch_gain
1045 # variables used:
1046 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPPGAIN, MPPGAINOPTS
1047 # FIXME #
1048 do_batch_gain ()
1049 {
1050         # The commands here don't go through run_command because they're never supposed to be silenced
1051         echo "Batch analizing gain in tracks: $TRACKQUEUE"
1052         (
1053         cd "$ABCDETEMPDIR"
1054         BLURB=
1055         TRACKFILES=
1056         for UTRACKNUM in $TRACKQUEUE
1057         do
1058                 MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
1059         done
1060         # FIXME # Hard-coded batch option!
1061         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1062         RETURN=$?
1063         if [ "$RETURN" != "0" ]; then
1064                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
1065         else
1066                 for UTRACKNUM in $TRACKQUEUE
1067                 do
1068                         echo normalizetrack-$UTRACKNUM >> status
1069                 done
1070         fi
1071         )
1072 }
1073
1074 # do_batch_normalize
1075 # variables used:
1076 # NORMALIZER, NORMALIZEROPTS
1077 do_batch_normalize ()
1078 {
1079         # The commands here don't go through run_command because they're never supposed to be silenced
1080         echo "Batch normalizing tracks: $TRACKQUEUE"
1081         (
1082         cd "$ABCDETEMPDIR"
1083         BLURB=
1084         TRACKFILES=
1085         for UTRACKNUM in $TRACKQUEUE
1086         do
1087                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
1088         done
1089         # XXX: Hard-coded batch option!
1090         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1091         RETURN=$?
1092         if [ "$RETURN" != "0" ]; then
1093                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
1094         else
1095                 for UTRACKNUM in $TRACKQUEUE
1096                 do
1097                         echo normalizetrack-$UTRACKNUM >> status
1098                 done
1099         fi
1100         )
1101 }
1102
1103 # do_normalize [tracknumber]
1104 # variables used:
1105 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
1106 do_normalize ()
1107 {
1108         IN="$ABCDETEMPDIR/track$1.wav"
1109         if [ -e "$IN" ] ; then
1110                 run_command '' echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
1111                 run_command normalizetrack-$1 $NORMALIZER $NORMALIZEROPTS "$IN"
1112         else
1113                 if [ "$(checkstatus encode-output)" = "loud" ]; then
1114                         echo "HEH! The file we were about to normalize disappeared:"
1115                         echo ">> $IN"
1116                 fi
1117                 run_command normalizetrack-$1 false "File $IN was not found"
1118         fi
1119 }
1120
1121 # do_move [tracknumber]
1122 # Deduces the outfile from environment variables
1123 # Creates directory if necessary
1124 # variables used:
1125 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
1126 do_move ()
1127 {
1128         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1129         do
1130                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
1131                 # Munge filenames as follows:
1132                 # ' ' -> '_'
1133                 # '/' -> '_'
1134                 # ''' -> ''
1135                 # '?' -> ''
1136                 # Eat control characters
1137                 ALBUMFILE="$(mungefilename "$DALBUM")"
1138                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1139                 TRACKFILE="$(mungefilename "$TRACKNAME")"
1140                 GENRE="$(mungegenre "$GENRE")"
1141                 YEAR="$(echo $CDYEAR)"
1142                 # If we want to start the tracks with a given number, we need to modify the
1143                 # TRACKNUM value before evaluation
1144                 do_gettracknum
1145                 # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
1146                 # TRACKFILE, and TRACKNUM.
1147                 if [ "$VARIOUSARTISTS" = "y" ]; then
1148                         OUTPUTFILE="$(eval echo "$VAOUTPUTFORMAT")"
1149                 else
1150                         OUTPUTFILE="$(eval echo "$OUTPUTFORMAT")"
1151                 fi
1152                 if checkerrors "tagtrack-$OUTPUT-$1"; then :; else
1153                         # Once we know the specific output was successful, we can change the OUTPUT to the value containing the container
1154                         case $OUTPUT in
1155                                 vorbis|ogg)
1156                                         OUTPUT=$OGGOUTPUTCONTAINER
1157                                         ;;
1158                                 flac)
1159                                         OUTPUT=$FLACOUTPUTCONTAINER
1160                                         ;;
1161                         esac
1162                         # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
1163                         OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
1164                         case $OUTPUT in
1165                                 wav)
1166                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1167                                                 # FIXME # introduce warnings?
1168                                                 :
1169                                         else
1170                                                 # mkdir -p shouldn't return an error if the directory already exists
1171                                                 mkdir -p "$OUTPUTFILEDIR"
1172                                                 run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1173                                                 if checkstatus movetrack-output-$OUTPUT; then :; else
1174                                                         run_command movetrack-output-$OUTPUT true
1175                                                 fi
1176                                         fi
1177                                         ;;
1178                                 *)
1179                                         # mkdir -p shouldn't return an error if the directory already exists
1180                                         mkdir -p "$OUTPUTFILEDIR"
1181                                         run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1182                                         if checkstatus movetrack-output-$OUTPUT; then :; else
1183                                                 run_command movetrack-output-$OUTPUT true
1184                                         fi
1185                                         ;;
1186                         esac
1187                         # Lets move the cue file
1188                         if CUEFILE=$(checkstatus cuefile) >/dev/null ; then 
1189                                 if [ -r "$ABCDETEMPDIR/$CUEFILE" ]; then
1190                                         if checkstatus movecue-$OUTPUT; then :; else
1191                                                 # Silence the Copying output since it overlaps with encoding processes...
1192                                                 #run_command '' vecho "Copying cue file to its destination directory..."
1193                                                 if checkstatus onetrack >/dev/null ; then
1194                                                         case $OUTPUT in
1195                                                                 wav)
1196                                                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1197                                                                                 # We dont have the dir, since it was not created before.
1198                                                                                 :
1199                                                                         else
1200                                                                                 run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1201                                                                         fi
1202                                                                         ;;
1203                                                                 # NOTE: Creating a cue file with the 3-char-extension files is to comply with
1204                                                                 # http://brianvictor.tripod.com/mp3cue.htm#details
1205                                                                 [a-z0-9][a-z0-9][a-z0-9])
1206                                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1207                                                                         ;;
1208                                                                 *)
1209                                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT.cue"
1210                                                                         ;;
1211                                                         esac
1212                                                 else
1213                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTFILEDIR/$CUEFILE"
1214                                                 fi
1215                                                 echo movecue-$OUTPUT >> "$ABCDETEMPDIR/status"
1216                                         fi
1217                                 fi
1218                         fi
1219                 fi
1220         done
1221 }
1222
1223 # do_playlist
1224 # Create the playlist if wanted
1225 # Variables used:
1226 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
1227 # VARIOUSARTISTS, OUTPUTDIR
1228 do_playlist ()
1229 {
1230         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1231         do
1232                 case $OUTPUT in
1233                         vorbis|ogg)
1234                                 OUTPUT=$OGGOUTPUTCONTAINER
1235                                 ;;
1236                         flac)
1237                                 OUTPUT=$FLACOUTPUTCONTAINER
1238                                 ;;
1239                 esac
1240                 # Create a playlist file for the playlist data to go into.
1241                 # We used to wipe it out if it existed. Now we request permision if interactive.
1242                 for LASTTRACK in $TRACKQUEUE; do :; done
1243                 ALBUMFILE="$(mungefilename "$DALBUM")"
1244                 ARTISTFILE="$(mungefilename "$DARTIST")"
1245                 GENRE=$(mungegenre "$GENRE")
1246                 YEAR=${CDYEAR:-$CDYEAR}
1247                 if [ "$VARIOUSARTISTS" = "y" ] ; then
1248                         PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
1249                 else
1250                         PLAYLISTFILE=$(eval echo $PLAYLISTFORMAT)
1251                 fi
1252                 FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
1253                 mkdir -p "$FINALPLAYLISTDIR"
1254                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
1255                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
1256                         if [ "$INTERACTIVE" = "y" ]; then
1257                                 while [ "$DONE" != "y" ]; do
1258                                         read ERASEPLAYLIST
1259                                         case $ERASEPLAYLIST in
1260                                                 e|E|a|A|k|K) DONE=y ;;
1261                                                 *) ;;
1262                                         esac
1263                                 done
1264                         else
1265                                 echo e >&2
1266                                 ERASEPLAYLIST=e
1267                         fi
1268                         # Once we erase the playlist, we use append to create the new one.
1269                         [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
1270                 else
1271                         # The playlist does not exist, so we can safelly use append to create the new list
1272                         ERASEPLAYLIST=a
1273                 fi
1274                 if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
1275                         touch "$OUTPUTDIR/$PLAYLISTFILE"
1276                         for UTRACKNUM in $TRACKQUEUE
1277                         do
1278                                 # Shares some code with do_move since the filenames have to match
1279                                 CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1280                                 #TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
1281                                 do_getcddbinfo TRACKNAME
1282                                 splitvarious
1283                                 TRACKFILE="$(mungefilename "$TRACKNAME")"
1284                                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1285                                 ALBUMFILE="$(mungefilename "$DALBUM")"
1286                                 # If we want to start the tracks with a given number, we need to modify the
1287                                 # TRACKNUM value before evaluation
1288                                 do_gettracknum
1289                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1290                                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
1291                                 else
1292                                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
1293                                 fi
1294                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1295                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
1296                                                 echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1297                                         else
1298                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1299                                         fi
1300                                 else
1301                                         if [ "$PLAYLISTDATAPREFIX" ]; then
1302                                                 echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1303                                         else
1304                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1305                                         fi
1306                                 fi
1307                         done
1308                 fi
1309                 ## this will convert the playlist to have CRLF line-endings, if specified
1310                 ## (some hardware players insist on CRLF endings)
1311                 if [ "$DOSPLAYLIST" = "y" ]; then
1312                         awk '{substr("\r",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
1313 #                       mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
1314                         cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
1315                 fi
1316                 echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
1317         done
1318 }
1319
1320 # do_discid
1321 # This essentially the start of things
1322 do_discid ()
1323 {
1324         # Query the CD to get the track info, unless the user specified -C
1325         # or we are using some actions which do not need the CDDB data at all
1326         #if [ ! X"$EXPACTIONS" = "X" ]; then
1327         #       :
1328         #elif [ -z "$DISCID" ]; then
1329         if [ -z "$DISCID" ]; then
1330                 vecho -n "Getting CD track info... "
1331                 # In OSX, unmount the disc before a query
1332                 if [ "$OSFLAVOUR" = "OSX" ]; then
1333                         disktool -u ${CDROM#/dev/}
1334                 fi
1335                 if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
1336                         TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- $CDROM | $CUE2DISCID)
1337                 else
1338                         TRACKINFO=$($CDDISCID $CDROM)
1339                 fi
1340                 # Make sure there's a CD in there by checking cd-discid's return code
1341                 if [ ! "$?" = "0" ]; then
1342                         if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
1343                                 log error "cuesheet information from the flac file could not be read."
1344                                 log error "Perhaps the flac file does not contain a cuesheet?."
1345                                 exit 1
1346                         else
1347                                 log error "CD could not be read. Perhaps there's no CD in the drive?"
1348                                 exit 1
1349                         fi
1350                 fi
1351                 # In OSX, remount the disc again
1352                 if [ "$OSFLAVOUR" = "OSX" ]; then
1353                         disktool -m ${CDROM#/dev/}
1354                 fi
1355                 WEHAVEACD=y
1356                 DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
1357         else
1358                 TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
1359         fi
1360
1361         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
1362         # This needs to be done now because a section of the resuming code will need
1363         # it later.
1364
1365         # get the number of digits to pad TRACKNUM with - we'll use this later
1366         # a CD can only hold 99 tracks, but since we support a feature for starting
1367         # numbering the tracks from a given number, we might need to set it as a
1368         # variable for the user to define... or obtain it somehow.
1369         if [ "$PADTRACKS" = "y" ] ; then
1370                 TRACKNUMPADDING=2
1371         fi
1372
1373         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
1374         if [ -z "$TRACKQUEUE" ]; then
1375                 if [ ! "$STRIPDATATRACKS" = "y" ]; then
1376                         case "$CDROMREADERSYNTAX" in
1377                                 cdparanoia|debug)
1378                                         if [ "$WEHAVEACD" = "y" ]; then
1379                                                 vecho "Querying the CD for audio tracks..."
1380                                                 CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -Q --verbose 2>&1 )"
1381                                                 RET=$?
1382                                                 if [ ! "$RET" = "0" ];then
1383                                                         log warning "something went wrong while querying the CD... Maybe a DATA CD?"
1384                                                 fi
1385                                                 TRACKS="$(echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
1386                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
1387                                         else
1388                                                 if [ -f "$ABCDETEMPDIR/status" ] && TRACKS=$(checkstatus cdparanoia-audio-tracks); then :; else
1389                                                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1390                                                 fi
1391                                         fi
1392                                         ;;
1393                                 *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
1394                         esac
1395                 else
1396                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1397                 fi
1398                 if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
1399                         log info "The disc does not contain any tracks. Giving up..."
1400                         exit 0
1401                 fi
1402                 echo -n "Grabbing entire CD - tracks: "
1403                 if [ ! "$PADTRACKS" = "y" ] ; then
1404                         TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
1405                 fi
1406                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
1407                 X=0
1408                 while [ "$X" -ne "$TRACKS" ]
1409                 do
1410                         X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
1411                         TRACKQUEUE=$(echo $TRACKQUEUE $X)
1412                 done
1413                 echo $TRACKQUEUE
1414         else
1415                 TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1416                 # User-supplied track queue.
1417                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
1418                 TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
1419                 # Once cleaned, obtain the highest value in the trackqueue for number padding
1420                 for LASTTRACK in $TRACKQUEUE; do :; done
1421                 if [ ! "$PADTRACKS" = "y" ] ; then
1422                         TRACKNUMPADDING=$(echo -n $LASTTRACK | wc -c | tr -d ' ')
1423                 fi
1424                 # Now we normalize the trackqueue
1425                 for TRACK in $TRACKQUEUE ; do
1426                         TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
1427                         PADTRACKQUEUE=$(echo $PADTRACKQUEUE $TRACKNUM)
1428                 done
1429                 TRACKQUEUE=$PADTRACKQUEUE
1430                 echo Grabbing tracks: "$TRACKQUEUE"
1431         fi
1432
1433         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
1434
1435         # We have the discid, create a temp directory after it to store all the temp
1436         # info
1437
1438         if [ -e "$ABCDETEMPDIR" ]; then
1439                 echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
1440                 # It already exists, see if it's a directory
1441                 if [ ! -d "$ABCDETEMPDIR" ]; then
1442                         # This is a file/socket/fifo/device/etc, not a directory
1443                         # Complain and exit
1444                         echo >&2
1445                         echo "abcde: file $ABCDETEMPDIR already exists and does not belong to abcde." >&2
1446                         echo "Please investigate, remove it, and rerun abcde." >&2
1447                         exit 1
1448                 fi
1449                 echo -n .
1450                 # It's a directory, let's see if it's owned by us
1451                 if [ ! -O "$ABCDETEMPDIR" ]; then
1452                         # Nope, complain and exit
1453                         echo >&2
1454                         echo "abcde: directory $ABCDETEMPDIR already exists and is not owned by you." >&2
1455                         echo "Please investigate, remove it, and rerun abcde." >&2
1456                         exit 1
1457                 fi
1458                 echo .
1459                 # See if it's populated
1460                 if [ ! -f "$ABCDETEMPDIR/discid" ]; then
1461                         # Wipe and start fresh
1462                         echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
1463                         echo -n "this directory to continue. Continue? [y/n] (n)" >&2
1464                         if [ "$INTERACTIVE" = "y" ]; then
1465                                 read ANSWER
1466                         else
1467                                 echo y >&2
1468                                 ANSWER=y
1469                         fi
1470                         if [ "$ANSWER" != "y" ]; then
1471                                 exit 1
1472                         fi
1473                         rm -rf "$ABCDETEMPDIR" || exit 1
1474                         mkdir "$ABCDETEMPDIR"
1475                         if [ "$?" -gt "0" ]; then
1476                                 # Directory already exists or could not be created
1477                                 echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
1478                                 exit 1
1479                         fi
1480                 else
1481                         # Everything is fine. Check for ^encodetracklocation-
1482                         # and encode-output entries in the status file and
1483                         # remove them. These are not relevant across sessions.
1484                         if [ -f "$ABCDETEMPDIR/status" ]; then
1485                                 mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
1486                                 grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
1487                                         | grep -v ^encode-output > "$ABCDETEMPDIR/status"
1488                         fi
1489                         # Remove old error messages
1490                         if [ -f "$ABCDETEMPDIR/errors" ]; then
1491                                 rm -f "$ABCDETEMPDIR/errors"
1492                         fi
1493                 fi
1494         else
1495                 # We are starting from scratch
1496                 mkdir "$ABCDETEMPDIR"
1497                 if [ "$?" -gt "0" ]; then
1498                         # Directory already exists or could not be created
1499                         echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
1500                         exit 1
1501                 fi
1502                 cat /dev/null > "$ABCDETEMPDIR/status"
1503         fi
1504         if [ X"$MAKECUEFILE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
1505                 if checkstatus cuefile > /dev/null 2>&1 ; then :; else
1506                         CUEFILE=cue-$(echo "$TRACKINFO" | cut -f1 -d' ').txt
1507                         vecho "Creating cue file..."
1508                         if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
1509                                 echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
1510                         else
1511                                 log warning "reading the CUE sheet with mkcue is still considered experimental"
1512                                 log warning "and there was a problem with the CD reading. abcde will continue,"
1513                                 log warning "but consider reporting the problem to the abcde author"
1514                         fi
1515                 fi
1516         fi
1517         # If we got the CDPARANOIA status and it is not recorded, save it now
1518         if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
1519                 if checkstatus cdparanoia-audio-tracks > /dev/null 2>&1; then :; else
1520                         echo cdparanoia-audio-tracks=$CDPARANOIAAUDIOTRACKS >> "$ABCDETEMPDIR/status"
1521                 fi
1522         fi
1523         
1524         # Create the discid file
1525         echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
1526 }
1527
1528 # do_cleancue
1529 # Create a proper CUE file based on the CUE file we created before.
1530 do_cleancue()
1531 {
1532         if CUEFILE_IN="$ABCDETEMPDIR"/$(checkstatus cuefile); then
1533                 CUEFILE_OUT=$CUEFILE_IN.out
1534                 ### FIXME ### checkstatus cddb
1535                 if [ -e "$CDDBDATA" ]; then
1536                         vecho "Adding metadata to the cue file..."
1537                         # FIXME It doesn't preserve spaces! Why?
1538                         # FIXME parse $track into PERFORMER and TITLE - abcde already has code for this?
1539                         n=1
1540                         echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
1541                         echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
1542                         cat "$CUEFILE_IN" | while read line
1543                         do
1544                                 if echo "$line" | grep -q "INDEX"
1545                                 then
1546                                         eval track="\$TRACK$n"
1547                                         n=$(expr $n + 1)
1548                                         echo "TITLE \"$track\"" >> "$CUEFILE_OUT"
1549                                 fi
1550                                 echo "$line" >> "$CUEFILE_OUT"
1551                         done
1552                         mv "$CUEFILE_OUT" "$CUEFILE_IN"
1553                         echo "cleancuefile" >> "$ABCDETEMPDIR/status"
1554                 fi
1555         fi
1556 }
1557
1558 # do_cddbparse
1559 # Parses a CDDB file and outputs the title and the track names.
1560 # Variables: CDDBFILE
1561 do_cddbparse ()
1562 {
1563         CDDBPARSEFILE="$1"
1564         # List out disc title/author and contents
1565         if [ "$ONETRACK" = "y" ]; then
1566                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
1567         fi
1568         echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
1569         if [ X"$SHOWCDDBYEAR" = "Xy" ]; then
1570                 PARSEDYEAR=$(grep DYEAR "${CDDBPARSEFILE}" | cut '-d=' -f2-)
1571                 if [ ! X"$PARSEDYEAR" = "X" ]; then
1572                         echo "Year: $PARSEDYEAR"
1573                 fi
1574         fi
1575         if [ X"$SHOWCDDBGENRE" = "Xy" ]; then
1576                 PARSEDGENRE=$(grep DGENRE "${CDDBPARSEFILE}" | cut '-d=' -f2-)
1577                 if [ ! X"$PARSEDGENRE" = "X" ]; then
1578                         echo "Genre: $PARSEDGENRE"
1579                 fi
1580         fi
1581         if [ ! "$ONETRACK" = "y" ]; then
1582                 for TRACK in $(f_seq_row 1 $TRACKS)
1583                 do
1584                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
1585                 done
1586         fi
1587 }
1588
1589 # do_localcddb
1590 # Check for a local CDDB file, and report success
1591 do_localcddb ()
1592 {
1593         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
1594         
1595                 CDDBLOCALSUCCESS="n"
1596                 CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1597                 CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1598                 USELOCALRESP="y"
1599                 
1600                 # If the user has selected to check a local CDDB repo, we proceed with it
1601                 if [ -r "${CDDBLOCALFILE}" ]; then
1602                         # List out disc title/author and contents
1603                         do_cddbparse "${CDDBLOCALFILE}"
1604                         echo -n "Locally cached CDDB entry found, use it? [y/n] (y): "
1605                         if [ "$INTERACTIVE" = "y" ]; then
1606                                 read USELOCALRESP
1607                                 while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
1608                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1609                                         read USELOCALRESP
1610                                 done
1611                                 [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
1612                         else
1613                                 echo "y" >&2
1614                         fi
1615                         if [ "$USELOCALRESP" = "y" ]; then
1616                                 #echo "Using local copy of CDDB data"
1617                                 echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
1618                                 cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
1619                                 echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
1620                                 echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
1621                                 do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
1622                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1623                                 CDDBLOCALSUCCESS="y"
1624                         else
1625                                 #echo "Not using local copy of CDDB data"
1626                                 CDDBLOCALSUCCESS="n"
1627                         fi
1628                 else
1629                         CDDBLOCALSUCCESS="n"
1630                 fi
1631         fi
1632 }
1633
1634 # do_cddbstat
1635 do_cddbstat ()
1636 {
1637         # Perform CDDB protocol version check if it hasn't already been done
1638         if checkstatus cddb-statcomplete; then :; else
1639                 if [ "$CDDBAVAIL" = "n" ]; then
1640                         ERRORCODE=no_query
1641                         echo 503 > "$ABCDETEMPDIR/cddbstat"
1642                 else
1643                         rc=1
1644                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1645                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1646                         while test $rc -eq 1 -a $CDDBPROTO -ge 3; do
1647                                 vecho "Checking CDDB server status..."
1648                                 $CDDBTOOL stat $CDDBURL $CDDBUSER $CDDBHOST $CDDBPROTO > "$ABCDETEMPDIR/cddbstat"
1649                                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
1650                                 case "$RESPONSECODE" in
1651                                 210)    # 210 OK, status information follows (until terminating `.')
1652                                         rc=0;
1653                                         ;;
1654                                 501|*)  # 501 Illegal CDDB protocol level: <n>. 
1655                                         CDDBPROTO=`expr $CDDBPROTO - 1`
1656                                         ;;
1657                                 esac 
1658                         done
1659                         if test $rc -eq 1; then
1660                                 CDDBAVAIL="n" 
1661                         fi
1662                 fi
1663                 echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
1664         fi
1665 }
1666
1667
1668 # do_cddbquery
1669 do_cddbquery ()
1670 {
1671         CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1672         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1673         
1674         # Perform CDDB query if it hasn't already been done
1675         if checkstatus cddb-querycomplete; then :; else
1676                 if [ "$CDDBAVAIL" = "n" ]; then
1677                         ERRORCODE=no_query
1678                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1679                 # The default CDDBLOCALSUCCESS is "n"
1680                 # This part will be triggered if the user CDDB repo does not 
1681                 # contain the entry, or if we are not trying to use the repo.
1682                 else
1683                         vecho "Querying the CDDB server..."
1684                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1685                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1686                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $TRACKINFO > "$ABCDETEMPDIR/cddbquery"
1687                         ERRORCODE=$?
1688                         case $ERRORCODE in
1689                                 0)  # success
1690                                 ;;
1691                                 12|13|14)
1692                                         # no match found in database,
1693                                         # wget/fetch error, or user requested not to use CDDB
1694                                         # Make up an error code (503) that abcde
1695                                         # will recognize in do_cddbread
1696                                         # and compensate by making a template
1697                                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1698                                 ;;
1699                                 *) # strange and unknown error
1700                                         echo ERRORCODE=$ERRORCODE
1701                                         echo "abcde: $CDDBTOOL returned unknown error code"
1702                                 ;;
1703                         esac
1704                 fi
1705                 echo cddb-querycomplete >> "$ABCDETEMPDIR/status"
1706         fi
1707 }
1708
1709 # do_cddbread
1710 do_cddbread ()
1711 {
1712         # If it's not to be used, generate a template.
1713         # Then, display it (or them) and let the user choose/edit it
1714         if checkstatus cddb-readcomplete; then :; else
1715                 vecho "Obtaining CDDB results..."
1716                 # If CDDB is to be used, interpret the query results and read all
1717                 # the available entries.
1718                 rm -f "$ABCDETEMPDIR/cddbchoices"
1719                 CDDBCHOICES=1 # Overridden by multiple matches
1720                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbquery" | cut -f1 -d' ')
1721                 case "$RESPONSECODE" in
1722                 200)
1723                         # One exact match, retrieve it
1724                         # 200 [section] [discid] [artist] / [title]
1725                         if checkstatus cddb-read-1-complete; then :; else
1726                                 echo -n "Retrieving 1 CDDB match..." >> "$ABCDETEMPDIR/cddbchoices"
1727                                 $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(cut -f2,3 -d' ' "$ABCDETEMPDIR/cddbquery") > "$ABCDETEMPDIR/cddbread.1"
1728                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
1729                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1730                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1731                         fi
1732                         # List out disc title/author and contents
1733                         echo ---- "$(cut '-d ' -f4- "$ABCDETEMPDIR/cddbquery")" ---- >> "$ABCDETEMPDIR/cddbchoices"
1734                         for TRACK in $(f_seq_row 1 $TRACKS)
1735                         do
1736                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1737                         done
1738                         echo >> "$ABCDETEMPDIR/cddbchoices"
1739                         ;;
1740                 202|403|409|503)
1741                         # No match
1742                         case "$RESPONSECODE" in
1743                         202) echo "No CDDB match." >> "$ABCDETEMPDIR/cddbchoices" ;;
1744                         403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
1745                         503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
1746                         esac
1747                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
1748                         # List out disc title/author and contents of template
1749                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
1750                         UNKNOWNDISK=y
1751                         for TRACK in $(f_seq_row 1 $TRACKS)
1752                         do
1753                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1754                         done
1755                         echo >> "$ABCDETEMPDIR/cddbchoices"
1756                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
1757                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
1758                         ;;
1759                 210|211)
1760                         # Multiple exact, (possibly multiple) inexact matches
1761                         IN=
1762                         if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
1763                         if [ "$(wc -l < "$ABCDETEMPDIR/cddbquery" | tr -d ' ')" -eq 3 ]; then
1764                                 echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
1765                                 tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
1766                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1767                         else
1768                                 echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
1769                         fi
1770                         vecho -n "Retrieving multiple matches... "
1771                         grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
1772                         read DISCINFO # eat top line
1773                         while read DISCINFO
1774                         do
1775                                 X=$(expr $X + 1)
1776                                 if checkstatus cddb-read-$X-complete; then :; else
1777                                         $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(echo $DISCINFO | cut -f1,2 -d' ') > "$ABCDETEMPDIR/cddbread.$X"
1778                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
1779                                 fi
1780                                 # List out disc title/author and contents
1781                                 echo \#$X: ---- "$DISCINFO" ---- >> "$ABCDETEMPDIR/cddbchoices"
1782                                 for TRACK in $(f_seq_row 1 $TRACKS)
1783                                 do
1784                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1785                                 done
1786                                 echo >> "$ABCDETEMPDIR/cddbchoices"
1787                         done )
1788                         vecho "done."
1789                         CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1790                         ;;
1791                 999)
1792                         # Using local copy.
1793                         for TRACK in $(f_seq_row 1 $TRACKS)
1794                         do
1795                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1796                         done
1797                         echo >> "$ABCDETEMPDIR/cddbchoices"
1798                         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1799                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1800                         ;;
1801                 esac    
1802                 echo "cddb-readcomplete" >> "$ABCDETEMPDIR/status"
1803         fi
1804 }
1805
1806 # do_cddbedit
1807 do_cddbedit ()
1808 {
1809         if checkstatus cddb-edit >/dev/null; then
1810                 CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1811                 VARIOUSARTISTS="$(checkstatus variousartists)"
1812                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
1813                 return 0
1814         fi
1815         if [ "$INTERACTIVE" = "y" ]; then
1816                 # We should show the CDDB results both when we are not using the local CDDB repo
1817                 # or when we are using it but we could not find a proper match
1818                 if [ "$CDDBUSELOCAL" = "y" ] && [ ! "$CDDBLOCALSUCCESS" = "y" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1819                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1820                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1821                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1822                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1823                                 CHOICE=$(checkstatus cddb-choice)
1824                                 if [ -n "$CHOICE" ] ; then
1825                                         case $CDDBCHOICES in
1826                                                 1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1827                                                 *)
1828                                                 echo "Selected: #$CHOICE"
1829                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1830                                                 ;;
1831                                         esac
1832                                 else
1833                                         # The user has a choice to make, display the info in a pager if necessary
1834                                         if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
1835                                                 page "$ABCDETEMPDIR/cddbchoices"
1836                                         else
1837                                                 # It's all going to fit in one page, cat it
1838                                                 cat "$ABCDETEMPDIR/cddbchoices" >&2
1839                                         fi
1840                                         
1841                                         CDDBCHOICENUM=""
1842                                         # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
1843                                         CDCHOICENUM=-1
1844                                         # I'll take CDDB read #3 for $400, Alex
1845                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
1846                                                 echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
1847                                                 read CDDBCHOICE
1848                                                 [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
1849                                                 if echo $CDDBCHOICE | egrep -q "[[:digit:]]+,[[:digit:]]+" ; then
1850                                                         if [ ! X"$DIFF" = "X" ]; then
1851                                                                 PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1)
1852                                                                 PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2)
1853                                                                 if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBCHOICES ] || \
1854                                                                    [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBCHOICES ] || \
1855                                                                    [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then 
1856                                                                         echo "Invalid diff range. Please select two coma-separated numbers between 1 and $CDDBCHOICES" >&2
1857                                                                 else
1858
1859                                                                         # We parse the 2 choices to diff, store them in temporary files and diff them.
1860                                                                         for PARSECHOICE in $(echo $CDDBCHOICE | tr , \ ); do
1861                                                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$PARSECHOICE" > "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE"
1862                                                                         done
1863                                                                         echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/cddbread.diff"
1864                                                                         $DIFF $DIFFOPTS "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/cddbread.diff"
1865                                                                         if [ $(cat "$ABCDETEMPDIR/cddbread.diff" | wc -l) -ge 24 ]; then
1866                                                                                 page "$ABCDETEMPDIR/cddbread.diff"
1867                                                                         else
1868                                                                                 cat "$ABCDETEMPDIR/cddbread.diff" >&2
1869                                                                         fi
1870                                                                 fi
1871                                                         else
1872                                                                 echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
1873                                                         fi
1874                                                 else
1875                                                         if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
1876                                                                 # Make sure we get a valid choice
1877                                                                 CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1878                                                                 echo "Invalid selection. Please choose a number between 0 and $CDDBCHOICES." >&2
1879                                                         fi
1880                                                 fi
1881                                         done
1882                                         if [ "$CDCHOICENUM" = "0" ]; then
1883                                                 vecho "Creating empty CDDB template..."
1884                                                 UNKNOWNDISK=y
1885                                                 $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
1886                                         else
1887                                                 echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
1888                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
1889                                         fi
1890                                         echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1891                                 fi
1892                         fi
1893                 else
1894                         # We need some code to show the selected option when local repository is selected and we have found a match
1895                         vecho "Using cached CDDB match..." >&2
1896                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1897                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1898                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1899                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1900                                 CHOICE=$(checkstatus cddb-choice)
1901                                 if [ "$USELOCALRESP" = "y" ]; then :; else
1902                                         if [ -n "$CHOICE" ] ; then
1903                                                 case $CDDBCHOICES in
1904                                                         0) 
1905                                                         UNKNOWNDISK=y
1906                                                         echo "Selected template."
1907                                                         ;;
1908                                                         1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1909                                                         *)
1910                                                         echo "Selected: #$CHOICE"
1911                                                         do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1912                                                         ;;
1913                                                 esac
1914                                         fi
1915                                 fi
1916                         fi
1917                 fi
1918         else
1919                 # We're noninteractive - pick the first choice.
1920                 # But in case we run a previous instance and selected a choice, use it.
1921                 if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1922                         # Show the choice if we are not using the locally stored one
1923                         # or when the local search failed to find a match.
1924                         PREVIOUSCHOICE=$(checkstatus cddb-choice)
1925                         if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSUCCESS" = "n" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1926                                 #if [ "$PREVIOUSCHOICE" ]; then
1927                                         cat "$ABCDETEMPDIR/cddbchoices"
1928                                 #fi
1929                         fi
1930                         if [ ! -z "$PREVIOUSCHOICE" ] ; then
1931                                 CDCHOICENUM=$PREVIOUSCHOICE
1932                         else
1933                                 CDCHOICENUM=1
1934                                 echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1935                         fi
1936                         echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
1937                 fi
1938         fi
1939
1940         # sanity check
1941         if checkstatus cddb-choice >/dev/null; then :; else
1942                 echo "abcde: internal error: cddb-choice not recorded." >&2
1943                 exit 1
1944         fi
1945         CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1946         echo -n "Edit selected CDDB data? [y/n] (" >&2
1947         if [ "$INTERACTIVE" = "y" ]; then
1948                 if [ "$UNKNOWNDISK" = "y" ]; then
1949                         echo -n "y): " >&2
1950                         read EDITCDDB
1951                         [ "$EDITCDDB" != "n" ] && EDITCDDB=y
1952                 else
1953                         echo -n "n): " >&2
1954                         read EDITCDDB
1955                 fi
1956         else
1957                 echo "n): n" >&2
1958                 EDITCDDB=n
1959         fi
1960         if [ "$EDITCDDB" = "y" ]; then
1961                 CDDBDATAMD5SUM=$($MD5SUM "$CDDBDATA" | cut -d " " -f 1);
1962                 
1963                 # Use the debian sensible-editor wrapper to pick the editor that the
1964                 # user has requested via their $EDITOR environment variable
1965                 if [ -x "/usr/bin/sensible-editor" ]; then
1966                         /usr/bin/sensible-editor "$CDDBDATA"
1967                 elif [ -n "$EDITOR" ]; then
1968                         if [ -x $(which "${EDITOR%%\ *}") ]; then
1969                                 # That failed, try to load the preferred editor, starting
1970                                 # with their EDITOR variable
1971                                 eval $(echo "$EDITOR") \"$CDDBDATA\"
1972                         fi
1973                 # If that fails, check for a vi
1974                 elif which vi >/dev/null 2>&1; then
1975                         vi "$CDDBDATA"
1976                 elif [ -x /usr/bin/vim ]; then
1977                         /usr/bin/vim "$CDDBDATA"
1978                 elif [ -x /usr/bin/vi ]; then
1979                         /usr/bin/vi "$CDDBDATA"
1980                 elif [ -x /bin/vi ]; then
1981                         /bin/vi "$CDDBDATA"
1982                 # nano should be on all (modern, i.e., sarge) debian systems
1983                 elif which nano >/dev/null 2>&1 ; then
1984                         nano "$CDDBDATA"
1985                 elif [ -x /usr/bin/nano ]; then
1986                         /usr/bin/nano "$CDDBDATA"
1987                 # mg should be on all OpenBSD systems
1988                 elif which mg >/dev/null 2>&1 ; then
1989                         mg "$CDDBDATA"
1990                 elif [ -x /usr/bin/mg ]; then
1991                         /usr/bin/mg "$CDDBDATA"
1992                 # bomb out
1993                 else
1994                         log warning "no editor available. Check your EDITOR environment variable."
1995                 fi
1996                 # delete editor backup file if it exists
1997                 if [ -w "$CDDBDATA~" ]; then
1998                         rm -f "$CDDBDATA~"
1999                 fi
2000         fi
2001
2002         # Some heuristics first. Look at Disc Title, and if it starts with
2003         # "Various", then we'll assume Various Artists
2004         if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
2005                 echo "Looks like a Multi-Artist CD" >&2
2006                 VARIOUSARTISTS=y
2007         else
2008                 echo -n "Is the CD multi-artist? [y/n] (n): " >&2
2009                 if [ "$INTERACTIVE" = "y" ]; then
2010                         read VARIOUSARTISTS
2011                 else
2012                         echo n >&2
2013                         VARIOUSARTISTS=n
2014                 fi
2015         fi
2016         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
2017                 # Set a default
2018                 DEFAULTSTYLE=1
2019                 # Need NUMTRACKS before cddb-tool will return it:
2020                 NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
2021                 if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
2022                         # More than 1/2 tracks contain a "/", so guess forward
2023                         DEFAULTSTYLE=1
2024                 elif [ "$(grep -c "^TTITLE.*\-" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
2025                         # More than 1/2 contain a "-", so guess forward-dash
2026                         DEFAULTSTYLE=2
2027                 elif [ "$(grep -c "^TTITLE.*(.*)" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
2028                         # More than 1/2 contain something in parens, so guess trailing-paren
2029                         DEFAULTSTYLE=6
2030                 fi
2031
2032                 echo "1) Artist / Title" >&2
2033                 echo "2) Artist - Title" >&2
2034                 echo "3) Title / Artist" >&2
2035                 echo "4) Title - Artist" >&2
2036                 echo "5) Artist: Title" >&2
2037                 echo "6) Title (Artist)" >&2
2038                 echo "7) This is a single-artist CD" >&2
2039                 echo -n "Which style of multiple artist entries is it? [1-7] ($DEFAULTSTYLE): " >&2
2040                 if [ "$INTERACTIVE" = "y" ]; then
2041                         read VARIOUSARTISTSTYLE
2042                 else
2043                         echo $DEFAULTSTYLE >&2
2044                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
2045                 fi
2046                 VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
2047                 # If they press Enter, then the default style (0) was chosen
2048                 while [ $VARIOUSARTISTSTYLE -lt 0 ] || [ $VARIOUSARTISTSTYLE -gt 7 ]; do
2049                         echo "Invalid selection. Please choose a number between 1 and 7."
2050                         echo -n "Selection [1-7]: "
2051                         read VARIOUSARTISTSTYLE
2052                         VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
2053                 done
2054                 if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
2055                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
2056                 fi
2057                 vecho "Selected: $VARIOUSARTISTSTYLE"
2058                 case "$VARIOUSARTISTSTYLE" in
2059                 1) # Artist / Title
2060                         VARIOUSARTISTSTYLE=forward
2061                         ;;
2062                 2) # Artist - Title
2063                         VARIOUSARTISTSTYLE=forward-dash
2064                         ;;
2065                 3) # Title / Artist
2066                         VARIOUSARTISTSTYLE=reverse
2067                         ;;
2068                 4) # Title - Artist
2069                         VARIOUSARTISTSTYLE=reverse-dash
2070                         ;;
2071                 5) # Artist: Title
2072                         VARIOUSARTISTSTYLE=colon
2073                         ;;
2074                 6) # Title (Artist)
2075                         VARIOUSARTISTSTYLE=trailing-paren
2076                         ;;
2077                 7) # Single Artist
2078                         VARIOUSARTISTS=n
2079                         ;;
2080                 esac
2081         fi
2082
2083         echo "variousartists=$VARIOUSARTISTS" >> "$ABCDETEMPDIR/status"
2084         echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
2085
2086         if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
2087                 if [ "$CDDBDATAMD5SUM" != "" ]  && [ "$CDDBDATAMD5SUM" != "$($MD5SUM "$CDDBDATA" | cut -d " " -f 1)" ]; then
2088                         # This works but does not have the necessary error checking
2089                         # yet. If you are familiar with the CDDB spec
2090                         # (see http://www.freedb.org/src/latest/DBFORMAT) 
2091                         # and can create an error-free entry on your own, then put
2092                         # UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE=y in your
2093                         # abcde.conf to enable it. Put CDDBSUBMIT=email@address in
2094                         # your abcde.conf to change the email address submissions are
2095                         # sent to.
2096
2097                         # submit the modified file, if they want
2098                         if [ "$NOSUBMIT" != "y" ]; then
2099                                 echo -n "Do you want to submit this entry to $CDDBSUBMIT? [y/n] (n): "
2100                                 read YESNO
2101                                 while [ "$YESNO" != "y" ] && [ "$YESNO" != "n" ] && [ "$YESNO" != "Y" ] && \
2102                                         [ "$YESNO" != "N" ] && [ "$YESNO" != "" ]
2103                                 do
2104                                         echo -n 'Invalid selection. Please answer "y" or "n": '
2105                                         read YESNO
2106                                 done
2107                                 if [ "$YESNO" = "y" ] || [ "$YESNO" = "Y" ]; then
2108                                         echo -n "Sending..."
2109                                         $CDDBTOOL send "$CDDBDATA" $CDDBSUBMIT
2110                                         echo "done."
2111                                 fi
2112                         fi
2113                 fi
2114         fi
2115         # Make sure the cache directory exists
2116         mkdir -p $CDDBLOCALDIR
2117         # Cache edited CDDB entry in the user's cddb dir
2118         if [ "$CDDBCOPYLOCAL" = "y" ] || [ "$COPYCDDBLOCAL" = "Y" ]; then
2119                 cat "$CDDBDATA" | tail -n $(expr $(cat "$CDDBDATA" | wc -l ) - 1 ) > ${CDDBLOCALDIR}/$(echo "$TRACKINFO" | cut -d' ' -f1)
2120         fi
2121
2122         echo "cddb-edit" >> "$ABCDETEMPDIR/status"
2123 }
2124
2125 # do_cdread [tracknumber]
2126 # do_cdread onetrack [firsttrack] [lasttrack]
2127
2128 do_cdread ()
2129 {
2130         # The commands here don't go through run_command because they're never supposed to be silenced
2131         # return codes need to be doublechecked anyway, however
2132         if [ "$1" = "onetrack" ]; then
2133                 # FIXME # Add the possibility of grabbing ranges of tracks in onetrack
2134                 # FIXME # Until then, we grab the whole CD in one track, no matter what
2135                 # the user said
2136                 # We need the first and last track for cdda2wav
2137                 FIRSTTRACK=$2
2138                 LASTTRACK=$3
2139                 UTRACKNUM=$FIRSTTRACK
2140                 case "$CDROMREADERSYNTAX" in
2141                         ### FIXME ### How are we calculating the tracks in flac mode?
2142                         flac) READTRACKNUMS="$FIRSTTRACK.1-$(($LASTTRACK + 1)).0" ;;
2143                         cdparanoia) READTRACKNUMS="$FIRSTTRACK-$LASTTRACK" ;;
2144                         cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTRACK" ;;
2145                         *) log error "$CDROMREADERSYNTAX does not support ONETRACK mode"
2146                            exit 1 ;;
2147                 esac
2148         else
2149                 UTRACKNUM=$1
2150         fi
2151         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
2152         if [ "$USEPIPES" = "y" ]; then
2153                 TEMPARG="PIPERIPPER_$CDROMREADERSYNTAX"
2154                 FILEARG="$( eval echo "\$$TEMPARG" )"
2155                 REDIR=""
2156                 PIPE_MESSAGE="and encoding "
2157         else
2158                 WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
2159                 case "$CDROMREADERSYNTAX" in
2160                 ## FIXME ## Find the cases for dagrab and flac, to avoid exceptions
2161                         flac)
2162                                 FILEARG="--output-name=$WAVDATA"
2163                                 ;;
2164                         dagrab)
2165                                 FILEARG="-f $WAVDATA"
2166                                 ;;
2167                         *)
2168                                 FILEARG="$WAVDATA"
2169                                 ;;
2170                 esac
2171                 REDIR=">&2"
2172         fi
2173         if [ "$1" = "onetrack" ]; then
2174                 echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK as one track ..." >&2
2175         else
2176                 if [ -r "$CDDBDATA" ]; then
2177                         #TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
2178                         do_getcddbinfo TRACKNAME
2179                         echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
2180                 else
2181                         echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
2182                 fi
2183         fi
2184         case "$CDROMREADERSYNTAX" in
2185                 ### FIXME ### use an exception for flac, since it uses -o
2186                 ### FIXME ### Shall we just use -o $FILEARG ??
2187                 flac)
2188                         nice $READNICE $FLAC -d --cue=${READTRACKNUMS:-$UTRACKNUM.1-$(($UTRACKNUM + 1)).0} "$FILEARG" "$CDROM" ;;
2189                 cdparanoia) 
2190                         nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR ;;
2191                 cdda2wav)
2192                         if [ "$OSFLAVOUR" = "OSX" ] ; then
2193                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
2194                                 disktool -u ${CDROM#/dev/} 0
2195                                 # Also, in OSX the cdrom device for cdda2wav changes...
2196                                 CDDA2WAVCDROM="IODVDServices"
2197                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
2198                                 CDDA2WAVCDROM="$CDROMID"
2199                         else
2200                                 if [ "$CDROMID" = "" ]; then
2201                                         CDDA2WAVCDROM="$CDROM"
2202                                 else
2203                                         CDDA2WAVCDROM="$CDROMID"
2204                                 fi
2205                         fi
2206                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} "$FILEARG" $REDIR
2207                         ;;
2208                 ## FIXME ## We have an exception for dagrab, since it uses -f
2209                 ## FIXME ## Shall we just use -f $FILEARG ??
2210                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -v $UTRACKNUM "$FILEARG" $REDIR
2211                         ;;
2212                 cddafs)
2213                         # Find the track's mounted path
2214                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
2215                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
2216                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
2217                         # If the file exists, copy it
2218                         if [ -e "$FILEPATH" ] ; then
2219                                 nice $READNICE $CDROMREADER "$FILEPATH" "$FILEARG" $REDIR
2220                         else
2221                                 false
2222                         fi ;;
2223                 debug) nice $READNICE $CDROMREADER -$CDPARANOIACDROMBUS $CDROM -w $UTRACKNUM-[:1] "$FILEARG" $REDIR
2224                         ;;
2225         esac
2226         RETURN=$?
2227         # If we get some error or we get some missing wav 
2228         # (as long as we dont use pipes)
2229         if [ "$RETURN" != "0" -o \( ! -s "$WAVDATA" -a X"$USEPIPES" != "Xy" \) ]; then
2230                 # Thank goodness errors is only machine-parseable up to the
2231                 # first colon, otherwise this woulda sucked
2232                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
2233                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
2234                 fi
2235                 if [ "$USEPIPES" = "y" ]; then
2236                         echo "readencodetrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
2237                 else
2238                         echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
2239                 fi
2240                 return $RETURN
2241         else
2242                 if [ "$USEPIPES" = "y" ]; then
2243                         echo readencodetrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
2244                 else
2245                         echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
2246                         if [ "$1" = "onetrack" ]; then
2247                                 echo onetrack >> "$ABCDETEMPDIR/status"
2248                         fi
2249                 fi
2250         fi
2251 }
2252
2253 # do_cdspeed
2254 # No values accepted, only uses env variables
2255 do_cdspeed () 
2256 {
2257         if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
2258                 vecho "Setting CD speed to ${CDSPEEDVALUE}x"
2259         else
2260                 echo "abcde: unable to set the device speed" >&2
2261         fi
2262 }
2263
2264 # vecho [message]
2265 #
2266 # vecho outputs a message if EXTRAVERBOSE is selected
2267 vecho ()
2268 {
2269 if [ x"$EXTRAVERBOSE" != "x" ]; then
2270         case $1 in
2271                 warning) log warning "$@" ;;
2272                 *) echo "$@" ;;
2273         esac
2274 fi
2275 }
2276
2277 # decho [message]
2278 #
2279 # decho outputs a debug message if DEBUG is selected
2280 decho ()
2281 {
2282 if [ x"$DEBUG" != "x" ]; then
2283         if echo $1 | grep -q "^\[" ; then
2284                 DEBUGECHO=$(echo "$@" | tr -d '[]')
2285                 echo "[DEBUG] $DEBUGECHO: `eval echo \\$${DEBUGECHO}`"
2286         else
2287                 echo "[DEBUG] $1"
2288         fi
2289 fi
2290 }
2291
2292 # User-redefinable functions
2293 # Custom filename munging:
2294 mungefilename ()
2295 {
2296         #echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
2297         echo "$@" | sed s,:,\ -,g | tr \ / __ | tr -d \'\"\?\[:cntrl:\]
2298 }
2299
2300 # Custom genre munging:
2301 mungegenre ()
2302 {
2303         echo $CDGENRE | tr "[:upper:]" "[:lower:]"
2304 }
2305
2306 # pre_read
2307 # Empty pre_read function, to be defined in the configuration file.
2308 pre_read ()
2309 {
2310 :
2311 }
2312
2313 # post_read
2314 # Empty post_read function, to be defined in the configuration file.
2315 post_read ()
2316 {
2317 :
2318 }
2319
2320 ###############################################################################
2321 # End of functions
2322 #
2323 # Start of execution
2324 ###############################################################################
2325
2326 # Builtin defaults
2327 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
2328 CDDBSUBMIT=freedb-submit@freedb.org
2329 CDDBPROTO=5
2330 HELLOINFO="$(whoami)@$(hostname)"
2331 CDDBCOPYLOCAL="n"
2332 CDDBLOCALDIR="$HOME/.cddb"
2333 CDDBUSELOCAL="n"
2334
2335 # List of fields we parse and show during the CDDB parsing...
2336 SHOWCDDBFIELDS="year,genre"
2337
2338 INTERACTIVE=y
2339 CDROMREADERSYNTAX=cdparanoia
2340 ENCODERSYNTAX=default
2341
2342 MP3ENCODERSYNTAX=default
2343 OGGENCODERSYNTAX=default
2344 FLACENCODERSYNTAX=default
2345 SPEEXENCODERSYNTAX=default
2346 MPPENCODERSYNTAX=default
2347 NORMALIZERSYNTAX=default
2348 CUEREADERSYNTAX=default
2349
2350 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
2351 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
2352 #VAOUTPUTFORMAT=${OUTPUTFORMAT}
2353 VAOUTPUTFORMAT='Various-${ALBUMFILE}/${TRACKNUM}.${ARTISTFILE}-${TRACKFILE}'
2354 ONETRACKOUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${ALBUMFILE}'
2355 VAONETRACKOUTPUTFORMAT='Various-${ALBUMFILE}/${ALBUMFILE}'
2356 PLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
2357 PLAYLISTDATAPREFIX=''
2358 VAPLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
2359 VAPLAYLISTDATAPREFIX=''
2360 DOSPLAYLIST=n
2361 COMMENT=''
2362 ID3TAGV=2
2363 ENCNICE=10
2364 READNICE=10
2365 DISTMP3NICE=10
2366 VARIOUSARTISTS=n
2367 VARIOUSARTISTSTYLE=forward
2368 KEEPWAVS=n
2369 PADTRACKS=n
2370 NOGAP=n
2371 BATCHNORM=n
2372
2373 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
2374 # i.e. CDROMID="1,0,0"
2375 CDROMID=""
2376 # If we are using the IDE bus, we need CDPARANOIACDROMBUS defined as "d"
2377 # If we are using the ide-scsi emulation layer, we need to define a "g"
2378 CDPARANOIACDROMBUS="d"
2379
2380 # program paths - defaults to checking your $PATH
2381 # mp3
2382 LAME=lame
2383 TOOLAME=toolame
2384 GOGO=gogo
2385 BLADEENC=bladeenc
2386 L3ENC=l3enc
2387 XINGMP3ENC=xingmp3enc
2388 MP3ENC=mp3enc
2389 # ogg
2390 VORBIZE=vorbize
2391 OGGENC=oggenc
2392 # flac
2393 FLAC=flac
2394 # speex
2395 SPEEXENC=speexenc
2396 # mpp (Musepack)
2397 MPPENC=mppenc
2398
2399 ID3=id3
2400 ID3V2=id3v2
2401 EYED3=eyeD3
2402 CDPARANOIA=cdparanoia
2403 CDDA2WAV=cdda2wav
2404 DAGRAB=dagrab
2405 CDDAFS=cp
2406 CDDISCID=cd-discid
2407 CDDBTOOL=cddb-tool
2408 EJECT=eject
2409 MD5SUM=md5sum
2410 DISTMP3=distmp3
2411 VORBISCOMMENT=vorbiscomment
2412 METAFLAC=metaflac
2413 NORMALIZE=normalize-audio
2414 CDSPEED=eject
2415 VORBISGAIN=vorbisgain
2416 MP3GAIN=mp3gain
2417 MPPGAIN=replaygain
2418 MKCUE=mkcue
2419 MKTOC=cdrdao
2420 DIFF=diff
2421 CUE2DISCID=cue2discid
2422
2423 # Options for programs called from abcde
2424 # mp3
2425 LAMEOPTS=
2426 TOOLAMEOPTS=
2427 GOGOOPTS=
2428 BLADEENCOPTS=
2429 L3ENCOPTS=
2430 XINGMP3ENCOPTS=
2431 MP3ENCOPTS=
2432 # ogg
2433 VORBIZEOPTS=
2434 OGGENCOPTS=
2435 # flac
2436 FLACOPTS=
2437 # speex
2438 SPEEXENCOPTS=
2439 # mpc
2440 MPPENCOPTS=
2441
2442 ID3OPTS=
2443 ID3V2OPTS=
2444 CDPARANOIAOPTS=
2445 CDDA2WAVOPTS=
2446 DAGRABOPTS=
2447 CDDAFSOPTS="-f"
2448 CDDBTOOLOPTS=
2449 EJECTOPTS=
2450 DISTMP3OPTS=
2451 NORMALIZEOPTS=
2452 CDSPEEDOPTS="-x"
2453 CDSPEEDVALUE=
2454 MKCUEOPTS=
2455 MKTOCOPTS=""
2456 VORBISCOMMENTOPTS="-R"
2457 METAFLACOPTS="--no-utf8-convert"
2458 DIFFOPTS=
2459
2460 # Default to one process if -j isn't specified
2461 MAXPROCS=1
2462
2463 # List of actions to perform - by default, run to completion
2464 ACTIONS=cddb,read,encode,tag,move,clean
2465
2466 # List of prefered outputs - by default, run with whatever we have in the path
2467 # This option is basicaly for Debian package dependencies
2468 DEFAULT_OUTPUT_BINARIES=vorbis:oggenc,flac:flac,mp3:lame,mp3:bladeenc,spx:speex
2469
2470 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
2471 # Let's use these checkings to determine the OS flavour, which will be used later
2472 if [ X$(uname) = "XFreeBSD" ] ; then
2473         HTTPGET=fetch
2474         MD5SUM=md5
2475         NEEDCDROMID=y
2476         OSFLAVOUR=FBSD
2477 elif [ X$(uname) = "XDarwin" ] ; then
2478         HTTPGET=curl
2479         OSFLAVOUR=OSX
2480         # We should have disktool in OSX, but let's be sure...
2481         NEEDDISKTOOL=y
2482         CDROMREADERSYNTAX=cddafs
2483 elif [ X$(uname) = "XOpenBSD" ] ; then
2484         HTTPGET=wget
2485         MD5SUM=md5
2486 elif [ X$(uname) = "XNetBSD" ] ; then
2487         HTTPGET=ftp
2488         MD5SUM=md5
2489 else
2490         HTTPGET=wget
2491 fi
2492
2493 # If CDDBAVAIL is set to n, no CDDB read is done
2494 # If USEID3 is set to n, no ID3 tagging is done
2495 CDDBAVAIL=y
2496 USEID3=y
2497 USEID3V2=y
2498
2499 if [ -z "$OUTPUTDIR" ]; then
2500         OUTPUTDIR=$(pwd)
2501 fi
2502
2503 if [ -z "$WAVOUTPUTDIR" ]; then
2504         WAVOUTPUTDIR="$OUTPUTDIR"
2505 fi
2506
2507 # Load system defaults
2508 if [ -r /etc/abcde.conf ]; then
2509         . /etc/abcde.conf
2510 fi
2511 # Load user preference defaults
2512 if [ -r $HOME/.abcde.conf ]; then
2513         . $HOME/.abcde.conf
2514 fi
2515
2516 # By this time, we need some HTTPGETOPTS already defined.
2517 # If the user has defined a non-default HTTPGET method, we should not be empty.
2518
2519 if [ "$HTTPGETOPTS" = "" ] ; then
2520         case $HTTPGET in
2521                 wget) HTTPGETOPTS="-q -O -";;
2522                 curl) HTTPGETOPTS="-f -s";;
2523                 fetch)HTTPGETOPTS="-q -o -";;
2524                 ftp)  HTTPGETOPTS="-q -o -";;
2525                 *) log warning "HTTPGET in non-standard and HTTPGETOPTS are not defined." ;;
2526         esac
2527 fi
2528
2529 # If the CDROM has not been set yet, find a suitable one.
2530 # If this is a devfs system, default to /dev/cdroms/cdrom0
2531 # instead of /dev/cdrom
2532 if [ "$CDROM" = "" ] ; then
2533         if [ -e /dev/cdroms/cdrom0 ]; then
2534                 CDROM=/dev/cdroms/cdrom0
2535         elif [ -e /dev/cdrom ]; then
2536                 CDROM=/dev/cdrom
2537         elif [ -e /dev/cd0c ]; then
2538                 CDROM=/dev/cd0c
2539         elif [ -e /dev/acd0c ]; then
2540                 CDROM=/dev/acd0c
2541         elif [ -e /dev/disk1 ]; then
2542                 CDROM=/dev/disk1
2543         fi
2544 fi
2545
2546 # Parse command line options
2547 #while getopts 1a:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
2548 while getopts 1a:bBc:C:d:Defghj:klLmMnNo:pPr:s:S:t:T:uvVxw:W:z opt ; do
2549         case "$opt" in
2550                 1) ONETRACK=y ;;
2551                 a) ACTIONS="$OPTARG" ;;
2552                 A) EXPACTIONS="$OPTARG" ;;
2553                 b) BATCHNORM=y ;;
2554                 B) NOBATCHREPLAYGAIN=y ;;
2555                 c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else log error "config file \"$OPTARG\" cannot be found." ; exit 1 ; fi ;;
2556                 C) DISCID="$( echo ${OPTARG#abcde.} | tr -d /)" ;;
2557                 d) CDROM="$OPTARG" ;;
2558                 D) set -x ;;
2559                 e) ERASEENCODEDSTATUS=y ;;
2560                 h) usage; exit ;;
2561                 e) ERASEENCODEDSTATUS=y ;;
2562                 E) ENCODING="$OPTARG" ;;
2563                 f) FORCE=y ;;
2564                 g) NOGAP=y ;;
2565                 i) INLINETAG=y ;;
2566                 j) MAXPROCS="$OPTARG" ;;
2567                 k) KEEPWAVS=y ;;
2568                 l) LOWDISK=y ;;
2569                 L) CDDBUSELOCAL=y ;;
2570                 n) CDDBAVAIL=n ;;
2571                 N) INTERACTIVE=n ;;
2572                 m) DOSPLAYLIST=y ;;
2573                 M) MAKECUEFILE=y ;;
2574                 o) OUTPUTTYPE="$OPTARG" ;;
2575                 p) PADTRACKS=y ;;
2576                 P) USEPIPES=y ;;
2577                 r) REMOTEHOSTS="$OPTARG" ;;
2578                 R) DOREPLAYGAIN=y ;;
2579                 s) SHOWCDDBFIELDS="$OPTARG" ;;
2580                 S) CDSPEEDVALUE="$OPTARG" ;;
2581                 t) STARTTRACKNUMBER="$OPTARG" ;;
2582                 T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
2583                 u) CDDBPROTO=6 ;;
2584                 v) 
2585                    echo "This is abcde v$VERSION."
2586                    echo "Usage: abcde [options] [tracks]"
2587                    echo "abcde -h for extra help"
2588                    exit
2589                    ;;
2590                 V) EXTRAVERBOSE="y" ;;
2591                 x) EJECTCD="y" ;;
2592                 w) COMMENT="$OPTARG" ;;
2593                 W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
2594                      STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
2595                    else
2596                      log error "argument of -W must be integer"
2597                          exit 1
2598                    fi
2599                    ;;
2600                 z) DEBUG=y ; CDROMREADERSYNTAX=debug ; EJECTCD="n" ;;
2601                 ?) usage; exit ;;
2602         esac
2603 done
2604
2605 shift $(($OPTIND - 1))
2606
2607 # If the user specified a flac file, then switch to special flac mode
2608 if echo $CDROM | grep -i -q '.flac$'; then
2609         vecho "abcde: switching to flac CDROMREADERSYNTAX..."
2610         CDROMREADERSYNTAX=flac
2611         if [ "$EJECTCD" = "y" ];then
2612                 vecho "abcde: CDROM flac mode, deactivating EJECTCD..."
2613                 EJECTCD=n
2614         fi
2615 fi
2616
2617 # If the user provided a DISCID, disable eject
2618 if [ -n "$DISCID" ]; then EJECTCD=n ; fi
2619
2620 # Decide if we can continue.
2621 if [ "$ONETRACK" = "y" ]; then 
2622         # FIXME # remove check as soon as we find out about the other readers
2623         case "$CDROMREADERSYNTAX" in
2624                 flac) ;;
2625                 cdparanoia) ;;
2626                 cdda2wav) ;;
2627                 *) log error "$CDROMREADERSYNTAX does not support ONETRACK mode"
2628                    exit 1 ;;
2629         esac
2630         if [ "$BATCHNORM" = "y" ]; then
2631                 log warning "BATCHNORM mode is not compatible with ONETRACK mode. Disabling..."
2632                 BATCHNORM=n
2633         fi
2634         if [ "$NOGAP" = "y" ]; then
2635                 log warning "NOGAP mode is not compatible with ONETRACK mode. Disabling..."
2636                 NOGAP=n
2637         fi
2638         # It does not matter how many tracks we want. In ONETRACK mode we grab them all
2639         # FIXME # allow ranges of tracks to be selected for onetrack ripping
2640         if [ $# -gt 0 ]; then
2641                 log warning "ONETRACK mode selected, grabbing all tracks..."
2642         fi
2643 else
2644         while [ $# -gt 0 ]; do
2645                 # Range parsing code courtesy of Vincent Ho
2646                 RSTART=$(echo $1 | cut -f1 -d-)
2647                 REND=$(echo $1 | cut -f2 -d-)
2648                 if [ "$RSTART" = "$REND" ]; then
2649                         NEWTRACKS="$RSTART"
2650                 else
2651                         NEWTRACKS=$(f_seq_line $RSTART $REND)
2652                 fi
2653                 TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
2654                 shift
2655         done
2656 fi
2657
2658 # List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
2659 # List of experimental actions: retag,transcode
2660
2661 # Determine what actions are to be done from $ACTIONS and set the
2662 # following environment variables for them:
2663 DOCDDB=n
2664 DOREAD=n
2665 DONORMALIZE=n
2666 DOPREPROCESS=n
2667 DOENCODE=n
2668 DOPOSTPROCESS=n
2669 DOTAG=n
2670 DOMOVE=n
2671 DOREPLAYGAIN=n
2672 DOPLAYLIST=n
2673 DOCLEAN=n
2674
2675 for ACTION in $(echo $ACTIONS | tr , \ )
2676 do
2677         case $ACTION in
2678                 cddb) DOCDDB=y;;
2679                 read) DOREAD=y;;
2680                 normalize) DONORMALIZE=y; DOREAD=y;;
2681 #               preprocess) DOPREPROCESS=y; DOREAD=y;;
2682                 encode) DOENCODE=y; DOREAD=y;;
2683 #               postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
2684                 tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
2685                 move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
2686                 replaygain) DOCDDB=y; DOREAD=y; DOENCODE=y; DOTAG=y; DOMOVE=y; DOREPLAYGAIN=y;;
2687                 playlist) DOCDDB=y; DOPLAYLIST=y;;
2688                 clean) DOCLEAN=y;;
2689         esac
2690 done
2691
2692 if [ "$DONORMALIZE" = "y" ] && [ "$DOREPLAYGAIN" = "y" ]; then
2693         # FIXME # should we abort on error or just inform the user?
2694         log warning "selected both normalize and replaygain actions"
2695 fi
2696
2697 for SHOWCDDBFIELD in $(echo $SHOWCDDBFIELDS | tr , \ ); do
2698         case $SHOWCDDBFIELD in
2699                 y*|Y*) SHOWCDDBYEAR="y";;
2700                 g*|G*) SHOWCDDBGENRE="y";;
2701                 *) ;;
2702         esac
2703 done
2704
2705 # Sanity checks:
2706
2707 # At this point a CDROM has to be defined, so we check it exists.
2708 if [ X"$CDROM" != "X" ] ; then 
2709         if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
2710                 if [ "$OSFLAVOUR" = "FBSD" ]; then
2711                         if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
2712                                 log error "CDROMID not in the right format for $CDROMREADERSYNTAX"
2713                                 log error "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
2714                                 exit 1
2715                         fi
2716                 fi
2717         elif [ ! -e "$CDROM" -a X"$DOREAD" = "Xy" ]; then
2718                 log error "CDROM device cannot be found."
2719                 exit 1
2720         fi
2721 # avoid processing if we are not going to hit the CDROM.
2722 elif [ X"$DOREAD" = "Xy" ]; then
2723         log error "CDROM has not been defined or cannot be found"
2724         exit 1
2725 fi
2726
2727 # USEPIPES pre-tests, before we get into more serious stuff
2728 # Not compatible with:
2729 # - multiple outputs
2730 # - normalize
2731 # - lowdisk algorithm
2732 # - anything else?
2733 if [ X"$USEPIPES" = "Xy" ]; then
2734         if [ $(echo "$OUTPUTTYPE" | tr , \  | wc -w ) -gt 1 ]; then
2735                 log error "Unix pipes not compatible with multiple outputs"
2736                 exit 1
2737         fi
2738         if [ X"$DONORMALIZE" = "Xy" ]; then
2739                 log error "Unix pipes not compatible with normalizer"
2740                 # FIXME # Do we need to exit or shall we just disable the mode?
2741                 exit 1
2742         fi
2743         if [ X"$BATCHNORM" = "Xy" ]; then
2744                 log error "Unix pipes not compatible with BATCHNORM encoding"
2745                 exit 1
2746         fi
2747         if [ X"$NOGAP" = "Xy" ]; then
2748                 log error "Unix pipes not compatible with NOGAP encoding"
2749                 exit 1
2750         fi
2751         if [ X"$DOENCODE" = "Xn" ]; then
2752                 vecho warning "Disabling Unix pipes since we are not encoding!"
2753                 USEPIPES=n
2754         fi
2755         if [ X"$LOWDISK" = "Xy" ]; then
2756                 log error "Unix pipes not compatible with lowdisk algorithm"
2757                 exit 1
2758         fi
2759 fi
2760
2761 # LOWDISK pre-tests, before we get into more problematic stuff
2762 # Not compatible with anything that needs all the files in the hard disc:
2763 # - BATCHNORM
2764 # - NOGAP lame mode
2765 if [ X"$LOWDISK" = "Xy" ]; then
2766         if [ X"$BATCHNORM" = "Xy" ]; then
2767                 log error "Unix pipes not compatible with BATCHNORM encoding"
2768                 exit 1
2769         fi
2770         if [ X"$NOGAP" = "Xy" ]; then
2771                 log error "Unix pipes not compatible with NOGAP encoding"
2772                 exit 1
2773         fi
2774 fi
2775
2776 # BATCHNORM pre-tests, before we get into serious problems
2777 # Not compatible with 
2778 if [ "$BATCHNORM" = "y" ] && [ "$DONORMALIZE" = "n" ]; then
2779         vecho warning "Disabling BATCHNORM since we are not normalizing!"
2780         BATCHNORM=n
2781 fi
2782
2783 # Check the encoding format from the ones available in the system, if nothing has been configured in the system.
2784 if [ X"$OUTPUTTYPE" = "X" ]; then
2785         for DEFAULT_OUTPUT in $( echo "$DEFAULT_OUTPUT_BINARIES" | tr , \ ); do
2786                 DEFAULT_OUTPUT_FORMAT="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 1)"
2787                 DEFAULT_OUTPUT_BINARY="$(echo $DEFAULT_OUTPUT | cut -d ":" -f 2)"
2788                 if [ -x $(which $DEFAULT_OUTPUT_BINARY) ] ; then
2789                         OUTPUTTYPE=$DEFAULT_OUTPUT_FORMAT
2790                         vecho "No default output type defined. Autoselecting $OUTPUTTYPE..." >&2
2791                         break
2792                 fi
2793         done
2794         if [ X"$OUTPUTTYPE" = "X" ]; then
2795                 log error "no encoder found in the PATH"
2796                 log error "hints: are all dependencies installed? has the \$PATH been modified?"
2797                 exit 1
2798         fi
2799 fi
2800
2801 # Decide which CDROM reader we're gonna use
2802 case "$CDROMREADERSYNTAX" in
2803         cdparanoia|debug)
2804                 CDROMREADER="$CDPARANOIA"
2805                 CDROMREADEROPTS="$CDPARANOIAOPTS"
2806                 ;;
2807         cdda2wav)
2808                 CDROMREADER="$CDDA2WAV"
2809                 CDROMREADEROPTS="$CDDA2WAVOPTS"
2810                 ;;
2811         dagrab)
2812                 CDROMREADER="$DAGRAB"
2813                 CDROMREADEROPTS="$DAGRABOPTS"
2814                 ;;
2815         cddafs)
2816                 CDROMREADER="$CDDAFS"
2817                 CDROMREADEROPTS="$CDDAFSOPTS"
2818                 ;;
2819         flac)
2820                 CDROMREADER="$FLAC"
2821                 CDROMREADEROPTS="$FLACOPTS"
2822                 ;;
2823 esac
2824
2825 # There's only one normalize...
2826 case "$NORMALIZERSYNTAX" in
2827         default|normalize)
2828                 NORMALIZER="$NORMALIZE"
2829                 NORMALIZEROPTS="$NORMALIZEOPTS"
2830                 ;;
2831 esac
2832
2833 # Allow -o OUTPUT(1):OPTIONS(1),...,OUTPUT(N):OPTIONS(N) mode of operation
2834 if echo "$OUTPUTTYPE" | grep ":" > /dev/null 2>&1 ; then
2835         for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
2836                 case "$OUTPUT" in
2837                         vorbis:*|ogg:*) OGGENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2838                         mp3:*)  MP3ENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2839                         flac:*) FLACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2840                         spx:*)  SPEEXENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2841                         mpc:*)  MPPENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2842                 esac
2843         done
2844         for OUTPUT in "$(echo "$OUTPUTTYPE" | tr , \ )"; do
2845                 TEMPOUTPUT=$( echo "$OUTPUT" | cut -d: -f1 )
2846                 TEMPOUTPUTTYPE="${TEMPOUTPUTTYPE:+$TEMPOUTPUTTYPE,}$TEMPOUTPUT"
2847         done
2848         OUTPUTTYPE="$TEMPOUTPUTTYPE"
2849 fi
2850
2851 # 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
2852
2853 # Getting ready for multiple output changes
2854 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
2855 do
2856         case $OUTPUT in
2857                 vorbis|ogg)
2858                         [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
2859                         [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
2860                         [ "$DOREPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
2861                         OGGOUTPUTCONTAINER=ogg
2862                         ;;
2863                 mp3)
2864                         [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
2865                         [ "$DOTAG" = "y" ] && NEEDTAGGER=y
2866                         [ "$DOREPLAYGAIN" = "y" ] && NEEDMP3GAIN=y
2867                         ;;
2868                 flac)
2869                         [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
2870                         [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
2871                         [ "$DOREPLAYGAIN" = "y" ] && NEEDMETAFLAC=y
2872                         ;;
2873                 spx)
2874                         [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc
2875 #                       [ "$DOREPLAYGAIN" = "y" ] &&
2876                         ;;
2877                 mpc)
2878                         [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc
2879                         [ "$DOREPLAYGAIN" = "y" ] && NEEDMPPGAIN=y
2880                         ;;
2881                 wav)
2882                         if [ "$KEEPWAVS" = "y" ]; then
2883                                 vecho "Unsetting the KEEPWAVS option, since the resulting wav files were requested..."
2884                         fi
2885                         KEEPWAVS=move
2886                         ;;
2887                 *)      log error "Invalid OUTPUTTYPE defined"
2888                         exit 1
2889                         ;;
2890         esac
2891 done
2892
2893 # decide which encoder
2894 case "$MP3ENCODERSYNTAX" in
2895         lame)
2896                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$LAMEOPTS}"
2897                 MP3ENCODER="$LAME"
2898                 ;;
2899         toolame)
2900                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$TOOLAMEOPTS}"
2901                 MP3ENCODER="$TOOLAME"
2902                 ;;
2903         gogo)
2904                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$GOGOOPTS}"
2905                 MP3ENCODER="$GOGO"
2906                 ;;
2907         bladeenc)
2908                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$BLADEENCOPTS}"
2909                 MP3ENCODER="$BLADEENC"
2910                 ;;
2911         l3enc)
2912                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$L3ENCOPTS}"
2913                 MP3ENCODER="$L3ENC"
2914                 ;;
2915         xingmp3enc)
2916                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$XINGMP3ENCOPTS}"
2917                 MP3ENCODER="$XINGMP3ENC"
2918                 ;;
2919         mp3enc)
2920                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$MP3ENCOPTS}"
2921                 MP3ENCODER="$MP3ENC"
2922                 ;;
2923 esac
2924 case "$OGGENCODERSYNTAX" in
2925         vorbize)
2926                 OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$VORBIZEOPTS}"
2927                 OGGENCODER="$VORBIZE"
2928                 ;;
2929         oggenc)
2930                 OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$OGGENCOPTS}"
2931                 OGGENCODER="$OGGENC"
2932                 ;;
2933 esac
2934 case "$FLACENCODERSYNTAX" in
2935         flac)
2936                 FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
2937                 FLACENCODER="$FLAC"     
2938                 # FLAC streams can be encapsulated on a Ogg transport layer
2939                 if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
2940                         log error "FLAC on an Ogg container is not yet supported"
2941                         log error "due to problem with adding comments to such files"
2942                         exit 1
2943                         FLACOUTPUTCONTAINER=ogg
2944                 else
2945                         FLACOUTPUTCONTAINER=flac
2946                 fi
2947                 ;;
2948 esac
2949 case "$SPEEXENCODERSYNTAX" in
2950         speexenc)
2951                 SPEEXENCODEROPTS="${SPEEXENCODEROPTSCLI:-$SPEEXENCOPTS}"
2952                 SPEEXENCODER="$SPEEXENC"
2953                 ;;
2954 esac
2955 case "$MPPENCODERSYNTAX" in
2956         mppenc)
2957                 MPPENCODEROPTS="${MPPENCODEROPTSCLI:-$MPPENCOPTS}"
2958                 MPPENCODER="$MPPENC"
2959                 ;;
2960 esac
2961                 
2962 # and which tagger
2963
2964 if [ "$ID3TAGV" = "1" ]; then
2965         TAGGER="$ID3"
2966         TAGGEROPTS="$ID3OPTS"
2967 else
2968         TAGGER="$ID3V2"
2969         TAGGEROPTS="$ID3V2OPTS"
2970 fi
2971
2972 # Specific for NOGAP is the use of lame. Another encoder fails...
2973 if [ "$NOGAP" = "y" ] && [ ! "$MP3ENCODER" = "lame" ]; then
2974         log warning "the NOGAP option is specific of lame. Deactivating..."
2975         NOGAP=n
2976 fi
2977
2978 # Options for mkcue
2979 case "$CUEREADERSYNTAX" in
2980         default|mkcue)
2981                 CUEREADEROPTS="${CDROM}"
2982                 CUEREADER="$MKCUE"
2983                 ;;
2984 esac
2985
2986 # Check if both OGGEOUTPUTCONTAINER and FLACOUTPUTCONTAINER are the same, and differentiante them
2987 if [ X"$OGGOUTPUTCONTAINER" = "Xogg" ] && [ X"$FLACOUTPUTCONTAINER" = "Xogg" ]; then
2988         log error "FLAC on an Ogg container is not yet supported"
2989         log error "due to problem with adding comments to such files"
2990         exit 1
2991         OGGOUTPUTCONTAINER=ogg.ogg
2992         FLACOUTPUTCONTAINER=flac.ogg
2993         vecho warning "modified file endings due to conflicting transport layers in Ogg/Vorbis and Ogg/FLAC"
2994 fi
2995
2996 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
2997
2998 if [ "$ENCNICE" ]; then
2999         ENCNICE="-n $ENCNICE"
3000 fi
3001 if [ "$READNICE" ]; then
3002         READNICE="-n $READNICE"
3003 fi
3004 if [ "$DISTMP3NICE" ]; then
3005         DISTMP3NICE="-n $DISTMP3NICE"
3006 fi
3007
3008 # Don't check for stuff if it's not needed
3009 if [ "$REMOTEHOSTS" ]; then 
3010         NEEDDISTMP3=y
3011 fi
3012 if [ "$DONORMALIZE" = "y" ]; then
3013         NEEDNORMALIZER=y
3014 fi
3015 if [ "$EJECTCD" = "y" ]; then
3016         NEEDEJECT=y
3017 fi
3018 if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
3019         NEEDHTTPGET=y
3020 fi
3021 if [ "$MAKECUEFILE" = "y" ]; then
3022         NEEDCUEREADER=y
3023 fi
3024
3025 if [ X"$CDSPEEDVALUE" != "X" ]; then
3026         case "$CDROMREADERSYNTAX" in
3027                 cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
3028                 ### FIXME ### translate "cue2discid" from python to bash
3029                 flac) NEEDMETAFLAC=y ; NEEDCUE2DISCID=y ;;
3030                 *) NEEDCDSPEED=y ;;
3031         esac
3032 fi
3033
3034 ###USEPIPESSUPPORT###
3035
3036 # Rippers with USEPIPE support
3037 # FIXME # Include here all the rippers we can figure out support pipes
3038 PIPERIPPER_cdparanoia="-"
3039 PIPERIPPER_debug="-"
3040 PIPERIPPER_flac="-c "
3041
3042 # Encoders with USEPIPE support
3043 # FIXME # Include here all the encoders we can figure out support pipes
3044 PIPE_lame="-"
3045 PIPE_bladeenc="-"
3046 PIPE_oggenc="-"
3047 PIPE_flac="-"
3048
3049 # Figure out if we can use pipes with the ripper/encoder combination
3050 # exit otherwise
3051 if [ "$USEPIPES" = "y" ]; then
3052         PIPERIPPERSVARCHECK="PIPERIPPER_${CDROMREADERSYNTAX}"
3053         case "$OUTPUT" in
3054                 mp3)
3055                         PIPEENCODERSVARCHECK="PIPE_$MP3ENCODERSYNTAX" ;;
3056                 vorbis|ogg)
3057                         PIPEENCODERSVARCHECK="PIPE_$OGGENCODERSYNTAX" ;;
3058                 flac)
3059                         PIPEENCODERSVARCHECK="PIPE_$FLACENCODERSYNTAX" ;;
3060                 spx)
3061                         PIPEENCODERSVARCHECK="PIPE_$SPEEXENCODER" ;;
3062                 mpc)
3063                         PIPEENCODERSVARCHECK="PIPE_$MPPENCODER" ;;
3064         esac
3065         decho "PIPERIPPERSVARCHECK: $( eval echo "\$$PIPERIPPERSVARCHECK" )"
3066         if [ "$( eval echo "\$$PIPERIPPERSVARCHECK" )" = "$" ] || \
3067            [ "$( eval echo "\$$PIPERIPPERSVARCHECK" )" = "" ] ; then
3068                 log error "no support for pipes with given ripper"
3069                 log error "read the USEPIPES file from the source tarball to get help."
3070                 log error "On a Debian system, it is under /usr/share/doc/abcde/USEPIPES.gz"
3071                 exit 1;
3072         fi
3073         decho "PIPEENCODERSVARCHECK: $( eval echo "\$$PIPEENCODERSVARCHECK" )"
3074         if [ "$( eval echo "\$$PIPEENCODERSVARCHECK" )" = "$" ] || \
3075            [ "$( eval echo "\$$PIPEENCODERSVARCHECK" )" = "" ] ; then
3076                 log error "no support for pipes with given encoder"
3077                 log error "read the USEPIPES file from the source tarball to help"
3078                 log error "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz"
3079                 exit 1;
3080         fi
3081 fi
3082
3083 # Make sure a buncha things exist
3084 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
3085         $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
3086         ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
3087         ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
3088         ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
3089         ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
3090         ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMP3GAIN+$MP3GAIN} \
3091         ${NEEDMPPGAIN+$MPPGAIN} \
3092         ${NEEDCUEREADER+$CUEREADER} ${NEEDCUE2DISCID+$CUE2DISCID}
3093 do
3094         # Cut off the command-line options we just added in
3095         X=$(echo $X | cut -d' ' -f2)
3096         if [ "$(which $X)" = "" ]; then
3097                 log error "$X is not in your path." >&2
3098                 exit 1
3099         elif [ ! -x $(which $X) ]; then
3100                 log error "$X is not executable." >&2
3101                 exit 1
3102         fi
3103 done
3104
3105 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
3106 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
3107 HTTPGET="$HTTPGET $HTTPGETOPTS"
3108
3109 # And last but not least, check if we can diff between files
3110 if [ -x $(which $DIFF) ]; then :; else
3111         vecho warning "Disabling diff since we cannot find it in the \$PATH..."
3112         DIFF=""
3113 fi
3114
3115 # Here it used to say:
3116 # One thousand lines in, we can start doing stuff with things
3117 # Well, right now we are at line 2736 ;)
3118
3119 # Export needed things so they can be read in this subshell
3120 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
3121 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
3122
3123 # User-definable function to set some things. Use it for
3124 #  - closing the CD tray with eject -t
3125 #  - set the CD speed value with eject -x
3126 vecho -n "Executing customizable pre-read function... "
3127
3128 pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
3129
3130 vecho "done."
3131
3132 do_discid # Get ABCDETEMPDIR created and status file initialized
3133
3134 if [ "$DOCDDB" = "y" ]; then
3135         if [ $CDDBUSELOCAL = "y" ]; then
3136                 do_localcddb
3137         fi
3138         if checkstatus cddb-choice > /dev/null; then
3139                 :
3140         else 
3141                 if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
3142                         do_cddbstat
3143                         do_cddbquery
3144                         do_cddbread
3145                 fi
3146         fi
3147         do_cddbedit
3148
3149         eval "$($CDDBTOOL parse "$CDDBDATA")"
3150 fi
3151
3152 # Before reading tracks, we set the speed of the device
3153
3154 if [ X"$CDSPEEDVALUE" != "X" ]; then
3155         case "$CDROMREADERSYNTAX" in
3156                 cdparanoia|debug) ;;
3157                 flac) ;;
3158                 *) do_cdspeed ;;
3159         esac
3160 fi
3161
3162 # Define the first and last track, since we might need them later in several places
3163 FIRSTTRACK=$( get_first $TRACKQUEUE )
3164 LASTTRACK=$( get_last $TRACKQUEUE )
3165
3166 if [ -f "$ABCDETEMPDIR/status" ] && [ X"$ERASEENCODEDSTATUS" = "Xy" ]; then
3167         mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
3168         grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
3169                 | grep -v ^encode-output > "$ABCDETEMPDIR/status"
3170 fi
3171
3172 # Create playlist if needed (backgroundable) and start reading in tracks
3173
3174 (
3175
3176 if [ ! "$ONETRACK" = "y" ]; then
3177         if [ "$DOPLAYLIST" = "y" ]; then
3178                 echo Creating playlist... >&2
3179                 do_playlist
3180         fi
3181 fi
3182
3183 # For the lowdisk option, only one program is running at once so the encoder
3184 # can be unsilenced right away.
3185 if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
3186         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
3187 fi
3188
3189 if [ "$ONETRACK" = "y" ]; then 
3190         TRACKS="$FIRSTTRACK"
3191         if checkstatus readtrack-$FIRSTTRACK; then :; else
3192                 if [ "$USEPIPES" = "y" ]; then
3193                         do_cdread onetrack $FIRSTTRACK $LASTTRACK | do_encode $FIRSTTRACK %local0% > /dev/null 2>&1
3194                 else
3195                         do_cdread onetrack $FIRSTTRACK $LASTTRACK
3196                 fi
3197         fi
3198 else
3199         for UTRACKNUM in $TRACKQUEUE
3200         do
3201                 if [ "$DOREAD" = "y" ]; then
3202                         if [ "$USEPIPES" = "y" ]; then
3203                                 if checkstatus readencodetrack-$UTRACKNUM; then :; else
3204                                         # Read, pipe, shut up!
3205                                         do_cdread $UTRACKNUM | do_encode $UTRACKNUM %local0% > /dev/null 2>&1
3206                                 fi
3207                         else
3208                                 if checkstatus readtrack-$UTRACKNUM; then :; else
3209                                         do_cdread $UTRACKNUM
3210                                 fi
3211                                 if [ "$?" != "0" ]; then
3212                                         # CD read failed - don't give the goahead to
3213                                         # the encoder
3214                                         echo NO
3215                                         exit
3216                                 fi
3217                         fi
3218                 fi
3219                 if [ "$NOGAP" = "y" ] || [ "$BATCHNORM" = "y" ]; then
3220                     :
3221                 else
3222                         # If we are not reading, set the encode output to loud already, so
3223                         # that we can see the output of the first track.
3224                         if [ "$MAXPROCS" = "1" ] && [ ! "$DOREAD" = "y" ]; then
3225                                 echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
3226                         fi
3227                         echo NEXTTRACK # Get the encoder machine churning again
3228                         if [ "$DOREAD" = "y" ]; then
3229                                 if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
3230                                         until checkstatus encodetrack-$UTRACKNUM
3231                                         do
3232                                                 if checkerrors encodetrack-$UTRACKNUM; then
3233                                                         break
3234                                                 fi
3235                                                 sleep 2
3236                                         done
3237                                 fi
3238                         fi
3239                 fi
3240         done
3241 fi
3242
3243 # Now that we're done the encoding can be loud again -
3244 # if we're not using SMP.
3245 if [ "$MAXPROCS" = "1" ]; then
3246         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
3247 fi
3248
3249 # All tracks read, start encoding.
3250 if [ "$NOGAP" = "y" ] || [ "$BATCHNORM" = "y" ] || [ "$ONETRACK" = "y" ]; then
3251         echo NEXTTRACK
3252 fi
3253
3254 # Execute the user-defined post_read funtion before ejecting CD
3255 post_read
3256
3257 # We are now finished with the cdrom - it can be safely ejected. Note that
3258 # abcde will not have completed yet.
3259 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
3260         # We check if the disk we are processing is actually the disk inside the 
3261         # CD tray. If not, we do not eject the CD, since it might be so that the
3262         # user ejected it manually.
3263         #CURRENTTRACKINFO=$($CDDISCID $CDROM)
3264         #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
3265         # More FreeBSD bits.
3266         if [ X"$(uname)" = X"FreeBSD" ] ; then
3267                 # FreeBSD eject uses the EJECT environment variable to name the CDROM
3268                 # but in this script EJECT is in the envionment and names the program
3269                 eject=$EJECT
3270                 unset EJECT
3271                 # The FreeBSD eject needs "adc0" not "/dev/adc0c"
3272                 cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
3273                 $eject $EJECTOPTS $cd
3274         elif [ X"$(uname)" = X"Darwin" ] ; then
3275                 disktool -e ${CDROM#/dev/} 0
3276         else
3277                 $EJECT $EJECTOPTS $CDROM
3278         fi
3279         #fi
3280 fi
3281
3282 ) | (
3283
3284 ## Do we need to pre-process 
3285 #if [ x"$PREPROCESS" = "x" ] ; then
3286 #       cat
3287 #else
3288 #       for PRETRACKNUM in $TRACKQUEUE
3289 #       do
3290 #               read GOAHEAD
3291 #               if [ "$GOAHEAD" = "NO" ]; then break; fi
3292 #               PREPROCEED=
3293 #               until [ $PREPROCEED ]
3294 #               do
3295 #                       if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
3296 #                       # all locations are working, wait and try again later
3297 #                       if [ ! $PREPROCEED ]; then sleep 3; fi
3298 #               done
3299 #               ( do_preprocess $PRETRACKNUM 
3300 #               echo "NEXTTRACK"
3301 #               ) &
3302 #       done
3303 #fi
3304 #
3305 #) | (
3306
3307 # In BATCHNORM and/or NOGAP modes, we want all tracks to be read first.
3308 #BACK
3309 if [ "$BATCHNORM" = "y" ] || [ "$NOGAP" = "y" ]; then
3310         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
3311         if [ "$GOAHEAD" = "NO" ]; then break; fi
3312         for LASTTRACK in $TRACKQUEUE; do :; done
3313         if checkstatus readtrack-$LASTTRACK; then
3314                 if [ "$DONORMALIZE" = "y" ] && [ "$BATCHNORM" = "y" ]; then
3315                         if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
3316                         if checkerrors batch-normalize; then exit 1; fi
3317                 fi
3318                 if [ "$DOENCODE" = "y" ] && [ "$NOGAP" = "y" ]; then