#!/usr/bin/perl 

use strict;
use CGI qw(:standard);
use GD;

print "Content-type: text/html\n\n";

         print "<HTML><head>\n";
         print "<title>Network Navigation</title></head>\n";
         print <<END_OF_BANNER;
         <BODY BGCOLOR="#FFFFFF" MARGINHEIGHT=0 MARGINWIDTH=0 TOPMARGIN=0 LEFTMARGIN=0>
         <FORM METHOD="GET" ACTION="http://bioinfo.mbb.yale.edu/genome/search/superlink.cgi">
         <TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR=#000077>
         <TR><TD NOWRAP ALIGN=LEFT><A HREF="http://www.yale.edu"><IMG SRC="http://bioinfo.mbb.yale.edu/genecensus/header/picture/yale.jpg"
         alt="Yale" HEIGHT="29" WIDTH="53" BORDER="0"></A>
         <A HREF="http://bioinfo.mbb.yale.edu"><IMG SRC="http://bioinfo.mbb.yale.edu//genecensus/header/picture/gerstein.jpg"
         HEIGHT="29" WIDTH="139" ALT="Gerstein Lab" BORDER="0"></A></TD>

         </TR></TABLE></FORM>
	   <body><center>

END_OF_BANNER


my $cgi = new CGI;
my $bait = $cgi->param('ORF_name');               ### node to start the navigation ###
my $cutoff = $cgi->param('cutoff');			 ### The likelihood ratio cutoff
my $PI = $cgi->param('dataset');			 ### The interaction dataset

my $Lfile = "../pull_down/L/L_PIT/" . $bait . ".txt"; # the file to read in the likelihood ratio information;
my %L; # the likelihood ratio for each pair of interaction;
my $N;
my $ratio;
my $orf;
my %nei;
my $group;
my $line;
my @data;
my @datasets;
my $i=0;
my $infile;
my ($NEW, $OUTPUT, $DATASET);
my @dataset_description;
my $k=0;
my $gnum=0;
my $description;
my $length=0;
my $total_level=0;
my $time_id=time;    ### different IDs for different tasks ###
my $element_file = './results/'.$time_id.'.txt';     ### output file ###

### checking the input ###
my $factor = 0;

if ($bait eq "")
  {
   $factor = 1;
   print "<B> Did you forget to input the starting node?</B><BR>";
  }

if ($PI eq "")
  {
   $factor = 1;
   print "<B> Did you forget to select any interaction datasets? </B><BR>";
  }

if ($cutoff eq "") {
	$factor = 1;
	print "<B> Did you forget to input the likelihood ratio cutoff?</B><BR>";
}

if (!($cutoff =~ /^(\d+\.?\d*|\.\d+)$/) || ($cutoff < 0)) {
	$factor = 1;
	print "<B> The cutoff has to be a number larger than or equal to 0!</B><BR>";
}

if ($factor)
  {
   print "<BR><B> Input error! </B><BR>";
   print "&nbsp&nbsp <a href = \"./index.html\">Return to the main menu </a></center></body></html>\n";
   exit;
  }
 
$bait =~ s/\-//g;
$bait =~ tr/[a-z]/[A-Z]/;

(open (OUTPUT, ">$element_file")) || die " cannot open the out file";

# Read in the Likelihood ratio information from the dataset that the user chooses;
if ($PI eq "PIP") {
	$N = 2;
}
if ($PI eq "PIE") {
	$N = 1;
}
if ($PI eq "PIT") {
	$N = 3;
}
open (DATA, $Lfile) || die "Unable to open $Lfile";
while (<DATA>) {
	chomp;
	my @temp = split (/\t/);
	$temp[0] =~ tr/[a-z]/[A-Z]/;
	$temp[0] =~ s/\-//g;
	$temp[$N] = -1 if ($temp[$N] eq "NA");
	$L{$temp[0]} = $temp[$N] if ($temp[$N] >= $cutoff);
	$nei{$temp[0]}[0] = 0 if ($temp[$N] >= $cutoff); # The neighbours of the orf that the user is interested in, the neighbors must have a ratio larger than the cutoff;
}
close (DATA);


