#!/usr/bin/perl -w

use strict;

$::BITS_CHANNEL = 5;
$::BITS_LINE = 5;
$::BITS_SLOT = 4;
$::BITS_REST = 32 - ($::BITS_CHANNEL + $::BITS_LINE + $::BITS_SLOT);

die "usage: parsenas.pl <integer>\n" unless ($ARGV[0]);
while (defined (my $port = shift @ARGV)) {
	my ($slot, $line, $channel) = port_split ($port);

	print "Parsed NAS-Port = $port\n";
	print "NAS-Port: [$port] = Slot [$slot];  Line [$line];";
	print " Channel[$channel];\n";

	my @ascii = split (//, join (" ", split (//, unpack ("B32",
	    pack ("N", $port)))));
	my $i = $::BITS_REST;
	$ascii[$i * 2 - 1] = "|";
	$i += $::BITS_SLOT;
	$ascii[$i * 2 - 1] = "|";
	$i += $::BITS_LINE;
	$ascii[$i * 2 - 1] = "|";
	my $ascii = join ("", @ascii);

	print <<EOF;
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|$ascii|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        Unused (All zeros)            Slot      Line    Channel
EOF
}


sub port_split
{
	my ($port) = @_;

	my $channel = $port & ((1 << $::BITS_CHANNEL) - 1);
	$port >>= $::BITS_CHANNEL;
	my $line = $port & ((1 << $::BITS_LINE) - 1);
	$port >>= $::BITS_LINE;
	my $slot = $port & ((1 << $::BITS_SLOT) - 1);
	$port >>= $::BITS_SLOT;

	return ($slot, $line, $channel);
}
