#!/usr/bin/perl
# file: record_to_zip.pm	G. Moody         16 March 2009
#				Last revised:	  25 May 2016
# _____________________________________________________________________________
# record_to_zip module for PhysioBank's Automated Teller Machine
# Copyright (C) 2009-2010 George B. Moody

use File::Basename;

sub mod_record_to_zip {
    # Set the path, URL, and final output filenames for this request.
    $ubase = "/atm/$database/$record/export";
    $pbase = "/ptmp$ubase";
    $orec = basename($record);
    $pzip = "$pbase/$orec.zip";
    $ptoc = "$pzip.toc";
    $uzip = "$ubase/$orec.zip";

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

    # Make sure the output has a place to go.
    mkpath($pbase);
    $tzip = "$pzip.$$";
    $ttoc = "$ptoc.$$";

    unless (fork) {
	open(STDOUT, ">$ttoc");
	chdir("/home/physionet/html/physiobank/database/$database");
	exec "$ZIP -r $tzip $record*";
    }

    # Wait until zip is finished.
    wait;

    if (-s $ptoc) {  # there was a race, and this process lost!
	unlink($tzip);
	unlink($ttoc);
    }
    else {
	rename($tzip, $pzip);
	rename($ttoc, $ptoc);
    }
    mod_record_to_zip_out();
}

sub mod_record_to_zip_out {
    if (-s $ptoc) {
	$tsize = -s $pzip;
	print "Download <a href=$uzip><tt>$orec.zip</tt></a>",
	      " ($tsize bytes).  Once you",
	      " have completed the download, unpack the zip file by running",
	      " the command:<pre>unzip $orec.zip</pre>",
	      " (or use your favorite PKZIP-compatible utility to unpack it).",
	      " By default, the contents of the zip file are unpacked into the",
	      " current directory.",
	      "<p>The contents of <tt>$orec.zip</tt> are listed below:",
	      "<hr><pre>";
	show_file($ptoc);
	print "</pre>";
    }
    else {
	print "A zip file of $database/$record could not be made.  Please",
              " go <a href=/physiobank/database/$database>here</a> to download",
	      " the individual files of record $record.";
    }
}

1;
