<%once>
use File::Temp;
</%once>
<%flags>
    inherit => undef
</%flags>


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

<%init>

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

my $basedir = Apache->request->dir_config('basedir');
my $conf = $m->comp("/$basedir/config");



	#clean up incoming data
$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);

	#here's our output method
my $send_img = sub {
      $r->content_type( "audio/midi" );
      $r->send_http_header;
      $m->out($_[0]);
      $m->abort(200);
    };

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

	#if it's already in the cache, just return that
if ( my $data = $m->cache( 
            action    => 'retrieve', 
            key       => $cache_key,
            expire_if => sub { (stat "$conf->{srcdir}/$songid.abc")[9] > shift },
     ) ) { 
      $send_img->($data);
}

	#it's not in the cache, get the ABC for this key (that at least 
	#might be cached)
my $abctext = $m->comp("/$basedir/abc/dhandler:get_abc",key=>$key, t=>$t, songid=>$songid);


	#Now we're going to convert the ABC to midi
	#using abc2midi
	#This uses way too many dump tempfiles, but abc2midi doesn't
	#seem to do stdin or stdout

my $dir = File::Temp::tempdir( DIR => $conf->{tmpdir}, CLEANUP => 1 );

open (F, ">$dir/in.abc") || die "can't open $dir/in $!";
print F $abctext;
close F;

	#Here's the pipe to the tempfile:
#my $cmd = "$conf->{abc2midi} $dir/in.abc -o $dir/output.mid";
my $cmd = "$conf->{abc2midi} - -o $dir/output.mid";
#`$cmd`;  #needs error checking
open (T, ">/tmp/kgtest");
print T "$cmd\n";
close T;
open (PIPE, "| $cmd ") || die "can't open pipe to $cmd $!";
print PIPE $abctext;
close PIPE || die "can't close pipe $!";

-f "$dir/output.mid" || die "abc2midi failed to produce output file: $cmd";

	#Now we read back from the temp file
my $img_data;
open (F, "$dir/output.mid") || die "can't open $dir/output.mid $!";
{ local $/ = undef; $img_data = <F>; }
close F;
unlink "$dir/output.mid" || die "can't unlink $dir/output.mid $!";
unlink "$dir/in.abc" || die "can't unlink $dir/in.abc $!";
rmdir $dir;

	#add it to the cache for next time
$m->cache( action => 'store', key => $cache_key, value => $img_data );

	#and send it out
$send_img->($img_data);

</%init>
