#!/usr/bin/perl
#
#	mpg2ogg
#	written by Jan Engelhardt, 2007
#
#	This program is free software; you can redistribute it and/or
#	modify it under the terms of the WTF Public License version 2 or
#	(at your option) any later version.
#

use Getopt::Long;
use strict;

my $wav;
my %pat;
my $regex;

&Getopt::Long::Configure(qw(bundling));
&GetOptions(
	"X=s" => \$regex,
	"G=s" => \&asgn,
	"N=s" => \&asgn,
	"a=s" => \&asgn,
	"d=s" => \&asgn,
	"l=s" => \&asgn,
	"o=s" => \&asgn,
	"q=s" => \&asgn,
	"t=s" => \&asgn,
	"w"   => \$wav,
);

if (!defined($regex) || $regex eq "") {
	die "You must supply the -X option\n";
}
if (!defined($pat{"o"}) || $pat{"o"} eq "") {
	die "You must supply the -o option\n";
}

sub asgn ()
{
	$pat{$_[0]} = $_[1];
	return;
}

foreach my $file (@ARGV) {
	my $cmd;
	my %res;

	if ($wav) {
		$cmd = "oggenc -q4 \"$file\"";
	} else {
		$cmd = "mpg123 -vw- \"$file\" | oggenc -q4 -";
	}

	eval '@_ = ($file =~ m{'.$regex.'});';

	foreach my $name (split(//, "GNadloqt")) {
		if (!defined($pat{$name})) {
			next;
		}
		my $tmp = $pat{$name};
		$tmp =~ s/(?<!\\)\$(\d+)/$_[$1-1]/gs;
		$tmp =~ s/(?<!\\)\$\{(\d+)}/$_[$1-1]/gs;
		if ($name eq "N" && $tmp !~ /\D/) {
			$tmp += 0;
		}
		$cmd .= " -$name \"$tmp\"";
	}

	print "Executing: $cmd\n";
	system $cmd;
}
