#!/usr/bin/env perl

# This script is used by tauex to run an executable multiple times
# in order to collect all the counters

use strict;

sub setCounters {
    my (@counters) = @_;
    my $index = 1;
    foreach my $c (0 .. $#counters) {
	$ENV{"COUNTER" . $index} = $counters[$c];
	$index++;
    }
    while ($index < 26) {
	delete $ENV{"COUNTER" . $index};
	$index++;
    }
#    system("env | grep COUNTER");
}


my @counters;
my $dashFound = 0;
my $runCmd;
foreach my $arg (@ARGV) {
    if ($arg eq "--") {
	$dashFound = 1;
    } else {
	if ($dashFound) {
	    $runCmd = "$runCmd $arg";
	} else {
	    push (@counters, $arg);
	}
    }
}

# $counters[0] = "PAPI_FP_INS";
# $counters[1] = "PAPI_TOT_CYC";
# $counters[2] = "PAPI_L1_DCM";
# $counters[3] = "PAPI_L2_DCM";

while (@counters > 0) {
    my @runlist;
    my @newlist;
    my $index = 0;
    $newlist[$index] = $counters[$index];
    my $ok = 1;

    while ($ok) {
	my $counterString;
	foreach my $c (0 .. $#newlist) {
	    if ($newlist[$c] =~ /PAPI_NATIVE_/) {
		my $mod = $newlist[$c];
		$mod =~ s/PAPI_NATIVE_//;
		$counterString = $counterString . " " . $mod;
	    } elsif ($newlist[$c] =~ /PAPI/) {
		$counterString = $counterString . " " . $newlist[$c];
	    } else {
		#skip
	    }
	}
#	print "Trying $counterString\n";
	my $retval;
	if ($counterString eq "") {
	    $retval = 0;
	} else {
	    my $chooser = `which papi_event_chooser 2>/dev/null`;
	    if ($chooser eq "") {
		print STDERR "Error: papi_event_chooser is not in the path!\n";
		exit;
	    } 
	    $retval = system("papi_event_chooser PRESET $counterString &>/dev/null");
	}
	if ($retval == 0) {
#	    print "passed\n";
	    $ok = 1;
	    $index = $index + 1;
	    $runlist[$index-1] = $counters[$index-1];
	    $newlist[$index] = $counters[$index];
	    if ($index > $#counters || $index > 23) {
		$ok = 0;
	    }
	} else {
#	    print "failed\n";
	    if (@newlist == 1) {
		print STDERR "counter \"$newlist[0]\" is not available\n";
		exit;
	    }
	    $ok = 0;
	}
    }

    my $counterString;
    foreach my $c (0 .. $#runlist) {
	$counterString = $counterString . " " . $runlist[$c];
	shift (@counters);
    }

#    print "Running with $counterString\n";
    setCounters(@runlist);
    system($runCmd);
}

