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

sub mod_samples_to_EDF {

    # If the record is already an EDF, provide a link for downloading it
    # but do nothing more.
    if ($record =~ /\./) {
	print "<p><b>This record is already in European Data Format (EDF). ",
	      "Download</b> <a href=/physiobank/database/$database/$record>",
	      "<tt>$database/$record</tt></a>.<hr>";
	return;
    }

    # Set the path, URL, and final output filenames and URLs for this request.
    $wd =    "export/edf";
    $wu =    "$baseurl/$wd";
    $wp =    "$basepath/$wd";
    $edf =   "$record" . ".edf";
    $pedf =  "$wp/$edf";
    $uedf =  "$wu/$edf";

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

    # Make sure the output has a place to go.  ($record may include path info.)
    $wt = "/ptmp/atm/scratch/$$/";
    $wtr = "$wt/$record";
    mkpath($wtr);

    # Make a temporary filename.
    $tedf = "$wt/$edf";

    unless (fork) {
	chdir $wt;
	exec($MIT2EDF, "-r", "$database/$record", "-o", $edf);
    }

    # Wait until mit2edf is finished.
    wait;

    if (-s "$pedf") {  # there was a race, and this process lost!
	unlink("$tedf");
	# cron will remove $wt
    }
    else {
	# make sure path to $pedf exists ($record might include path info)
	mkpath("$wp/$record");
	rename("$tedf", "$pedf");
    }
    mod_edf_out();
}

sub mod_edf_out {
    # Show the command and the download link.
    if (-s $pedf) {
	$tsize = -s $pedf;
	print '<font size=-1><b>The output was prepared using this',
        ' command:</b><br> <pre><a href=/physiotools/wag/mit2ed-1.htm' .
	    ' title="mit2edf is a WFDB application">mit2edf</a>' .
	    " -r $database/$record -o " .
	    "<a href=$uedf ". 'title="this is the generated EDF file">' .
	    "$edf</a></pre>" .
	    "<b>Download</b>: <a href=$uedf>$edf</a> ($tsize bytes)<br>" .
	    "<b>Note</b>:  The entire record has been converted " .
	    "(<tt>mit2edf</tt> does not convert only a region of interest)." .
	    "</font><hr>";
    }
    else {
	show_html("no-samples");
    }
}

1;
