#!/usr/bin/perl -w
use strict;

sub readraw {
    my ($fname) = @_;
    local $/;
    open (IN,"<$fname");
    my $ret=<IN>;
    close IN;
    return $ret;
}

use IO::Socket;

######################### CHANGE HERE

my $ip="localhost";
my $port=389;

my $bind = readraw ("1_bind.raw");
my $search = readraw ("2_search.raw");

my $abandon = pack ('C8',
		    0x30,0x06,
		    0x02,0x01,0x03,
		    0x50,0x01,0x02,
    );

my $unbind = pack ('C7',
		   0x30,0x05,
		   0x02,0x01,0x03, # 0x03 if abandon is not used
		   0x42,0x00);

select STDOUT; $| = 1;

my @sockets;

sub cleanup {
    my @newsockets;
    foreach my $s (@sockets) {
	next if ! defined $s;
	if (! defined <$s>) {
	    close $s;
	    next;
	}
	push @newsockets, $s;
    }
    @sockets=@newsockets;
    print scalar @sockets;
}

my $msec=-1;
while ($msec++ < 200) {

    cleanup;
    printf (" %05d\r",$msec);

    my $socket = new IO::Socket::INET (
	PeerAddr  => $ip,
	PeerPort  => $port,
	Proto => 'tcp',
	Type => SOCK_STREAM,
	)                
	or die "No server found on $ip:$port $msec\n";

    push @sockets, $socket;

    print $socket $bind;

    select (undef, undef, undef, 0.5 ); # sleep half a second

    print $socket $search, $unbind;

    select (undef, undef, undef, 0.5 ); # sleep half a second
}

print "\nFinished\n";
