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

sub mod_describe_record {
    # Set the path, URL, and final output filenames and URLs for this request.
    $wd = "description";

    $ubase = "/atm/$database/$record";
    $pbase = "/ptmp$ubase";
    $dr = "record.txt";
    $pdr = "$pbase/$wd/$dr";
    $udr = "$ubase/$wd/$dr";

    $da = "$annotator.txt";
    $pda = "$basepath/$wd/$da";
    $uda = "$baseurl/$wd/$da";

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

    # Make sure there is a place for the results to go.
    mkpath("$pbase/$wd");
    mkpath("$basepath/$wd");
    
    # Make temporary filenames.
    $tdr = "$pdr.$$";
    $tda = "$pda.$$";

    unless (-s $pdr) {
	# Get and save the description in a temporary file.
	unless (fork) {
	    open(STDOUT, ">$tdr");
	    exec($WFDBDESC, $database . "/" . $record);
	}

	# Wait for wfdbdesc to finish writing the file.
	wait;
	rename($tdr, $pdr);
    }

    unless (-s $pda || !$annotator) {
	# Get and save the annotation file summary in a temporary file.
	unless (fork) {
	    open(STDOUT, ">$tda");
	    exec($SUMANN, "-r", $database . "/" . $record,
		 "-a", $annotator, "-f", $tstart, "-t", $tend);
	}
	# Wait for sumann to finish writing the file.
	wait;
	rename($tda, $pda);
    }
    mod_describe_record_out();
}

sub mod_describe_record_out {
    # Show the wfdbdesc command and its output.
    if (-s $pdr) {
	print '<font size=-1><b>The output below was prepared using this',
        ' command:</b><br> <pre><a href=/physiotools/wag/wfdbde-1.htm' .
	    ' title="wfdbdesc is a WFDB application">wfdbdesc</a> -r' .
	    " $database/$record" .
	    " &gt;<a href=$udr title='a text file (see below)'>" .
            "record.txt</a><br></pre></font><hr>";
	show_pre($pdr);
    }
    else {
	show_html("no-desc");
    }

    # Show the sumann command and its output.
    if (-s $pda) {
	print '<hr><font size=-1><b>The output below was prepared using this',
        ' command:</b><br> <pre><a href=/physiotools/wag/sumann-1.htm' .
	    ' title="sumann is a WFDB application">sumann</a> -r' .
	    " $database/$record -a $annotator -f $tstart -t $tend" .
	    " &gt;<a href=$uda title='a text file (see below)'>" .
            "$annotator.txt</a><br></pre></font><hr>";
	show_pre($pda);
    }
    else {
	show_html("no-annotations");
    }
}

1;
