#!/usr/bin/perl -w

use strict;

use File::Basename;
use File::Spec;

my $pattern = '\.mp3$';

defined(my $topdir = shift @ARGV) or die "Must specify directory";
die "Must specify absolute path!\n" if substr($topdir, 0, 1) ne "/";

for (split /\x0/, `find $topdir -type f -print0`) {
#chomp(my @files = `find $topdir -type f -print`);
#for (@files) {
	my $basename = basename $_;
	if ($basename !~ /$pattern/i) {
		warn "File not matched '$_'!\n";
		next;
	}
	my ($first) = ($basename =~ m/([a-z])/i);
	if (!defined $first) {
		warn "No alphabetic character to use for file '$_'!\n";
		next;
	}
	my $dir = uc $first;
	if (! -d $dir) {
		mkdir $dir, 0700 or die "Cannot make directory! '$dir': $!\n"
	}
	my $fname = File::Spec->catfile($dir, $basename);
	link $_, $fname or die "Cannot create link from '$_' to '$fname': $!\n";
}