#deal with the data sets $datasets
#=======================
### Selection of databases ###

    $dataset_description[$k++]='Gold standard positives';            ### description for this interaction dataset ###
    $datasets[$gnum++]='MIPS.txt'; ### path for this interaction dataset ###

    $dataset_description[$k++]='Interacting pairs from BIND and DIP';
    $datasets[$gnum++]='BD.txt';

    $dataset_description[$k++]='in vivo pull down dataset by Gavin et al';
    $datasets[$gnum++]='Gavin.txt';

    $dataset_description[$k++]='in vivo pull down dataset by Ho et al';
    $datasets[$gnum++]='Ho.txt';

    $dataset_description[$k++]='Yeast two hybrid dataset by Uetz et al';
    $datasets[$gnum++]='Uetz.txt';

    $dataset_description[$k++]='Yeast two hybrid dataset by Ito et al';
    $datasets[$gnum++]='Ito.txt';

    $dataset_description[$k++]='Gold standard negatives';
    $datasets[$gnum++]='Neg.txt';
 



####################################################
# read in the negative data in virtual-bait format #
####################################################
my $k = $gnum - 1;
my $negfile = $bait . ".txt";
open (DATA, "./Neg/$negfile");
while (<DATA>) {
	chomp;
	$nei{$_}[$k] = 1 if (exists $nei{$_});
}
close (DATA);
#########################
# End of read negatives #
#########################




for($i=0; $i<$k; $i++)
   {
    $infile=$datasets[$i];
    ### combine all the interaction datasets ###
    (open(DATASET, "<$infile")) || die "cannot open the data file";
    while($line=<DATASET>)
        {
        chomp($line);
        @data=split("\t", $line);
        $data[0] =~ s/\-//g;
        $data[0] =~ tr/[a-z]/[A-Z]/;
        $data[1] =~ s/\-//g;
        $data[1] =~ tr/[a-z]/[A-Z]/;

        if (($data[0] eq $bait) && (exists $nei{$data[1]}))
          {
           $nei{$data[1]}[$i]=1;
           }
        elsif(($data[1] eq $bait) && (exists $nei{$data[0]}))
          {
           $nei{$data[0]}[$i]=1;
          }
      }
	close (DATASET);
   }

for $group(keys %nei)
   {
    $length++;
    for ($i=0; $i<$gnum; $i++)
        {
         if (!defined($nei{$group}[$i]))
            {
             $nei{$group}[$i]=0;
            }
        }
    } 



print "<h1>Network Navigation Output for <b>$bait</b></h1><BR>\n";
print <<END_DES;
<table border="1" width="700" cellspacing=0 cellpadding =2 bgcolor="FFFFFF">
	<tr>
		<td><B>Probabilistic interactome</B></td>
END_DES
	   print "<td>$PI</td></tr>\n";
	   print "<td><B>Virtual bait</B></td>\n";
         print "<td>$bait</td></tr>\n";
	   print "<tr><td><B>Likelihood ratio cutoff</B></td>";
	   print "<td>$cutoff</td></tr>\n";
         print "<tr><td><B>Number of Interactions</B></td>";
         print "<td>$length</td></tr>\n";
         print "</table><BR><BR><P>\n";


print 'You can also choose to display the result in a table (recomended when too many interactions)<BR>';
print '<form method="post" action="table.cgi">'."\n";
print "<input type=\"hidden\" name=\"orf\" value=$bait>\n";
print "<input type=\"hidden\" name=\"cutoff\" value=$cutoff>\n";
print '<input type="hidden" name="dataset" value="'."$PI".'">'."\n";
print '<input type="hidden" name="file" value="'.$element_file.'">'."\n";
print '<input type="submit" value="Display the table">';
print '</form>';
print '<BR>Click <A HREF="http://genome-www4.stanford.edu/cgi-bin/SGD/locus.pl?locus='."$bait".'"><b><i>here</i></b></a> to get SGD annotation for <B>'."$bait"."</B><BR>";
print '<BR><A HREF="index.html"><i>Return to the main menu</i></A></BR>';
print OUTPUT "ORF\tLikelihood ratio";
for ($i=0; $i<$k; $i++)
   {
    print OUTPUT "\t$dataset_description[$i]";
   }
