#!/usr/bin/perl

# I0:   0 if  local max
# I1:   0 if  cluster >= EBIT
# I2:   0 if  single >= EBIS
#
#
# EBIL:
#
#                sin  cl   max
# bit 0 (LSB):    0    0    0          
# bit 1:          0    0    1       
# bit 2:          0    1    0        
# bit 3:          0    1    1       
# bit 4:          1    0    0       
# bit 5:          1    0    1       
# bit 6:          1    1    0       
# bit 7 (MSB):    1    1    1       



$zsname = shift;

# Default lookup table: never mark pad
$ebil = 0xFF;

# Default cluster threshold: 1
$ebit = 1;

# Default single hit threshold: 1
$ebis = 1;

# Ignore neigbor by default
$ebin = 1;

$ebsmask_hi = 0xffffffff;
$ebsmask_lo = 0x3fffffff; 

if ($zsname eq "zs-off") {

    $ebin = 1;    # ignore neighbor
    $ebil = 0x00; # always mark pad

} 

# Single hit threshold
if ($zsname =~ /^zs-.*s(\d+)/) {
    $ebis = $1;
    $ebil &= 0xF0; 
}

# Cluster threshold
if ($zsname =~ /^zs-[^s]*c(\d+)/) {
    $ebit = $1;
    $ebil &= 0xCC; 
}

# Single + Cluster threshold
if ($zsname =~ /^zs-.*sc(\d+)\.(\d+)/) {
    $ebis = $1;
    $ebit = $2;
    $ebil &= 0xFC; 
}

# Local maximum
if ($zsname =~ /^zs-.*m/) {
    $ebil |= 0xAA;
}

if ($zsname =~ /^zs-.*n/) {
    $ebin = 0;
}

printf "EBIS=$ebis EBIT=$ebit EBIN=$ebin EBIL=0x%02X\n", $ebil;



open outfile, ">src/zs/$zsname.auto.tcs";


print outfile "// EBIL Table: mark pad if one of the conditions is true:\n";
for ($i=0; $i<8; $i++) {

    if ( ! ((1<<$i) & $ebil) ) {
	# bit is not set - condition must be met
	print outfile "//  $i:  ";

	if ( $i & 4 ) { print outfile "hit <  $ebis && "; }
	else          { print outfile "hit >= $ebis && "; }

	if ( $i & 2 ) { print outfile "cluster <  $ebit && "; }
	else          { print outfile "cluster >= $ebit && "; }

	if ( $i & 1 ) { print outfile "not local max\n"; }
	else          { print outfile "local max\n"; }

    }
}

print outfile "\n\n";


print  outfile "const EBSingleIndicatorThreshold=$ebis;\n";
print  outfile "const EBSumIndicatorThreshold=$ebit;\n";
printf outfile "const EBIndicatorLookupTable=0x%02X;\n", $ebil;
print  outfile "const EBmarkIgnoreNeighbour=$ebin;\n";
print  outfile "const EBmaskHigh=$ebsmask_hi;\n";
print  outfile "const EBmaskLow=$ebsmask_lo;\n\n";

print  outfile<<EOF;

// Event Buffer Single Indicator Threshold
write EBIS, EBSingleIndicatorThreshold;

// Event Buffer Sum Indicator Threshold
write EBIT, EBSumIndicatorThreshold;

// Event Buffer Indicator Look-up Table
write EBIL, EBIndicatorLookupTable; //  0xF0;

// Event Buffer Indicator Neighbor Sensitivity
write EBIN, EBmarkIgnoreNeighbour;

// timebin mask for zs
write 0xc026, EBmaskLow;
write 0xc027, EBmaskHigh;

EOF

close outfile;
