#!/usr/bin/perl
#
# Released under the Artistic license 2.0
# http://www.perlfoundation.org/artistic_license_2_0 
#
# Pedro Larroy Tovar. 
#
use strict;
use warnings;
use File::Find;
use File::Copy;

my @files;
my $dest;


sub shuffle {
	my $deck = shift;  # $deck is a reference to an array
	my $i = @$deck;
	while (--$i) {
		my $j = int rand ($i+1);
		@$deck[$i,$j] = @$deck[$j,$i];
	}
}

sub usage
{
die <<EOV
$0 usage:
$0 [dir1] [dir2] ... [dirN] dest
	Copies random mp3 from dir1 .. dirN to destination dir, great for filling your mp3 player with fresh music!

EOV
	
}

sub found 
{
	if( $_ =~ m/\.mp3$/i ) {
		push @files, $File::Find::name;
	}
}

sub move_files
{
	shuffle(\@files);
	foreach my $file (@files) {
		print "$file -> $dest\n";
		copy($file,$dest) or die "copy($file,$dest): $!";
	}
}

my $DIR;
my $dir;

if( ($dest = pop @ARGV) ) {
	if( -d $dest ) {
		while($dir = shift @ARGV) {
			find(\&found, $dir);
		}	
		move_files();
	} else {
		die "$dest: not a directory";
	}
} else {
	usage();
}

