#!/usr/bin/perl
#
#	playalot - wrapper for formats
#	written by Jan Engelhardt <jengelh [at] medozas de>, 2004 - 2007
#	http://jengelh.medozas.de/
#	released in the Public Domain
#
use Getopt::Long;
use strict;

my($Quiet, $Shuffle, $Alt, $Aac_workaround);
my @list;

&Getopt::Long::Configure(qw(bundling pass_through));
GetOptions(
	"aac" => \$Aac_workaround,
	"a" => \$Alt,
	"q" => \$Quiet,
	"z" => \$Shuffle,
);

while (defined(my $opt = shift @ARGV)) {
	if ($opt eq "-") {
		# Playlist on STDIN
		open(IN, "< $opt");
		foreach my $x (<IN>) {
			chomp $x;
			unshift(@list, $x);
		}
		close IN;
	}
	push(@list, $opt);
}

if ($Shuffle) {
	@list = sort s_random @list;
}

foreach my $file (@list) {
	if ($file =~ /\.(mid|mus|mod|669|s3m|xm|it)$/io) {
		my $t = $Quiet ? "" : "t";
		if ($Alt) {
			system "timidity -Or1sl -id$t \"$file\" -o- | ".
			       "oplay /dev/stdin -qq";
		} else {
			system "timidity", "-Os", "-id$t", $file;
		}
	} elsif ($file =~ /\.umx$/io) {
		&play_umx($file);
	} elsif ($Aac_workaround && $file =~ /\.aac$/io) {
		&play_aac($file);
	} else {
		system "mplayer", $file;
	}
}

sub play_umx ()
{
	my $name = shift @_;
	my $buffer;

	if (!open(IN, "< $name")) {
		warn "Could not open $name: $!\n";
		return;
	}

	my $of = "/tmp/playmuch-$$-$name.it";
	open(OUT, "> $of");
	read(IN, $buffer, 256);
	$buffer =~ s/^.*?(IMP|SCRM|Extended Module)/$1/o;
	print OUT $buffer;
	while (read(IN, $buffer, 65536)) {
		print OUT $buffer;
	}
	close IN;
	close OUT;

	system "timidity", "-Os", "-id".($Quiet ? "" : "t"), $of;
	unlink $of;
	return;
}

sub play_aac ()
{
	my $file = shift @_;

	system "faad -f2 -w \"$file\" | oplay -";
}

sub s_random ()
{
	return int(rand 2) ? 1 - (int(rand(256 ** 4)) % 3) :
	       ((time() ^ $$ ^ int(rand(256 ** 4))) % 3) - 1;
}
