#!/usr/bin/perl
#WagnerTest.pl version 0.0
#   author: Sonja J. Prohaska
#institute: Bioinformatics, Institute for Computer Science
#  address: Haertelstr. 16-18, 04107 Leipzig, Germany
#     date: 27.04.2010

use strict;

my $usage= << "JUS";
  usage: WagnerTest_plot.pl [OPTIONS] WAGNERTEST-OUTFILE TREEFILE
options: -d          debug
         -z          use z instead of z' values
JUS

my @options = grep {substr($_, 0, 1) eq '-'} @ARGV;
my @others  = grep {substr($_, 0, 1) =~ /^[^-]/} @ARGV;

##default settings:
my $debug   = 0 ;         # no debugging
my $col     = 15 ;        # default: z'
##----------

##setting parameters:
foreach my $option (@options){
  if    ($option eq "-d")                 { $debug = 1; }
  elsif ($option eq "-z")                {  $col = 14; }
  else  { die "Invalid command line option: \'$option\'!\n$usage"; }
}
##----------

die "Two files expected: WAGNERTEST-OUTFILE, TREEFILE!\n$usage" 
    unless scalar(@others)==2;
foreach my $file (@others) {
  die "'$file' no such file or directory!" unless -e $file;
}
my $datafile =$others[0];
my $treefile=$others[1];

my ($ABdataref, $ABbootref, $ABref)=read_data($datafile);

foreach my $a (@$ABref) {
  foreach my $b (@$ABref) {
    foreach my $ox (keys (%{$ABbootref->{$a}->{$b}})) {
      my $i=0;
      my $sum;
      foreach my $rep (@{$ABbootref->{$a}->{$b}->{$ox}}) {
	$i++;
	$sum+=$rep;
      }
      my $mean=$sum/$i;
      my $std='na';
      my $sum=0;
      if ($i>1) {
	foreach my $rep (@{$ABbootref->{$a}->{$b}->{$ox}}) {
	  $sum+=($rep-$mean)*($rep-$mean);
	}
	$std=sqrt($sum/($i-1));
      }
      push @{$ABdataref->{$a}->{$b}->{$ox}}, sprintf("%.3f", $mean), sprintf("%.3f", $std), $i;
    }
  }
}

print "#O-X A B data->z(') sampling_mean->z(') sampling_std->z(') replicates\n";
foreach my $a (@$ABref) {
  foreach my $b (@$ABref) {
    foreach my $ox (keys (%{$ABdataref->{$a}->{$b}})) {
      print "$ox $a $b @{$ABdataref->{$a}->{$b}->{$ox}} \n";
    }
  }
}

sub read_data {
  my $file=shift;
  my %ABdata;
  my %ABboot;
  my %AB;
  open (IN, "<$file") or die "Can\'t open \'$file\'!\n";
  my $mark=0;
  while (<IN>) {
    my @line=split;
    my $OX=$line[0] . "-" . $line[1];

    if ($_ =~ m/^#+-+\s*$/) {
      $mark=1;
    }
    elsif ($_ =~ m/^\s*[^#]/ & $mark==0) {
      ${${$ABdata{$line[2]}}{$line[3]}}{$OX}=[$line[$col]];
      $AB{$line[2]}=1;
    }
    elsif ($_ =~ m/^\s*[^#]/ & $mark==1) {
      push @{${${$ABboot{$line[2]}}{$line[3]}}{$OX}}, $line[$col];
    }
  }
  close IN;

  my @AB;
  foreach my $key (keys(%AB)) {
    push @AB, $key;
  } 

  return \%ABdata, \%ABboot, \@AB;
}
