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

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

    # Set defaults.
    $tflag = ""; # standard time format if no other specified

    # Adjust options based on user's choice of time format.
    if ($tfmt eq "elapsed time") { $tflag = "e"; }
    if ($tfmt eq "seconds") { $tflag = "x"; }
    if ($tfmt eq "minutes") { $tflag = "x"; }
    if ($tfmt eq "hours") { $tflag = "x"; }

    # Set the path and URL for this request.
    if ($tflag) { $wd = "rdann/$tflag"; }
    else { $wd = "rdann"; }
    $wu = "$baseurl/$wd";
    $wp = "$basepath/$wd";

    # If results for this request are already in the cache, return them.
    if (-s "$wp/annotations.txt") {
	mod_show_annotations_out();
	return;
    }
	
    # Create the working directory for this request.
    mkpath($wp);

    # Make a temporary filename.
    $txt = "$wp/$$.txt";

    # Convert the selected data and save in a temporary file.
    unless (fork) {
	open(STDOUT, ">$txt");
	if ($tflag) {
	    exec($RDANN, "-r", "$database/$record", "-f",
		 $tstart, "-t", $tend, "-a", $annotator, "-v", "-$tflag");
	}
	else {
	    exec($RDANN, "-r", "$database/$record", "-f",
		 $tstart, "-t", $tend, "-a", $annotator, "-v");
	}
    }
    # When rdann is finished, check if it wrote anything.
    wait;

    if (-s "$wp/annotations.txt") { # there was a race, and this process lost!
	unlink($txt);
    }
    else {
	rename($txt, "$wp/annotations.txt");
    }
    mod_show_annotations_out();
}

sub mod_show_annotations_out {
    if (-s "$wp/annotations.txt") {
	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/rdann-1.htm' .
	    ' title="rdann is a WFDB application">rdann</a>' .
	    " -r $database/$record -f $tstart -t $tend -a $annotator -v";
	if ($tflag) { print " -$tflag"; }
	print " &gt;<a href=$wu/annotations.txt title='annotations.txt is " .
	    "the output shown below'>annotations.txt</a>" .
	    "</pre></font></td>" .
	    '<td align="right">' .
	    '<a href="/physiobank/annotations.shtml">Annotation key</a></td>' .
	    '<tr></table><hr>';
	print '<pre>';
	show_file("$wp/annotations.txt");
	print '</pre>';
    }
    else {
	show_html("no-annotations");
    }
}

1;
