#!/usr/bin/perl -w
use strict;
use DB_File;

my @files;
if ($ARGV[0] eq '-z') {
    shift @ARGV;
    while (@ARGV) {
        push @files, splice @ARGV, rand(@ARGV), 1;
    }
}
else {
    @files = @ARGV;
}
die "Nothing to play..." unless @files;

my $int = 0;
my $lastint = time;

my %hate;
my $handle;
$handle = tie %hate, 'DB_File', '.hate.db', O_CREAT|O_RDWR;

$SIG{INT} = sub {
    $int = 1;
    if (time - $lastint < 1) {
        $handle->sync;
        exit;
    }
    $lastint = time
    };

foreach (@files) {
    $handle->sync;
    print "***************\ntrying to play $_\n***************\n";
    open(MPG, "|mpg123 - 2>&1 > /dev/null") or die "Could not launch mpg123";
    my $data;
    open(FOO, "<$_") or die "Could not open $_";
    PLAY: while (sysread(FOO, $data, 1024)) {
        if ($int) {
            $hate{$_} = $hate{$_}+1;
            print "hate $_ ($hate{$_}) int\n";
            close FOO; close MPG;
            $int = 0;
            last PLAY;
        }
        if (!defined(syswrite MPG, $data)) {
            $hate{$_} = $hate{$_}+1;
            print "hate $_ ($hate{$_}) err\n";
            close FOO; close MPG;
            last PLAY;
        }
    }
}