print OUTPUT "\n";

for $group(keys %nei)
   {
    print OUTPUT "$group\t$L{$group}";
    for ($i=0; $i<$gnum; $i++)
        {
         print OUTPUT "\t$nei{$group}[$i]";
        }
    print OUTPUT "\n";
    }
close(OUTPUT); 
close (DATASET);

# draw the graph
#==============================
if ($length==0)
  {
   print "<BR><h3>No interactions found for $bait with likelihood ratios larger than or equal to $cutoff</h3>";
   print "</center></body></html>\n";
   exit;
  }
$total_level=int(log($length/5)/log(2))+2;
my $total_x = 180 * $total_level + 100;
my $total_y = 200 * $total_level+100;
$total_x=(($total_x < 400)?400:$total_x);
$total_y=(($total_y < 400)?400:$total_y);

my $center_x= $total_x/2;
my $center_y= $total_y/2+80;

print '<br><map name=img_map>'."\n";
my $im = new GD::Image ($total_x, $total_y+20);
my $i=0;
my ($ALL, $FILE);
my ($x1, $y1, $x2, $y2);
my $label;
my $radius;
my $angle;
my $ele_angle;
my $start_angle;
my $level=0;
my @level_num;
my $line;
my @data;
my $left=$length;
my $pi=atan2(1,1)*4;
my $piover180=$pi/180;
my $ele_num;
my $html;
my @colors;
my $label;
my $time='results/'."$time_id".'.png';

(open (FILE, "<$element_file")) || die "cannot open the infile";
<FILE>;
(open (ALL, ">$time")) || print "cannot open the time file";
binmode ALL;

$colors[0] = $im->colorAllocate(255,255,255);   #white
$colors[1] = $im->colorAllocate(0,0,0);         #black
$colors[2] = $im->colorAllocate(0,255,0);       #green
$colors[3] = $im->colorAllocate(0,0,255);       #blue
$colors[4] = $im->colorAllocate(255,180,0);     #Orange
$colors[5] = $im->colorAllocate(230,230,0);     #Yellow
$colors[6] = $im->colorAllocate(160,160,0);     #Purple
$colors[7] = $im->colorAllocate(255,0,0);       #red
$colors[8] = $im->colorAllocate(170,170,170);   #gray

$im->transparent($colors[0]);
$im->interlaced('true');

#intiate the process
$im->arc($center_x, $center_y, 20, 20, 0, 360, $colors[1]);    # the center of the picture
$level_num[0]=5;
for ($i=1; $i<15; $i++)
   {
    $level_num[$i]=0;
   }

while($left>0)
   {
    $ele_num=&find_level_num($level);
    # radius and angles of this level
    $radius=80*($level+1);
    $ele_angle=360/$ele_num;
    $start_angle=72*(2**(-$level));
         
    $ele_num=&min($left, $ele_num);
    for ($i=0; $i<$ele_num; $i++)
        {
         chomp($line=<FILE>);
         ($orf, $ratio, @data) = split("\t", $line);
         $angle = $start_angle + $i*$ele_angle;
         $x1 =$center_x + ($radius-10) * sin($angle * $piover180);
         $y1 =$center_y - ($radius-10) * cos($angle * $piover180);
         $x2 =$center_x; 
         $y2 =$center_y;
         $im->line($x1, $y1, $x2, $y2, $colors[1]);
         $x1 =$center_x + $radius * sin($angle * $piover180);
         $y1 =$center_y - $radius * cos($angle * $piover180);
         &draw_pie($x1, $y1); 

         $x1=$x1-10;
         $y1=$y1-10;
         $x2=$x1+20;
         $y2=$y1+20;
         $html='<area shape="rect" coords="'."$x1,"."$y1,"."$x2,"."$y2".'" href="./cal_nav.cgi?ORF_name='."$orf".'&cutoff='. "$cutoff". '&dataset='. "$PI".'">'."\n";
         print "$html";

         if($angle<180)
           {
            $x1-=6;
           }
         else
           {
            $x1-=30;
           } 
         if(($angle<270)&&($angle>90))
           {
            $y1+=15;
           }
         else
           {
            $y1-=25;
           }
         $im->string(gdSmallFont, $x1, $y1, $orf, $colors[1]); 
        }
    $left-=$ele_num;
    $level++;
   }
