#!/usr/bin/perl

use strict;
use vars;

    if (@ARGV != 2)
    {
        print "Usage: $0 <expectedResults> <compareResult>\n\n";
        print "Does validation of returned results against the original results. Results must be properly formatted.\n";
        print "\texpectedResults   The file containing the expected results for the query.\n";
        print "\tcompareResults    The file containing the results received for the query.\n";
        exit(0);
    } 
    
    my $EXPECTED = $ARGV[0];
    my $RESULT   = $ARGV[1];
    
    open(FEXP, "<$EXPECTED") or die "Validation Failed: Can't open file: $EXPECTED";
    open(FRES, "<$RESULT") or die "Validation Failed: Can't open file: $RESULT";
    
    my @exp = <FEXP>;
    close(FEXP);
    
    my @res = <FRES>;    
    close(FRES);
    
    die "Validation Failed: Number of lines differs: ".int(@exp)." != ".int(@res)."\n" if (@exp != @res);
    
    #skip the first two lines (header)
    for(my $row = 2; $row<@res; $row++)
    {
        my @ecols = split(/\|/, $exp[$row]);
        my @rcols = split(/\|/, $res[$row]);
       
        die "Validation Failed: Number of columns differs: ".int(@ecols)." != ".int(@rcols)."\n" if (@ecols != @rcols);

        #just try to do rough matching
        #check always the original answers exa_orig_answers/q*.out vs. tpch_answers/q*.out (not 100% exact)
        for(my $col=0; $col<@rcols; $col++)
        {
            #compare as strings
            if (trim($ecols[$col]) ne trim($rcols[$col])) 
            {	
                #string compare doesn't match, try to compare as number
                if (round2($ecols[$col]) != round2($rcols[$col]))
                {
                    #check for rounding problems
                    if (int($ecols[$col]) != int($rcols[$col]))
                    {
                        die "Validation Failed: Row ".($row+1).", column $col differs: (TPCH) \"$ecols[$col]\" != \"$rcols[$col] (EXA)\"\n"
                    } else
                    {
                        print "Check rounding: Row ".($row+1).", column $col differs: (TPCH) \"$ecols[$col]\" != \"$rcols[$col] (EXA)\"\n"
                    }
                }
            }
        }
    }
    
    print "Validation Passed\n";
    

sub trim()
{
  my ($s) = @_;
  
  #remove leading and trailing white spaces
  $s =~ s/^\s*//;
  $s =~ s/\s*$//;
  
  return $s;
}    

sub round2()
{
  my ($n) = @_;
  
  $n = int($n*100.0 + 0.5);
  $n /= 100.0;
  
  return $n;
}


