#!/usr/bin/perl -w
#
# Convert a single gnuplot demo script to a web page
# Usage:
#	webify xxx
#
# Reads xxx.dem and creates xxx.html along with associated 
# images output to xxx.<n>.html
#
# If gpsavediff is present also create a set of scripts
# xxx.<n>.gnu corresponding to the minimal set of commands 
# needed to generate that png image.
#
# If gnuplot_demo.css is present, link to it as a stylesheet.
#
# Ethan A Merritt <merritt@u.washington.edu>
# December 2003
#
# EAM Jan 2004
#   use gpsavediff if available
#   link to gnuplot_demo.css if available
#
# EAM Aug 2005
# If DEMOTERM is present as an environmental variable, then use
#    set term DEMOTERM
# rather than the default terminal settings
# E.g. (for image demo)
#    setenv DEMOTERM "png truecolor font 'arial,8' transparent size 420,320"
#    ./webify.pl image
#
# EAM Jan 2009
#    set term canvas
#
# EAM May 2009
#    generalized mousing support in the demos
#    each plot has its own mousebox
#    FIXME:  mousing should depend on some recognizable line in the demo script,
#	     or the mouseable demos should have a separate make target
#
# EAM May 2013
#    I've always hated the dangling partial frame at the end of the html page.
#    Re-order the main loop to get rid of it.
#
use Env qw(DEMOTERM GNUPLOT_LIB);

use Time::localtime;
use HTML::Entities;

# Use the in-tree copy of gnuplot if there is one
	my $gnuplot = ( -x "../../src/gnuplot" ) ? "../../src/gnuplot" : "gnuplot" ;

	if ((!defined $ENV{GNUPLOT_LIB}) || $GNUPLOT_LIB eq "") {
	    $GNUPLOT_LIB = "..";
	}
	my $date = ctime();
	my $plot = 1;
	my $mousing = 0;
	my $grid = 0;
	my $name = "foo";

# options
	my $iar = 0;
	if ($ARGV[$iar] eq "--mouse") {
	    $mousing = 1;
	    $iar++;
	} 
	if ($ARGV[$iar] eq "--grid") {
	    $grid = 1;
	    $iar++;
	}
	$name = $ARGV[$iar];

print STDERR $name, "\n";

# input and output files
	open(IN,  "<$GNUPLOT_LIB/$name.dem") or die "can't open $GNUPLOT_LIB/$name.dem";
	open(OUT, ">$name.html") or die "can't open $ARGV[0].html";
	binmode IN, ":encoding(UTF-8)";
	binmode OUT,":encoding(UTF-8)";

# open pipe to gnuplot and set terminal type
	open(GNUPLOT, "|$gnuplot") or die "can't find gnuplot";
	binmode GNUPLOT,":encoding(UTF-8)";
	if ((defined $ENV{DEMOTERM}) && $DEMOTERM ne "") {
	    print GNUPLOT "set term $DEMOTERM\n";
	} else {
	    print GNUPLOT "set term canvas name \"$name"."_$plot\" jsdir \".\" lw 1.6\n";
	}
	print GNUPLOT "set output \"$name.$plot.js\"\n";
	if ($grid) {
	    print GNUPLOT "set grid x y mx my\n";
	}

# find out if gpsavediff is available in current path
	my $savescripts = T;
	{local $^W=0; $savescripts = open(FOO, "|gpsavediff") }
	close FOO if ($savescripts);

# Boiler plate header
	print OUT "<!DOCTYPE HTML>\n";
	print OUT "<html>\n<head>\n<title>gnuplot demo script: $name.dem </title>\n";
	print OUT "<meta charset=\"UTF-8\" />\n";
	print OUT "<link rel=\"stylesheet\" href=\"gnuplot_demo.css\" type=\"text/css\">\n"
		  if (-e "gnuplot_demo.css");
	print OUT "<link rel=\"stylesheet\" href=\"gnuplot_mouse.css\" type=\"text/css\">\n"
		  if ($mousing && -e "gnuplot_mouse.css");

	print OUT "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n";
	print OUT "<script src=\"canvasmath.js\"></script>\n";
	print OUT "<script src=\"gnuplot_common.js\"></script>\n";
	print OUT "<script src=\"gnuplot_dashedlines.js\"></script>\n";
	print OUT "<script src=\"gnuplot_mouse.js\"></script>\n"
		  if ($mousing);

	print OUT "<script type=\"text/javascript\">\n";
	print OUT "var canvas, ctx;\n";
	print OUT "gnuplot.grid_lines = true;\n";
	print OUT "gnuplot.zoomed = false;\n";
	print OUT "gnuplot.active_plot_name = \"gnuplot_canvas\";\n";
	print OUT "gnuplot.active_plot = gnuplot.dummyplot;\n";
	print OUT "gnuplot.display_is_uptodate = false;\n";
	print OUT "gnuplot.help_URL = \"canvas_help.html\";\n";
	print OUT "gnuplot.dummyplot = function() {};\n";
	print OUT "function gnuplot_canvas( plot ) { gnuplot.active_plot(); };\n";
	print OUT "</script>\n";

	print OUT "</head>\n";
	print OUT "<body oncontextmenu=\"return false;\">\n";
	print OUT "<a href=index.html><image src=return.png alt=\"Back to demo index\" class=\"icon-image\"></a>\n";
	print OUT "<h2>gnuplot demo script: <font color=blue>$name.dem</font> </h2>\n";
	print OUT "<i>autogenerated by webify.pl on $date</i>";

