#! /usr/bin/perl
#
# No argument is necessary. DCS serial and ROC type are got from _setup

my $testgood = `modules/check_dir.pl | tail -1`;
if ( $testgood != 1 ) {
    printf("Strange directory.\n");
    printf("Please run this script only in Stand1 or Stand2 directory.\n");
    exit;
}

# invoke _setup
@lines = `cat _setup`;
foreach( @lines ) {
    chop;
    if( /DCS_SERIAL=(\d+)$/ ) { $DCS_SERIAL = $1; }
    if( /ROC_TYPE=(\d+)$/ )   { $ROC_TYPE = $1; }
}

$DCS_ID   = "dcs$DCS_SERIAL";
$N_Linkpair = $ROC_TYPE + 3;
$flag_bad = 0;

printf("Checking DCS_ID=$DCS_ID as ROC_TYPE=$ROC_TYPE (%d linkpairs).\n\n", $N_Linkpair );

@nslaves_should_be = ( 34, 34, 36, 34 );

for( $lp = 0 ; $lp < $N_Linkpair ; $lp++ ) {
    printf("Getting data from Linkpair $lp ... ");
    open(FILE, "ssh $DCS_ID /usr/local/sbin/dcs2trap -link $lp 0 -i /dcsnfs/ROC_Test/rstate.dat |");
    $nslaves      = 0;
    $nslaves_ec   = 0;
    $nslaves_nfsm = 0;
    while(<FILE>) {
	if( /^0x9\s0xa04\s\S+\s(\d+)\s+.+\s+(\S+)\s*$/ ) {  ## TRAP status
	    ($slave, $state) = ($1, $2);
	    $states{$slave."-".$lp} = $state;
	    $nslaves++;
	}
	if( /^0x9\s+0xc04\s+0x(\S+)\s+(\d+)\s+/ ) { ## Event counter 
	    ($slave, $state) = ($2, $1);
	    $evcs{$slave."-".$lp} = $state;
	    $nslaves_ec++;
	}
	if( /^0x9\s+0xdc2\s+0x(\S+)\s+(\d+)\s+/ ) { ## NI state machine
	    ($slave, $state) = ($2, $1);
	    $nfsm{$slave."-".$lp} = hex($state);
	    $nslaves_nfsm++;
	}
    }
    printf("% 2d slaves returned data.", $nslaves);
    if( $nslaves != $nslaves_should_be[$lp] ) {
	printf(" ... It is strange!! It should be % 2d.\n", $nslaves_should_be[$lp] );
	$flag_bad++;
    } else {
	printf("\n");
    }
} 

printf("\n");

# Show Results

$evc_ref = $evcs{"1-0"}; # reference to set to lp0-slv1

printf("       Linkpair0             Linkpair1             Linkpair2             Linkpair3\n");
printf("Slave   GSM       NI events   GSM       NI events  GSM        NI events   GSM       NI events\n");
for( $s = 1 ; $s <= 36 ; $s++ ) {
    printf("%02d   ", $s);
    for( $lp = 0 ; $lp < $N_Linkpair ; $lp++ ) {
	printf(" %9s % 4s % 5s", $states{$s."-".$lp},  $nfsm{$s."-".$lp}, $evcs{$s."-".$lp} );
	if( defined( $states{$s."-".$lp}) ) {
	    if( ($states{$s."-".$lp} ne "wait_pre") || ($evcs{$s."-".$lp} ne $evc_ref) ) {
		$flag_bad += 10;
		printf("*");
	    } else {
		printf(" ");
	    }
	} else {
	    printf(" ");
	}
    }
    printf("\n");
}

printf("\n");

# Show Summary

if( $flag_bad > 0 ) {
    printf("Result looks NOT OK...");
    if( $flag_bad >= 10 ) {
	printf("There are non \"wait_pre\" chips or discrepancies in event counters.\n");
    } else {
	printf("See log detail.\n");
    }
} else {
    $evc_ref =~ s/^0x//;
    printf("Result looks OK. All chips processed %s events.\n", hex($evc_ref)-10 );
}

printf("\nNow: %s", `date`);

# EOF
