#!/usr/bin/env perl
########################################################################
#
# LICENSE
#
# Copyright (C) 2005 Felix Suwald
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
# USA.
#
#
########################################################################
#
# CODE
#
# ripit.pl - Rips CD Audio and encodes files in the following steps:
#	     1) Query CDDB data for Album/Artist/Track info
#	     2) Rip the audio files from the CD
#	     3) Encode the wav files
#	     4) ID3 tag the encoded files
#	     5) Optional: Create a playlist (M3U) file.
#	     6) Optional: Prepares and sends a CDDB submission.
#
# Version 3.5.1 - June 16th 2006 - Felix Suwald, credits to
#                                  E. Riesebieter (deb-package)
#                                  C. Walter (normalize option)
#                                  S. Warten (general support & loop)
#                                  S. Warten (signal handling)
# Version 3.4 - December 3rd 2005 - Felix Suwald, credits to
#                                   M. Bright (infolog file)
#                                   M. Kaesbauer (lcdproc) and
#                                   C. Walter (config file).
# Version 2.5 - November 13th 2004 - Felix Suwald
# Version 2.2 - October 18th 2003 - Mads Martin Joergensen
# Version 1.0 - February 16th 1999 - Simon Quinn
#
#
########################################################################
#
# User configurable variables:
# Keep these values and save your own settings
# in the config file with option --save!
#
my $cddev	= "/dev/dvd";	# Path of audio CD device.
my $outputdir	= "/media/mp3/tmp";		# Where the sound should go to.
my $ripopt	= "";		# Options for audio CD ripper.
my $ripper	= 1;		# 0 - dagrab, 1 - cdparanoia,
				# 2 - cdda2wav, 3 - tosha, 4 - cdd.
my @coder	= (0);		# 0 - Lame, 1 - OggVorbis, 2 - Flac,
				# 3 - Faac, comma seperated list.
my $bitrate	= 192;		# Bitrate for lame, if --vbrmode used,
				# bitrate is equal to the -b option.
my $maxrate	= 0;		# Bitrate for lame using --vbrmode,
				# maxrate is equal to the -B option.
my @quality	= (5,3,5,100);# Quality for lame in vbr mode (0-9),
				# best quality = 0, quality for ogg
				# (1-10) best = 10; or compression
				# level for Flac (0-8), lowest = 0.
my $qualame	= 5;		#
my $qualoggenc= 3;		#
my $quaflac	= 5;		#
my $quafaac	= 100;		#
my $lameopt	= "";		#
my $oggencopt	= "";		#
my $flacopt	= "";		#
my $faacopt	= "";		#
my $lcd	= 0;		# Use lcdproc (1 yes, 0 no).
my $chars	= "off";	# Exclude special chars in file names.
my $verbose	= 2;		# Normal output: 2, no output: 0, minimal
				# output 1, verbose: 3
my $commentag	= "";		# Comment ID3 tag.
my $genre	= "";		# Genre of Audio CD for ID3 tag.
my $year	= "";		# Year of Audio CD for ID3 tag.
my $utftag	= 1;		# Keep Lame-tags in utf or decode them to
				# ISO8895-1 (1 yes, 0 no).
my $eject	= 1;		# Eject the CD when done (1 yes, 0 no).
my $halt	= 0;		# Shutdown machine when finished
				# (1 yes, 0 no).
my $nice	= 0;		# Set nice.
my $savenew	= 0;		# Saved passed parameters to new config
				# file (1 yes, 0 no).
my $savepara	= 0;		# Save parameters passed in config file
				# (1 yes, 0 no).
my $config	= 1;		# Use config file to read paramaters
				# (1 yes, 0 no).
my $submission= 1;		# Send CDDB submission
				# (1 yes, 0 no).
my $parano	= 1;		# Use paranoia mode in cdparanoia
				# (1 yes, 0 no).
my $playlist	= 1;		# Do create the m3u playlist file
				# (1 yes, 0 no).
my $infolog	= "";		# InfoLog
				# (filename)
my $interaction= 1;		# If 0 do not ask anything, take the 1st
				# CDDB entry found or use default names!
				# (1 yes, 0 no).
my $underscore= 0;		# Use _ instead of spaces in filenames
				# (1 yes, 0 no).
my $lowercase	= 0;		# Lowercase filenames
				# (1 yes, 0 no).
my $archive	= 0;		# Save CDDB files in ~/.cddb dir
				# (1 yes, 0 no).
my $mirror	= "freedb";	# The host (a freedb mirror) that
				# shall be used instead of freedb.
my $transfer	= "cddb";	# Transfer mode, cddb or http, will set
				# default port to 8880 or 80 (for http).
my $vbrmode	= "";		# Variable bitrate, only used with lame,
				# (new or old), see lame-manpage.
my $proto	= 6;		# CDDB protocol level for CDDB query.
my $proxy	= "";		# Set proxy.
my $CDDB_HOST	= "freedb.org"; # Set cddb host
my $mailad	= "";		# Users return e-mail address.
my @sshlist	= ();		# List of remote machines.
my $scp	= 0;		# Use scp to access files (1 yes, 0 no).
my $local	= 1;		# Encode on locale machine (1 yes, 0 no).
my $wav	= 0;		# Keep the wav files (1 yes, 0 no).
my $encode	= 1;		# Encode the wav files (1 yes, 0 no).
my $rip	= 1;		# Rip the CD files (1 yes, 0 no).
my $cdtoc	= 0;		# Create a cd.toc for CDRDAO (1 yes, 0 no).
my $loop	= 0;		# Restart ripit as soon as a new CD is
				# inserted. This option implies that the CD
				# is ejected (option --eject)!
my $multi	= 0;		# Not yet official. Do NOT use!
#
#
#
# Directory and track template variables:
# Contains the format the track names will be written as.
# The '" and "' are important and must surround the template.
# Example variables to use are: $tracknum, $album, $artist, $genre,
# $trackname or $year.
# E.g. example setting of $tracktemplate produces a trackname of
# "07 The Game - Swandive" .
# $tracktemplate  = '"$tracknum $trackname - $artist"';
#
my $dirtemplate = '"$artist - $album"';
my $tracktemplate  = '"$tracknum $trackname"';
#
#
# lcdproc settings:
#
my $lcdhost	= "localhost";
my $lcdport	= "13666";
my $lcdline1	= "   [initializing]   ";
my $lcdline2	= " ripit-lcd-module     ";
my $lcdline3	= "          2005 ";
my $lcdoline1	= "";
my $lcdoline2	= "";
my $lcdoline3	= "";
my $lcdproc;
my $lcdtrackno	= 0;
#
#
#
# normalize settings:
#
my $normalize	= 0;		# normalize CD, needs 'normalize' in $path
my $normopt	= "-bv";	# options for normalize
my $subdir	= "Unsorted";
#
#
########################################################################
#
# No User configurable parameters below here.
#
########################################################################
#
use strict;
use CDDB_get qw(get_cddb get_discids);
use Fcntl;
use Getopt::Long qw(:config no_ignore_case);
use IO::Socket;
use LWP::Simple;
#use warnings;
#
# Initialize paths.
#
my $homedir = "$ENV{HOME}";
my $workdir = "$ENV{PWD}";
my $usename = "$ENV{USER}";
my $hostnam = "$ENV{HOSTNAME}";
#print ($_,$ENV{$_},"\n") foreach (keys %ENV);
#
# Initialise global variables.
#
my $categ		= "";	# CDDB category
my $cddbid		= 0;	# Needed in several subroutines
my $lameflag		= 0;	# Flag to check if lame is used.
my $trackselection	= "";	# Passed from command line
my @seltrack		= ();  # Array of all track numbers, including
				# those not explicitly stated.
my @framelist		= ();	# Needed in several subroutines
my @secondlist	= ();	# Needed in several subroutines
my @tracklist		= ();	# Needed in several subroutines
my @tracktags		= ();	# Needed in several subroutines
my %cd			= ();	# Hash of all CD-data.
my $cddbsubmission	= 2;	# If zero then data for CDDB submission is
				# incorrect, if 1: submission OK, if 2: CDDB
				# entry not changed (edited)
my $wpreset		= "";	# Preset written into config file.
my $wcoder		= "";	# Use a comma seperated string to write the
				# coder-array into the config file.
my $wsshlist		= "";	# As above for the list of remote machines.
my $sshflag		= 0;	# Ssh encoding OK if sshflag == 1.
my %sshlist		= ();	# Hash of remote machines.
my $version		= "3.5.1";
my $hiddenflag	= 0;
my $logpath		= "";	# Used with not *to-use* option --multi,
				# is one level below sound-dir.
my $logfile		= "";	# Used with not *to-use* option --multi,
				# is the "device-log"-file in `pwd`.
my $help		= 0;   # Print help and exit if 1.
my $printver		= 0;	# Print version and exit if 1.
#
# Initialize subroutines without ().
#
sub check_bitrate;
sub check_cddev;
sub check_chars;
sub check_vbrmode;
sub choose_genre;
sub extract_comm;
sub get_rev;
sub init_var;
sub lame_preset;
sub main_sub;
#
# Define the variables which catch the command line input.
# The p stands for passed (from command line).
my (
   $parchive,       $pbitrate,       $pmaxrate,         $PCDDB_HOST,
   $pcddev,         $pcdtoc,         @pcoder,           $pcommentag,
   $pconfig,        $pdirtemplate,   $ptracktemplate,   $peject,
   $pencode,        $pfaacopt,       $pflacopt,         $plameopt,
   $poggencopt,     $pgenre,         $phalt,            $pinfolog,
   $pinteraction,   $plcdhost,       $plcdport,         $plcd,
   $plocal,         $ploop,          $plowercase,       $pmirror,
   $pmailad,        $pmulti,         $pnice,            $pnormalize,
   $pnormopt,       $poutputdir,     $pparano,          $pplaylist,
   $ppreset,        $pproto,         $pproxy,           @pquality,
   $pripopt,        $prip,           $pripper,          $psavenew,
   $psavepara,      $pscp,           @psshlist,         $psubdir,
   $psubmission,    $ptransfer,      $punderscore,      $putftag,
   $pvbrmode,       $pverbose,       $pwav,             $pyear
);
#
# Get the parameters from the command line.
# available:     A       E F G  IjJkK       O   Q R           X Y
# already used: a bBcCdDe f g hi     lLmMnNo pPq r sStTuUvVwWx y zZ
#
GetOptions(
   "archive|a!"		=> \$parchive,
   "bitrate|b=s"		=> \$pbitrate,
   "maxrate|B=i"		=> \$pmaxrate,
   "chars|W:s"		=> \$chars,
   "cddbserver|C=s"		=> \$PCDDB_HOST,
   "cdtoc=i"			=> \$pcdtoc,
   "config!"			=> \$pconfig,
   "coder|c=s"		=> \@pcoder,
   "comment=s"		=> \$pcommentag,
   "device|d=s"		=> \$pcddev,
   "dirtemplate|D=s"		=> \$pdirtemplate,
   "eject|e!"			=> \$peject,
   "encode!"			=> \$pencode,
   "faacopt=s"		=> \$pfaacopt,
   "flacopt=s"		=> \$pflacopt,
   "lameopt=s"		=> \$plameopt,
   "oggencopt=s"		=> \$poggencopt,
   "genre|g=s"		=> \$pgenre,
   "halt"			=> \$phalt,
   "help|h"			=> \$help,
   "infolog=s"		=> \$pinfolog,
   "interaction|i!"		=> \$pinteraction,
   "lcd!"			=> \$plcd,
   "lcdhost=s"		=> \$plcdhost,
   "lcdport=s"		=> \$plcdport,
   "lowercase|l!"		=> \$plowercase,
   "local!"			=> \$plocal,
   "loop!"			=> \$ploop,
   "mirror|m=s"		=> \$pmirror,
   "mail|M=s"			=> \$pmailad,
   "multi"			=> \$pmulti,
   "nice|n=s"			=> \$pnice,
   "normalize|N!"		=> \$pnormalize,
   "normopt|z=s"		=> \$pnormopt,
   "subdir=s"			=> \$psubdir,
   "outputdir|o=s"		=> \$poutputdir,
   "playlist|p!"		=> \$pplaylist,
   "preset|S=s"		=> \$ppreset,
   "proxy|P=s"		=> \$pproxy,
   "protocol|L=i"		=> \$pproto,
   "quality|q=s"		=> \@pquality,
   "rip!"			=> \$prip,
   "ripper|r=s"		=> \$pripper,
   "ripopt=s"			=> \$pripopt,
   "savenew"			=> \$psavenew,
   "save"			=> \$psavepara,
   "scp"			=> \$pscp,
   "sshlist=s"		=> \@psshlist,
   "submission|s!"		=> \$psubmission,
   "tracktemplate|T=s"	=> \$ptracktemplate,
   "transfer|t=s"		=> \$ptransfer,
   "underscore|u!"		=> \$punderscore,
   "utftag|U!"		=> \$putftag,
   "vbrmode|v=s"		=> \$pvbrmode,
   "verbose|x=i"		=> \$pverbose,
   "version|V"		=> \$printver,
   "year|y=i"			=> \$pyear,
   "wav|w!"			=> \$pwav,
   "disable-paranoia|Z"	=> \$pparano,
)
or exit print_usage();
#
# Evaluate the command line parameters if passed. We need to do it this
# way, because passed options have to be saved (in case user wants to
# save them) before config file is read to prevent overriding passed
# options with options from config file. And the passed options shall be
# stronger than the config file options!
# Problems arrise with options that can be zero. Because a usual if-test
# can not distinguish between zero or undef, use the defined-test!
#
# First for the normal options, e. g. options which are never zero.
# @coder will be done in the subroutine!
$faacopt = $pfaacopt if($pfaacopt);
$flacopt = $pflacopt if($pflacopt);
$lameopt = $plameopt if($plameopt);
$oggencopt = $poggencopt if($poggencopt);
$CDDB_HOST = $PCDDB_HOST if($PCDDB_HOST);
$cddev = $pcddev if($pcddev);
# Get the default "no-argument" values.
$chars = ":*#?\$!" if($chars eq "");
# On the other hand, clean the initialization if operator
# wants to save the the default "no-argument" values.
if(defined $psavenew) {
   $chars = "" if($chars eq "off" && $psavenew == 1);
}
$commentag = $pcommentag if($pcommentag);
$dirtemplate = $pdirtemplate if($pdirtemplate);
$tracktemplate = $ptracktemplate if($ptracktemplate);
$halt = $phalt if($phalt);
$infolog = $pinfolog if($pinfolog);
$lcdhost = $plcdhost if($plcdhost);
$lcdport = $plcdport if($plcdport);
$mailad = $pmailad if($pmailad);
$mirror = $pmirror if($pmirror);
$normopt = $pnormopt if($pnormopt);
$outputdir = $poutputdir if($poutputdir);
my $preset = $ppreset if($ppreset);
$ripopt = $pripopt if($pripopt);
$proto = $pproto if($pproto);
$proxy = $pproxy if($pproxy);
# $psshlist will be done in the subroutine!
$transfer = $ptransfer if($ptransfer);
$vbrmode = $pvbrmode if($pvbrmode);
$year = $pyear if($pyear);
#
# Options which might be zero.
$bitrate = $pbitrate if($pbitrate);
$cdtoc = $pcdtoc if defined $pcdtoc;
$genre = $pgenre if defined $pgenre;
$maxrate = $pmaxrate if defined $pmaxrate;
$nice = $pnice if defined $pnice;
$parano = 0 if defined $pparano;
$ripper = $pripper if defined $pripper;
$savepara = $psavepara if defined $psavepara;
$savenew = $psavenew if defined $psavenew;
$scp = $pscp if defined $pscp;
$verbose = $pverbose if defined $pverbose;
#
# And for the negatable options.
$archive = $parchive if defined $parchive;
$config = $pconfig if defined $pconfig;
$encode = $pencode if defined $pencode;
$eject = $peject if defined $peject;
$interaction = $pinteraction if defined $pinteraction;
$lcd = $plcd if defined $plcd;
$local = $plocal if defined $plocal;
$loop = $ploop if defined $ploop;
$lowercase = $plowercase if defined $plowercase;
$multi = $pmulti if defined $pmulti;
$normalize = $pnormalize if defined $pnormalize;
$playlist = $pplaylist if defined $pplaylist;
$rip = $prip if defined $prip;
$submission = $psubmission if defined $psubmission;
$underscore = $punderscore if defined $punderscore;
$utftag = $putftag if defined $putftag;
$wav = $pwav if defined $pwav;
#
# Do some checks before writing the config file.
#
if($help ne 1 && $printver ne 1) {
   check_coder();		# Check encoder array.
   check_quality();		# Check if quality is valid.
##   check_host();		# Check if host is valid.
   check_proto();		# Check if protocol level is valid.
   check_sshlist();		# Check list of remote machines.
   check_preset() if($preset);	# Check preset settings.
#
# To be able to overwrite the config file we have to write it before...
#
   save_config() if($savenew == 1);
   print "Saved a new config file!\n"
      if($verbose >= 3 && $savenew == 1);
#
# ...reading the parameters not yet passed from the config file.
#
   read_config() if($config == 1);
   # The xxx enables reading this value, but should be switched off
   # before writing!
   $chars = "" if($chars eq "xxx" || $chars eq "off");
# This will go away again.
   $maxrate = 0 if($maxrate eq "" && !defined $pmaxrate);
   save_config() if($savepara == 1);
   print "Updated the config file!\n"
      if($verbose >= 3 && $savepara == 1);
##   check_host();		# Do it again to concatenate mirror.host.
   check_coder();		# Check it again for lame cbr vs vbr.
   check_sshlist();		# Check it again to create the hash.
}
#
# Security check for new options: give them default value if empty.
# This will go away again.
$normalize = 0 if($normalize eq "");
$cdtoc = 0 if($cdtoc eq "");
#
#
########################################################################
#
# MAIN ROUTINE
#
########################################################################
#
log_info("RipIT version $version infolog-file.\n");
print "\nRipIT version $version.\n" if($verbose >= 2);
if($printver) {
   print "\n";
   exit 2;
}

if($help == 1) {
   print_help();
   exit 3;
}


if($cddev eq "") {			# Check CD dev if none defined.
   check_cddev;
}
else {					# Ugly hack to close the tray.
   system("more $cddev > /dev/null 2> /dev/null");
}

if($chars) {
   check_chars;
}

if($lcd == 1) {			# lcdproc
   init_lcd();
}

if($outputdir eq "") {
   $outputdir = $homedir;
   chomp $outputdir;
}

if($outputdir =~ /^\.\//){		# Change relative paths to full ones.
   $outputdir =~ s/^\./$workdir/;
}

if($outputdir =~ /^~\//){		# If one wrote ~ in the config file.
   $outputdir =~ s/^~/$homedir/;
}
$poutputdir = $outputdir; # Ugly hack to keep a virgin copy of that var.

if(length($year) > 0 && length($year) != 4 ) {
   print STDERR "Warning: year is not Y2K compliant - $year\n"
      if($verbose >= 1);
}

if($halt == 1 && $verbose >= 1) {
   print "Will halt machine when finished.\n";
}

if($eject == 1 && $verbose >= 1) {
   print "Will eject CD when finished.\n";
}

if($cdtoc >= 1) {
   print "Will create a cd.toc file.\n";
}

if($playlist == 0 && $verbose >= 1) {
   print "Won't create a m3u file.\n";
}

if($utftag == 0 && $verbose >= 1) {
   print "Will change encoding of Lame-tags to ISO8859-1.\n";
}

if($wav == 1 && $verbose >= 1) {
   print "Will keep the wav files.\n";
}

if ($normalize == 1) {
   print "Will normalize the CD.\n";
}

