#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:standard/;
use IPC::Run qw(run timeout);


my $h2d = "/homes/dcw/bin/haskell2dafny";

print header,
	start_html('Haskell-Subset 2 Dafny mini translator'),
	h1('Haskell-Subset 2 Dafny mini translator'),
	start_form,
	"Enter a Haskell subset program (containing any number of functions of Int->Int, with or without their type declaration, defined by guarded expressions, plus a single expression - eg. calling f(x) for some value of x) ",br,
	textarea('program',"f x = 10\nf(1)", 10,80),p,
	submit("Translate to Dafny"),
	end_form,
	hr;

if (param())
{
	my $prog = param('program') || "";
	#my $prog = "f x = 10\nf(10)";
	$prog =~ tr/\015//d;

	my @proglines = split(/\n/, $prog);

	#my @ch = split(//, $prog );
	#foreach my $ch (@ch)
	#{
	#	my $x = ord $ch;
	#	print br, "debug: ch=$ch ($x)\n";
	#}

	#my $htmlprog = join( "<br>", @proglines );
	#print "Your program is",br,em($htmlprog),p, hr;
	#print "translating to dafny:",br;

	my @cmd = ($h2d, "-e", "3");
	#print p, "debug: running @cmd with input<p> <pre>$prog</pre>\n";
	my $err = "";
	my $out = "";
	run \@cmd, \$prog, \$out, \$err, timeout( 10 );
	if( $err )
	{
		$err =~ s/^\s+//;
		print p, pre($err);
	} else
	{
		my @x = ( "// Dafny program corresponding to the following Haskell:", "//" );
		push @x, map { "// $_" } @proglines;
		push @x, split(/\n/, $out);
		my $htmlout = join( "\n", @x );
		print p, "result: ", p, "<pre>$htmlout</pre>";
	}
}
