#!/usr/bin/perl
#dl.ph

use IO::File;
use File::Find;

open(FH, "> dl.out");
my %hash = ();
my %hash2 = ();

find(\&downl, ("/home/johnny/dd/data"));
byRace();
byRacer();



sub byRacer {
  foreach $size (keys %hash ) {
    foreach $first (keys %{$hash{$size}} ) {
      foreach $second (keys %{$hash{$size}{$first}} ) {
	$newKey = $first . "," . $second; 
	$hash2{$newKey}{$size}[0] = $hash{$size}{$first}{$second}[0];
	$hash2{$newKey}{$size}[1] = $hash{$size}{$first}{$second}[1];
      }
    }
  }
  
  foreach $race (keys %hash2) {
    foreach $size (sort( keys %{$hash2{$race}} )) {
      $x = $hash2{$race}{$size}[0];
      $y = $hash2{$race}{$size}[1];
      $out = $size . "," . $race . "," . "$x,$y\n";
      #print $out;
      print FH $out;
    }  
  }
}

sub byRace {
  foreach $keyI (keys %hash ) {
    foreach $keyJ (keys %{$hash{$keyI}} ) {
      foreach $keyK (keys %{$hash{$keyI}{$keyJ}} ) {
	$x = $hash{$keyI}{$keyJ}{$keyK}[0];
	$y = $hash{$keyI}{$keyJ}{$keyK}[1];
	$out =  $keyI . "," . $keyJ . "," . $keyK . "," . $x . "," . $y . "\n";
	#print $out;
        print FH $out;
      }
    }
  }
}

sub downl {
  my($outf) = @_;
 
  $f = $File::Find::name; 
  $f =~ /^(.*)\/(.*)$/;
  $path = $1;
  $file = $2; 
      
  if($file =~ /^\.\.?$/) { return };
  if( !($file =~ /\.txt$/)) { return };
  if($file =~ /^SKIP/) { return };

  my($ps, $r1, $vs, $r2, $ext) = split(/\./, $file);

  $fh = IO::File->new("< $f")
   or die "Can't open $f\n";

  while(<$fh>) {
    $lastLine = $_;
  }
  
  my($time, $wnd) = split(/\s/, $lastLine);
  $t1 = sprintf("%.1f", $time);
  $hash{$ps}{$r1}{$r2}[0] = $t1; 

  $fh->close();
  $f = $path . "/SKIP" . $file;
  $fh = IO::File->new("< $f")
   or die "Can't open $f\n";
   
  while(<$fh>) {
    $lastLine = $_;
  }

  my($time, $wnd) = split(/\s/, $lastLine);
  $t2 = sprintf("%.1f", $time);
  $hash{$ps}{$r1}{$r2}[1] = $t2; 

  #print "($ps) $r1 vs. $r2 : ($t1,$t2)\n";
  #print FH "($ps) $r1 vs. $r2 : ($t1,$t2)\n";
  $fh->close();

}