if($loop) {
   print "Will loop and eject CD.\n";
   $eject = 1;
   while(1) {
      main_sub;
      init_var;
   }
}
else {
   main_sub;
}
########################################################################
#
# Main subroutine.
#
sub main_sub{

   if(@ARGV) {
      $trackselection = $ARGV[0];
   }

   if($bitrate != 0 && $lameflag == 1) {
      check_bitrate;
   }

   if($vbrmode ne "" && $lameflag == 1) {
      check_vbrmode;
   }

   if($preset) {
      lame_preset;
   }

   unless( cd_present() ) {
      print "\nPlease insert an audio CD!\n";
      while ( not cd_present() ) {
         sleep(4);
      }
   }

   get_cdinfo();
   create_seltrack($trackselection);
   create_dirs();

   if($normalize == 1) {
      &rip_cd();
      &norm_cd();
      &enc_cd();
   }
   else {
      &rip_cd();
   }

   if($eject == 1) {
      log_system("eject $cddev");
   }

   if($verbose >= 1) {
      print "Waiting for Encoder to finish...\n";
   }

   if($sshflag == 1) {
      print "Deleting the wavs...\n" if($verbose >= 1);
      del_wav();
}
   else {
      wait;
   }

   if($playlist == 1) {
      create_m3u();
   }

   my ($riptime,$enctime,$encend) = cal_times();
   del_erlog();

   if(-r "$outputdir/error.log") {
      if($verbose >= 1) {
         print "\nCD may NOT be complete! ",
               "Check the error.log in $outputdir!"; ##hh
      }
      elsif($verbose >= 2){
         print "\nRipping needed $riptime min and encoding needed ",
               "$enctime min.\n\n";
      }
   }
   else {
      if($verbose >= 1) {
         print "\nAll complete!\nRipping needed $riptime min and ",
               "encoding needed $enctime min.\n\n";
      }
   }

   log_info("\nRipping needed $riptime minutes.");
   log_info("Encoding needed $enctime minutes.");

   if($lcd == 1) {			# lcdproc
      $lcdline1 = " ";
      $lcdline2 = "   RipIT finished   ";
      $lcdline3 = " ";
      ulcd();
      close($lcdproc) || die "close: $!";
   }

   if($halt == 1 && $verbose >= 1) {
      print "\nShutdown PC...\n";
      log_system("shutdown -h now");
   }

   if($multi == 1) {
      open(SRXY,">>$logfile")
         or print "Can not append to file \"$logfile\"!";
      print SRXY "\nEncoding   ended: $encend";
      print SRXY "\nRipping  needed: $riptime min.";
      print SRXY "\nEncoding needed: $enctime min.";
      close(SRXY);
      open(SUCC,">>$logpath/success.log")
         or print "Can not append to file \"$logpath/succes.log\"!";
      print SUCC "$cd{artist};$cd{title};$genre;$categ;$cddbid;";
      print SUCC "$logfile;$hostnam;$riptime;$enctime\n";
      close(SUCC);
   }

   log_info("*" x 72, "\n");

#   rename("$infolog","$outputdir/info.log") if($infolog && $loop);
   exit unless($loop);
}
########################################################################
#
# SUBROUTINES
#
########################################################################

