#! /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;

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

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/rstate.dat |");
    $nslaves    = 0;
    $nslaves_ec = 0;
    while(<FILE>) {
	if( /^0x9\s0xa04\s\S+\s(\d+)\s+.+\s+(\S+)\s*$/ ) {  ## TRAP status
	    $slave = $1;
	    $state = $2;
	    $states{$slave."-".$lp} = $state;
	    # printf("$slave $state");
	    $nslaves++;
	}
	if( /^0x9\s+0xc04\s+(\S+)\s+(\d+)\s+/ ) { ## Event counter 
	    $slave = $2;
	    $state = $1;
	    $evcs{$slave."-".$lp} = $state;
	    # printf("$slave $state");
	    $nslaves_ec++;
	}
    }
    printf("% 2d slaves returned data.\n", $nslaves);
} 

printf("\n");


printf("Slave   Linkpair0         Linkpair1         Linkpair2         Linkpair3\n");
for( $s = 1 ; $s <= 36 ; $s++ ) {
    printf("%02d   ", $s);
    for( $lp = 0 ; $lp < $N_Linkpair ; $lp++ ) {
	printf(" %10s % 6s", $states{$s."-".$lp}, $evcs{$s."-".$lp} );
    }
    printf("\n");
}

$errors = 0;

for( $lp = 0 ; $lp < $N_Linkpair ; $lp++ ) {
    for ( $s = 1 ; $s <= 36 ; $s++ ) {
	
	next if ($lp!=2 and $s>=35);

	if ( $states{$s."-".$lp} ne "wait_pre" ) {
	    printf "%1d.%02d: %10s %8s\n", $lp, $s, $states{$s."-".$lp}, $evcs{$s."-".$lp};
	    $errors++;
	}

	if ( $evcs{$s."-".$lp} ne $evcs{"1-0"} ) {
	    printf ( "%1d.%02d: WRONG COUNTER %8s ( != %8s)\n", 
		     $lp, $s, $evcs{$s."-".$lp}, $evcs{"1-0"});
	}
	
    }
}

#foreach $i ( keys %evcs ) {
#    print "$i\n";
#}


if ($errors == 0) {
    printf "\n\nChamber is GOOD at %s\n", `date`;
} else {
    printf "$errors errors found in RO tree at %s", `date`;
}


# EOF

