#!/usr/bin/perl

require 'libCGI.pl';
require "MBGD_commonPath.pl";
use MBGD::WWW;
use UserInfo;

$WWWROOT = $ENV{'WWWROOT'};

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

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

$| = 1;

##%Args = &CGI_GetArgs;
$WWW = MBGD::WWW->new;
%Args = $WWW->cgiGetArgs;
$uInfo = $WWW->uInfo;

if ($Args{'tree'}) {
	$tree = $Args{'tree'};
} elsif ($Args{'alifile'}) {
	my($opt);
	if ($Args{bootstrap}) {
		$type = 'bootstrap';
	} else {
		$type = 'NJ';
	}
	if ($Args{format} =~ /newick_boot/i) {
		$type = 'bootstrap';
	} elsif ($Args{format} =~ /dist/i) {
		$opt .= " -outputtree=dist";
		$type = 'dist';
	}
	if ($Args{tossgaps}) {
		$opt .= " -tossgaps";
	}
	if ($Args{kimura}) {
		$opt .= " -kimura";
	}
	
	$tree = &create_tree($Args{'alifile'}, $type, $opt);
}
if ($type ne 'dist') {
	$tree =~ s/\n//g;
}

if ($Args{format} =~ /png/i) {
    print "content-type: text/html\n";
    print "\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=$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=\"$tree\">\n";
    print "<INPUT TYPE=submit VALUE=\"Postscript\">\n";
    print "</FORM>\n";
    print "</BODY>\n";
} elsif ($Args{format} =~ /postscript/i) {
    my $input = "image=postscript&tree=$tree";
    $ENV{CONTENT_LENGTH} = length($input);
    exec("$DIR_www/htbin/drawtree<<EOF
$input
EOF");
} else {
    print "content-type: text/plain\n\n";
    print "$tree\n";
}


sub create_tree {
	my($tmpfilename, $type, $opt) = @_;
	my($tree);
	$tmpfile = $uInfo->getpath($tmpfilename);
	if ($type eq 'NJ' || $type eq 'dist') {
		$opt = "-tree $opt";
	} elsif ($type eq 'bootstrap') {
		$opt = "-bootstrap $opt";
	}
	system("$CMD_clustalw $tmpfile.aln $opt >& /dev/null");
	
	if ($type eq 'NJ') {
		rename("$tmpfile.ph", "$tmpfile.dnd");
	} elsif ($type eq 'bootstrap') {
		rename("$tmpfile.phb", "$tmpfile.dnd");
	} elsif ($type eq 'dist') {
		rename("$tmpfile.dst", "$tmpfile.dnd");
	}
	if (open(TMP, "$tmpfile.dnd")) {
		while (<TMP>){
			$tree .= $_;
		}
		close(TMP);
	}
	$tree;
}
