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