#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;

# byte values of <GALAXY>/static/images/square_running.gif
my @square_gif = (71,73,70,56,57,97,9,0,9,0,179,11,0,0,0,0,41,74,74,115,132,148,165,82,41,189,189,189,206,132,57,222,222,222,255,165,0,255,214,0,255,255,0,255,255,206,160,82,45,0,0,0,0,0,0,0,0,0,160,82,45,33,255,11,78,69,84,83,67,65,80,69,50,46,48,3,1,0,0,0,33,249,4,5,50,0,15,0,44,0,0,0,0,9,0,9,0,0,4,31,16,200,73,149,74,24,203,139,145,151,157,135,28,160,120,156,146,119,158,133,180,30,69,177,184,176,188,204,84,30,1,0,33,249,4,5,20,0,15,0,44,1,0,1,0,7,0,7,0,0,4,20,208,24,66,233,172,66,224,172,9,15,1,39,128,225,72,2,100,0,172,17,0,59,83,52,21,1,0,59);

my $output_html ;
my $output_path ;
my $output_count; 

# Get options from command line (i.e. galaxy)
my $result = GetOptions ( "output_html=s" => \$output_html,
			   "output_path=s" => \$output_path,
		  	   "count=i" => \$output_count )
			   or die "Bad options";

# Create the output directory (for the multiple output files)
mkdir $output_path 
	or die "Failed to create output directory '$output_path': $! ";

# Create a couple of dummy files
my @all_files = qw/FOO.txt BAR.txt BAZ.txt OOF.txt RAB.txt ZAB.txt/ ;

# Take as many files as the user requested
my @subfiles = splice @all_files, 0, $output_count ;

# Create each dummy output file
foreach my $sub_filename ( @subfiles ) {
	my $filename = $output_path . '/' . $sub_filename ;
	open FILE, ">", $filename 
		or die "Failed to create file '$filename': $! " ;
	print FILE "This is the $sub_filename file\n";
	print FILE "\n";
	print FILE "output_path = $output_path\n";
	print FILE "This file= $filename\n";
	close FILE ;
}

# Create a GIF image
open GIF, ">", $output_path . '/square.gif'
	or die "Failed to create $output_path/square.gif: $! ";
binmode GIF;
print GIF join('', map { chr } @square_gif );
close GIF;


# Create the output HTML, with links to the files and the square gif.
#
open HTML, ">", $output_html 
	or die "Failed to create output HTML file '$output_html': $! ";

print HTML<<EOF;
<html>
<head>
<style>
iframe { 
	border: 0px; 
	background: #eeeeee ;
}
</style>
</head>
<body>
<h1>Multiple Outputs in a Galaxy Tool</h1>
<h2>Genereated $output_count output files + 1 GIF file</h2>
EOF

# Put direct links to each output file
foreach my $sub_filename ( @subfiles ) {
	print HTML "<img src=\"square.gif\">&nbsp;";
	print HTML "Direct link to the <a href=\"$sub_filename\">$sub_filename</a> file.<br/>\n";
}

print HTML "<br/><br/><br/>\n";

# Show each output file as inlined <IFRAME>
foreach my $sub_filename ( @subfiles ) {
	print HTML "<br/><br/>\nContent of the ${sub_filename} file:<br/>\n";
	print HTML "<iframe src=\"$sub_filename\"></iframe>\n";
}

print HTML "</body></html>\n" ;

close HTML ;