########################################################################
#
# Read the Album, Artist, DiscID and Track Titles from the get_CDDB()
# generated TOC file.
#
sub get_cdinfo {
   my ($artist, $album, %config, $revision);
   my ($CDDB_INPUT, $CDDB_MODE, $CDDB_PORT);
   my @comment = ();

   if($pgenre) {
      $genre = $pgenre;
   }
   else {
      $genre = "";
   }
   if($pyear) {
      $year = $pyear;
   }
   else {
      $year = "";
   }

   # Get ID and number of tracks of CD.
   my $cd = get_discids($cddev);
   my ($id,$toc) = ($cd->[0], $cd->[2]);
   my $tracks = $cd->[1];
   $cddbid = sprintf("%08x", $id);

   my $usearch = "x";
   my @categs = ();
   if($archive == 1 && $multi == 0) {
      print "\nChecking for a local DB entry, please wait...\n\n"
         if($verbose >= 1);
      log_system("mkdir -m 0777 -p $homedir/.cddb")
         or die "Can not create directory $homedir/.cddb: $!\n";
      opendir(CDDB, "$homedir/.cddb/")
         or print "Can not read in $homedir/.cddb: $!";
      @categs = grep {/\w/i} readdir(CDDB);
      close CDDB;
      my @cddbid = ();
      foreach (@categs) {
         if(-d "$homedir/.cddb/$_") {
            opendir(CATEG, "$homedir/.cddb/$_")
               or print "Can not read in $homedir/.cddb: $!";
            my @entries = grep {/$cddbid/} readdir(CATEG);
            close CATEG;
            push @cddbid, $_ if($entries[0]);
         }
         elsif(-f "$homedir/.cddb/$_" && -s "$homedir/.cddb/$_") {
            push @cddbid, $_ if($_ =~ /$cddbid/);
         }
      }
      my $count = 1;
      my @dirflag = ();
      if($cddbid[0]) {
         print "Found local entry $cddbid in $homedir/.cddb !\n"
            if($interaction == 1);
         print "This CD could be:\n\n" if($interaction == 1);
         foreach (@cddbid) {
            my $openflag = "no";
            if(-s "$homedir/.cddb/$_/$cddbid") {
               open(LOG, "$homedir/.cddb/$_/$cddbid");
               $openflag = "ok";
               $dirflag[$count-1] = 1;
            }
            elsif(-s "$homedir/.cddb/$cddbid") {
               open(LOG, "$homedir/.cddb/$cddbid");
               $_ = "no category found!";
               $openflag = "ok";
               $dirflag[$count-1] = 0;
            }
            if($openflag eq "ok") {
               my @loglines = <LOG>;
               close(LOG);
               # Here we should test if @loglines is a good entry!
               # If there are empty files, we get warnings!
               my @artist = grep(s/^DTITLE=//, @loglines);
               $artist = clean_all($artist[0]);
               chomp $artist;
               my @genre = grep(s/^DGENRE=//, @loglines);
               my $agenre = $genre[0];
               $agenre =~ s/[\015]//g;
               chomp $agenre;
               print "$count: $artist (genre: $agenre, category: $_)\n"
                  if($interaction == 1);
               $count++;
               $agenre = "";
            }
         }
         print "\n0: Use online freeDB instead!\n"
            if($interaction == 1);
         if($interaction == 0) {
            $usearch = 1;
         }
         else {
            while($usearch !~ /\d/ || $usearch >= $count) {
               print "\nChoose: (1) ";
               $usearch = <STDIN>;
               chomp $usearch;
               $usearch = 1 if($usearch eq "");
            }
         }
      }
      else {
         $usearch = 0;
      }
      if($usearch != 0) {
         if($dirflag[$usearch-1] == 1) {
            read_entry("$homedir/.cddb/$cddbid[$usearch-1]/$cddbid",
               $cddbid[$usearch-1],$tracks);
         }
         elsif($dirflag[$usearch-1] == 0) {
            read_entry("$homedir/.cddb/$cddbid",
               $cddbid[$usearch-1],$tracks);
         }
      }
   }
   else {
      $usearch = 0;
   }

   if($usearch == 0) {
      print "\nChecking for a DB entry \@ $mirror.$CDDB_HOST...\n"
         if($verbose >= 1);

      #Configure CDDB_get parameters
      $config{CDDB_HOST} = $mirror . "." . $CDDB_HOST;
      while($transfer !~ /^cddb$|^http$/) {
         print "Transfer mode not valid!\n";
         print "Enter cddb or http : ";
         $transfer = <STDIN>;
         chomp $transfer;
      }
      if($transfer eq "cddb") {
         $CDDB_PORT = 8880;
         $CDDB_MODE = "cddb";
      }
      elsif($transfer eq "http") {
         $CDDB_PORT = 80;
         $CDDB_MODE = "http";
      }
      $config{CDDB_MODE} = $CDDB_MODE;
      $config{CDDB_PORT} = $CDDB_PORT;
      $config{CD_DEVICE} = $cddev;
      $config{HTTP_PROXY}= $proxy if($proxy);
      if($interaction == 0) {
         $CDDB_INPUT = 0;
      }
      else {
         $CDDB_INPUT = 1;
      }
      $config{input} = $CDDB_INPUT;
      $config{PROTO_VERSION} = $proto;

      # Change to whatever, but be aware to enter exactly 4 words!
      # E.g. username hostname clientname version
      my $hid = "RipIT www.suwald.com/ripit/ripit.html RipIT $version";
      my @hid = split(/ /, $hid);
      if($hid[4]) {
         print "There are more than 4 words in the \"HELLO_ID\"!\n";
         print "The handshake with the freeDB-server will fail!\n\n";
      }
      $config{HELLO_ID} = $hid;

      eval {%cd = get_cddb(\%config);};
      if($@) {
         print "No connection to internet? The error message is:\n";
         $@ =~ s/at\s\//at\n\//;
         print "$@\$! is <$!> and \$? is <$?>\n" if($verbose >= 1);
         $submission = 0;
      }
   }

   # Write CDDB entry to ~/.cddb/category if there is not already
   # an entry present (then $usearch != 0).
   if($archive == 1 && $usearch == 0 && defined $cd{title}) {
      $categ = $cd{cat};
      chomp $categ;
      log_system("mkdir -m 0777 -p $homedir/.cddb/$categ/")
         or die "Can not create directory $homedir/.cddb/$categ: $!\n";
      open(TOC, "> $homedir/.cddb/$categ/$cddbid")
         or print "Can not write to $homedir/.cddb/$categ/$cddbid: $!";
      foreach (@{$cd{raw}}) {
         print TOC $_;
      }
      close TOC;
   }

   if($multi == 1) {
      my @devnameblock = split(/\//, $cddev);
      $logfile = $devnameblock[$#devnameblock];
      read_entry($logfile);

      # This has nothing to do here, but has to be
      # done somewhere, because the bash is not able doing it.
      open(LOG, "settings.log") || print "Can not open settings.log!\n";
      my @settinglines = <LOG>;
      close(LOG);
      my @commentagno=grep(s/^comment=//g, @settinglines);
      my $commentagno=$commentagno[0];
      $commentag="Rip2media" if($commentagno == 1);
      $commentag="Respect ©!" if($commentagno == 2);
   }

   if(defined $cd{title}) {
      $album = clean_all($cd{title});
      $artist = clean_all($cd{artist});
      $categ = $cd{cat};

      # Set the year if it wasn't passed on command line.
      unless($year) {
         $year = $cd{year} if($cd{year});
         $year =~ s/[\015]//g;
      }

      # Set the genre if it wasn't passed on command line.
      if(!defined $pgenre && defined $cd{genre}) {
         $genre = $cd{genre};
         $genre =~ s/[\015]//g;
      }

      @comment = extract_comm;
      $revision = get_rev;
   }
   else {
#      # We don't want tracks to be defined globally. Hack it into the
#      # cd-hash! Note that it won't exist afterwards!
#      %cd = (track => $tracks);
      if($submission == 0) {
         print "\nNo CDDB info choosen or found for this CD\n"
            if($verbose >= 1);
      }
      # Set submission OK, will be set to zero if default
      # names are used.
      $cddbsubmission = 1;
      # Don't ask for default settings, use them! ...
      if($interaction == 0) {
         create_deftrack(1);
      }
      # ... or ask whether 1) default or 2) manual entries
      # shall be used or entered.
      else {
         create_deftrack(2);
      }
      $album = $cd{title};
      $artist = $cd{artist};
      $revision = $cd{revision};
   }
   my $genreno = "";
   if($genre eq "" && $interaction == 1) {
      print "\nPlease enter a valid CDDB genre (or none): ";
      $genre = <STDIN>;
      chomp $genre;
      $cd{genre} = $genre;
   }
   if($genre ne "") {
      $genre =~ s/[\015]//g;
      ($genre,$genreno) = check_genre($genre);
   }

   # What if someone wants underscore and/or lowercase in filenames
   # and has genre in the dir or tracktemplate? So we have to
   # lowercase genre and underscore it if it is a 2 word expression.
   if(($dirtemplate =~ /\$genre/ or $tracktemplate =~ /\$genre/) && $genre ne "") {
      my $tempgenre = $genre;
      $tempgenre = lower_case($tempgenre) if($lowercase == 1);
      if($genre =~ /\w\s\w/ && $underscore == 1) {
         $tempgenre =~ s/ /_/g;
         # Do it the hard way: assume we have the definitive
         # genre, so replace the string "$genre" with the
         # value of $tempgenre!
         $dirtemplate =~ s/\$genre/$tempgenre/g;
         $tracktemplate =~ s/\$genre/$tempgenre/g;
      }
   }

   if($verbose >= 1) {
      print "\n-----------------";
      print "\nCDDB and tag Info";
      print "\n-----------------\n";
      print "Artist: $artist\n";
      print "Album: $album\n";
      print "Category: $categ\n" if($verbose >= 2);
      print "ID3-Genre: $genre ($genreno)\n";
      if(lc($genre) ne lc($cd{'genre'})) {
         print "CDDB-Genre: $cd{genre}\n";
      }
      print "Year: $year\n";
      print "Revision: $revision\n" if($verbose >= 2);
      # It happens, that the ID from CDDB is NOT
      # identical to the ID calculated from the
      # frames of your CD...
      if($cddbid ne $cd{id} && defined $cd{id} ) {
         print "CDDB id: $cd{id}\n";
      }
      print "CD id: $cddbid\n";
      if(@comment && $verbose >= 2) {
         foreach (@comment) {
            print "Comment: $_\n" if($_);
         }
      }
      print "\n";
   }
   log_info("\nArtist: $artist");
   log_info("Album: $album");
   log_info("ID3-Genre: $genre ($genreno)");
   log_info("Category: $categ");
   log_info("CD id: $cddbid\n");

   # Read out pregap before calculating track lengths.
   my $frames = $toc->[0]->{'frames'};
   push @framelist, "$frames";
   if ($frames > 300) {
      my $second = int($frames/75);
      my $frame = $frames - $second * 75;
      my $minute = int($second/60);
      $second = $second - $minute * 60;
      printf("%s %02d:%02d %s\n",
         "There might be a hidden track", $minute, $second,
         "long, because offset of track 01 is $frames.")
         if($verbose >= 1);
      my $riptrackname = "Hidden Track";
      $riptrackname = lower_case($riptrackname) if($lowercase == 1);
      $riptrackname =~ s/ /_/g if($underscore == 1);
      printf("%s: [%02d:%02d.%02d] %s\n",
             "00", $minute, $second, $frame, $riptrackname)
         if($verbose >= 1);
      $second = int($frames/75);
      # We can't add this track to seltrack and framelist,
      # because this would break (re-) submission of CDDB.
      # Note: seltrack is not yet defined...
      # Add the hidden track to @seltrack only if ripping the hidden
      # track was successful.
      $hiddenflag = 1 if($trackselection eq ""
         || $trackselection =~ /^0/
         || $trackselection =~ /\D0/);
      push @secondlist, "$second" if($hiddenflag == 1);
   }
   my $n = 1;
   # Print track infos.
   foreach (@{$cd{track}}) {
      $_ = clean_all($_);
      push @tracktags, $_;
      # Get frames and total time.
      my $frames = $toc->[$n]->{'frames'};
      push @framelist, "$frames";
      $frames = $frames - $framelist[$n-1];
      my $second = int($frames/75);
      push @secondlist, "$second";
      my $frame = $frames - $second * 75;
      my $minute = int($second/60);
      $second = $second - $minute * 60;
      $_ = clean_chars($_) if($chars);
      printf("%02d: [%02d:%02d.%02d] %s\n",
             $n, $minute, $second, $frame, $_)
         if($verbose >= 2);
      $_ = clean_name($_);
      $_ = lower_case($_) if($lowercase == 1);
      $_ =~ s/ /_/g if($underscore == 1);
      push @tracklist, $_;
      $n++;
   }
   print "\n\n" if($verbose >= 1);

   # Some more error checking.
   if($artist eq "") {
      die "ERROR: No Artist Found!\n";
   }

   # lcdproc
   if($lcd == 1){
      $lcdline1 = $artist . "-" . $album;
      $lcdline2 = "R00|00.0%|----------";
      $lcdline3 = "E00|00.0%|----------";
      ulcd();
   }
}
########################################################################
#
# Create the track selection from the parameters passed on the command-
# line, i. e. create an array with all track numbers including those not
# explicitly stated at the command line.
#
sub create_seltrack {
   my($tempstr,$intrack);
   ($tempstr) = @_;
   if(($tempstr =~ /,/) || ($tempstr =~ /\-/)) {
      my @intrack = split(/,/ , $tempstr);
# If last character is a , add an other item with a -
      if($tempstr =~ /,$/) {
         push @intrack, ($intrack[$#intrack]+1) . "-";
      }
      foreach $intrack (@intrack) {
         if($intrack =~ /\-/) {
            my @outrack = split(/-/ , $intrack);
# If last character is a -, add last track to $outrack
            if($#outrack == 0) {
               $outrack[1] = $#tracklist + 1;
            }
            for(my $i = $outrack[0]; $i <= $outrack[1]; $i++) {
               push @seltrack, $i;
            }
         }
         else {
            push @seltrack, $intrack;
         }
      }
   }
   elsif($tempstr eq '') {
      for(my $i = 1; $i <= ($#tracklist + 1); $i++) {
         $seltrack[$i - 1] = $i;
      }
   }
   elsif($tempstr =~ /^[0-9]*[0-9]$/) {
      $seltrack[0] = $tempstr;
   }
   else {
      die "Track selection invalid!\n";
   }

   # Sort the tracks in order, perl is so cool :-)
   @seltrack = sort {$a <=> $b} @seltrack;

   # Check the validaty of the track selection.
   foreach (@seltrack) {
      if($_ > ($#tracklist + 1)) {
         die "Track selection higher than number of tracks on CD.\n\n";
      }
      elsif($_ == 0) {
         shift @seltrack;
      }
   }
}
########################################################################
#
# Ask if CDDB submission shall be done because one might change some
# settings a last time before writing to directories and files! Then
# create the directory where the flac, mp3, m4a or ogg files will go.
# Fail if directory exists or can't be created.
#
sub create_dirs {
   # Directory created will be: /outputdir/$dirtemplate

   my $index = 2;
   unless($cddbsubmission == 0 || $interaction == 0) {
      while($index !~ /^[0-1]$/) {
         print "\nDo you want to edit or submit the CDDB entry?";
         print "\nTo confirm each question type Enter!\n\n";
         print "1: Yes, and I know about the naming-rules of ";
         print "freedb.org!\n\n";
         print "0: No\n\nChoose [0-1]: (0) ";
         $index = <STDIN>;
         chomp $index;
         if($index eq "") {
            $index = 0;
         }
         print "\n";
      }
      if($index == 1) {
         my $revision = get_rev();
         if($revision) {
            print "\nPlease change some settings!";
            print "\nYou may confirm all CDDB settings with Enter!\n";
            create_deftrack(0);
         }
      }
      elsif($index != 0) {
         print "You should choose 0 or 1!\n";
      }
   }
   if($index == 1) {
      pre_subm();
   }

   my $album = clean_all($cd{title});
   my $artist = clean_all($cd{artist});
   $album = clean_name($album);
   $artist = clean_name($artist);
   $album = clean_chars($album) if($chars);
   $artist = clean_chars($artist) if($chars);
   $album =~ s/ /_/g if($underscore == 1);
   $artist =~ s/ /_/g if($underscore == 1);

   # Check and create the full path "outputdir" where the files
   # will go. First Check the dirtemplate and use the actual year
   # as default if $year is in the template and none is given!
   if(($dirtemplate =~ /\$year/ || $tracktemplate =~ /\$year/)
       && $year eq "") {
      $year = `date \'+%Y\'`;
      chomp $year;
   }
   if(($dirtemplate =~ /\$genre/ || $tracktemplate =~ /\$genre/)
       && $genre eq "") {
      $genre = "Other";
      chomp $genre;
   }
   my $dir;
   if(!eval("\$dir = $dirtemplate")) {
      die "Directory Template incorrect, caused eval to fail: $!";
   }

   $dir = lower_case($dir) if($lowercase == 1);
   $dir =~ s/ /_/g if($underscore == 1);

   $outputdir = $outputdir . "/" . $dir;
   # Delete ending . in directory name if no special characters
   # wanted!
   $outputdir =~ s/[.]+$// if($chars);
   # Check if the outputdir alread exists, if it does, try
   # "outputdir i" with i an integer until it works.
   my $cdexistflag = 0;
   my $i = 1;
   my $noutputdir = $outputdir;
   if($multi == 0) {
      while(defined(opendir(TESTDIR, $noutputdir)) && $rip == 1) {
         $noutputdir = $outputdir . " " . $i if($underscore == 0);
         $noutputdir = $outputdir . "_" . $i if($underscore == 1);
         $i++;
      }
   }
   else {
      if(defined(opendir(TESTDIR, $outputdir))) {
         # Delete error.log now, else the next device will
         # start to encode!
         if(-r "$outputdir/error.log") {
            print "Found an orfand error.log in $outputdir.\n";
            unlink("$outputdir/error.log");
         }
         open(SRXY,">>$logfile")
            or print "Can not append to file \"$logfile\"!\n";
         print SRXY "\nThe directory $outputdir is already present!";
         close(SRXY);
         # We supposed it would be better to write into the same
         # directory, if identical CDDB entry for another CD found.
         # But there are plenty of Compilations with more than one
         # disc which have all the same titles...
         while(defined(opendir(TESTDIR, $noutputdir))) {
            $noutputdir = $outputdir . " " . $i if($underscore == 0);
            $noutputdir = $outputdir . "_" . $i if($underscore == 1);
            $i++;
            $cdexistflag = 1;
         }
         if(-r "$noutputdir/error.log") {
            print "Found an orfand error.log in $noutputdir.\n";
            unlink("$noutputdir/error.log");
         }
         $i--;
      }
      my @logpath = split(/\//, $noutputdir);
      my $aadir = pop(@logpath);
      if($cdexistflag == 1){
         open(SRXY,"$logfile") or print "Can not open \"$logfile\"!\n";
         my @srxylines = <SRXY>;
         close(SRXY);
         grep(s/^album:\s(.*)$/album: $1 $i/, @srxylines)
            if($underscore == 0);
         grep(s/^album:\s(.*)$/album: $1_$i/, @srxylines)
            if($underscore == 1);
         open(SRXY,">$logfile")
            or print "Can not write to file \"$logfile\"!\n";
         print SRXY @srxylines;
         close(SRXY);
      }
      open(SRXY,">>$logfile")
         or print "Can not append to file \"$logfile\"!\n";
      print SRXY "\nArtist - Album:$aadir";
      close(SRXY);
      pop(@logpath);
      $logpath = join('/', @logpath);
   }
   $outputdir = $noutputdir . "/";

   if(!opendir(TESTDIR, $outputdir)) {
      # Explicitly log outputdir creation.
      log_info("new-mediadir: $outputdir");
      log_system("mkdir -m 0777 -p \"$outputdir\"")
         or die "Can not create directory $outputdir: $!\n";
   }
   else {
      closedir(TESTDIR);
   }
}
########################################################################
#
# Create the full-path track file name from the tracktemplate variable.
#
sub get_trackname {
   my($trnum,$trname,$riptrname);

   ($trnum,$trname) = @_;

   my $album = clean_all($cd{title});
   my $artist = clean_all($cd{artist});
   $album = clean_name($album);
   $artist = clean_name($artist);
   $album = clean_chars($album) if($chars);
   $artist = clean_chars($artist) if($chars);
   $album =~ s/ /_/g if($underscore == 1);
   $artist =~ s/ /_/g if($underscore == 1);
   # Create the full file name from the track template, unless
   # the disk is unknown.
   if(defined $cd{title}) {
      # We do not need to lowercase the tracktemplate, because
      # all variables in are already lowercased!
      $tracktemplate =~ s/ /\\_/g if($underscore == 1);
      # We have to update tracknum and trackname because they
      # are evalueted by the tracktemplate!
      my $tracknum = sprintf("%02d", $trnum);
      my $trackname = $trname;
      if(!eval("\$riptrname = \$outputdir.$tracktemplate")) {
         die "Track Template incorrect, caused eval to fail: $!";
      }
   }
   else {
      $trname  = lower_case($trname) if($lowercase == 1);
      $trname =~ s/ /_/g if($underscore == 1);
      $riptrname = $outputdir . $trname;
   }

   return $riptrname;
}
########################################################################
#
# Rip the CD.
#
sub rip_cd {
   my($shortname,@shortname,$trackcn,$riptrackname);
   my $startenc = 0;

   my $albumtag = clean_all($cd{title});
   my $artistag = clean_all($cd{artist});
   my $album = clean_name($albumtag);
   my $artist = clean_name($artistag);
   $album = clean_chars($album) if($chars);
   $artist = clean_chars($artist) if($chars);
   $album =~ s/ /_/g if($underscore == 1);
   $artist =~ s/ /_/g if($underscore == 1);

   if($#seltrack == 0 && $hiddenflag == 0) {
      print "Track @seltrack will be ripped!\n\n" if($verbose >= 1);
   }
   elsif(!@seltrack && $hiddenflag == 1) {
      print "Track 0 will be ripped!\n\n" if($verbose >= 1);
   }
   elsif($hiddenflag == 1) {
      print "Tracks 0 @seltrack will be ripped!\n\n" if($verbose >= 1);
   }
   else {
      print "Tracks @seltrack will be ripped!\n\n" if($verbose >= 1);
   }
   $trackcn = 0;

   my $date = `date`;
   $date =~ s/\s+/ /g;
   chomp $date;
   my @ripstart = split(/ /, $date);
   @ripstart = split(/:/, $ripstart[3]);
   my $ripstart = $ripstart[0] . ":" . $ripstart[1];
   chomp $ripstart;

   open(ERO,">>$outputdir/error.log")
      or print "Can not append to file \"$outputdir/error.log\"!\n";
      print ERO "Ripping  started: $ripstart\n";
   close(ERO);

   if($multi == 1) {
      open(SRXY,">>$logfile")
         or print "Can not append to file \"$logfile\"!\n";
      print SRXY "\nRipping  started: $ripstart";
      close(SRXY);
   }
   if($cdtoc == 1){
      my $cdtocartis = oct_char($artistag);
      my $cdtocalbum = oct_char($albumtag);
      open(CDTOC ,">$outputdir/cd.toc")
         or print "Can not append to file \"$outputdir/cd.toc\"!\n";
      print CDTOC "CD_DA\n//Ripit $version cd.toc file generated $date";
      print CDTOC "\n\n//CD Text:\nCD_TEXT{LANGUAGE_MAP {0 : EN}\n\t";
      print CDTOC "LANGUAGE 0 {\n\t\tTITLE \"$cdtocalbum\"\n\t\t";
      print CDTOC "PERFORMER \"$cdtocartis\"\n";
##      print CDTOC "\t\tGENRE \"$genreno\"\n" if($genreno);
      print CDTOC "\t\tDISC_ID \"$cddbid\"\n\t}\n}\n";
      close(CDTOC);
   }

   # Start to rip the hidden track if ther's one.
   # Check if cdparanoia is available.
   if($ripper != 1) {
      unless(log_system("cdparanoia -V")) {
         print "Cdparanoia not installed? Can't rip the hidden track ";
         print "without cdparanoia!\n"
            if($hiddenflag == 1);
         $hiddenflag = 0;
      }
   }
   if($hiddenflag == 1) {
      $riptrackname = "Hidden Track";
      $riptrackname = lower_case($riptrackname) if($lowercase == 1);
      $riptrackname =~ s/ /_/g if($underscore == 1);
      my $cdtocname = $riptrackname;
      unshift @tracklist, $riptrackname;
      unshift @seltrack, 0;
      unshift @tracktags, $riptrackname;
      $riptrackname = get_trackname(0, $tracklist[0]);
      @shortname = split(/\// , $riptrackname);
      $shortname = $shortname[$#shortname];
      my $saveripopt = $ripopt;
      $ripopt = $ripopt . " -Z" if($parano == 0);
      $ripopt = $ripopt . " -q" if($verbose le 1);
      unless(log_system("cdparanoia $ripopt -d $cddev [00:00]1 \"$riptrackname.wav\"")) {
         $hiddenflag = 0;
         shift(@tracklist);
         shift(@tracktags);
         shift(@seltrack);
         shift(@secondlist);
      }
      elsif($cdtoc == 1){
         open(CDTOC ,">>$outputdir/cd.toc")
            or print "Can not append to file \"$outputdir/cd.toc\"!\n";
         print CDTOC "\n//Track 0:\nTRACK AUDIO\nTWO_CHANNEL_AUDIO\n";
         print CDTOC "CD_TEXT {LANGUAGE 0 {\n\t\tTITLE \"$cdtocname\"";
         print CDTOC "\n\t\tPERFORMER \"$artistag\"\n\t}\n}\n";
         print CDTOC "FILE \"$shortname.wav\" 0\n";
         close(CDTOC);
      }
      $ripopt = $saveripopt;
   }

   foreach (@seltrack) {
      next if($_ == 0);
      $trackcn++;
      $riptrackname = get_trackname($_, $tracklist[$_ - 1]);
      $riptrackname = get_trackname($_, $tracklist[$_])
         if($hiddenflag == 1);
      my $riptrackno = $_;
      @shortname = split(/\//, $riptrackname);
      $shortname = $shortname[$#shortname];
      if($cdtoc == 1){
         my $cdtoctitle = $tracklist[$_ - 1];
         $cdtoctitle = $tracklist[$_] if($hiddenflag == 1);
         my $cdtocartis = oct_char($artistag);
         $cdtoctitle = oct_char($cdtoctitle);
         open(CDTOC, ">>$outputdir/cd.toc")
            or print "Can not append to file \"$outputdir/cd.toc\"!\n";
         print CDTOC "\n//Track $riptrackno:\nTRACK AUDIO\n";
         print CDTOC "TWO_CHANNEL_AUDIO\nCD_TEXT {LANGUAGE 0 {\n\t\t";
         print CDTOC "TITLE \"$cdtoctitle\"\n\t\t";
         print CDTOC "PERFORMER \"$cdtocartis\"\n\t}\n}\n";
         print CDTOC "FILE \"$shortname.wav\" 0\n";
         close(CDTOC);
      }

      print "Ripping \"$shortname\"...\n" if($verbose >= 1);

      # lcdproc
      if($lcd == 1){
         my $_lcdtracks = scalar @seltrack;
         $lcdtrackno++;
         my $lcdperc;
         if($_lcdtracks eq $lcdtrackno) {
            $lcdperc = "*100";
         }
         else {
            $lcdperc = sprintf("%04.1f", $lcdtrackno/$_lcdtracks*100);
         }
         $lcdline2=~ s/\|\d\d.\d/\|$lcdperc/;
         my $lcdtracknoF = sprintf("%02d", $lcdtrackno);
         $lcdline2=~ s/\r\d\d/\r$lcdtracknoF/;
         substr($lcdline2,10,10) = substr($shortname,3,13);
         ulcd();
      }

      # There is a problem with too long file names,
      # encountered e.g. with some classical CDs.
      # Cdparanoia cuts the length, cdda2wav too...
      # but how should RipIT know?
      # Use a shorter track name if total length (incl.
      # path) > 230 characters.
      if(length($riptrackname) > 230) {
         $riptrackname = get_trackname($_, $_ . "short");
      }

      # Choose the cdaudio ripper to use.
      #
      # TODO: Check behaviour of all rippers when data track
      # encountered. Choose to use print instead of die if
      # ripper stops itself!
      # dagrab fails @ data-track, so don't die! and create an error.log
      # cdparanoia fails @ data-track, so don't die! and create an
      # error.log.
      #
      # cdda2wav prints errors @ data-track, therefore die!
      if($ripper == 0 && $rip == 1) {
         if($trackcn == 1) {
            $ripopt = $ripopt . " -r 3" if($parano == 0);
            $ripopt = $ripopt . " -v" if($verbose >= 2);
         }
         unless(log_system("(dagrab $ripopt -d $cddev -f \"$riptrackname.rip\" $riptrackno 3>&1 1>&2 2>&3 | tee -a \"$outputdir/error.log\" ) 3>&1 1>&2 2>&3 ")) {
            print "Dagrab detected some read errors on $tracklist[$_ - 1]\n\n";
            # Create error message in CD-directory for encoder: don't wait.
            open(ERO,">>$outputdir/error.log")
               or print "Can not append to file \"$outputdir/error.log\"!";
            print ERO "Dagrab detected some read errors at $riptrackno";
            print ERO " on CD $artist - $album, do not worry!\n";
            close(ERO);
         }
         print "\n";
      }
      elsif($ripper == 1 && $rip == 1) {
         if($trackcn == 1) {
            $ripopt = $ripopt . " -Z" if($parano == 0);
            $ripopt = $ripopt . " -q" if($verbose le 1);
         }
         if($multi == 0) {
            unless(log_system("cdparanoia $ripopt -d $cddev $riptrackno \"$riptrackname.rip\"")) {
               print "cdparanoia failed on $tracklist[$_ - 1]\n\n";
               # Create error message in CD-directory for encoder:
               # don't wait.
               open(ERO,">>$outputdir/error.log")
                  or print "Can not append to file \"$outputdir/error.log\"!";
               print ERO "Track $riptrackno on CD $artist - $album ";
               print ERO "failed!\n";
               close(ERO);
            }
         }
         elsif($multi == 1) {
            $ripopt = $ripopt . " -X" if($trackcn == 1);
            unless(log_system("cdparanoia $ripopt -d $cddev $riptrackno \"$riptrackname.rip\" 2>> \"$logfile.$riptrackno.txt\"")) {
               # Apend error message to file srXY for rip2m to start
               # checktrack.
               open(SRXY,">>$logfile")
                  or print "Can not append to file \"$logfile\"!";
               print SRXY "\ncdparanoia failed on $tracklist[$_ - 1] ";
               print SRXY "in device $logfile";
               close(SRXY);
               # Create error message in CD-directory for encoder:
               # don't wait.
               open(ERO,">>$outputdir/error.log")
                  or print "Can not append to file ",
                           "\"$outputdir/error.log\"!";
               print ERO "Track $riptrackno on CD $artist - $album ";
               print ERO "failed!\n";
               close(ERO);
               # Kill failed CD only if it is not the last track. Last
               # track may be data/video track.
               # I.e. print error message to file srXY.Z.txt, checktrack
               # will grep for string
               # "cdparanoia failed" and kill the CD immediately!
               if($riptrackno != $seltrack[$#seltrack]) {
                  open(SRTF,">>$logfile.$riptrackno.txt")
                     or print "Can not append to file ",
                              "\"$logfile.$riptrackno.txt\"!";
                  print SRTF "cdparanoia failed on $tracklist[$_ - 1]";
                  print SRTF "\nin device $logfile, error !";
                  close(SRTF);
                  # Create on the fly error message in log-directory.
                  open(ERO,">>$logpath/failed.log")
                     or print "Can not append to file ",
                              "\"$logpath/failed.log\"!";
                  print ERO "$artist;$album;$genre;$categ;$cddbid;";
                  print ERO "$logfile;$hostnam\n";
                  close(ERO);
                  # Now wait to be terminated by checktrack.
                  sleep 360;
                  exit;
               }
            }
         }
      }
      elsif($ripper == 2 && $rip == 1) {
         if($trackcn == 1) {
            $ripopt = $ripopt . " -q" if($verbose le 1);
         }
         if($multi == 0) {
            unless(log_system("cdda2wav -D $cddev -H $ripopt -t $riptrackno \"$riptrackname\_rip\"")) {
               print "cdda2wav failed on $tracklist[$_ - 1]";
               open(ERO,">>$outputdir/error.log")
                  or print "Can not append to file ",
                           "\"$outputdir/error.log\"!";
               print ERO "Track $riptrackno on CD $artist - $album ";
               print ERO "failed!\n";
               close(ERO);
            }
         }
         elsif($multi == 1) {
            unless(log_system("cdda2wav -D $cddev -H $ripopt -t $riptrackno \"$riptrackname\_rip\" 2>> \"$logfile.$riptrackno.txt\"")) {
               # Apend error message to file srXY for rip2m to start
               # checktrack.
               open(SRXY,">>$logfile")
                  or print "Can not append to file \"$logfile\"!";
               print SRXY "\ncdda2wav failed on $tracklist[$_ - 1] in ";
               print SRXY "device $logfile";
               close(SRXY);
               # Create error message in CD-directory for encoder:
               # don't wait.
               open(ERO,">>$outputdir/error.log")
                  or print "Can not append to file ",
                           "\"$outputdir/error.log\"!";
               print ERO "Track $riptrackno on CD $artist - $album ";
               print ERO "failed!\n";
               close(ERO);
               # Kill failed CD only if it is not the last track.
               # Last track may be data/video track.
               # I.e. print error message to file srXY.Z.txt, checktrack
               # will grep for string
               # "cdparanoia failed" and kill the CD immediately!
               if($riptrackno != $seltrack[$#seltrack]) {
                  open(SRTF,">>$logfile.$riptrackno.txt")
                     or print "Can not append to file ",
                              "\"$logfile.$riptrackno.txt\"!";
                  print SRTF "cdda2wav failed on $tracklist[$_ - 1]\n";
                  print SRTF "in device $logfile, error !";
                  close(SRTF);
                  # Create on the fly error message in log-directory.
                  open(ERO,">>$logpath/failed.log")
                     or print "Can not append to file ",
                              "\"$logpath/failed.log\"!";
                  print ERO "$artist;$album;$genre;$categ;$cddbid;";
                  print ERO "$logfile;$hostnam\n";
                  close(ERO);
                  # Now wait to be terminated by checktrack.
                  sleep 360;
                  exit;
               }
            }
         }
      }
      elsif($ripper == 3 && $rip == 1) {
         unless(log_system("tosha -d $cddev -f wav -t $riptrackno -o \"$riptrackname.rip\"")) {
            die "tosha failed on $tracklist[$_ - 1]";
         }
      }
      elsif($ripper == 4 && $rip == 1) {
         my $cdd_dev = $cddev;
         $cdd_dev =~ s/^\/dev\/r//;
         $cdd_dev =~ s/c$//;
         unless(log_system("cdd -t $riptrackno -q -f $cdd_dev - 2> /dev/null | sox -t cdr -x - \"$riptrackname.rip\"")) {
            die "cdd failed on $tracklist[$_ - 1]";
         }
      }
      elsif($rip == 1) {
         print "No CD Ripper defined";
      }

      # Rename rip file to a wav for encoder so that it will be picked
      # up by the encoder background process.
      # Cdda2wav output is not easy to handle.
      # Everything beyond the last . has been erased.
      if($ripper == 2) {
         if($riptrackname =~ /\./) {
            # And split is too clever! If a trackname
            # ends with "name..." all points get lost,
            # so we've to add a word at the end!
            my $cddatrackname = $riptrackname . "end";
            my @riptrackname = split(/\./, $cddatrackname);
            delete($riptrackname[$#riptrackname]);
            $cddatrackname = join('.',@riptrackname);
            rename("$cddatrackname.wav","$riptrackname.rip");
         }
         else {
            rename("$riptrackname\_rip.wav","$riptrackname.rip");
         }
      }
      rename("$riptrackname.rip","$riptrackname.wav");
      unlink("$logfile.$riptrackno.txt") if($multi == 1);

      if ($normalize == 0) {
         # Start the encoder in the background, but only once.
         if($startenc == 0 && $encode == 1) {
            my $encstart = `date \'+%R\'`;
            chomp $encstart;
            if($multi == 1) {
               open(SRXY,">>$logfile")
                  or print "Can not append to file \"$logfile\"!";
               print SRXY "\nEncoding started: $encstart";
               close(SRXY);
            }
            $startenc = 1;
            unless(fork) {
               enc_cd();
            }
         }
      }
      # Let output look nice. Keep ENCODER message together!
      if($riptrackno != $seltrack[$#seltrack]) {
         sleep 1;
      }
   }

   # Ugly hack to tell the child process that we are waiting for it
   # to finish.
   my $ripend = `date \'+%R\'`;
   chomp $ripend;
   open(ERR, ">>$outputdir/error.log")
      or print "Can not append to file error.log!\n";
   print ERR "The audio CD ripper reports: all done!\n";
   print ERR "Ripping  ended: $ripend\n";
   close(ERR);
   if($multi == 1) {
      open(SRXY,">>$logfile")
         or print "Can not append to file \"$logfile\"!";
      print SRXY "\nRipping complete: $ripend";
      close(SRXY);
   }
}
########################################################################
#
# Normalize the wav.
# Using normalize will disable parallel ripping & encoding.
#
sub norm_cd {

   print "Normalizing the wave-files...\n";
   my($norm,$normtrackname);

   # Generate filelist.
   foreach (@seltrack) {
      my $riptrackname = &get_trackname($_, $tracklist[$_ - 1]);
      # normalize is picky about certain characters - get them escaped!
      $riptrackname = esc_char($riptrackname);
      $normtrackname = "$normtrackname $riptrackname.wav";
   }

   $norm = "normalize $normopt -- $normtrackname";

   if ( ! system("$norm")) {
      print "\nNormalizing complete.\n";
   }
   else {
      die "\nNormalizing failed.\n";
   }
}
########################################################################
#
# Encode the wav.
# This runs as a separate process from the main program which
# allows it to continuously encode as the ripping is being done.
# The encoder will also wait for the ripped wav in-case the encoder
# is faster than the CDROM.
#
sub enc_cd {
   my ($x, $enc, $ncount, $riptrackno, $riptrackname);
   my ($albumlametag, $artislametag, $commentlametag, $tracklametag);
   my ($ripcomplete, $totalencs) = (0, 0);

   my $albumtag = clean_all($cd{title});
   my $artistag = clean_all($cd{artist});
   my $album = clean_name($albumtag);
   my $artist = clean_name($artistag);
   $album = clean_chars($album) if($chars);
   $artist = clean_chars($artist) if($chars);
   $album =~ s/ /_/g if($underscore == 1);
   $artist =~ s/ /_/g if($underscore == 1);
   if($utftag == 0) {
      $artislametag = back_encoding($artistag);
      $albumlametag = back_encoding($albumtag);
      $commentlametag = back_encoding($commentag);
   }
   else{
      $artislametag = $artistag;
      $albumlametag = $albumtag;
      $commentlametag = $commentag;
   }

   foreach (@seltrack) {
      $riptrackname = get_trackname($_, $tracklist[$_ - 1]);
      $riptrackname = get_trackname($_, $tracklist[$_])
         if($hiddenflag == 1);
      $riptrackno = $_;
      $ncount++;

      # lcdproc
      if($lcd == 1){
         my $_lcdtracks = scalar @seltrack;
         my $_lcdenctrack = $ncount;
         my $lcdperc;
         if($_lcdtracks eq $_lcdenctrack) {
            $lcdperc = "*100";
         }
         else {
            $lcdperc = sprintf("%04.1f",$_lcdenctrack/$_lcdtracks*100);
         }
         $lcdline3=~ s/\|\d\d.\d/\|$lcdperc/;
         my $_lcdenctrackF = sprintf("%02d",$_lcdenctrack);
         $lcdline3=~ s/\E\d\d/\E$_lcdenctrackF/;
         my @shortname = split(/\// , $riptrackname);
         my $shortname = $shortname[$#shortname];
         substr($lcdline3,10,10) = substr($shortname,3,13);
         ulcd();
      }

      # Cosmetics for nice output.
      my $lasttrack = $seltrack[$#seltrack];
      my $lasttrackname = get_trackname($lasttrack, $tracklist[$lasttrack - 1]);
      my @shortname = split(/\// , $riptrackname);
      my $shortname = $shortname[$#shortname];

      my $tracktag = $tracktags[$_ - 1];
      $tracktag = $tracktags[$_] if($hiddenflag == 1);
      if($utftag == 0) {
         $tracklametag = back_encoding($tracktag);
      }
      else{
         $tracklametag = $tracktag;
      }

      # Keep looping until the wav file appears, i.e. wait for
      # ripper timeout. Timeout is 3 times the length of track
      # to rip/encode. Then leave that one and finish the job!
      my $slength = $secondlist[$_ - 1];
      my $mlength = (int($slength / 60) + 1) * 3;
      my $tlength = (int($slength / 10) + 6) * 3;
      my $x = 0;

      # If the file name is too long, look for special
      # name.
      my $wavname = $riptrackname;
      if(length($riptrackname) > 230) {
         $wavname = get_trackname($_,$_."short");
      }
      while(! -r "$wavname.wav") {
         $x++;
         last if($x > $tlength);
         # Condition 1: Too long waiting for the track!
         if($x >= $tlength) {
            if($multi != 1) {
               print "Encoder waited $mlength minutes for file\n";
               print "$shortname.wav to appear, now giving up!\n";
               print "with $artist - $album in device $cddev\n"
                  if($multi == 1);
               $x = $tlength + 1;
            }
            else {
               $x = 0;
               print "Don't worry, I continue the job!\n\n";
            }
         }
         sleep 10;
         # Condition 2: Check the error log!
         # If at this moment the ripper did not start with
         # the riptrackname.rip, assume it was a data track!
         # If cdparanoia failed on a data track, there will
         # be an entry in the error.log.
         # If dagrab gave error messages, but the wav file
         # was created, we won't get to this point, so don't
         # worry.
         if(-r "$outputdir/error.log") {
            open(ERR, "$outputdir/error.log")
               or print "error.log disappeared!\n";
            my @errlines = <ERR>;
            close ERR;
            my @errtrack = grep(/^Track $riptrackno /, @errlines);
            my $errtrack = "@errtrack";
            @errtrack = split(/ /, $errtrack);
            $errtrack = $errtrack[1];
            if($errtrack) {
               $x = $tlength + 1;
               if($verbose >= 2) {
                  print "\nDid not detect track $errtrack";
                  print " ($shortname.rip), assume ripper failure!\n";
               }
               print "I will finish the job! Check the error.log!\n"
                  if($verbose >= 2 && $sshflag == 0);
            }
         }
      }
      next if($x > $tlength);
      if(length($riptrackname) > 230) {
         rename("$wavname.wav","$riptrackname.wav");
      }

      my $delwav = 0;
      my $starts = `date \'+%s\'`;
      chomp $starts;
      # Set the encoder(s) we are going to use.
      for(my $c=0; $c<=$#coder; $c++) {
         # This file exists if the ripper finished. It is used to
         # enhance the output. Don't mess up the messages!
         if($ripcomplete == 0 ) {
            if(-r "$outputdir/error.log") {
               open(ERR, "$outputdir/error.log")
                  or print "Can not open file error.log!\n";
               my @errlines = <ERR>;
               close ERR;
               my @ripcomplete = grep(/^The audio CD ripper reports: all done!$/, @errlines);
               $ripcomplete = 1 if(@ripcomplete);
            }
         }
         if($ripcomplete == 1 && $verbose >= 2) {
            print "\n";
         }
         if($ncount == 1 && $ripcomplete == 0 && $c > 0 && $verbose >= 2) {
            print "\n\n";
         }
         if($ncount > 1 && $ripcomplete == 0 && $verbose >= 2) {
            print "\n\n";
         }
         my $sufix = "";

         # Get the command for the encoder to use!
         if($coder[$c] == 0) {
            if($ncount == 1) {
               if($preset) {
                  $lameopt = $lameopt . " --preset $preset";
               }
               else {
                  $lameopt = $lameopt . " --vbr-$vbrmode"
                     if($vbrmode);
                  $lameopt = $lameopt . " -b $bitrate"
                     if($bitrate ne "off");
                  $lameopt = $lameopt . " -B $maxrate"
                     if($maxrate != 0);
                  $lameopt = $lameopt . " -V $qualame"
                     if($qualame ne "off" && $vbrmode);
                  $lameopt = $lameopt . " -q $qualame"
                     if($qualame ne "off" && !$vbrmode);
               }
            }
            $enc = "lame $lameopt -S --tt \"$tracklametag\" \\
              --ta \"$artislametag\" --tl \"$albumlametag\" \\
              --ty \"$year\" --tg \"$genre\" --tn $riptrackno \\
              --tc \"$commentlametag\" --add-id3v2 \\
              \"$riptrackname.wav\" \"$riptrackname.mp3\"";
            print "Lame $lameopt encoding track " . $ncount . " of " .
                  ($#seltrack + 1) . " " if($verbose >= 2);
            print "\@ quality $qualame\n" if($verbose >= 2 && !$preset);
            print "\n" if($verbose >= 2);
            log_info("new-mediafile: ${riptrackname}.mp3");
            $sufix = "mp3";
         }
         elsif($coder[$c] == 1) {
            if($ncount == 1) {
               $oggencopt = $oggencopt . " -q $qualoggenc" if($qualoggenc ne "off");
               $oggencopt = $oggencopt . " -M $maxrate" if($maxrate != 0);
            }
            $enc = "oggenc $oggencopt -t \"$tracktag\" -a \"$artistag\" \\
              -l \"$albumtag\" -d \"$year\" -G \"$genre\" \\
              -N $riptrackno -c \"DESCRIPTION=$commentag\" \\
              -o \"$riptrackname.ogg\" \"$riptrackname.wav\"";
            print "Oggenc $oggencopt encoding track $ncount of " .
                  ($#seltrack + 1) . " \@ quality $qualoggenc\n"
               if($verbose >= 2);
            log_info("new-mediafile: ${riptrackname}.ogg");
            $sufix = "ogg";
         }
         elsif($coder[$c] == 2) {
            if($ncount == 1) {
               $flacopt = $flacopt . " -$quaflac" if($quaflac ne "off");
            }
            $enc = "flac $flacopt --tag=TITLE=\"$tracktag\" \\
              --tag=ARTIST=\"$artistag\" --tag=ALBUM=\"$albumtag\" \\
              --tag=DATE=\"$year\" --tag=TRACKNUMBER=\"$riptrackno\" \\
              --tag=GENRE=\"$genre\" --tag=CATEGORY=\"$categ\" \\
              --tag=DESCRIPTION=\"$commentag\" --tag=CDID=\"$cddbid\" \\
              \"$riptrackname.wav\"";
            print "Flac $flacopt encoding track " .$ncount . " of " .
               ($#seltrack + 1) . " \@ compression $quaflac\n"
               if($verbose >= 2);
            log_info("new-mediafile: ${riptrackname}.flac");
            $sufix = "flac";
         }
         elsif($coder[$c] == 3) {
            if($ncount == 1) {
               $faacopt = $faacopt . " -q $quafaac"
                  if($quafaac ne "off");
            }
            $enc = "faac $faacopt -w --title \"$tracktag\" \\
              --artist \"$artist\" --album \"$album\" \\
              --year \"$year\" --genre \"$genre\" --track $riptrackno \\
              --comment \"$commentag\" \"$riptrackname.wav\" ";
            print "Faac $faacopt encoding track " . $ncount . " of " .
               ($#seltrack + 1) . " \@ quality $quafaac\n"
               if($verbose >= 2);
            log_info("new-mediafile: ${riptrackname}.m4a");
            $sufix = "m4a";
         }
         $sufix = "mp3" if($sufix eq "");
         # Set "last encoding of track" - flag.
         $delwav = 1 if($wav == 0 && $c == $#coder);
         # Set nice if wished.
         $enc="nice -n $nice ".$enc if($nice);
         print "Encoding \"$shortname\"...\n" if($verbose >= 1);
         # Make the output look nice, don't mess the messages!
         if($ripcomplete == 0 ) {
            if(-r "$outputdir/error.log") {
               open(ERR, "$outputdir/error.log")
                  or print "Can not open file error.log!\n";
               my @errlines = <ERR>;
               close ERR;
               my @ripcomplete = grep(/^The audio CD ripper reports: all done!$/, @errlines);
               $ripcomplete = 1 if(@ripcomplete);
            }
            print "\n" if($verbose >= 2);
         }
         # Finally, do the job of encoding, and a lot of cosmetics...
         if($sshflag == 1) {
            enc_ssh($delwav,$enc,$riptrackname,$shortname,$sufix);
         }
         else {
            if(log_system("$enc > /dev/null 2> /dev/null")) {
               if($ripcomplete == 0) {
                  if(-r "$outputdir/error.log") {
                     open(ERR, "$outputdir/error.log")
                     	or print "Can open file error.log!\n";
                     my @errlines = <ERR>;
                     close ERR;
                     my @ripcomplete = grep(/^The audio CD ripper reports: all done!$/, @errlines);
                     $ripcomplete = 1 if(@ripcomplete);
                  }
                  print "\n\n" if($verbose >= 2);
               }
               print "Encoding complete \"$shortname\"\n"
                  if($verbose >= 1);
               if($ripcomplete == 0) {
                  if(-r "$outputdir/error.log") {
                     open(ERR, "$outputdir/error.log")
                     	or print "Can not open file error.log!\n";
                     my @errlines = <ERR>;
                     close ERR;
                     my @ripcomplete = grep(/^The audio CD ripper reports: all done!$/, @errlines);
                     $ripcomplete = 1 if(@ripcomplete);
                  }
                  print "\n" if($verbose >= 2);
               }
            }
            else {
               print "Encoder failed on $tracklist[$_ - 1] in $cddev.",
                     "\nError message says: $?\n";
               if($multi == 1) {
                  # Print error message to file srXY.Z.txt, checktrack
                  # will grep for string "encoder failed" and kill the
                  # CD immediately!
                  open(SRTF,">>$logfile.$riptrackno.txt")
                     or print "Can not append to file ",
                              "\"$logfile.$riptrackno.txt\"!";
                  print SRTF "\nencoder failed on $tracklist[$_ - 1] ";
                  print SRTF "in device $cddev, error $? !";
                  close(SRTF);
                  # Create on the fly error message in log-directory.
                  open(ERO,">>$logpath/failed.log")
                     or print "Can not append to file ",
                              "\"$logpath/failed.log\"!";
                  print ERO "$artist;$album;$genre;$categ;$cddbid;";
                  print ERO "$logfile;$hostnam\n";
                  close(ERO);
                  # Wait to be terminated by checktrack.
                  sleep 360;
               }
            }
            sleep 1;
         }
      }
      my $endsec = `date \'+%s\'`;
      chomp $endsec;
      $totalencs = $totalencs + $endsec - $starts;
      if($delwav == 1 && $sshflag == 0) {
         unlink("$riptrackname.wav");
      }
   }
   # Ugly hack to tell the mother process the encoding time.
   open(ERR, ">>$outputdir/error.log")
      or print "Can not append to file error.log!\n";
   print ERR "Encoding needed $totalencs seconds!\n";
   close(ERR);
   exit ;
}
########################################################################
#
# Create the M3U file used by players such as X11Amp.
#
sub create_m3u {
   my ($file);
   my @mp3s = ();
   my $sufix = "";

   my $album = clean_all($cd{title});
   my $artist = clean_all($cd{artist});

   $file = "$artist" . " - " . "$album" . ".m3u";
   if($underscore == 1) {
      $file =~ s/ /_/g;
   }

   foreach (@coder) {
      opendir(DIR, $outputdir);
      @mp3s = readdir(DIR);
      closedir(DIR);

      if($_ == 1) {
         @mp3s = grep { /\.ogg$/i } @mp3s;
         $sufix = "ogg";
      }
      elsif($_ == 2) {
         @mp3s = grep { /\.flac$/i } @mp3s;
         $sufix = "flac";
      }
      else {
         @mp3s = grep { /\.mp3$/i } @mp3s;
         $sufix = "mp3";
      }
      @mp3s = sort {lc($a) cmp lc($b)} @mp3s;

      # Start writing to the playlist file:
      open(PLIST, ">$outputdir$file");
      print PLIST "#EXTM3U\n";
      #
      # Remember to write according to the trackselection, i.e.
      # don't write the names from first track on to the file!
      my $i = 0;
      foreach (@mp3s) {
         my $n = $seltrack[$i] - 1;
         $n = $seltrack[$i] if($hiddenflag == 1);
         # Use tags to write into m3u file, not filenames!
         if($tracktags[$n]) {
            print PLIST "#EXTINF:$secondlist[$n],$tracktags[$n]\n";
         }
         # Use filenames for m3u file only if no tags found!
         # This should not happen!
         else {
            my $riptrackname = get_trackname($seltrack[$i], $tracklist[$_ - 1]);
            my @shortname = split(/\// , $riptrackname);
            my $shortname = $shortname[$#shortname];
            $shortname =~ s/^\d\d[\s_]//;
            $shortname =~ s/_/ /g if($underscore == 1);
            print PLIST "#EXTINF:$secondlist[$n],$shortname\n";
         }
         print PLIST $outputdir, $_, "\n";
         $i++;
      }
      close(PLIST);
      if($#coder != 0){
         my $nfile = $file;
         $nfile =~ s/\.m3u/_$sufix\_\.m3u/;
         rename("$outputdir$file","$outputdir$nfile") ;
      }
   }
}
########################################################################
#
# Create a default or manual track list.
#
sub create_deftrack {
# Chose if you want to use default names or enter them manually.
# Do not ask if we come form CDDB submission, i.e. index == 0,
# or if $interaction == 0, then $index == 1.
   my ($i, $j, $index) = (0,1,@_);
   my ($album, $artist);

   my $tracks = substr($cddbid, 6);
   $tracks = hex($tracks);

   $album = clean_all($cd{title}) if(defined $cd{title});
   $artist = clean_all($cd{artist}) if(defined $cd{artist});

   # Preselect answer if no interaction whished.
   $index = 1 if($interaction == 0);

   while($index !~ /^[0-1]$/ ) {
      print "\nThis CD shall be labeled with:\n\n";
      print "1: Default Album, Artist and Tracknames\n\n";
      print "0: Manual input\n\nChoose [0-1]: (0) ";
      $index = <STDIN>;
      chomp $index;
      if($index eq "") {
         $index = 0;
      }
      print "\n";
   }
   # Create default tracklist and cd-hash.
   # NOTE: here we define an additional key: revision, which does not
   # exist if %cd is filled by CDDB_get. When this key exists, we know
   # that it is a new entry.
   if($index == 1) {
      $artist = "Unknown Artist";
      $album = "Unknown Album";
      %cd = (
         artist => $artist,
         title => $album,
         cat => $categ,
         genre => $genre,
         id => $cddbid,
         revision => 0,
         year => $year,
      );
      while($i < $tracks) {
         $j = $i + 1;
         $j = "0" . $j if($j < 10);
         $cd{track}[$i] = "Track " . "$j";
         ++$i;
      }
      $cddbsubmission = 0;
   }
   # Create manual tracklist.
   elsif($index == 0) {
      # In case of CDDB resubmission
      if(defined $cd{artist}) {
         print "\n   Artist ($artist): ";
      }
      # In case of manual CDDB entry.
      else {
         print "\n   Artist : ";
      }
      $artist = <STDIN>;
      chomp $artist;
      # If CDDB entry confirmed, take it.
      if(defined $cd{artist} && $artist eq "") {
         $artist = $cd{artist};
      }
      # If CDDB entry CHANGED, submission OK.
      elsif(defined $cd{artist} && $artist ne "") {
         $cddbsubmission = 1;
         $cd{artist} = $artist;
      }
      if($artist eq "") {
         $artist = "Unknown Artist";
         $cddbsubmission = 0;
      }
      if(defined $cd{title}) {
         print "\n   Album ($album): ";
      }
      else {
         print "\n   Album : ";
      }
      $album = <STDIN>;
      chomp $album;
      # If CDDB entry confirmed, take it.
      if(defined $cd{title} && $album eq "") {
         $album = $cd{title};
      }
      # If CDDB entry CHANGED, submission OK.
      elsif(defined $cd{title} && $album ne "") {
         $cddbsubmission = 1;
         $cd{title} = $album;
      }
      if($album eq "") {
         $album = "Unknown Album";
         $cddbsubmission = 0;
      }
      %cd = (
         artist => $artist,
         title => $album,
         cat => $categ,
         genre => $genre,
         id => $cddbid,
         revision => 0,
         year => $year,
      ) unless(defined $cd{title});
      print "\n";
      $i = 1;
      while($i <= $tracks) {
         if(defined $cd{track}[$i-1]) {
            printf("   Track %02d (%s): ", $i, $tracktags[$i-1]);
         }
         else {
            printf("   Track %02d: ", $i);
         }
         my $tracktag = <STDIN>;
         chomp $tracktag;
         $tracktag = clean_all($tracktag);
         my $track = clean_name($tracktag);
         $track = clean_chars($track) if($chars);
         $track = lower_case($_) if($lowercase == 1);
         $track =~ s/ /_/g if($underscore == 1);
         # If CDDB entry confirmed, take and replace it in tracklist.
         if(defined $cd{track}[$i-1] && $track ne "") {
            splice @tracklist, $i-1, 1, $track;
            splice @tracktags, $i-1, 1, $tracktag;
            $cddbsubmission = 1;
         }
         elsif(!$cd{track}[$i-1] && $track eq "") {

            $j = $i;
            $j = "0" . $j if($j < 10);
            $track = "Track " . "$j";
            $cddbsubmission = 0;
         }
         # Fill the "empty" array @{$cd{track}}.
         push @{$cd{track}}, "$track";
         $i++;
      }
   }
   else {
      die "You should choose 0 or 1!\n\n";
   }
}
########################################################################
#
# Read the CD and generate a TOC with DiscID, track frames and total
# length. Then prepare CDDB-submission with entries from @tracklist.
#
sub pre_subm {
   my($check,$i,$ans,$date,$genreno,$line,$oldcat,$subject) = (0,0);

   my $tracks = $#framelist;
   my $totals = int($framelist[$#framelist] / 75);

   my $album = clean_all($cd{title});
   my $artist = clean_all($cd{artist});

   my $revision = get_rev();
   if($revision) {
      # TODO: if submission fails, set revision back.
      $revision++;
   }
   elsif(defined $cd{revsision}) {
      $revision = $cd{revision};
   }
   else {
      $revision = 0;
   }

   # Check for CDDB ID vs CD ID problems.
   if($cddbid ne $cd{id} && defined $cd{id}) {
      print "\nObsolet warning: CDID ($cddbid) is not identical to ";
      print "CDDB entry ($cd{id})!";
      print "\nYou might get a collision error. Try anyway!\n";
      $revision = 0;
   }
   # Questioning to change CDDB entries and ask to fill missing fields.
   if(defined $cd{year} && $year ne "") {
      $year = get_answ("year",$year);
   }
   if(!$year) {
      while($year !~ /^\d{4}$| / || !$year ) {
      print "\nPlease enter the year (or none): ";
      $year = <STDIN>;
      chomp $year;
      $cd{year} = $year;
      last if(!$year);
      }
   }
   $cddbsubmission = 1 unless($year eq $cd{year});
   # Ask if CDDB category shall be changed and check if done;
   # $categ will be an empty string if user wants to change it.
   $oldcat = $categ;
   if(defined $cd{cat} && defined $categ) {
      $categ = get_answ("CDDB category",$categ);
   }

   my @categ = ();
   my @categories = (
      "blues",  "classical", "country", "data",
      "folk",   "jazz",      "misc",    "newage",
      "reggae", "rock",      "soundtrack"
   );
   if(!$categ && $submission != 0) {
      print "I check for available categories, please wait.";
      print "\n\nAvailable categories:\n";
      foreach $_ (@categories) {
         my $templines = "";
         my $source = "http://www.freedb.org/freedb/" . $_ . "/" . $cddbid;
         $templines = get $source;
         # Question: what is wrong that I need to put a \n the print
         # command to force perl to print right away, and not to print
         # the whole bunch only when the foreach-loop is done???
         if($templines) {
            push @categ, $_;
##            print "   $_ is used!\n"
         }
         else {
            print "   $_\n"
         }
      }
      if($categ[10]) {
         print "\nAll 11 categories are used, bad luck!";
         print "\nSave the file locally with --archive!\n";
         print "\nUse one of the following categories:";
         print "\nblues, classical, country, data, folk";
         print "\njazz, misc, newage, reggae, rock, soundtrack\n";
         $cddbsubmission = 0;
      }

      # Check if the $categ variable is correct.
      while($categ !~ /^blues$|^classical$|^country$|^data$|^folk$|^jazz$|^newage$|^reggae$|^rock$|^soundtrack$|^misc$/ ) {
         print "\nPlease choose one of the available CDDB categories: "
            if($categ[10]);
         print "\nPlease choose one of the categories: "
            unless($categ[10]);
         $categ = <STDIN>;
         chomp $categ;
      }
      $cddbsubmission = 1 unless($categ eq $cd{cat});
   }
   # If one changes catecory for a new submission, set Revision to 0.
   if($oldcat ne $categ && defined $cd{cat}){
      $revision = 0;
   }
   # Remind the user if genre is not ID3v2 compliant even if Lame is
   # not used! Reason: There should be no garbage genres in the DB.
   # If Lame is used, genre has already been checked!
   if($lameflag != 1 && defined $genre) {
      ($genre,$genreno) = check_genre($genre);
      $cddbsubmission = 1 unless($genre eq $cd{'genre'});
   }
   # Do not to ask if genre had been passed from command line.
   unless($pgenre) {
      $genre = get_answ("genre",$genre);
   }
   unless($genre) {
      print "\nPlease enter a valid CDDB genre (or none): ";
      $genre = <STDIN>;
      chomp $genre;
      $cd{genre} = $genre;
      # Allow to submit no genre! Else check it!
      if($genre ne "") {
         $genre =~ s/[\015]//g;
         ($genre,$genreno) = check_genre($genre);
      }
   }
   $cddbsubmission = 1 unless($genre eq $cd{'genre'});
   my $dtitle = $artist . " / " . $album;
   substr($dtitle, 230, 0, "\nDTITLE=") if(length($dtitle) > 250);
   substr($dtitle, 460, 0, "\nDTITLE=") if(length($dtitle) > 500);

   # Start writing the CDDB submission.
   open(TOC, ">$homedir/cddb.toc")
      or die "Can not write to cddb.toc $!\n";
   print TOC "# xmcd CD database generated by RipIT\n";
   print TOC "#\n";
   print TOC "# Track frame offsets:\n";
   $i = 0;
   foreach (@framelist) {
      print TOC "# $_\n" if($i < $#framelist);
      $i++;
   }
   print TOC "#\n";
   print TOC "# Disc length: $totals seconds\n";
   print TOC "#\n";
   print TOC "# Revision: $revision\n";
   $date = `date`;
   chomp $date;
   print TOC "# Submitted via: RipIT $version ";
   print TOC "www.suwald.com/ripit/ripit.html at $date\n";
   print TOC "#\n";
   print TOC "DISCID=$cddbid\n";
   print TOC "DTITLE=$dtitle\n";
   print TOC "DYEAR=$year\n";
   if(defined $genre){
      print TOC "DGENRE=$genre\n";
   }
   elsif($genre eq "" && defined $categ) {
      print TOC "DGENRE=$categ\n";
   }
   $i = 0;
   foreach (@tracktags) {
      substr($_, 230, 0, "\nTTITLE$i=") if(length($_) > 250);
      substr($_, 460, 0, "\nTTITLE$i=") if(length($_) > 500);
      print TOC "TTITLE$i=$_\n";
      ++$i;
   }
   my @comment = extract_comm;
   my $commentest = "@comment";
   if($commentest) {
      $ans = "x";
      $check = 0;
      print "Confirm (Enter), delete or edit each comment line ";
      print "(c/d/e)!\n";
      foreach (@comment) {
         while($ans !~ /^c|^d|^e/) {
            print "$_ (c/d/e): ";
            $ans = <STDIN>;
            chomp $ans;
            if($ans eq "") {
               $ans = "c";
            }
         }
         if($ans =~ /^c/ || $ans eq "") {
            print TOC "EXTD=$_\\n\n";
            $check = 1;
         }
         elsif($ans =~ /^e/) {
            print "Enter a different line: \n";
            my $ans = <STDIN>;
            chomp $ans;
            substr($ans, 230, 0, "\nEXTD=") if(length($ans) > 250);
            substr($ans, 460, 0, "\nEXTD=") if(length($ans) > 500);
            print TOC "EXTD=$ans\\n\n";
            $cddbsubmission = 1;
            $check = 1;
         }
         else {
            # Don't print the line.
            $cddbsubmission = 1;
         }
         $ans = "x";
      }
      $line = "a";
      while(defined $line) {
         print "Do you want to add a line? (Enter for none or type!): ";
         $line = <STDIN>;
         chomp $line;
         $cddbsubmission = 1 if($line ne "");
         last if(!$line);
         substr($line, 230, 0, "\nEXTD=") if(length($line) > 250);
         substr($line, 460, 0, "\nEXTD=") if(length($line) > 500);
         print TOC "EXTD=$line\\n\n";
         $check = 1;
      }
      # If all lines have been deleted, add an empty EXTD line!
      if($check == 0){
         print TOC "EXTD=\n";
      }
   }
   # If there are no comments, ask to add some.
   elsif(!$comment[0]) {
      $line = "a";
      my $linecn = 0;
      while(defined $line) {
         print "Please enter a comment line (or none): ";
         $line = <STDIN>;
         chomp $line;
         $cddbsubmission = 1 if($line ne "");
         substr($line, 230, 0, "\nEXTD=") if(length($line) > 250);
         substr($line, 460, 0, "\nEXTD=") if(length($line) > 500);
         print TOC "EXTD=$line\n" if($linecn == 0);
         print TOC "EXTD=\\n$line\n" if($linecn != 0);
         $linecn++;
         # This line has to be written, so break the
         # while loop here and not before, as above.
         last if(!$line);
      }
   }
   else {
      print TOC "EXTD=\n";
   }

   # Extract the track comment lines EXTT.
   my @trackcom = grep(/^EXTT\d+=/, @{$cd{raw}});
   @trackcom = grep(s/^EXTT\d+=//, @trackcom);
   foreach (@trackcom) {
      chomp $_;
      $_ =~ s/[\015]//g;
   }
   $ans = get_answ('Track comment','existing ones');
   if($ans eq "") {
      $i = 0;
      while($i < $tracks) {
         my $track;
         if($trackcom[$i]) {
            printf("   Track comment %02d (%s):", $i+1, $trackcom[$i]);
         }
         else {
            printf("   Track comment %02d: ", $i+1);
         }
         $track = <STDIN>;
         chomp $track;
         substr($track, 230, 0, "\nEXTT$i=") if(length($track) > 250);
         substr($track, 460, 0, "\nEXTT$i=") if(length($track) > 500);

         # If CDDB entry confirmed, take and replace it in tracklist.
         if(defined $trackcom[$i] && $track eq "") {
            print TOC "EXTT$i=$trackcom[$i]\n";
         }
         elsif(defined $trackcom[$i] && $track ne "") {
            print TOC "EXTT$i=$track\n";
            $cddbsubmission = 1;
         }
         elsif($track ne "") {
            print TOC "EXTT$i=$track\n";
            $cddbsubmission = 1;
         }
         else {
            print TOC "EXTT$i=\n";
         }
         $i++;
      }
   }
   elsif(@trackcom) {
      $i = 0;
      foreach (@tracklist) {
         print TOC "EXTT$i=$trackcom[$i]\n";
         ++$i;
      }
   }
   else {
      $i = 0;
      foreach (@tracklist) {
         print TOC "EXTT$i=\n";
         ++$i;
      }
   }

   # Extract the playorder line.
   my @playorder = grep(/^PLAYORDER=/, @{$cd{raw}});
   @playorder = grep(s/^PLAYORDER=//, @playorder);
   if(@playorder) {
      my $playorder = $playorder[0];
      chomp $playorder;
      print TOC "PLAYORDER=$playorder\n";
   }
   else {
      print TOC "PLAYORDER=\n";
   }
   close(TOC);
   # Copy the *edited* CDDB file if variable set to the ~/.cddb/
   # directory.
   if($archive == 1 && $cddbsubmission != 2) {
      log_system("mkdir -m 0777 -p \"$homedir/.cddb/$categ\"")
         or die "Can not create directory \"$homedir/.cddb/$categ\": $!\n";
      log_system("cp \"$homedir/cddb.toc\" \"$homedir/.cddb/$categ/$cddbid\"")
         or die "Can not copy cddb.toc to directory \"$homedir/.cddb/$categ/$cddbid\": $!";
      print "Saved file $cddbid in \"$homedir/.cddb/$categ/\"";
   }
   print "\n";
   # Don't send mail if nail command unknown or not connected to
   # the internet.
   unless(log_system("nail -V")) {
      print "nail (mail) not installed?\n";
      $cddbsubmission = 0;
   }
   # If no connection to the internet do not submit.
   if($submission == 0) {
      $cddbsubmission = 0;
   }
   if($cddbsubmission == 1) {
      my $ans = "x";
      while($ans !~ /^y$|^n$/) {
         print "Do you really want to submit your data? [y/n] (y) ";
         $ans = <STDIN>;
         chomp $ans;
         if($ans eq ""){
            $ans = "y";
         }
      }
      if($ans =~ /^y/){
         $cddbsubmission = 1;
      }
      else{
         $cddbsubmission = 0;
      }
   }
   if($cddbsubmission == 1) {
      while($mailad !~ /.@.+[.]./) {
         print "\nReady for submission, enter a valid return ";
         print "e-mail address: ";
         $mailad = <STDIN>;
         chomp $mailad;
      }
      $subject = "cddb " . $categ . " " . $cddbid;
      open TOC, "cat \"$homedir/cddb.toc\" |"
         or die "Can not open file cddb.toc $!\n";
      # For testing use this e-mail address.
#      open MAIL, "|nail -r $mailad -s \"$subject\" test-submit\@freedb.org"
      open MAIL, "|nail -r $mailad -s \"$subject\" freedb-submit\@freedb.org"
         or die "nail not installed? $!";
      my @lines = <TOC>;
      foreach (@lines) {
         print MAIL "$_";
      }
      close MAIL;
      die "Mail exit status not zero: $?" if($?);
      close TOC;
      print "CDDB entry submitted.\n\n";
      unlink("$homedir/cddb.toc");
   }
   elsif($cddbsubmission == 2) {
      print "\n CDDB entry created and saved in \$HOME, but not send, ";
      print "because no changes";
      print "\n were made! Please edit and send it manually to ";
      print "freedb-submit\@freedb.org";
      print "\n with subject: cddb $categ $cddbid\n\n";
      sleep (4);
   }
   else {
      print "\n CDDB entry saved in your home directory, but not send,";
      print "\n please edit it and send it manually to:";
      print "\n freedb-submit\@freedb.org with subject:";
      print "\n cddb $categ $cddbid\n\n";
   }
}
########################################################################
#
# Check if genre is correct.
#
sub check_genre {
   my $genre = $_[0];
   my $genreno = "";
   my $genrenoflag = 1;

   $genre = "  " if ($genre eq "");

   # If Lame is not used, don't die if ID3v2-tag is not compliant.
   if($lameflag == 0) {
      unless(log_system("lame --genre-list | grep -i \" $genre\$\" > /dev/null ")) {
         print "Genre $genre is not ID3v2 compliant!\n"
            if($verbose >= 1);
         print "I continue anyway!\n\n" if($verbose >= 1);
         $genreno = "not ID3v2 compliant!\n";
         chomp $genreno;
      }
      return;
   }

   # Check if (similar) genre exists. Enter a new one with interaction,
   # or take the default one.
   while(!log_system("lame --genre-list | grep -i \"$genre\" > /dev/null ")) {
      print "Genre $genre is not ID3v2 compliant!\n" if($verbose >= 1);
      if($interaction == 1) {
         print "Use \"lame --genre-list\" to get a list!\n";
         print "\nPlease enter a valid CDDB genre (or none): ";
         $genre = <STDIN>;
         chomp $genre;
         $cd{genre} = $genre;
      }
      else {
         print "Genre \"Other\" will be used instead!\n"
            if($verbose >= 1);
         $genre = "12 Other";
      }
   }

   if($genre eq "") {
      return;
   }
   else {
      # First we want to be sure that the genre from the DB, which might
      # be "wrong", e.g. wave (instead of Darkwave or New Wave) or synth
      # instead of Synthpop, will be correct. Put the DB genre to ogenre
      # and get a new right-spelled genre... Note, we might get several
      # possibilites, e.g. genre is Pop, then we get a bunch of
      # "pop-like" genres!
      # There will be a linebreak, if multiple possibilities found.
      my $ogenre = $genre;
      $genre = `lame --genre-list | grep -i \'$genre\'`;
      chomp $genre;
      # Second we want THE original genre, if it precisly exists.
      my $testgenre = `lame --genre-list | grep -i \'\^... $ogenre\$\'`;
      chomp $testgenre;
      $genre = $testgenre if($testgenre);
      # If we still have several genres:
      # Either let the operator choose, or if no interaction, take
      # default genre: "12 Other".
      if($genre =~ /\n/ && $interaction == 1) {
         print "More than one genre possibility found!\n";
         my @list = split(/\n/,$genre);
         my ($i,$j) = (0,1);
         while($i > $#list+1 || $i == 0) {
            # TODO: Here we should add the possibility to choose none!
            # Or perhaps to go back and choose something completely
            # different.
            foreach (@list) {
               printf(" %2d: $_ \n",$j);
               $j++;
            }
            $j--;
            print "\nChoose [1-$j]: ";
            $i = <STDIN>;
            chomp $i;
            $j = 1;
         }
         $genre = $list[$i-1];
         chomp $genre;
      }
      # OK, no interaction! Take the default genre!
      elsif($genre =~ /\n/ && $interaction != 1 && $lameflag == 1) {
         $genre = "12 Other" if($genre eq "");
      }
      # OK, the genre is not Lame compliant, and we do not care about,
      # because Lame is not used. Set the genre-number-flag to 0 to
      # prevent genre-number-extracting at the end of the subroutine.
      elsif($lameflag != 1) {
         $genre = $ogenre;
         $genrenoflag = 0;
      }
      chomp $genre;
   }

   # Extract genre-number.
   if($genre ne "" && $genrenoflag == 1){
      $genre =~ s/^\s*//;
      my @genre = split(/ /, $genre);
      $genreno = shift(@genre);
      $genre = "@genre";
   }

   return ($genre,$genreno);
}
########################################################################
#
# Check mirrors
#
sub check_host {
   while($mirror !~ /^freedb$|^at$|^au$|^ca$|^es$|^fi$|^fr$|^jp$|^jp2$|^ru$|^uk$|^uk2$|^us$/){
      print "host mirror ($mirror) not valid!\n";
      print "enter freedb, at, au, ca, es, fi, fr, jp, jp2, ru, uk, uk2 or us: ";
      $mirror = <STDIN>;
      chomp $mirror;
   }
}
########################################################################
#
# Reply to question
#
sub get_answ {
   my $ans = "x";
   while($ans !~ /^y|^n/) {
      print "Do you want to enter a different ".$_[0]." than ".$_[1];
      print "? [y/n], (n): ";
      $ans = <STDIN>;
      chomp $ans;
      if($ans eq ""){
         $ans = "n";
      }
   }
   if($ans =~ /^y/){
      return "";
   }
   return $_[1];
}
########################################################################
#
# Check quality passed from command line for oggenc, flac and lame only
# if vbr wanted (then it's encoder no 3).
#
sub check_quality {
   my $corrflag = 0;
   if($qualame ne "off") {
      while($qualame > 9) {
         print "\nThe quality $qualame is not valid for Lame!\n";
         print "Please enter a different quality (0 = best), [0-9]: ";
         $qualame = <STDIN>;
         chomp $qualame;
         $corrflag = 1;
      }
   }
   if($qualoggenc ne "off") {
      while($qualoggenc > 10 || $qualoggenc == 0) {
         print "\nThe quality $qualoggenc is not valid for Ogg!\n";
         print "Please enter a different quality (10 = best), [1-10]: ";
         $qualoggenc = <STDIN>;
         chomp $qualoggenc;
         $corrflag = 1;
      }
   }
   if($quaflac ne "off") {
      while($quaflac > 8) {
         print "\nThe compression level $quaflac is not valid";
         print " for Flac!\n";
         print "Please enter a different compression level ";
         print "(0 = lowest), [0-8]: ";
         $quaflac = <STDIN>;
         chomp $quaflac;
         $corrflag = 1;
      }
   }
   if($quafaac ne "off") {
      while($quafaac > 500 || $quafaac < 10) {
         print "\nThe quality $quafaac is not valid for Faac!\n";
         print "Please enter a different quality (500 = max), ";
         print "[10-500]: ";
         $quafaac = <STDIN>;
         chomp $quafaac;
         $corrflag = 1;
      }
   }
   # Save the corrected values to the pquality array! Do it in
   # the same order the encoders had been passed! If no encoders
   # were passed, test if there are encoders in the config file...
   if($corrflag == 1) {
      @pquality = split(/,/, join(',', @pquality));
      for(my $index = 0; $index <= $#pquality; $index++) {
         if($coder[$index] =~ /^\d/) {
            $pquality[$index] = $qualame if($coder[$index] == 0);
            $pquality[$index] = $qualoggenc if($coder[$index] == 1);
            $pquality[$index] = $quaflac if($coder[$index] == 2);
            $pquality[$index] = $quafaac if($coder[$index] == 3);
         }
         else {
            $pquality[$index] = $qualame if($index == 0);
            $pquality[$index] = $qualoggenc if($index == 1);
            $pquality[$index] = $quaflac if($index == 2);
            $pquality[$index] = $quafaac if($index == 3);
         }
      }
      my $pquality = join(',',@pquality);
      @pquality = ();
      $pquality[0] = $pquality;
   }
}
########################################################################
#
# Check bitrate for Lame only if vbr is wanted.
#
sub check_vbrmode {
   while($vbrmode ne "new" && $vbrmode ne "old") {
      print "\nFor vbr using Lame choose *new* or *old*! (new): ";
      $vbrmode = <STDIN>;
      chomp $vbrmode;
      $vbrmode = "new" if ($vbrmode eq "");
   }
}
########################################################################
#
# Check preset for Lame only.
#
sub lame_preset {
   if($vbrmode eq "new") {
      $preset = "fast " . $preset;
   }
}
########################################################################
#
# Check if there is an other than $cddev which has a CD if no --device
# option was given.
#
sub check_cddev {
   # Try to get a list of possible CD devices.
   open(DEV, "/etc/fstab");
   my @dev = <DEV>;
   close DEV;
   @dev = grep(/^\s*\/dev/, @dev);
   @dev = grep(!/^\s*\/dev\/[f|h]d/, @dev);
   @dev = grep(!/sd/, @dev);
   my @devlist = ();
   foreach (@dev) {
      my @line = split(/\s/, $_);
      chomp $line[0];
      push(@devlist, $line[0]);
   }
   # First check the default address.
   if(open(CD, "$cddev")) {
      $cddev = $cddev;
      close CD;
   }
   else {
      foreach (@devlist) {
         if(open(CD, "$_")) {
            $cddev = $_;
            chomp $cddev;
            close CD;
         }
      }
   }
   # On a notebook, the tray could not be closed automatically!
   # Print error message and retry detection.
   if($cddev eq "") {
      print "Is there a CD and the tray of the device closed?\n";
      print "I pause 12 seconds.\n";
      sleep(12);
      foreach (@devlist) {
         if(open(CD, "$_")) {
            $cddev = $_;
            chomp $cddev;
            close CD;
         }
      }
   }
   if($cddev eq ""){
      print "Could not detect CD device! The default /dev/cdrom ";
      print "device will be used.\n";
      $cddev = "/dev/cdrom";
   }
}
########################################################################
#
# Check bitrate if bitrate is not zero.
#
sub check_bitrate {
   while($bitrate !~ /^32$|^40$|^48$|^56$|^64$|^80$|^96$|^112$|^128$|^160$|^192$|^224$|^256$|^320$|^off$/) {
      print "\nBitrate should be one of the following numbers or ";
      print "\"off\"! Please Enter";
      print "\n32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, ";
      print "256 or 320: (128) \n";
      $bitrate = <STDIN>;
      chomp $bitrate;
      if($bitrate eq "") {
         $bitrate = 128;
      }
   }
}
########################################################################
#
# Check protocol level for CDDB query.
#
sub check_proto {
   while($proto > 6) {
      print "Protocol level for CDDB query should be less-equal 6!\n";
      print "Enter an other value for protocol level (6): ";
      $proto =  <STDIN>;
      chomp $proto;
      $proto = 6 if($proto eq "");
   }
}
########################################################################
#
# Check, clean and sort the coder array, and then, according to, the
# qualities.
#
sub check_coder {
   my $lameindex;

   # Create encoder array if passed or read from config file.
   if(@pcoder) {
      @coder = split(/,/, join(',',@pcoder));
   }
   else {
      @coder = split /,/, join(',', @coder);
   }
   # Now check if an encoder was passed several times.
   my @scoder = sort {$a <=> $b} @coder;
   my $index = 0;
   while($index < $#scoder) {
      if($scoder[$index] == $scoder[$index+1]) {
         # TODO delete entry if encoder appears more than once.
#			splice @coder,$index,1;
         die "Found encoder $scoder[$index] twice, confused!\n";
      }
      $index++;
   }
   # Now check, that there is no entry >= 4, find the index
   # of lame if present and calculate the number of encoders
   # that need a quality entry.
   my $nofcoders=0;
   for(my $index = 0; $index <= $#coder; $index++) {
      if($coder[$index] >= 4) {
         print "Encoder number $coder[$index] does not yet exist, ";
         print "please enter\n";
         die "0 for Lame, 1 for Oggenc, 2 for Flac and 3 for Faac!\n\n";
      }
      $nofcoders++;
      if($coder[$index] == 0 || $coder[$index] >= 4) {
         $lameindex = $index;
         $nofcoders = $nofcoders - 1;
         $lameflag = 1;
      }
   }
   # Use comma separated string to write the encoder array to the
   # config file!
   $wcoder = join(',',@coder);
   $nofcoders=$nofcoders-1;
   # Order the qualities (if passed) in the same way as coders!
   # Note, the array of coders is NOT sorted!
   # First, check if there is a config file with an probably unusual
   # order of encoders. In this way, the check-quality subroutine
   # will ask the correct questions and not mess up the encoders!
   my $openflag="no";
   if(!@pcoder && -r "$homedir/.ripit/config") {
      open(CONF, "$homedir/.ripit/config");
      my @conflines = <CONF>;
      close CONF;
      @pcoder = grep(s/^coder=//, @conflines) unless(@pcoder);
      chomp @pcoder;
      if($pcoder[0] =~ /^\d/) {
         @coder = split(/,/, join(',',@pcoder));
      }
   }
   # Second, check if quality was passed.
   if(@pquality) {
      @quality = split(/,/, join(',', @pquality));
      # If lame was passed, but no quality for lame (because
      # user wants cbr), then add the default quality for lame
      # at the right place of array @quality to ensure that the
      # check_quality() subroutine works! NOTE: $nofcoder is
      # the number of non-lame encoders!
      if($#quality == $nofcoders && $lameflag == 1) {
         splice @quality, $lameindex, 0, 5;
      }
      for(my $index = 0; $index <= $#quality; $index++) {
         if($coder[$index] =~ /^\d/) {
            $qualame = $quality[$index] if($coder[$index] == 0);
            $qualoggenc = $quality[$index] if($coder[$index] == 1);
            $quaflac = $quality[$index] if($coder[$index] == 2);
            $quafaac = $quality[$index] if($coder[$index] == 3);
         }
         else {
            $qualame = $quality[$index] if($index == 0);
            $qualoggenc = $quality[$index] if($index == 1);
            $quaflac = $quality[$index] if($index == 2);
            $quafaac = $quality[$index] if($index == 3);
         }
      }
   }
}
########################################################################
#
# Over or re-write the config file (depends on option savenew or save).
#
sub save_config {
   log_system("mkdir -m 0777 -p $homedir/.ripit")
      or die "Can not create directory $homedir/.ripit/config: $!\n";
   my $ripdir = $homedir . "/.ripit";
   rename("$ripdir/config","$ripdir/config.old")
      if(-r "$ripdir/config");
   open(CONF, "> $ripdir/config")
      or die "Can not write to $homedir/.ripit/config: $!\n";
   print CONF "
#####
#
# RipIT $version configuration file.
#
# For further information on ripit
# configuration / parameters and examples see
# the manpage or type ripit --help
# or the README provided with ripit.


#####
#
# Ripping device & path.
#

# cddevice: Define ripping device
# if other than /dev/cdrom
# Default: /dev/cdrom

cddevice=$cddev

# output: Path for audio files
# Default: not set

output=$outputdir

#####
#
# Ripping options.
#

# ripper: Selects CD ripper
# 0 - dagrab
# 1 - cdparanoia
# 2 - cdda2wav
# 3 - tosha
# 4 - cdd
# Default: cdparanoia

ripper=$ripper

# ripopt: User definable options for the CD ripper
# Default: not set

ripopt=$ripopt

# paranoia: Turn \"paranoia\" on or off for dagrab
# and cdparanoia
# Possible values: 0 - off, 1 - on
# Default: on

paranoia=$parano

#####
#
# Encoding options
#

# Encode the wavs
# Possible values: 0 - off, 1 - on
# Default: on

encode=$encode

# coder: Select encoders for audio files
# 0 - Lame (mp3)
# 1 - Oggenc (ogg)
# 2 - Flac (flac)
# 3 - Faac (m4a)
# Multiple encoders can be selected by giving
# a comma-seperated list
# Example: coder=0,1,2 encodes CD to mp3, ogg and flac files
# Default: Lame

coder=$wcoder

###
#
# lame (mp3) encoder options
#

# qualame: Sets audio quality for lame encoder
# in vbr (variable bitrate) mode
# Possible values: 0...9
# 0: higest quality
# 9: lowest quality
# Default: 5

qualame=$qualame

# lameopt: Additional options for lame encoder
# Default: not set

lameopt=$lameopt

# vbrmode: Enable varibale bitrate for lame encoder
# Values: \"old\" or \"new\"
# Default: not set

vbrmode=$vbrmode

# bitrate: Sets bitrate for lame encoder
# Possible values: 32...320, off
# Should be set to \"off\" if vbr is used
# Default: 128

bitrate=$bitrate

# maxrate: Sets maximum bitrate for lame (when using vbr)
# and ogeenc
# Possible values: 0 - off, 32...320
# Default: 0

maxrate=$maxrate

# preset: Use lame presets
# To set the \"fast\" switch, use --vbrmode new.
# Possible values: medium, standard, extreme, insane
#
# medium: 160kbps
# standard: 192kbps
# extreme: 256kbps
# insane: 320kbps
# Default: not set

preset=$wpreset

###
#
#  oggenc (ogg) encoder options
#

# qualoggenc: Sets audio quality for oggenc
# Possible values: 1..10
# 1: lowest quality
# 10: highest quality
# Default: 3

qualoggenc=$qualoggenc

# oggencopt: Additional options for oggenc
# Default: not set

oggencopt=$oggencopt

###
#
# flac (lossless) encoder options
#

# quaflac: Sets audio quality for flac encoder
# Possible values: 0...8
# 0: highest quality
# 8: lowest quality
# Default: 5

quaflac=$quaflac

# flacopt: Additional options for flac encoder
# Default: not set

flacopt=$flacopt

###
#
# faac (m4a) encoder options
#

# quafaac: Sets audio quality for faac encoder
# Possible values: 10...500
# 500: highest quality
# 10: lowest quality
# Default: 100

quafaac=$quafaac

# faacopt: Additional options for faac encoder
# Default: not set

faacopt=$faacopt

#####
#
# Trackname and directory template
#

# dirtemplate: Template for directory structure
# The template can be created using the following
# variables (tags)
# \$album
# \$artist
# \$genre
# \$trackname
# \$tracknum
# \$year
# Example: \"\$artist - \$year\"
# The double quotes (\") are mandatory!
# Default: \"\$artist - \$album\"

dirtemplate=$dirtemplate

# tracktemplate: Template for track names
# \"tracktemplate\" is used similarly to \"dirtemplate\"
# Default:  \"\$tracknum \$trackname\"

tracktemplate=$tracktemplate

# infolog: Log certain operations to file
# (e.g. system calls, creation of dirs/files)
# Possible values: filename (full path, no ~ here!)
# Default: not set

infolog=$infolog

# lowercase: Convert filenames to lowercase
# Possible values: 0 - off, 1 - on
# Default: off

lowercase=$lowercase

# underscore: Replace blanks in filenames with undersocres
# Possible values: 0 - off, 1 - on
# Default: off

underscore=$underscore

# chars: Exclude special characters and (ending!) periods
# in file names. If no argument passed to option, then
# following characters will be purged:   :*#?\$\!   and
# (ending) periods deleted. Else only the passed ones
# will be erased, and (ending) periods. No need to escape
# the special characters here, if one enters them manually.
# Possible values: none, any (?)
# Default: off

chars=$chars

# playlist: Create m3u playlist
# Possible values: 0 - off, 1 - on
# Default: on

playlist=$playlist

#####
#
# Audio file tagging
#

# year-tag: State a year (mp3, m4a) or a date (ogg, flac) tag.
# Default: not set

year=$year

# comment-tag: State a comment (mp3, m4a) or a
# description (ogg, flac) tag.
# Default: not set

comment=$commentag

# utftag: Use Lame-tags in UTF-8 or convert them
# (but not the filenames) from Unicode to ISO8859-1.
# Use when your mp3-audio player doesn't support Unicode tags.
# Recommended with Lame.
# Possible values: 0 - off, 1 - on
# Default: on

utftag=$utftag

#####
#
# CDDB options
#

# CDDBHOST: Specifies the CDDB server
# Note: Full name of the server used is \$mirror.\$CDDBHOST
# E.g., default server is freedb.freedb.org
# Default: freedb.org

CDDBHOST=$CDDB_HOST

# mirror: Selects freedb mirror
# Possible values: \"freedb\" or any freedb mirrors
# See www.freedb.org for mirror list
# Note: Full name of the server used is \$mirror.\$CDDBHOST
# E.g., default server is freedb.freedb.org
# Default: freedb

mirror=$mirror

# trasfer: Set transfer mode for cddb queries
# Possible values: cddb, http
# Default: http

transfer=$transfer

# proto: Set CDDP protocol level
# Possible values: 5,6
# Protocol level 6 supports Unicode (UTF-8)
# Default: 6

proto=$proto

# proxy: Address of http-proxy, if needed
# Default: not set

proxy=$proxy

# mailad: Mail address for cddb submissions
# Valid user email address for submitting cddb entries
# Default: not set

mailad=$mailad

# archive: Read and save cddb data on local machine
# Possible values: 0 - off, 1 - on
# Default: off

archive=$archive

# submission: Submit new or edited cddb entries to
# freeCDDB
# Possible values: 0 - off, 1 - on
# Default: on

submission=$submission

# interaction: Turns on or off user interaction in cddb dialog
# Possible values: 0 - off, 1 - on
# Default: on

interaction=$interaction

#####
#
# LCD options
#

# lcd: Use lcdproc to display status on LCD
# Possible values: 0 - off, 1 - on
# Default: not set

lcd=$lcd

# lcdhost: Specify the lcdproc host
# Default: localhost

lcdhost=$lcdhost

# lcdport: Specify port number for $lcdhost
# Default: 13666

lcdport=$lcdport

#####
#
# Distributed ripping options
#

# sshlist: Comma seperated list of remote machines
# that ripit shall use for encoding
# The output path must be the same for all machines.
# Specify the login (login\@machine) only if not the
# same for the remote machine. Else just state the
# machine names.
# Default: not set

sshlist=$wsshlist

# scp: Copy files to encode to the remote machine
# Use if the fs can not be accessed on the remote machines
# Possible values: 0 - off, 1 - on
# Default: off

scp=$scp

# local: Turn off encoding on local machine,
# e.g. use only remote machines
# Possible values: 0 - off, 1 - on
# Example: local=0 (off) turns off encoding on the
# local machine
# Default: on

local=$local

#####
#
# Misc. options
#

# verbosity: Run silent (do not output comments, status etc.)
# or normal or be very verbose.
# Possible values: 0 - off, 1 - minimal, 2 - normal,
# 3 - be very verbose
# Default: normal

verbose=$verbose

# eject: Eject cd after finishing encoding
# Possible values: 0 - off, 1 - on
# Default: off

eject=$eject

# loop: Continue as soon a new CD is inserted,
# implies that the CD is ejected when done!
# Possible values: 0 - off, 1 - on
# Default: off

loop=$loop

# halt: Powers off machine after finishing encoding
# Possible values: 0 - off, 1 - on
# Default: off

halt=$halt

# nice: Sets \"nice\" value for the encoding process
# Possible values: 0..19 for normal users,
#                  -20..19 for user \"root\"
# Default: 0

nice=$nice

# wav: Don't delete wave-files after encoding
# Possible values: 0 - off, 1 - on
# Default: off

wav=$wav

# normalize: Normalizes the wave-files to a given dB-value
# (Default: -12dB)
# See http://normalize.nongnu.org for details
# Possible values: 0 - off, 1 - on
# Default: off

normalize=$normalize

# normopt: Options to pass to normalize
# Possible values: -a -nndB   : Normalize to -nn dB, default is -12dB,
#                  Value range: All values <= 0dB
#                  Example    : normalize -a -20dB *.wav
#                  -b         : Batch mode - loudness differences
#                               between individual tracks of a CD are
#                               maintained
#                  -m         : Mix mode - all track are normalized to
#                               the same loudness
#                  -v         : Verbose operation
#                  -q         : Quiet operation
# For further options see normalize documentation.
# Default: -bv

normopt=$normopt

# cdtoc: Create a toc (cue) file to burn the wavs with
# cd-text using cdrdao or cdrecord (in dao mode)
# Possible values: 0 - off, 1 - on
# Default: off

cdtoc=$cdtoc
\n";
   close CONF;
}
########################################################################
#
# Read the config file, take the parameters only if NOT yet defined!
#
sub read_config {
   my $ripdir = $homedir."/.ripit/config";
   if(-r "$ripdir" ) {
      open(CONF, "$ripdir") || print "Can not read config file!\n";
      my @conflines = <CONF>;
      close CONF;
      my @confver = grep(s/^# RipIT //, @conflines);
      @confver = split(/ /, $confver[0]) if($confver[0] =~ /^\d/);
      my $confver = $confver[0] if($confver[0] =~ /^\d/);
      chomp $confver;
      if($version ne $confver && $savepara == 0) {
         $verbose = 2;
         print "\nPlease update your config-file with option --save";
         print "\nto ensure correct settings! I pause 3 seconds!\n\n";
         grep(s/^chars=[01]\s*$/chars=/, @conflines);
         sleep(3);
      }
      elsif($version ne $confver) {
         grep(s/^chars=[01]\s*$/chars=/, @conflines);
      }
      my @archive = grep(s/^archive=//, @conflines);
      $archive = $archive[0] unless defined $parchive;
      chomp $archive;
      my @bitrate = grep(s/^bitrate=//, @conflines);
      $bitrate = $bitrate[0] unless($pbitrate);
      chomp $bitrate;
      my @maxrate = grep(s/^maxrate=//, @conflines);
      $maxrate = $maxrate[0] unless($pmaxrate);
      chomp $maxrate;
      my @cddev = grep(s/^cddevice=//, @conflines);
      $cddev = $cddev[0] unless($pcddev);
      chomp $cddev;
      my @cdtoc = grep(s/^cdtoc=//, @conflines);
      $cdtoc = $cdtoc[0] unless($pcdtoc);
      chomp $cdtoc;
      my @chars = grep(s/^chars=//, @conflines) if($chars eq "xxx");
      $chars = $chars[0] if($chars[0]);
      chomp $chars;
      my @commentag = grep(s/^comment=//, @conflines);
      $commentag = $commentag[0] unless($pcommentag);
      chomp $commentag;
      my @CDDB_HOST = grep(s/^CDDBHOST=//, @conflines);
      $CDDB_HOST = $CDDB_HOST[0] unless($PCDDB_HOST);
      chomp $CDDB_HOST;
      @pcoder = grep(s/^coder=//, @conflines) unless(@pcoder);
      # NOTE: all coders are in array entry $pcoder[0]!
      # NOTE: we have to fill the w_RITE_coder variable!
      $wcoder = $pcoder[0] if(@pcoder);
      chomp $wcoder;
      my @dirtemplate = grep(s/^dirtemplate=//, @conflines);
      $dirtemplate = $dirtemplate[0] unless($pdirtemplate);
      chomp $dirtemplate;
      my @eject = grep(s/^eject=//, @conflines);
      $eject = $eject[0] unless defined $peject;
      chomp $eject;
      my @encode = grep(s/^encode=//, @conflines);
      $encode = $encode[0] unless defined $pencode;
      chomp $encode;
      my @halt = grep(s/^halt=//, @conflines);
      $halt = $halt[0] unless($phalt);
      chomp $halt;
      my @infolog = grep(s/^infolog=//, @conflines);
      $infolog = $infolog[0] unless($pinfolog);
      chomp $infolog;
      my @interaction = grep(s/^interaction=//, @conflines);
      $interaction = $interaction[0] unless defined $pinteraction;
      chomp $interaction;
      my @lcd = grep(s/^lcd=//, @conflines);
      $lcd = $lcd[0] unless defined $plcd;
      chomp $lcd;
      my @lcdhost = grep(s/^lcdhost=//, @conflines);
      $lcdhost = $lcdhost[0] unless($plcdhost);
      chomp $lcdhost;
      my @lcdport = grep(s/^lcdport=//, @conflines);
      $lcdport = $lcdport[0] unless($plcdport);
      chomp $lcdport;
      my @local = grep(s/^local=//, @conflines);
      $local = $local[0] unless defined $plocal;
      chomp $local;
      my @loop = grep(s/^loop=//, @conflines);
      $loop = $loop[0] unless defined $ploop;
      chomp $loop;
      my @lowercase = grep(s/^lowercase=//, @conflines);
      $lowercase = $lowercase[0] unless defined $plowercase;
      chomp $lowercase;
      my @mailad = grep(s/^mailad=//, @conflines);
      $mailad = $mailad[0] unless($pmailad);
      chomp $mailad;
      my @mirror = grep(s/^mirror=//, @conflines);
      $mirror = $mirror[0] unless($pmirror);
      chomp $mirror;
      my @normalize = grep(s/^normalize=//, @conflines);
      $normalize = $normalize[0] unless defined $pnormalize;
      chomp $normalize;
      my @normopt = grep(s/^normopt=//, @conflines);
      $normopt = $normopt[0] unless($pnormopt);
      chomp $normopt;
      my @nice = grep(s/^nice=//, @conflines);
      $nice = $nice[0] unless defined $pnice;
      chomp $nice;
      my @outputdir = grep(s/^output=//, @conflines);
      $outputdir = $outputdir[0] unless($poutputdir);
      chomp $outputdir;
      my @parano = grep(s/^paranoia=//, @conflines);
      $parano = $parano[0] unless defined $pparano;
      chomp $parano;
      my @playlist = grep(s/^playlist=//, @conflines);
      $playlist = $playlist[0] unless defined $pplaylist;
      chomp $playlist;
      my @preset = grep(s/^preset=//, @conflines);
      $preset = $preset[0] unless($ppreset);
      # NOTE: we have to fill the w_RITE_preset variable!
      $wpreset = $preset[0] unless($ppreset);
      chomp $preset;
      chomp $wpreset;
      my @proto = grep(s/^proto=//, @conflines);
      $proto = $proto[0] unless($pproto);
      chomp $proto;
      my @proxy = grep(s/^proxy=//, @conflines);
      $proxy = $proxy[0] unless($pproxy);
      chomp $proxy;
      my @quafaac = grep(s/^quafaac=//, @conflines) unless(@pquality);
      $quafaac = $quafaac[0] unless(@pquality);
      chomp $quafaac;
      my @quaflac = grep(s/^quaflac=//, @conflines) unless(@pquality);
      $quaflac = $quaflac[0] unless(@pquality);
      chomp $quaflac;
      my @qualame = grep(s/^qualame=//, @conflines) unless(@pquality);
      $qualame = $qualame[0] unless(@pquality);
      chomp $qualame;
      my @qualoggenc = grep(s/^qualoggenc=//, @conflines) unless(@pquality);
      $qualoggenc = $qualoggenc[0] unless(@pquality);
      chomp $qualoggenc;
      # These lines will go away again! Say, 3.6 and 3.7 will have it,
      # 3.8 not. TODO
      unless($qualoggenc){
         my @qualoggenc = grep(s/^qualogg=//, @conflines) unless(@pquality);
         $qualoggenc = $qualoggenc[0] unless(@pquality);
         chomp $qualoggenc;
      }
      my @faacopt = grep(s/^faacopt=//, @conflines);
      $faacopt = $faacopt[0] unless($pfaacopt);
      chomp $faacopt;
      my @flacopt = grep(s/^flacopt=//, @conflines);
      $flacopt = $flacopt[0] unless($pflacopt);
      chomp $flacopt;
      my @lameopt = grep(s/^lameopt=//, @conflines);
      $lameopt = $lameopt[0] unless($plameopt);
      chomp $lameopt;
      my @oggencopt = grep(s/^oggencopt=//, @conflines);
      $oggencopt = $oggencopt[0] unless($poggencopt);
      chomp $oggencopt;
      # These lines will go away again! Say, 3.6 and 3.7 will have it,
      # 3.8 not. TODO
      unless($oggencopt){
         my @oggencopt = grep(s/^oggopt=//, @conflines);
         $oggencopt = $oggencopt[0] unless($poggencopt);
         chomp $oggencopt;
      }
      my @ripper = grep(s/^ripper=//, @conflines);
      $ripper = $ripper[0] unless defined $pripper;
      chomp $ripper;
      my @ripopt = grep(s/^ripopt=//, @conflines);
      $ripopt = $ripopt[0] unless defined $pripopt;
      chomp $ripopt;
      my @rlist = grep(s/^sshlist=//, @conflines) unless($psshlist[0]);
      chomp @rlist;
      # NOTE: all machine names are in array entry $rlist[0]!
      @sshlist = split(/,/, join(',',@rlist));
      my @scp = grep(s/^scp=//, @conflines);
      $scp = $scp[0] unless defined $pscp;
      chomp $scp;
      my @submission = grep(s/^submission=//, @conflines);
      $submission = $submission[0] unless defined $psubmission;
      chomp $submission;
      my @transfer = grep(s/^transfer=//, @conflines);
      $transfer = $transfer[0] unless($ptransfer);
      chomp $transfer;
      my @tracktemplate = grep(s/^tracktemplate=//, @conflines);
      $tracktemplate = $tracktemplate[0] unless($ptracktemplate);
      chomp $tracktemplate;
      my @underscore = grep(s/^underscore=//, @conflines);
      $underscore = $underscore[0] unless defined $punderscore;
      chomp $underscore;
      my @utftag = grep(s/^utftag=//, @conflines);
      $utftag = $utftag[0] unless defined $putftag;
      chomp $utftag;
      my @verbose = grep(s/^verbose=//, @conflines);
      $verbose = $verbose[0] unless defined $pverbose;
      chomp $verbose;
      my @vbrmode = grep(s/^vbrmode=//, @conflines);
      $vbrmode = $vbrmode[0] unless($pvbrmode);
      chomp $vbrmode;
      my @year = grep(s/^year=//, @conflines);
      $year = $year[0] unless($pyear);
      chomp $year;
      my @wav = grep(s/^wav=//, @conflines);
      $wav = $wav[0] unless defined $pwav;
      chomp $wav;
   }
   else {
      print "\nNo config file found! Use option --save to create one.\n"
         if($verbose >= 2);
   }
}

########################################################################
#
# Change encoding of tags back to iso-8859-1.
#
sub back_encoding {
   my $temp_file = "/tmp/utf8-$$\.txt";
   open(TMP, ">$temp_file") or print "$temp_file $!";
   print TMP $_[0];
   close TMP;
   my $decoded = `/usr/bin/iconv -f UTF-8 -t ISO-8859-1 $temp_file`;
   unlink("/tmp/utf8-$$\.txt");
   return $decoded;
}
########################################################################
#
# Check the preset options.
#
sub check_preset {
   if($preset !~ /^\d/) {
      while($preset !~ /^insane$|^extreme$|^standard$|^medium$/) {
         print "\nPreset should be one of the following words! Please";
         print " Enter \ninsane (320\@CBR), extreme (256), standard";
         print " (192) or medium (160), (standard): ";
         $preset = <STDIN>;
         chomp $preset;
         if($preset eq "") {
            $preset = "standard";
         }
      }
   }
   else {
      while($preset !~ /^32$|^40$|^48$|^56$|^64$|^80$|^96$|^112$|^128$|^160$|^192$|^224$|^256$|^320$/) {
         print "\nPreset should be one of the following numbers!";
         print " Please Enter \n32, 40, 48, 56, 64, 80, 96, 112, 128,";
         print " 160, 192, 224, 256 or 320, (128):\n";
         $preset = <STDIN>;
         chomp $preset;
         if($preset eq "") {
            $preset = 128;
         }
      }
   }
   $preset = "medium" if($preset =~ /\d+/ && $preset == 160);
   $preset = "standard" if($preset =~ /\d+/ && $preset == 192);
   $preset = "extreme" if($preset =~ /\d+/ && $preset == 256);
   $preset = "insane" if($preset =~ /\d+/ && $preset == 320);
   $wpreset = $preset;
}
########################################################################
#
# Check sshlist of remote machines and create a hash.
#
sub check_sshlist {
   if(@psshlist) {
      @sshlist = split(/,/, join(',',@psshlist));
   }
   if(@sshlist) {
      $sshflag = 1;
      $wsshlist = join(',',@sshlist);
      # Create a hash with all machines and a flag.
      # We don't need the flag yet...
      $sshlist{'local'} = '0' if($local == 1);
      foreach (@sshlist) {
         $sshlist{$_} = '0';
      }
   }
   else {
      $sshflag = 0;
   }
}
########################################################################
#
# Dispatcher for encoding on remote machines. If there are no .lock
# files, a ssh command will be passed, else the dispatcher waits until
# an already passed ssh command terminates and removes the lock file.
# The dispatcher checks all machines all 6 seconds until a machine is
# available. If option -scp is used, the dispatcher will not start an
# other job while copying. If it happens, that one machine ended, it
# looks like nothing would happen during scp.
#
sub enc_ssh {
   my $machine;
   my @codwav = ();
   my $delwav = $_[0];
   my $enccom = $_[1];
   my $ripnam = $_[2];
   my $shortname = $_[3];
   my $sufix = $_[4];
   my $old_outputdir = $outputdir;
   my $old_ripnam = $ripnam;
   my $esc_name;
   my $esc_dir;

   $sshflag = 2;
   while ($sshflag == 2) {
      # Start on the local machine first.
      if(! -r "$outputdir/local.lock") {
         if($local == 1) {
            $sshflag = 1;
            $machine = "local";
            push @codwav, "$shortname";
         }
      }
      last if($sshflag == 1);
      foreach $_ (keys %sshlist) {
         $machine = $_;
         if(! -r "$outputdir/$machine.lock") {
            $sshflag = 1;
         }
         # Prepare array @codwav with all tracknames in,
         # which are still in progress.
         else {
            open(LOCK, "$outputdir/$machine.lock");
            my @locklines = <LOCK>;
            close LOCK;
            my $locklines = $locklines[0] if($locklines[0]);
            chomp $locklines;
            # Push trackname into array only if not yet
            # present.
            my @presence = grep(/$locklines/, @codwav);
            my $presence = $presence[0];
            push @codwav, "$locklines" if(! $presence);
         }
         last if($sshflag == 1);
      }
      last if($sshflag == 1);
      sleep 3;
   }
   # Untested patch by joni-@gmx.de
   # He reported problems while deleting the local lock files on a nfs.
   # Could not reproduce problems.
   #$esc_name = esc_char($shortname.".".$sufix);
   #$esc_dir  = esc_char($outputdir$machine.".lock");
   #log_system("ssh $machine 'echo \"$esc_name\" > $esc_dir'");
    open(LOCKF, ">$outputdir/$machine.lock");
    print LOCKF "$shortname.$sufix\n";
    close (LOCKF);

   # We need more quotes for the commands (faac,flac,lame,ogg)
   # passed to the remote machen. NOTE: But now pay attention
   # to single quotes in tags. Quote them outside of single quotes!
   # TODO: Please tell me how to quote leading periods, thanks!!!
   if($machine !~ /^local$/) {
      $enccom =~ s/'/'\\''/g;
      $enccom = "'".$enccom."'";
      $enccom = "ssh $machine " . $enccom;
      if($scp) {
         # CREATE the directory:
         # Please tell me why one has to quote the double quotes
         # with a backslash when using ssh!
         $outputdir = esc_char($outputdir);
         log_info("new-outputdir: $outputdir");
         log_system("ssh $machine mkdir -p \\\"$outputdir\\\"");
         # COPY the File:
         # Please tell me why one should NOT quote a file name
         # with blanks when using scp!
         $ripnam = esc_char($ripnam);
         log_system("scp $ripnam.wav $machine:\"$ripnam.wav\" > /dev/null 2> /dev/null");
      }
   }
   $enccom = $enccom . " > /dev/null 2> /dev/null ";
   if($machine !~ /^local$/ && $scp) {
      $enccom = $enccom . " && scp $machine:\"$ripnam.$sufix\" $ripnam.$sufix > /dev/null 2> /dev/null && ssh $machine rm \"$ripnam.*\" ";
   }
   $enccom = $enccom . " && rm \"$old_outputdir$machine.lock\" &";
   log_system("$enccom");
   $outputdir = $old_outputdir;
   $ripnam = $old_ripnam;
   # Delete the wav only if all encodings of this track are done!
   # When the last encoding of a track started, its name is pushed
   # into the array @delname. Then the first (oldest) entry is
   # compared to the @codwav array. If still present, nothing
   # happens, else the wav will be deleted and the trackname
   # shifted.
   if($delwav == 1) {
      push my @delname, "$shortname";
      my $delflag = 0;
      while ($delflag == 0) {
         my $delname = $delname[0];
         my @delwav = grep(/$delname/, @codwav);
         if($delwav[0] eq "" && $#delname > 1) {
            unlink("$outputdir/$delname.wav");
            shift(@delname);
            # Prevent endless loop if array is empty.
            $delflag = 1 if($delwav[0] eq "");
         }
         else {
            $delflag = 1;
         }
      }
   }
}
########################################################################
#
# Delete wavs if sshlist was used. TODO: Improve code for following
# situation: if no .lock files are found, but the encoder did not yet
# finish, don't delete the wavs. Do it only after 3*4 seconds timeout
# with no .lock file.
#
sub del_wav {
   my $waitflag = 1;
   sleep 3;
   while ($waitflag <= 3) {
      sleep 3;
      opendir(DIR, "$outputdir");
      my @locks = readdir(DIR);
      closedir(DIR);
      @locks = grep { /\.lock$/ } @locks;
      $waitflag++ if(! @locks);
      $waitflag = 0 if(@locks);
   }
   if($wav == 0) {
      opendir(DIR, "$outputdir");
      my @wavs = readdir(DIR);
      closedir(DIR);
      @wavs = grep { /\.wav$/ } @wavs;
      unlink("$outputdir/$_") foreach (@wavs);
   }
   if($scp) {
      my $old_outputdir = $outputdir;
      $outputdir = esc_char($outputdir);
      foreach $_ (keys %sshlist) {
         my $machine = $_;
         log_system("ssh $machine rmdir \\\"$outputdir\\\" > /dev/null 2> /dev/null")
            if($machine !~ /^local$/);
      }
      $outputdir = $old_outputdir;
   }
}
########################################################################
#
# LCDproc subroutines, all credits to Max Kaesbauer. For comments and
# questions contact max [dot] kaesbauer [at] gmail [dot] com.
#

# print

sub plcd {
   my ($data) = @_;
   print $lcdproc $data."\n";
   my $res = <$lcdproc>;
}

# update

sub ulcd {
   if($lcdoline1 ne $lcdline1) {
      $lcdoline1 = $lcdline1;
      plcd("widget_set ripitlcd line1 1 2 {$lcdline1}");
       }
   if($lcdoline2 ne $lcdline2) {
      $lcdoline2 = $lcdline2;
      plcd("widget_set ripitlcd line2 1 3 {$lcdline2}");
   }
   if($lcdoline3 ne $lcdline3) {
      $lcdoline3 = $lcdline3;
      plcd("widget_set ripitlcd line3 1 4 {$lcdline3}");
   }
}

# init

sub init_lcd {
   $lcdproc = IO::Socket::INET->new(
      Proto     => "tcp",
      PeerAddr  => $lcdhost,
      PeerPort  => $lcdport,
   ) || die "Can not connect to LCDproc port\n";
   $lcdproc->autoflush(1);
   sleep 1;

   print $lcdproc "hello\n";
   my @lcd_specs = split(/ /,<$lcdproc>);
   my %screen;

   $screen{wid} = $lcd_specs[7];
   $screen{hgt} = $lcd_specs[9];
   $screen{cellwid} = $lcd_specs[11];
   $screen{cellhgt} = $lcd_specs[13];

   $screen{pixwid} = $screen{wid}*$screen{cellwid};
   $screen{pixhgt} = $screen{hgt}*$screen{cellhgt};

   fcntl($lcdproc, F_SETFL, O_NONBLOCK);

   plcd("client_set name {ripit.pl}");
   plcd("screen_add ripitlcd");
   plcd("screen_set ripitlcd name {ripitlcd}");

   plcd("widget_add ripitlcd title title");
   plcd("widget_set ripitlcd title {RipIT $version}");

   plcd("widget_add ripitlcd line1 string");
   plcd("widget_add ripitlcd line2 string");
   plcd("widget_add ripitlcd line3 string");
}
########################################################################
#
# Read the CDDB on the local machine.
#
sub read_entry {
   my ($album, $artist, $trackno);
   my $logfile = $_[0];
   open(LOG, $logfile);
   my @cddblines = <LOG>;
   close(LOG);
   %cd = ();
   # Note that long lines may be splited into several lines
   # all starting with the same keyword, e.g. DTITLE.
   if($multi == 0) {
      $cd{raw} = \@cddblines;
      my @artist = grep(s/^DTITLE=//g, @cddblines);
      $artist = join(' / ',@artist);
      $artist =~ s/[\015]//g;
      $artist =~ s/\n\s\/\s//g;
      chomp $artist;
      # Artist is just the first part before first occurrence of
      # the slash (/), album gets all the rest!
      my @disctitle = split(/\s\/\s/, $artist);
      $artist = shift(@disctitle);
      $album = join(' / ',@disctitle);
      chomp $artist;
      chomp $album;
      $categ = $_[1];
      my @genre = grep(s/^DGENRE=//, @cddblines);
      $genre = $genre[0] if($genre eq "");
      $genre =~ s/[\015]//g;
      chomp $genre;
      my @year = grep(s/^DYEAR=//, @cddblines);
      $year = $year[0] if($year eq "");
      $year =~ s/[\015]//g;
      chomp $year;
      $trackno = $_[2];
   }
   else {
      my @artist = grep(s/^artist:\s//i, @cddblines);
      $artist = $artist[0];
      chomp $artist;
      my @album = grep(s/^album:\s//i, @cddblines);
      $album = $album[0];
      chomp $album;
      my @category = grep(s/^category:\s//i, @cddblines);
      $categ = $category[0];
      chomp $categ;
      my @genre = grep(s/^genre:\s//i, @cddblines);
      $genre = $genre[0];
      chomp $genre;
      my @year = grep(s/^year:\s//i, @cddblines);
      $year = $year[0];
      chomp $year;
      my @cddbid = grep(s/^cddbid:\s//i, @cddblines);
      $cddbid = $cddbid[0];
      chomp $cddbid;
      my @trackno = grep(s/^trackno:\s//i, @cddblines);
      $trackno = $trackno[0];
      chomp $trackno;
   }
   $cd{artist} = $artist;
   $cd{title} = $album;
   $cd{cat} = $categ;
   $cd{genre} = $genre;
   $cd{id} = $cddbid;
   $cd{year} = $year;
   my $i=1;
   my $j=0;
   while($i <= $trackno){
      my @track = ();
      @track = grep(s/^TTITLE$j=//, @cddblines) if($multi == 0);
      @track = grep(s/^track\s$i:\s//i, @cddblines) if($multi == 1);
      my $track = join(' / ',@track);
      $track =~ s/[\015]//g;
      $track =~ s/\n\s\/\s//g;
      chomp $track;
      $cd{track}[$j]=$track;
      $i++;
      $j++;
   }
}
########################################################################
#
# Delete error.log if there is no Track comment in!
#
sub del_erlog {
   if(-r "$outputdir/error.log") {
      open(ERR, "$outputdir/error.log")
        or print "error.log disappeared!\n";
      my @errlines = <ERR>;
      close ERR;
      my @ulink = grep(/Track /, @errlines);
      if(!@ulink && $multi == 0) {
         unlink("$outputdir/error.log");
      }
   }
}
########################################################################
#
# Escape special characters when using scp.
#
sub esc_char {
   $_[0] =~ s/\(/\\\(/g;
   $_[0] =~ s/\)/\\\)/g;
   $_[0] =~ s/\[/\\\[/g;
   $_[0] =~ s/\]/\\\]/g;
   $_[0] =~ s/\&/\\\&/g;
   $_[0] =~ s/\!/\\\!/g;
   $_[0] =~ s/\?/\\\?/g;
   $_[0] =~ s/\'/\\\'/g;
   $_[0] =~ s/ /\\ /g;
   return $_[0];
}
########################################################################
#
# Calculate how much time ripping and encoding needed.
#
sub cal_times{
   my $encend = `date \'+%R\'`;
   chomp $encend;
   # Read times from the file $outputdir/error.log.
   open(ERR, "$outputdir/error.log")
      or print "error.log disappeared!\n";
   my @errlines = <ERR>;
   close ERR;
   my @enctime = grep(s/^Encoding needed //, @errlines);
   my @ripstart = grep(s/^Ripping  started: //, @errlines);
   my @ripend = grep(s/^Ripping  ended: //, @errlines);

   @ripstart = split(/:/, $ripstart[0]);
   @ripend = split(/:/, $ripend[0]);
   my $riptime = ($ripend[0]*60+$ripend[1])-($ripstart[0]*60+$ripstart[1]);

   my $enctime = "@enctime";
   chomp $enctime;
   @enctime = split(/ /, $enctime);
   $enctime = int($enctime[0]/60);
   return ($riptime,$enctime,$encend)
}
########################################################################
#
# Thanks to mjb: log info to file.
#
sub log_info {
   if(!defined($infolog)){ return; }
   elsif($infolog eq ""){ return; }
   open(SYSLOG, ">> $infolog") || die "Can't open info log file\n";
   print SYSLOG "@_\n";
   close(SYSLOG);
}
########################################################################
#
# Thanks to mjb and Stefan Wartens improvements:
# used throughout in place of system().
#
sub log_system {
   my $P_command=shift;

   if($verbose >= 3){
      print "system: $P_command\n\n";
   }
   log_info("system: $P_command");

   system($P_command);

   # system() returns several pieces of information about the launched
   # subprocess squeezed into a 16-bit integer:
   #
   #     7  6  5  4  3  2  1  0  7  6  5  4  3  2  1  0
   #   +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   #   |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  [ $? ]
   #   +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   #    \_____________________/ \/ \__________________/
   #          exit code        core    signal number
   #
   # To get the exit code, use        ($? >> 8)
   # To get the signal number, use    ($? & 127)
   # To get the dumped core flag, use ($? & 128)

   # Subprocess has been executed successfully.
   return 1 if $? == 0;

   # Subprocess was killed by SIGINT (CTRL-C). Exit RipIT.
   die "\n\nRipit caught a SIGINT.\n" if(( $? & 127) == 2);

   # Subprocess could not be executed or failed.
   return 0;
}
########################################################################
#
# Special characters in cd.toc file won't be written correctly by
# cdrdao, so change them to octal!
#
sub oct_char{
   $_[0] =~ s/À/\\300/g;
   $_[0] =~ s/Á/\\301/g;
   $_[0] =~ s/Â/\\302/g;
   $_[0] =~ s/Ã/\\303/g;
   $_[0] =~ s/Ä/\\304/g;
   $_[0] =~ s/Å/\\305/g;
   $_[0] =~ s/Æ/\\306/g;
   $_[0] =~ s/Ç/\\307/g;
   $_[0] =~ s/È/\\310/g;
   $_[0] =~ s/É/\\311/g;
   $_[0] =~ s/Ê/\\312/g;
   $_[0] =~ s/Ë/\\313/g;
   $_[0] =~ s/Ì/\\314/g;
   $_[0] =~ s/Í/\\315/g;
   $_[0] =~ s/Î/\\316/g;
   $_[0] =~ s/Ï/\\317/g;
   $_[0] =~ s/Ð/\\320/g;
   $_[0] =~ s/Ñ/\\321/g;
   $_[0] =~ s/Ò/\\322/g;
   $_[0] =~ s/Ó/\\323/g;
   $_[0] =~ s/Ô/\\324/g;
   $_[0] =~ s/Õ/\\325/g;
   $_[0] =~ s/Ö/\\326/g;
   $_[0] =~ s/×/\\327/g;
   $_[0] =~ s/Ø/\\330/g;
   $_[0] =~ s/Ù/\\331/g;
   $_[0] =~ s/Ú/\\332/g;
   $_[0] =~ s/Û/\\333/g;
   $_[0] =~ s/Ü/\\334/g;
   $_[0] =~ s/Ý/\\335/g;
   $_[0] =~ s/Þ/\\336/g;
   $_[0] =~ s/ß/\\337/g;
   $_[0] =~ s/à/\\340/g;
   $_[0] =~ s/á/\\341/g;
   $_[0] =~ s/â/\\342/g;
   $_[0] =~ s/ã/\\343/g;
   $_[0] =~ s/ä/\\344/g;
   $_[0] =~ s/å/\\345/g;
   $_[0] =~ s/æ/\\346/g;
   $_[0] =~ s/ç/\\347/g;
   $_[0] =~ s/è/\\350/g;
   $_[0] =~ s/é/\\351/g;
   $_[0] =~ s/ê/\\352/g;
   $_[0] =~ s/ë/\\353/g;
   $_[0] =~ s/ì/\\354/g;
   $_[0] =~ s/í/\\355/g;
   $_[0] =~ s/î/\\356/g;
   $_[0] =~ s/ï/\\357/g;
   $_[0] =~ s/ð/\\360/g;
   $_[0] =~ s/ñ/\\361/g;
   $_[0] =~ s/ò/\\362/g;
   $_[0] =~ s/ó/\\363/g;
   $_[0] =~ s/ô/\\364/g;
   $_[0] =~ s/õ/\\365/g;
   $_[0] =~ s/ö/\\366/g;
   $_[0] =~ s/÷/\\367/g;
   $_[0] =~ s/ø/\\370/g;
   $_[0] =~ s/ù/\\371/g;
   $_[0] =~ s/ú/\\372/g;
   $_[0] =~ s/û/\\373/g;
   $_[0] =~ s/ü/\\374/g;
   $_[0] =~ s/ý/\\375/g;
   $_[0] =~ s/þ/\\376/g;
   return $_[0];
}
########################################################################
#
# Check if there is a CD in the CD device.
#
sub cd_present {
#   require "ioctl.ph";
   sysopen(CD, $cddev, O_RDONLY | O_NONBLOCK)
      or die "Can not open device $cddev: $!\n";
   my $os = `uname -s`;
   my $CDROMREADTOCHDR=0x5305;		# Linux
   if($os eq "SunOS") {
      $CDROMREADTOCHDR=0x49b;
   }
   elsif($os =~ /BSD/i) {
      $CDROMREADTOCHDR=0x40046304;
   }
   my $tochdr = "";
   my $err = ioctl(CD, $CDROMREADTOCHDR, $tochdr);
   close(CD);
   return $err;
}
########################################################################
#
# A very ugly hack to reinitialize global variables before starting a
# new loop.
#
sub init_var {
   $categ		= "";
   $cddbid		= 0;
   @framelist		= ();
   @secondlist	= ();
   @tracklist		= ();
   @tracktags		= ();
   @seltrack		= ();
   %cd			= ();
   $cddbsubmission	= 2;
   $hiddenflag	= 0;
   $outputdir		= $poutputdir;
}
########################################################################
#
# Get the revision number of the CDDB entry.
#
sub get_rev {
   my @revision = grep(/^\#\sRevision:\s/, @{$cd{raw}});
   @revision = grep(s/^\#\sRevision:\s//, @revision);
   my $revision = $revision[0];
   chomp $revision if($revision);
   return $revision;
}
########################################################################
#
# Lowercase.
#
sub lower_case{
   $_[0] = lc($_[0]);
   $_[0] =~ tr/[ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ]/[àáâãäåæçèéêëìíîï]/;
   $_[0] =~ tr/[ÐÑÒÓÔÕÖØÙÚÛÜÝÞ]/[ðñòóôõöøùúûüýþ]/;
   return $_[0];
}
########################################################################
#
# Strip dodgey chars I. This will be done for file names and tags.
#
# TODO: Do we really have to erase all of them? Maybe we should keep
# some for the tags...
#
sub clean_all{
   $_[0] =~ s/[;|><"\015]//g;
   $_[0] =~ s/\`|[´]/\'/g;
   return $_[0];
}
########################################################################
#
# Strip dodgey chars II. This will only be done for file names.
#
sub clean_name{
   $_[0] =~ s/[*]//g;
   $_[0] =~ s/\// - /g;
   $_[0] =~ s/\s+/ /g;
   return $_[0];
}
########################################################################
#
# Strip dodgey chars III. This will optionally be done for file names.
# Remember the default chars to be erased are:   :*#?$!  .
#
sub clean_chars{

   $_[0] =~ s/$chars//g;
   return $_[0];
}
########################################################################
#
# Put all chars in brackets and escape some.
#
sub check_chars {
   $chars =~ s/-/\\-/;
   $chars =~ s/]/\\]/;
   $chars =~ s/\s/\\s/;
   $chars = "[" . $chars . "]";
}
########################################################################
#
# Extract the CDDB comment lines starting with EXTD=.
# NOTE: Each EXTD line my have \n's, but two EXTD lines do NOT
# mean that there's a linebreak in between! So, what we have to do
# is, put all comment lines into a string and split the string
# according to the explicitly \n's (i.e. use \\n).and add a \n at the
# end of each line!
#
sub extract_comm {
   my @comment = grep(/^EXTD=/, @{$cd{raw}});
   @comment = grep(s/^EXTD=//, @comment);
   my $line = "@comment";
   $line =~ s/[\015]//g;
   @comment = split(/\\n/, $line);
   foreach (@comment) {
      chomp $_;
      $_ =~ s/^\s+//g;
   }
   return (@comment);
}
########################################################################
#
# Display a help page and exit!
#
sub print_help {
   print <<END

SYNOPSIS:
   ripit [options]

OPTIONS:
 [track_selection]
              If not specified, all tracks will be ripped. Type a number
              or a selection of tracks using numbers separated by commas
              or hyphens.
 -o, --outputdir dir
              Where the sound should go, default: not set.
 -d, --device cddevice
              Path of audio CD device, default: /dev/cdrom.
 -r, --ripper ripper
              0 dagrab, 1 cdparanoia, 2 cdda2wav, 3 tosha, 4 cdd,
              default: 1.
 --ripopt     User definable options for CDripper.
 -Z, --disable-paranoia
              When using dagrab, the number of retries will be set to 3,
              with cdparanoia this option is equal to the -Z option.
              Default: off.
 -c, --coder encoder
              0 Lame, 1 Ogg, 2 Flac,  3 Faac, a comma seperated list!
 --faacopt Faac-options
              Pass other options to the encoder,  quote them with double
              quotes if needed; default: not set.
 --flacopt Flac-options
              Same as above.
 --lameopt Lame-options
              Same as above.
 --oggencopt Oggenc-options
              Same as above.
 -q, --quality quality
              A comma seperated list of values or the word \"off\", passed
              in the same order as the list of encoders! If no  encoders
              passed, follow the order of the config file!
 -v, --vbrmode mode
              Variable bitrate, only used with Lame, mode is new or old,
              see Lame manpage.  The Lame-option quality will be changed
              to -V instead of -q if vbr-mode is used; default: not set.
 -b, --bitrate rate
              Encode \"mp3\" at this bitrate for Lame. If option --vbrmode
              used, bitrate is equal to the -b option, so one might want
              to set it \"off\", default: 128.
 -B, --maxrate rate
              maxrate (Bitrate) for Lame using --vbrmode is equal to the
              -B option in Lame or the -M option in Oggenc, default: 0.
 -S, --preset mode
              Use the preset switch when encoding with Lame. With otpion
              --vbrmode new --preset fast will be used.
 -W, --chars [list]
              Exclude special characters and  (ending!)  periods in file
              names. The argument is optional. Following characters will
              be erased, if no argument stated: :*#?\$\!  else only ending
              periods and all passed ones.  Default: off.
 --comment comment
              Specify a comment (mp3, m4a), or a description (ogg, flac)
              tag, default: not set.
 -g, --genre genre
              Specify (and  override CDDB)  genre,  must be a valid ID3-
              genre name  if using Lame, can (but shouldn't) be anything
              if using other encoders, default: not set.
 -y, --year year
              Specify (and override CDDB) year tag (mp3, m4a), or a date
              (ogg, flac) tag, default: not set.
 --sshlist list
              Comma seperated list of remote machines where RipIT should
              encode. Default: off.
 --scp        If the fs can not be accessed on the remote machines, copy
              the wavs to the remote machines, default: off.
 --local      Only used with option --sshlist; if all encodings shall be
              done on remote machines, use --nolocal, default: on.
 -t, --transfer mode
              Transfer mode, cddb or http, will set default port to 8880
              or 80 (for http), default: cddb.
 -C, --cddbserver server
              CDDB server, default freedb.org. Note, the full address is
              \"mirror\".freedb.org, i. e. default is freedb.freedb.org.
 -m, --mirror mirror
              Choose \"freedb\" or one of the possible freedb mirrors.
 -L, --protocol level
              CDDB protocol level for CDDB query. Level 6 supports UTF-8
              and level 5 not.Default: 6
 -P, --proxy address
              The http proxy to use when accessing the cddb server.  The
              protocol must be http! Default: not set.
 -M, --mail address
              Users return email address, needed for submitting an entry
              to freedb.org; default: not set.
 -D, --dirtemplate '\"...\$parameters...\"'
              Use single AND double quotes to pass the parameters of the
              templates!
 -T, --tracktemplate '\"...\$parameters...\"'
              See above.
 -n, --nice value
              Set niceness of encoding process, default 0.
 -a, --archive
              Read and save CDDB files in  ~/.cddb/\"category\" directory.
              Default: off.
 -e, --eject  Ejects the CD when finished, default off.
 --halt       Powers off the machine when finished if your configuration
              supports it; default: off.
 -s, --submission
              Specify --nosubmission if the computer is  offline and the
              created file cddb.toc shall be saved in the home directory
              instead of being submitted. With option  --archive it will
              also be saved in the ~/.cddb directory. Default: on.
 -p, --playlist
              Create the m3u playlist file, or use --noplaylist. Default
              on.
 -i, --interaction
              Specify --nointeraction if ripit shall take the first CDDB
              entry found and rip without any questioning. Default: on.
 --lcd        Use lcdproc to display status, default: not set.
 --lcdhost    Specify the lcdproc host, default: localhost.
 --lcdport    Specify the lcdport, default: default: 13666.
 --infolog file
              Log operations (system calls,  file/directory creation) to
              file, given with full path; default: not set.
 -l, --lowercase
              Lowercase filenames, default: off.
 -u, --underscore
              Use underscores _ instead of spaces in filenames, default:
              off.
 -U, --utftag Use Lame-tags or decode them (but not the filenames)  from
              UTF-8 to ISO8859-1 if mp3-player doesn't support  Unicode.
              Applies only for Lame. Default: off.
 --encode     Do encode the wavs. Prevent encoding if only the wav-files
              shall be created (then use option --wav, see below).
              Default: on, else use --noencode.
 -w, --wav    Keep the wav files after encoding instead of deleting them
              default: off.
 -N, --normalize
              Normalizes the wave-files to a given dB-value (default:
              -12dB). Default: off.
 -z, --normopt
              Options to pass to normalize . For further options see
              normalize documentation (http://normalize.nongnu.org).
              Keeping the default value of -12dB is recommended.
              Default: -bv
 --cdtoc n
              n=1: Create a toc file to burn the wavs with cd-text using
              cdrdao or cdrecord (in dao mode), default off.
 -h, --help   Print this and exit.
 -V, --version
              Print version and exit.
 -x, --verbose number
              Run silent (0), with minimal (1), normal (2), or excessive
              output (3). Default 2
 --config     Read parameters from config file or specify  --noconfig to
              prevent reading it; default: on.
 --save       Add parameters passed on command line to config file. This
              options does not  overwrite other  settings.  An  existing
              config file will be saved as config.old. Default: off.
 --savenew    Save all parameters passed on command line to a new config
              file, backup an existing file to config.old. Default: off.
--loop        Continue to  ripp and encode as soon as a new  audio CD is
              inserted.  This option implies that the CD is ejected when
              done. Default off.

SEE ALSO
       ripit(1), cdparanoia(1), lame(1), oggenc(1), flac(1),
       normalize(1), cdda2wav(1),

AUTHORS
       RipIT is now maintained by Felix Suwald, please send bugs, wishes
       comments to ripit _[at]_ suwald _[dot]_ com. For bugs, wishes and
       comments about lcdproc, contact max.kaesbauer [at] gmail[dot]com.
       Former maintainer:  Mads Martin Joergensen;  RipIT was originally
       developed by Simon Quinn.

DATE
       07 Feb 2006

END
}

sub print_usage {
   print <<END

Usage:
ripit [--device|d cd-device] [--outputdir|o path] [--ripper|r cdripper]
      [--ripopt options]  [--wav|w]  [--disable-paranoia|Z]  [--encode]
      [--coder|c encoders-list] [--faacopt options] [--flacopt options]
      [--lameopt options] [--oggencopt options] [--quality qualities-list]
      [--bitrate|b rate] [--maxrate|B maxrate] [--vbr-mode|v old / new]
      [--preset|S mode]  [--comment id3-comment]  [--genre|g genre-tag]
      [--lowercase|l] [--underscore|u] [--utftag|U] [--year|y year-tag]
      [--dirtemplate '\"\$parameters\"'] [--tracktemplate '\"\$parameters\"']
      [--cddbserver|C server] [--mirror|m mirror]  [--protocol|L level]
      [--proxy|P path]  [--transfer|t cddb or http]  [--mail|M address]
      [--submission|s] [--interaction|i] [--nice|n adjustment] [--halt]
      [--eject|e] [--help|h]  [--lcd] [--lcdhost host] [--lcdport port]
      [--sshlist remote machines] [--local] [--scp] [--config] [--save]
      [--savenew] [--archive|a] [--playlist|p] [--infolog path] [--rip]
      [--cdtoc number] [--loop] [--verbose|x number] [--chars|W [list]]
      [--normalize|N] [--normopt|z options] [--version|V]
      [track_selection]

For general usage information see the manpage or type:
       ripit --help | less
or try to run
       ripit
without any options.

END
}