$im->fill(1, 1, $colors[0]);

#legends:
for ($i=0; $i<$gnum; $i++)
    {
    $x1=$center_x-60;
    $y1=10+$i*15;
    $x2=$center_x-50;
    $y2=20+$i*15;
    $im->filledRectangle($x1, $y1, $x2, $y2, $colors[$i+1]);
    $x1=$center_x-30;
    $y1=10+$i*15;
    $label=$dataset_description[$i];
    $im->string(gdSmallFont, $x1, $y1, $label, $colors[$i+1]);
    }

binmode STDOUT;
print ALL $im->png;
close(ALL);

print '</map><IMG USEMAP="#img_map" src="'."$time".'" border=0 ISMAP><br><br>'."\n";

 
print '</center></body></html>';
sub min
  {
   my $a=shift; 
   my $b=shift;
   return (($a>$b)?$b:$a);
  }

sub find_level_num
   {
    my $level=shift;
    if ($level>0)
       {
        for ($i=0; $i<$level; $i++)
            {
             $level_num[$level]+=$level_num[$i];
            }
        }
    else
        {
         $level_num[$level]=5;
        }
    return($level_num[$level]);
    }

sub draw_pie
  {
   my $x=shift;
   my $y=shift;
   my $sector_num=0;
   my $angle_start;
   my $angle_end;
   my $angle_elem;
   my $i=0;
   my $j=0;
   my $cut_x;
   my $cut_y;
   my $cut_angle=0;
   my $fill_x;
   my $fill_y;
   my $fill_angle;
   my $radius=5;
   my $pi=atan2(1,1)*4;
   my $piover180=$pi/180;

   $im->arc($x, $y, 20, 20, 0, 360, $colors[1]);
   for ($i=0; $i<$gnum; $i++)
       {
        $sector_num+=$data[$i];
       }
   $angle_elem=360/$sector_num if ($sector_num != 0); 
   for ($i=0; $i<$gnum; $i++)
       {
        if ($data[$i])
           {
            $angle_start = $j * $angle_elem;
            $angle_end   = ($j+1) * $angle_elem;
            $cut_angle = $angle_end;
            if ($sector_num>1)
               {
                $cut_x = $x;
                $cut_y = $y-10;
                $im->line($x, $y, $cut_x, $cut_y, $colors[1]);
                $cut_x = $x + 10 * sin($cut_angle * $piover180);
                $cut_y = $y - 10 * cos($cut_angle * $piover180);
                $im->line($x, $y, $cut_x, $cut_y, $colors[1]);
               }

            $fill_angle = ($angle_start + $angle_end)/2;
            $fill_x =  $radius * sin($fill_angle * $piover180);
            $fill_y =  $radius * cos($fill_angle * $piover180);
            $fill_x = $x + $fill_x;
            $fill_y = $y - $fill_y;
            $im->fill($fill_x, $fill_y, $colors[$i+1]);
            $j++;
           }
       } 
  if ($sector_num == 0) 
	{
	$im->fill($x, $y, $colors[8]);
	}
  }

close(FILE);
exit;
