#!/usr/bin/perl -w
use strict;
use Cwd qw(abs_path);
foreach(@ARGV) {
    $_ = abs_path($_);
    my $disc;
    my $album;
    my $track;
    my $artist;
    my $composer;
    my $title;
    if(m%/([^/]*)/([0-9]+)/([^/]+).mp3$%) {
	# multi disc album.
	$disc = $2;
	$album = $1;
	$track = $3;
    } else {
	m%/([^/]*)/([^/]+).mp3$% or goto error;
	$album = $1;
	$track = $2;
    }
    if($track =~ /([0-9]+)\.(.*)/) {
	$track = $1; $title = $2;
    } else {
	$title = $track;
	$track = '';
    }
    if($album =~ /(.*?) - (.*)/) {
	$artist = $1;
    } else {
	# various artists cd.
	$title =~ /(.*?) - (.*)/ or goto error;
	$artist = $1; # $title = $2;
    }

    $disc and disc($_, $disc);
    $album and album($_, $album);
    $track and track($_, $track);
    $artist and artist($_, $artist);
    $composer and composer($_, $composer);
    $title and title($_, $title);
    next;
  error:
     print STDERR "Warning: could not parse $_\n";
     next;
}

sub recode {
    my $tocode = shift;
    $tocode =~ s/"/\\"/g;
    $tocode =~ s/_/?/g;
    return $tocode;
}

sub album {
    my ($filename, $value) = @_;
    system('id3v2', '-A', recode($value), $filename);
}

sub title {
    my ($filename, $value) = @_;
    system('id3v2', '--TIT1', '', '--TIT3', '', '-t', recode($value), $filename);
}

sub composer {
    my ($filename, $value) = @_;
    system('id3v2', '--TCOM', recode($value), $filename);
}

sub artist {
    my ($filename, $value) = @_;
    system('id3v2', '-a', recode($value), $filename);
}

sub disc {
    my ($filename, $value) = @_;
    system('id3v2', '--TPOS', recode($value), $filename);
}

sub track {
    my ($filename, $value) = @_;
    system('id3v2', '--TRCK', recode($value), $filename);
}
