#!/usr/bin/perl
# file: show_rr.pm		G. Moody	28 February 2009
#				Last revised:	12 December 2010
# _____________________________________________________________________________
# show_rr module for PhysioBank's Automated Teller Machine
# Copyright (C) 2009-2010 George B. Moody

sub mod_show_rr {
    # Return immediately if no output is possible.
    if (!$annotator) {
	show_html("no-rr");
	return;
    }

    # Adjust options based on user's choice of time format.
    $tflag = "r"; # default: raw units (sample intervals)
    if ($tfmt eq "time/date") {	$tflag = "T"; }
    if ($tfmt eq "elapsed time") { $tflag = "t"; }
    if ($tfmt eq "seconds") { $tflag = "s"; }
    if ($tfmt eq "minutes") { $tflag = "m5"; }
    if ($tfmt eq "hours") { $tflag = "h7"; }

    # Set the path and URL for this request.
    $wd = "rr/$tflag";
    $wu = "$baseurl/$wd";
    $wp = "$basepath/$wd";
    $prr = "$wp/rr.txt";
    $urr = "$wu/rr.txt";

    # If results for this request are already in the cache, return them.
    if (-s $prr) {
	mod_show_rr_out();
	return;
    }

    # Create the working directory for this request.
    mkpath($wp);

    # Make a temporary filename.
    $trr = "$prr.$$";

    # Convert the selected data and save in a temporary file.
    unless (fork) {
	open(STDOUT, ">$trr");
	exec($ANN2RR, "-r", $database . "/" . $record, "-f",
	     $tstart, "-t", $tend, "-a", $annotator,
	     "-v", $tflag, "-i", "s3", "-V", $tflag, "-w", "-W");
    }

    # Wait until ann2rr is finished.
    wait;

    if (-s $prr) { # there was a race, and this process lost!
	unlink($trr);
    }
    else {
	rename($trr, $prr);
    }
    mod_show_rr_out();
}

sub mod_show_rr_out {
    if (-s $prr) {  # ann2rr was successful!
	print '<table width="100%"><tr><td align=left>';
	print '<font size=-1><b>The output below was prepared using this',
        ' command:</b><br> <pre><a href=/physiotools/wag/ann2rr-1.htm' .
	    ' title="ann2rr is a WFDB application">ann2rr</a>' .
	    " -r $database/$record -a $annotator -f $tstart -t $tend" .
	    " -v $tflag -i s3 -V $tflag -w -W" .
	    " &gt;<a href=$urr title='rr.txt is " .
	    "the output shown below'>rr.txt</a>" .
	    "</pre></font></td>" .
	    '<td align="right">' .
	    '<a href="/physiobank/annotations.shtml">Annotation key</a></td>' .
	    '<tr></table><hr>';
	print '<pre>';
	print '    t0          b0   RR (sec)   b1          t1<br>';
	show_file($prr);
	print '</pre>';
    }
    else {
	show_html("no-rr");
    }
}

1;
