#!/usr/local/bin/perl
#
# Amay Champaneria
# 6.338 Final Project
# Parallel Pen-Tracker
#
# diffcoords.pl - determines the average error between the output file
#                 and the reference coordinate file

if ($#ARGV < 0) {
    print "Usage: diffcoords.pl <coordsfile> [referencefile]\n";
    exit(1);
} 

if ($#ARGV == 0) {
    $refname = 'output.reference';
} else {
    $refname = $ARGV[1];
}

$outname = $ARGV[0];

if (!open(REF, $refname)) {
    print "Could not open $refname.\n";
    exit(1);
} 

if (!open(OUT, $outname)) {
    print "Could not open $outname.\n";
    close(REF);
    exit(1);
}

while (<REF>) {

    if (/stopacquire/) {
	break;
    }

    if (/MAXCORRGLOBAL\((\d+),(\d+)\)/) {
	$refx = int($1);
	$refy = int($2);

	push(@refcoords, $refx);
	push(@refcoords, $refy);
    }
}

$i = 0;
$j = 0;
$errorx = 0;
$errory = 0;

while (<OUT>) {

    if (/stopacquire/) {
	exit(0);
    }

    if (/tracking \((\d+),(\d+)\)/g) {
	$outx = int($1);
	$outy = int($2);

	$diffx = $refcoords[$i]-$outx;
	$diffy = $refcoords[$i+1]-$outy;

	$i++;
	$i++;

	$errorx += $diffx*$diffx;
	$errory += $diffy*$diffy;
	$j++;
    }

    # skip the last coordinates because the pen isn't even in the frame
    if ($i > $#refcoords-44) {

	$avgx = sqrt($errorx/$j);
	$avgy = sqrt($errory/$j);	
	
	print "Avg xerror=$avgx, avg yerror=$avgy, sum=".($avgx+$avgy)."\n";

	exit(0);
    }
}
