#!/usr/bin/perl
# simple driver to convert flac files to mp3
# just drives flac and lame, mainly to allow
# wildcards and to remember options so I don't 
# have to. Assumes flac and lame are on path.
#
# Created on May 22, 2004
# Copyright (c) 2004, Pat Farrell, All rights reserved.
# This code will be released with a suitable Open Source
# license, probably BSD-like.
# 
# make it handle arguments the way Windows users expect.
use File::DosGlob 'glob';
use Getopt::Long;
use File::Basename;

my $help;
my $outspec;
my $quality = 2;
my $otherLameOptions;

    usage() if ( $#ARGV < 0 ); 
    GetOptions('help|?' => \$help, 'output=s' => \$outspec, 'quality=i' => \$quality, 
	'lame=s' => \$otherLameOptions);
    usage() if $help;

while ($anArg = shift(@ARGV)) {
    $anArg =~ s/(\s)/\\\1/g;	# quote any spaces before we glob
    @argfile = glob ($anArg);
    foreach $aFile (@argfile) {
	($basename, $dir, $ext) = fileparse($aFile, '\..*?');
	if ($ext =~ /.flac$/i ) {
	    $needQuotes = ($aFile =~ m/\s/) ? "\"" : "";
	    $outfn = (($outspec) ? $outspec :  $dir) . $basename . ".mp3"; 
	    $cmd = "flac -dcs " . $needQuotes . $aFile . $needQuotes   
	        . " | lame --silent -q " . $quality . " --tt " . $needQuotes . $basename . $needQuotes
		. " --resample 44100 " . $otherLameOptions . " - " 
		. $needQuotes . $outfn . $needQuotes ;
   	    print "$cmd\n";
	    $retval = system($cmd);
	}
	else {
	    print "$aFile will be ignored\n";
	}
    }
} 
sub usage {
    print "convert flac files to mp3\n";
    print "Usage:\n   flac2mp3.pl [-output=path] [-quality=[0-9]] [-lame=[lame-options]] {files}\n";
    print "     quality is passed straight to lame,\n";
    print "        -q 0:  Highest quality, very slow\n";
    print "        -q 9:  Poor quality, but fast.\n";
    print "     lame-options is passed straight to lame, this is nice for -vbr or bit rate options\n";
    print "note, the output path has to end with the directory separator character.\n";
    print "   \\ on Windows, \/ on linux, etc.\n";
    exit;
}
