#!/usr/bin/perl

require 'libCGI.pl';
require "MBGD_commonPath.pl";

$WWWROOT = $ENV{'WWWROOT'};

$tmpdir = "$DIR_tmp/drawtree.$$";
$tmpfile = "drawtree.$$";

$SIG{'INTR'} = 'IGNORE';
$SIG{'HUP'} = 'IGNORE';

$| = 1;

%Args = &CGI_GetArgs;
print STDERR ">$Args{tree}<\n";

if (! $Args{'image'}) {
	print "content-type: text/html\n\n";
	print "<HTML><HEAD><TITLE>Phylogenetic tree</TITLE></HEAD>\n";
	print "<BODY bgcolor=#ffffff><H2>Phylogenetic tree</H2>\n";
	print "<IMG SRC=\"/htbin/drawtree?image=1&tree=$Args{'tree'}\">\n";
	print "<FORM ACTION=/htbin/drawtree METHOD=POST>\n";
	print "<INPUT TYPE=hidden NAME=image VALUE=postscript>\n";
	print "<INPUT TYPE=hidden NAME=tree VALUE=\"$Args{'tree'}\">\n";
	print "<INPUT TYPE=submit VALUE=\"Postscript\">\n";
	print "</FORM>\n";
	print "</BODY>\n";
	exit(0);
}
if ($Args{'image'} eq 'postscript') {
	print "content-type: application/postscript\n";
	print "\n";
} else {
	print "content-type: image/png\n\n";
}

die if (! $Args{'tree'});

mkdir "$tmpdir", 0770;
chdir("$tmpdir");
$ENV{PWD} =  $tmpdir;

open(TMP, ">$tmpfile") || die;
print TMP "$Args{'tree'}\n";
close(TMP);

#
system("$DIR_phylip/drawtree > /dev/null <<EOF
$tmpfile
$DIR_phylip/font1
v
n
i
i
y
EOF");

if(! -f "plotfile"){
	print STDERR "error: plot file not found\n";
}
rename("plotfile", "${tmpfile}.ps");
if ($Args{image} eq 'postscript') {
	system("cat -u ${tmpfile}.ps");
} else {
	system("$CMD_convert ${tmpfile}.ps ${tmpfile}.png");
	if (-f "${tmpfile}.png.0") {
		system("cat -u ${tmpfile}.png.0");
	} elsif (-f "${tmpfile}.png") {
		system("cat -u ${tmpfile}.png");
	} else {
		print STDERR "drawtree: ${tmpfile}.png.0 not found\n";
	}
}

unlink( "${tmpfile}" );
unlink( "${tmpfile}.ps" );
unlink( "${tmpfile}.png" ) if (-f "${tmpfile}.png");
unlink( "${tmpfile}.png.0" );
unlink( "${tmpfile}.png.1" );
chdir("$tmpdir/..");
rmdir( "${tmpdir}" );
