#! /usr/bin/perl
#
# Usage:
#   shift_id.pl shift_value robtype filename
#         
# Arguments:
#   shift_value: how many SCSN_IDs it should be shifted.
#                Especially to make ROB setup for A side.
#   robtype    : like T1A, T1B,,,,
#   filename   : input filename
#
# Example:
#   shift_id.pl 0 T1A main.dat
#     changes line   10 100 200 2
#     to             10 100 200 12
#   shift_id.pl 17 T1A main.dat
#     to             10 100 200 29
# Notice:
#   Broadcast ID (127) is still usable but it is expanded to all slaves.
# Example:
#   shift_id.pl 0 T1A main.dat
#     changes line   10 100 200 127
#     to             10 100 200 10
#                    10 100 200 11
#                    10 100 200 12
#                     :
#                    10 100 200 17
#
# This is just a temporary tool to be used before CE is ready.
#
# By Ken Oyama

$shift_id = $ARGV[0];
$robtype  = $ARGV[1];
$file     = $ARGV[2];

# Table for each ROB's used in the class.
#                    0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 BM HM
$SCSN_TBL{'T1A'} = "10 11 12 13  9 16 15 14  8  6  7  1  5  4  3  2 17";
$SCSN_TBL{'T1B'} = "11 12 13 14 10 17 16 15  9  7  8  2  6  5  4  3  1";
$SCSN_TBL{'T2B'} = "11 12 13 14 10 17 16 15  9  7  8  2  6  5  4  3  1";
$SCSN_TBL{'T3A'} = "10 11 12 13  9 16 15 14  8  6  7  1  5  4  3  2 18 17";
$SCSN_TBL{'T3B'} = "12 13 14 15 11 18 17 16 10  8  9  3  7  6  5  4  2  1";
$SCSN_TBL{'T4A'} = "10 11 12 13  9 16 15 14  8  6  7  1  5  4  3  2 17";
$SCSN_TBL{'T4B'} = "11 12 13 14 10 17 16 15  9  7  8  2  6  5  4  3  1";

printf( stderr "I expect input dat is now in Alice numbering and convert to SCSN ID.\n");
printf( stderr "ROB Type: %s\n", $robtype);
printf( stderr "Selected SCSN Table: %s\n", $SCSN_TBL{$robtype} );
@TBL = split( /\s+/, $SCSN_TBL{$robtype} )  ;
$n_slaves = $#TBL + 1;
printf( stderr "n_slaves = %d\n", $n_slaves );
printf( stderr "Shift $shift_id, and expand 127 to $n_slaves slaves.\n");

open( infile, $file ) || die;

while( <infile> ) {
    if( /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ ) {
	$command = $1;
	$address = $2;
	$data    = $3;
	$slave   = $4;
	if( $slave == 127 ) {
	    for( $i = 1 ; $i <= $n_slaves ; $i++ ) {
		$slave = $i + $shift_id;
		printf( "$command $address $data $slave\n");
	    }
	} else {
	    # $slave = $TBL[$slave] + $shift_id;
	    if( $slave < $n_slaves ) {
		$slave = $TBL[$slave] + $shift_id;
		printf( "$command $address $data $slave\n");
	    }
	}
    }
}

close( infile );

# EOF
