#
#  ParseSVG
#
#  Created by Eduardo Andrés León on 2014-03-18.
#  Copyright (c) 2014 IBIS. All rights reserved.
#
#!/usr/bin/perl
$|=1;
use strict;
use Getopt::Long;
use LWP::Simple;

my $svg;
my $help;
my $pmid_file;
my $host="localhost";
my $dbname;
GetOptions(
	"help" => \$help,
	"svg=s" => \$svg,
	"pmid_file=s" => \$pmid_file,
	"dbname=s" => \$dbname
);
if($svg and $pmid_file and $dbname){
	 use DBI;
	
	#Reading PMID info
	my $pmids;
	my $refs;
	open(PMID,"$pmid_file")|| die $!;
	while(<PMID>){
		chomp;
		my($id,$pmid,$ref)=split(/\t/);
		$pmids->{$id}=$pmid;
		$refs->{$id}=$ref;
	}
	close PMID;
	
	#Reading database genes :
	my $genes;
	my $desc;
	my $dbh = DBI->connect("dbi:mysql:$dbname",'eandres','')
	or die "Connection Error: $DBI::errstr\n";
	
	my $sql = "select id_entity,`Gene Name`,`Synonym`,Description from entity";
	my $sth = $dbh->prepare($sql);
	$sth->execute
	or die "SQL Error: $DBI::errstr\n";
	while (my @row = $sth->fetchrow_array) {
		$genes->{$row[1]}=$row[0];
		$desc->{$row[0]}=$row[3];
		if($row[2] =~ " "){
			my @split=split(" ",$row[2]);
			foreach my $syn (@split){
				$genes->{$syn}=$row[0];
			}
		}else{
			$genes->{$row[2]}=$row[0];
		}
	}
	#for Pathways
	my $modifications;
	my $sql = "select distinct modification from modification";
	my $sth = $dbh->prepare($sql);
	$sth->execute or die "SQL Error: $DBI::errstr\n";
	
	while (my @row = $sth->fetchrow_array) {
		$modifications->{$row[0]}++;
	}
	
	open(SVG,$svg)|| die $!;
	while(<SVG>){
		chomp;
		if($_ =~ /=\"3\.9407\"/){
			my $bck=$_;
			$bck =~ s/>(.+)<//;
			my $info=$1;
			#$info could be a gene, a link to a pmid or a pathway description :
			
			#for pmid:
			if($info =~ /\(/){
				my $id=$info;
				$id =~s /\((\d+[\w+]?)\)/$1/g;
				if($pmids->{$id} and $refs->{$id}){
					print "<a xlink:href=\"http://www.ncbi.nlm.nih.gov/pubmed/".$pmids->{$id}."\" target=\"new\" xlink:title=\"".$refs->{$id}."\">\n";
					print $_ ."\n";
					print "</a>\n";
				}
			}
			#for genes
			elsif(exists $genes->{uc($info)}){
					#print STDERR $info ."\t" . $genes->{$info} ."\n";
				print "<a xlink:href=\"../Php/result.php?GeneSearch=".uc($info)."\" target=\"_top\" xlink:title=\"".$desc->{$genes->{uc($info)}}."\">\n";
				print $_ ."\n";
				print "</a>\n";
			}
			#for pathways
			elsif(exists $modifications->{$info}){
				print "<a xlink:href=\"../Php/result.php?ptm=".$info."\" target=\"_top\" xlink:title=\"".$info."\">\n";
				print $_ ."\n";
				print "</a>\n";
			}
			else{
				print STDERR "($info)\n";
				print $_ ."\n";
			}
		}
		else{
			print $_ ."\n";
		}
	}
	close SVG;
}
elsif($help){
	help();
}
else{
	help();
}

sub help{
	print STDERR "Error\n\nperl $0 -svg=../Web/svg/pathways.svg -pmid_file=../data_for_Edu/Tables_source_data/interactios_figure_pathway.txt -dbname=DDR_130314 > ../Web/svg/DDR_complete.svg\n\n";
}

__END__