#!/usr/bin/env perl

# generates interaction link files for CRI circos plot from Collaborations-SunsetReview-FINAL.tsv
# format looks like this:
# Faculty1Last   Faculty2Last    Pubs    Grants  New     Patents Companies
# Andersen,B      Dai,X   1                               
# Andersen,B      Ganesan,A       1                               
# Andersen,B      Grando,S        1                               
# Andersen,B      Gratton,E       1                               
# Andersen,B      Lander,A                1       1               


# eats that file and generates 2 separate link files whic hcan be plotted together or separately.
my $lnkwdth = 2;
my $mid = 50; # the midpoint of the size of PI span (currently 100).
my %offset;

my @FH = ("JNK", "JNK", "PUBS", "GRANTS", "NEWCOLS");

open ($FH[2],  ">", "pub.links" )     or die "Can't open [pub.links]\n";
open ($FH[3],  ">", "grants.links" )   or die "Can't open [grants.links]\n";
open ($FH[4],  ">", "newcols.links" )  or die "Can't open [newcols.links]\n";

# for links
my @color= ("blah", "blah", "red", "green", "blue" );

# color=green (grants)
# color=blue (new)

# in format:
# L1  L1Abegin L1Bbegin L2 L2Abegin L2Bbegin
# hs1 100 200 hs2 250 300 color=red,thickness=5p
# hs1 400 550 hs3 500 750 color=green,thickness=5p
# hs1 600 800 hs4 150 350 color=blue,thickness=5p

open(CNTS, "<", "longname.id.interactions.tsv") or die  "Can't open [longname.id.interactions.tsv] for reading\n";
# format is (with TAB delimiters)
# Andersen,B      AndB    10
# Atwood,S        AtwS    2
# Benavente,C     BenC    2
# Blumberg,B      BluB    2

while (<CNTS>) {
    my $N = my @A = split (/\t/);
    $offset{$A[1]} = (($A[2] * $lnkwdth) % 2);
}

print "Ate longname.id.interactions.tsv, apparently OK\n";
# so at each link, the start point shifts by the size of the link base


while (<>) {
    my $N = my @A = split(/\t/);
    my $L1 = mkID($A[0]); my $L2 = mkID($A[1]);
    for ($i=2; $i<5; $i++) {
        if ($A[$i] == 1) { 
            my $L1Ab = ($mid - $offset{$L1}++); my $L1Ae = ($mid - $offset{$L1}++);
            my $L2Ab = ($mid - $offset{$L2}++); my $L2Ae = ($mid - $offset{$L2}++);
            select $FH[$i];
            #print    "$L1 $L1Ab $L1Ae $L2 $L2Ab $L2Ae color=$color[$i]\n"; 
            print    "$L1 $L1Ab $L1Ae $L2 $L2Ab $L2Ae \n"; 
       }
    }
}
#     if    ($A[2] == 1) { 
#       my $L1Ab = ($mid - $offset{$L1}++); my $L1Ae = ($mid - $offset{$L1}++;
#       my $L2Ab = ($mid - $offset{$L2}++); my $L2Ae = ($mid - $offset{$L2}++;
#       print PUBS    "$L1 $L1Ab $L1Ae $L2 $L2Ab $L2Ae color=red\n"; }
#     elsif ($A[3] == 1) { print GRANTS  "\n"; }
#     elsif ($A[4] == 1) { print NEWCOLS "\n"; }


sub mkID($) {
  my $FN = shift;
  $Nn = @An = split(/,/, $FN);
  $LN = substr($An[0],0,3);
  return "${LN}${An[1]}";;
}






