#!/usr/bin/perl -w

use strict;

my @traces;

my @lines = <STDIN>;
my $old_value = 0;
my %ptr_account;
my $first_ever = 1;

while (my $line = shift @lines) {
    if ($line =~ m/^Old value = ([-\d]+)/) {
	$old_value = $1;

    } elsif ($line =~ m/^New value = (\d+)/) {
	my $new_value = $1;
	my $delta = $new_value - $old_value;
	my @stack;
	my $has_ptrv = 0;
	while (my $frame = shift @lines) {
	    $frame =~ m/^Hardware watchpoint/ && last;
	    $frame =~ m/^\s*$/ && last;
	    push @stack, $frame;
	    if (!$has_ptrv) {
		if ($frame =~ m/ VclPtr<[^>]+>::.*\(this=0x([^\) ,]+)/) {
		    my $vthis = $1;
#		    print "VclPtr $vthis: $delta\n";
		    $has_ptrv = 1;
		    $ptr_account{$vthis} = 0 if (!defined $ptr_account{$vthis});
		    $ptr_account{$vthis} = $ptr_account{$vthis} + $delta;
#		    print "change to $ptr_account{$vthis}\n";
		}
	    }
	}
	if (!$first_ever) {
	    die "Failed to find VclPtr in frame @stack" if (!$has_ptrv);
	}
	$first_ever = 0;
    }
}

my $problems = 0;
print "Problematic ref-count mis-matches on VclPtr instances with values:\n";
for my $a (sort keys %ptr_account) {
    if ($ptr_account{$a} != 0) {
	print "this=0x$a\t$ptr_account{$a}\n";
	$problems++;
    }
}
if ($problems > 0) {
    print "Search for the above pointer values in your log.\n";
} else {
    print "No problems found !\n";
}
