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

sub mod_show_map {
    # Set the path, URL, and final output filenames for this request.
    $ubase = "/atm/$database/$record";
    $umap = "$ubase/map.png";
    $ups = "$ubase/map.ps";
    $pbase = "/ptmp$ubase";
    $pmap = "/ptmp$umap";
    $pps = "/ptmp$ups";

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

    # Make sure the output has a place to go.
    $tbase = "/ptmp/atm/scratch/$database/$record/$$";
    mkpath($tbase);
    $tscript = "$tbase/map.sh";
    $ttxt = "$tbase/map.txt";
    $tplt = "$tbase/map.plt";
    $tps = "$tbase/map.ps";
    $tmap = "$tbase/map.png";

    # Make the script for generating map.plt
    unless (fork) {
	open(STDOUT, ">$tscript");
	if ($#alist >= 0) {
	    exec($WFDBMAP, "-r", "$database/$record",
		 "-a", @alist);
	}
	else {
	    exec($WFDBMAP, "-r", "$database/$record");
	}
    }

    # Wait until wfdbmap is finished.
    wait;

    # Run the script to make map.txt and map.plt
    unless (fork) {
	open(STDOUT, ">$tplt");
	chdir($tbase);
	exec($BASH, $tscript);
    }

    # Wait until $tscript is finished.
    wait;

    # Use lwcat to convert map.plt into map.ps
    unless (fork) {
	open(STDOUT, ">$tps");
	chdir($tbase);
	exec($LWCAT, '-strip', '-eps', $tplt);
    }

    # Wait until lwcat is finished.
    wait;

    # Convert the map to a PNG.
    unless (fork) {
#	exec($CONVERT, "-density", "150", $tps, $tmap);
	exec($CONVERT, "-density", "300", $tps, $tmap);
    }

    # Wait until convert is finished.
    wait;
    if (-s $pmap) {  # there was a race, and this process lost!
	unlink($tmap);
    }
    else {
	mkpath($pbase);
	rename($tmap, $pmap);
    }
    unlink($tscript);
    unlink($ttxt);
    unlink($tplt);
    unlink($tps);
    mod_show_map_out();
}

sub mod_show_map_out {
    if (-s $pmap) {
#	print "<img src=$umap width=\"100%\">";
#	print "<img src=$umap style='width: 1200px;'>";
	print "<img src=$umap alt='[map of record]'>";
    }
    else {
	print "A map of $database/$record could not be made.";
    }
}

1;
