#!/afs/athena/contrib/perl/perl

($port) = @ARGV;
$port = 2345 unless $port;

$AF_INET = 2;
$SOCK_STREAM = 1;
undef $/;
$buffer = 10000;

open(AUDIO, ">/dev/audio");

$sockaddr = 'S n a4 x8';

($name, $aliases, $proto) = getprotobyname('tcp');
if ($port !~ /^\d+$/) {
    ($name, $aliases, $port) = getservbyport($port, 'tcp');
}

print "Port = $port\n";

$this = pack($sockaddr, $AF_INET, $port, "\0\0\0\0");

select(NS); $| = 1; select(stdout);

socket(S, $AF_INET, $SOCK_STREAM, $proto) || die "socket: $!";
bind(S,$this) || die "bind: $!";
listen(S,5) || die "connect: $!";

select(S); $| = 1; select(stdout);

$con = 0;
print "Listening for connection 1....\n";
for(;;) {
    ($addr = accept(NS,S)) || die $!;

    $con++;
    print "accept ok\n";
    
    ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
    @inetaddr = unpack('C4',$inetaddr);
    print "$con: $af $port @inetaddr\n";
    
    if(!fork()){
	while(1){
	    read(NS, $_, 128);
#	    print "$con: $_";
	    $sound .= $_;
	    if(length($sound) > $buffer){
#	    print(STDOUT "Dumping buffer to /dev/audio\n");
		$tot=0;
#		for $c (0..length($sound)){
#		    $val  = ord(substr($sound, $c, 1));
#		    $total += $val;
#		    if($val < 50){
#			substr($sound, $c, 1) = 0;
#		    }
#		}
#		print("Total: $total\n");
#		$sound =~ s/\000-\400//g;
		print(AUDIO $sound);
		$sound = '';
	    }
	}
    }
    printf("Listening for connection %d\n",$con+1);
}
