#!/usr/bin/perl

use strict;

=pod

Script to add id3 tags to mp3 files that don't have them.

Prerequisites: id3tool (http://kitsumi.xware.cx/id3tool/)

Parameters: a pathname to an mp3 file, in the format

   ..../artist_name/album_name/file_name.mp3

What it does: munge artist name and album name and file name to come up
with a vaguely readable set of tags, then use id3tool to apply them to the
mp3 file.

Copyright: Created by Charles Stross, 2002. Distributed under the
terms of the GNU Lesser Public License (LGPL): see 
http://www.gnu.org/copyleft/lesser.html for details.


=cut

# when preparing song titles, we uppercase all words that don't appear in
# this list. (We also uppercase these words if they're the first in the 
# song title.)

my %nu = ( 
  the => 1,
  a => 1,
  to => 1,
  in => 1,
  and => 1,
  my => 1,
  of => 1,
  it => 1,
  got => 1,
  go => 1,
  then => 1,
  only => 1,
  or => 1,
  only => 1,
);

# groups with acronyms; if some of your artists have long names or live
# in directories that don't carry their names, this table is used to
# translate directory names into group names

my %groupmap = ( 
  "Klf" => "KLF",
  "Fsol" => "The Future Sound of London",
  "Kmfdm" => "KMFDM",
  "Wmtid" => "WMTID",
  "Pwei" => "Pop Will Eat Itself",
);

# get pathname to work on and start munching on it

my $target = shift @ARGV;
chomp $target;
my @targetpath = split(/\//, $target);

my $fname = pop @targetpath;

my $album = pop @targetpath;
$album =~ s/_/ /g;
$album = join( ' ',  map {ucfirst $_ } split(/\s+/, $album));
$album =~ s/'/\\'/g;

my $group = pop @targetpath;
# convert underscores to spaces
$group =~ s/_/ /g;
# canonicalize whitespace 
$group = join( ' ',  map {ucfirst $_ } map { lc $_ } split(/\s+/, $group ));
# expand acronyms
if (exists $groupmap{$group}) { 
   $group = $groupmap{$group} ;
};
# escape apostrophes
$group =~ s/'/\\'/g;


my $title = $fname; 
# sanitize song  titles
$title =~ s/\.mp3//;
$title =~ s/^(\d+[-\.]\s*)(.*$)/$2/;
$title =~ s/_([ts])_/'$1_/g;
$title =~ s/([su])nt/$1n't/g;
$title =~ s/can_t/can't/g;
$title =~ s/_/ /g;

# do the funky mostly-uppercase thing
$title = join ' ', map {
                 if (exists $nu{lc($_)}) { lcfirst $_ } else { ucfirst $_ }
                       } split(/\s+/, $title);

$title = ucfirst($title); # override no-uppercase table if first letter 
$title =~ s/'/\\'/g;


#$target =~ s/([\W])/\\$1/g;
#$target =~ s|\\/|/|g;
$target =~ s/'/\'/g;
$target = "'" . $target . "'";

# ready to run id3tool
print "$target\n";
my $exec = "id3tool --set-title='$title' --set-album='$album' --set-artist='$group' $target";

system $exec;

