<html>
<head>
<title>
<%$title .'ABC'%>
<pre>
<%$text%>
</pre>
</html>

<%flags>
    inherit => undef
</%flags>

<%args>
$key
$t=>''
$songid=>''
</%args>

<%init>

($songid)  ||= $m->dhandler_arg;

my ($text, $title) = $m->current_comp->call_method('get_abc', key=>$key, t=>$t, songid=>$songid);

</%init>

%# ******************************
%# get_abc METHOD
%# making this a method so that other components
%# can call it and take advantage of its cacheing
%# ******************************
<%method get_abc>
<%args>
$key
$t=>''
$songid=>''
</%args>
<%init>

my $conf = $m->comp('/config');
my $srcdir = $conf->{srcdir};



$key =~ s/[^ABCDEFG#b,]//gi;
$key = substr($key,0,3);

$t =~ s/[^\d-]//g;
if ($t > 12 || $t < -12){
	die "illegal value for t ($t)";
}

$songid =~ s/\..+//;
$songid =~ s/[^\w_-]//g;
$songid = substr($songid,0,100);

my $cache_key = "$songid.$key.$t";

my $text = '';
my $title;

if ( $text = $m->cache( 
            action    => 'retrieve', 
            key       => $cache_key,
            expire_if => sub { (stat "$conf->{srcdir}/$songid.abc")[9] > shift },
     ) ) { 
    ($title) = $text =~ /^T:(.+)$/m;
    return (wantarray ? ($text, $title) : $text);
}


#if no transposition necessary
if (! $t ){
    open (F, "$srcdir/$songid.abc") || die "can't open $srcdir/$songid";
    local $/ = undef;
    $text = <F>;
    close F;
}else{
    open (PIPE, "$conf->{abc2abc} $srcdir/$songid.abc -b -t $t |") || die "can't open pipe abc2abc $!";
    local $/ = undef;
    $text = <PIPE>;
    close PIPE;
}
$m->cache( action => 'store', key => $cache_key, value => $text );

($title) = $text =~ /^T:(.+)$/m;
    
return (wantarray ? ($text, $title) : $text);

</%init>

</%method>


