#!/usr/local/bin/perl -w

BEGIN 
{
	push(@INC, "/Perl/lib");
	#push(@INC, "/Perl/site/lib");
}


use FindBin qw($Bin);
use lib "$Bin/include";
use Graph::Directed;
use Tie::File;
use FileHandle;
use Cwd;
use strict;

calcPath(2, 998, 742);

sub calcPath
{
	my ($pathStart, $pathEnd);
	my ($pair, $node, $weight);
	my ($idx, @resInfo, @resList, %weightHash);
	my (@allDist);
	my ($line, $inner, $outer);
	my ($g, $u, $v, $uType, $vType, $numDist, $radius, $dist);
	my (@path, $currentDir, $outputDir, $pathFile, $priorPathFile, @array);
	my (@allLines, $numLines, $x, $y, $z);
	
	
	$radius = shift;
	$pathStart = shift;
	$pathEnd = shift;
	
	
	open(PDBRES, "data/pdbseq.txt") || die("PDB sequence file cannot be opened");
	$idx = 0;
	while($pair = <PDBRES>)
	{
		chop($pair);
		@resInfo = split(/\t/, $pair);
		push(@{$resList[$idx]}, @resInfo);
		$idx++;
	}
	close(PDBRES);
	
	open(WEIGHT, "data/weights.txt") || die ("Weights file cannot be opened");
	while($pair = <WEIGHT>)
	{
		($node, $weight) = ($pair =~/(.*?)\t(.*?)\n/);
		$weightHash{$node} = $weight;
	}
	close(WEIGHT);
	
	open(MATRIX, "data/distances.txt") || die ("Distance matrix file cannot be opened");
	
	$g = Graph::Directed ->new();
	
	
	#for edge construction, we need to pay attention to HET and whether HET is a start/end 
	#IF HET = beginning: can only construct edges FROM this het
	#IF HET = end: can only construct edges TO this het
	
	$outer = 0;
	while($line = <MATRIX>)
	{
		$u = $resList[$outer][0];
		$uType = $resList[$outer][1];
	
		if($uType eq "HET" and $u != $pathStart)
		{
			$outer++;
			next;
		}
	
		chop($line);
	    @allDist = split(/\s/, $line);
		$numDist = @allDist;
		
		for($inner = 0; $inner < $numDist; $inner++)
		{
			$v = $resList[$inner][0];
			$vType = $resList[$inner][1];
			if($vType ne "HET" or $v == $pathEnd )
			{
			    $dist = $allDist[$inner];
			 	if(($dist <= $radius) && ($dist != 0))
				{
					$g->add_weighted_edge($u, $weightHash{$v}, $v);
		 		}
			}
	 	}
	 	$outer++;
	}
	close(MATRIX);
	
	$currentDir = cwd();
	$outputDir = $currentDir . "/data";
   	
	my ($numPaths, $pathWeight) = $g -> SSSP_Dijkstra_Prior($pathStart, $pathEnd, $outputDir);
		
	$pathFile = $currentDir . "/data/paths.txt";
	$priorPathFile = $currentDir . "/data/priorPaths.txt";
	
	if ($numPaths == 0)
	{	
		#No path exists, so we remove paths.txt and priorPaths.txt before returning to UI. UI 
		#will use absence of either these 2 files for detecting the lack of a 
		#shortest path when presenting results.

		unlink($priorPathFile);
		unlink($pathFile);
	
	}
	else
	{
		tie @array, 'Tie::File', $pathFile;
		unshift @array, $pathWeight;
	}
	
}
			
		