# try to find gnuplot version
	$version = `$gnuplot --version`;
	print OUT "\n<br><i>gnuplot version $version</i>";
	print OUT "<hr>\n";

# Echo plot commands to a temp file
	open(ECHO, "+>commands.tmp") or die "can't open commands.tmp";
	binmode ECHO,":encoding(UTF-8)";

# Start processing
	while (<IN>) {
		if (/^ *pause -1/) {
			print OUT "<table class=\"noborder\"><tr><td>";

			print OUT "<script src=\"$name.$plot.js\"></script>\n";
			print OUT "<canvas id=\"$name"."_$plot\" width=600 height=400 tabindex=\"0\">\n";
			print OUT "    <div id='errorDiv'>Your browser does not support the HTML 5 canvas element</div>\n";
			print OUT "</canvas>\n";
			print OUT "<script>\n";
			print OUT "if (window.attachEvent) {window.attachEvent('onload', $name"."_$plot);}\n";
			print OUT "else if (window.addEventListener) {window.addEventListener('load', $name"."_$plot, false);}\n";
			print OUT "else {document.addEventListener('load', $name"."_$plot, false);}\n";
			print OUT "gnuplot.grid_lines = true;\n";
			print OUT "gnuplot.zoom = false;\n";
			print OUT "</script>\n";

			print OUT "</td><td class=\"noborder\">\n";

			# Copy mouse box into output stream
			if ($mousing && -e "mousebox.template") {
			    my $spanid = $name."_".$plot;
	    		    open(MOUSEBOX,  "<mousebox.template") or die "can't open mousebox.template";
	    		    while (<MOUSEBOX>) { s/ACTIVE_PLOT_NAME/$spanid/; print OUT; }
	    		    close MOUSEBOX;
			}

			print OUT "<pre>\n";

			## FIXME: dump contents of ECHO into OUT here
			seek ECHO, 0, 0;
			print OUT <ECHO>;
			close ECHO;
			open(ECHO, "+>commands.tmp") or die "can't open commands.tmp";
			binmode ECHO,":encoding(UTF-8)";

			if ($savescripts) {
			    print OUT "<br>Click <a href=$name.$plot.gnu>here</a> ",
				  "for minimal script to generate this plot\n";
			    print GNUPLOT "save \"| gpsavediff > $name.$plot.gnu\"\n";
			}
			print OUT "</pre></td></tr></table>\n<br clear=all>\n<hr>\n";

			$plot++;
	    		print GNUPLOT "set term canvas name \"$name"."_$plot\" jsdir \".\" lw 1.6\n";
			print GNUPLOT "set output \"$name.$plot.js\"\n";
	
		} elsif (/^pause/) {
	    		print GNUPLOT "set term canvas name \"$name"."_$plot\" jsdir \".\" lw 1.6\n";
			print GNUPLOT "set output \"$name.$plot.js\"\n";
		} elsif (/^ *reset/) {
			print GNUPLOT;
		} else {
			print ECHO HTML::Entities::encode($_);
			print GNUPLOT;
		}
	}

# Amazingly enough, that's it.
# Unlink leftover empty plot before leaving.
	close GNUPLOT;
	unlink("$name.$plot.js");
	close ECHO;
	unlink("commands.tmp");
# The filled curve mechanism requires an associated canvas element somewhere in the document.
# We stick it at the end and mark it "hidden".
	print OUT "<canvas id=\"Tile\" width=\"32\" height=\"32\" hidden></canvas>\n";
	print OUT "</body>\n</html>\n";

