#!/usr/bin/perl -w
%delta_hash=();

#assign table name
if (!(@ARGV == 1)) {die"need name of \$mytable in input line :$!";}
$my_table=$ARGV[0];
@temp=split(/\./,$my_table);
$genome_name=$temp[0];
chomp ($my_table);
print "\n\n$my_table is the file name of the table being analyzed \n";

$outfile='oligo_bias.'.$genome_name;
open (IN,"<$my_table") or die "cannot open my_table:$!";
open (OUT,">$outfile") or die "cannot open file to store output:$!";
#$numlin=0;

$line = <IN>;
chomp($line);
@oligos=split(/\t/,$line);
$number_oligos=@oligos;
print "$number_oligos oligos will be analyzed\n";
$number = <IN>;
chomp($number);
chomp($line);
@numbers = split(/\t/,$line);

#for each oligonucleotide set the min and max bias to zero initially
for ($i = 0 ; $i<=($number_oligos-1) ;$i++) {
	$maxoligo[$i]= 0;
	$minoligo[$i]= 0;};

# for each line of the table check if the value for each oligo,
# if it is larger/smaller than the previous extrem values
while (defined ($line = <IN>)){
    chomp($line);
    @numbers = split(/\t/,$line);
	for ($i = 0 ; $i<=($number_oligos-1) ;$i++) {
	if ($maxoligo[$i] < $numbers[$i]) {$maxoligo[$i] = $numbers[$i]};
	if ($minoligo[$i] > $numbers[$i]) {$minoligo[$i] = $numbers[$i]};
	}
}

#create a hash that has the maximum delta for each oligo as KEY 
#and the name of the oligo as value - this allows to sort the keys and print the values
for ($i = 0 ; $i<=($number_oligos-1) ;$i++) {
	$delta[$i]= $maxoligo[$i]-$minoligo[$i];
	#	$oligo_hash{$oligos[$i]}=$delta[$i];
	$delta_hash{$delta[$i]}=$delta_hash{$delta[$i]}.'_'.$oligos[$i];
	# the concatenation adds the name of the oligos to the value,
	#in case there is more than one oligo with the same bias
};

@sorted_deltas=sort {$b <=> $a}(keys(%delta_hash));
foreach (@sorted_deltas) {
	@temp=split(/_/,$delta_hash{$_});
	print " oligo(s) @temp occured max $_ times in excess\n";
	print OUT "$_\t@temp\n";
	#$_ is the value of the bias; @temp is the array of oligos with that name.
	}

exit;




