#!/usr/bin/perl -w
#convertmp3: Is basically a hack off of mp32sql that converts (using xing)
# files found in a recursed directory into whatever bitrate you specify
#
# Writen by Chris Milbert: Thanks to #perl on efnet.  Special Thanks to dynweb

##################################################################
#External modules to use								         #
##################################################################
use MPEG::MP3Info;# qw(:all);	   #Returns mp3 tag info
use Getopt::Std;			   #Checks the parameters passed during exec
use Getopt::Long;			   #Checks the parameters passed during exec
use Cwd;                       #Current working directory mod
use File::Find;				   #Directory mod
##################################################################

##################################################################
#Variables section 											     #
#This is basically the main configuration section				 # 
##################################################################
getopt('d:e:n:b:m:a:y:v');            #reads in data to opt_o and opt_T
GetOptions("help" => \$needhelp);

$searchdir = getcwd;		  #Start directory
$newdir = '/tmp';
$filetype = '.mp3';			  #File extention
$bitrate = '128';
$mode = '1';
$algorithm = '0';

#help check
if ($needhelp || $opt_h) {
print "Syntax: \n";
print "convertmp3.pl [parameters] \n";
print "Parameters: \n";
print "  -d [Directory to recurse Default: $searchdir] \n";
print "  -e [File extention to look for Default: .mp3] \n";
print "  -n [New dir to put converted .mp3 Default: $newdir] \n";
print "  -b [Bitrate / Mono: 16, 24, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 \n";
print "              Stereo: 32, 48, 64, 96, 112, 128, 160, 192, 224, 256, 320\n";
print "              Default: 128 kbps stereo, 64 kbps mono] \n";
print "  -m [Mode / 0 mode-0 stereo, 1 mode-1 stereo (default), 2 dual stereo, 3 mono] \n";
print "  -a [Algorithm / 0 match rate, 1 mpeg-1 (32,44.1,48), 2 mpeg-2 (16, 22.05, 24) \n";
print "                   xxxxx (48000, 44100, 32000, 24000, 22050, 16000) \n";
print "                          44100 stereo, 22050 mono] \n";
print "  -y Prompt for confirmation of commandline options \n";
print "  -v Output Verbose from mpg123 and xing \n";
print "\n";
print "\n";
die "              \n";
$opt_h = "Needed help";
}

#Check params and use default if not specified
if ($opt_d) {$searchdir = $opt_d;}
else {$searchdir = getcwd;}

if ($opt_e) {$filetype = $opt_e;}

if ($opt_n) {$newdir = $opt_n;}

if ($opt_b) {$bitrate = $opt_b;}

if ($opt_m) {$mode = $opt_m;}

if ($opt_a) {$algorithm = $opt_a;}

if ($opt_v) {$mpg123verbose = '-v'; $xingverbose = '';}
else {$mpg123verbose = ''; $xingverbose = '-Q';}

$numfiles = `find $searchdir | grep mp3 | wc -l`;
$numfiles = $numfiles - 1;
#Echo values back to the user and check for correctness
if ($opt_y) {
  print "Directory to recurse: $searchdir \n";
  print "Number of files to convert: $numfiles \n";
  print "File extention:       $filetype \n";
  print "New Directory:        $newdir \n";
  print "Bitrate:              $bitrate \n";
  print "Mode:                 $mode \n";
  print "Algorithm:            $algorithm \n";
  print "Verbose:              mpg:$mpg123verbose xing:$xingverbose \n";
  print "\n";
  print "Is this information correct?[y/n]  ";
  $correct = <STDIN>;
  chop($correct);
  if ($correct eq "n" || $correct eq "N") {
    print "\n";
    die "Wrong information so quitting \n";
  }
}
##################################################################
#Start loop check

print "Adding.. \n";

find sub { if ($_ =~ m/$filetype$/si)
{
	$filename = $_;
        #Get the mp3 info from the id3 tag							     #
	#this basicaly outputs all the tag info and the song time and    #
	#bitrate info to a data                                          #
	#array called$tag and $info to get to that data we use           #
	#$tag->{TITLE} for the title                                     #
	#and $info->{MM} for the play time in minitutes				     #
	
	$tag = get_mp3tag($filename);
	#$info = get_mp3info($filename);

	#$tag->{GENRE} = use_winamp_genres($tag->{GENRE});
	
	#check all of the insert variables and find ' and replace it with \'
	$filename =~ tr/'//d;
	$filename =~ tr/"//d;
	$filename =~ tr/?//d;
	$filename =~ tr/%//d;
	
	$File::Find::dir =~ tr/'//d;
	$File::Find::dir =~ tr/"//d;
	$File::Find::dir =~ tr/?//d;
	$File::Find::dir =~ tr/%//d;
	
	if ($tag->{GENRE}){
		$tag->{GENRE} =~ tr/'//d;
		$tag->{GENRE} =~ tr/"//d;
		$tag->{GENRE} =~ tr/?//d;
		$tag->{GENRE} =~ tr/%//d;	
	}
	else {$tag->{GENRE} = "Other";}

	if ($tag->{ARTIST}){
		$tag->{ARTIST} =~ tr/'//d;
		$tag->{ARTIST} =~ tr/"//d;
		$tag->{ARTIST} =~ tr/?//d;
		$tag->{ARTIST} =~ tr/%//d;	
	}
	else {$tag->{ARTIST} = "None";}

	if ($tag->{TITLE}){
		$tag->{TITLE} =~ tr/'//d;
		$tag->{TITLE} =~ tr/"//d;
		$tag->{TITLE} =~ tr/?//d;
		$tag->{TITLE} =~ tr/%//d;	
	}
	else {$tag->{TITLE} = "None";}
	
	if ($tag->{ALBUM}){
		$tag->{ALBUM} =~ tr/'//d;
		$tag->{ALBUM} =~ tr/"//d;
		$tag->{ALBUM} =~ tr/?//d;
		$tag->{ALBUM} =~ tr/%//d;
	}
	else {$tag->{ALBUM} = "None";}
	
	$filenamewav = $_;
	$filenamewav =~ s/mp3/wav/;
	`exec mkdir -p $newdir$File::Find::dir`;
	`exec mpg123 -v -w $newdir$File::Find::dir/$filenamewav $File::Find::dir/$filename`;
	`exec xingmp3enc -B $bitrate -M $mode -A $algorithm $newdir$File::Find::dir/$filenamewav $newdir$File::Find::dir/$filename`;
	unlink("$newdir$File::Find::dir/$filenamewav");
	set_mp3tag("$newdir$File::Find::dir/$filename",$tag);
	
	$sum++;
	print "Finished $sum of $numfiles\n";
}
}, $searchdir;
#Loop Ended
print "Done processing $searchdir \nA total of $sum files were added\n";
