#!/usr/local/bin/perl5.6.1 -w
# $Id: Medusa.pm,v 1.1 2003/10/21 15:42:03 jx1 Exp $

package Medusa;

use strict;
use warnings;
use Carp qw(croak cluck carp);
use Data::Dumper;

use IO::Socket;

use constant PORT => 300;
use constant RESP_SZ => [7, 3];

my $empty_sign = "No ";
my $remote_host = "DummyHost";
my %connected; #{hostname=>port};

sub new
{
     my $invocant = shift;
     my $class = ref($invocant) || $invocant;
     my $self = {
                 host => $remote_host,
		 port => PORT,
		 @_,
	     };

#     print "input par: @_ \n";

     if( exists $connected{ $self->{host} } ) 
     {
	 die "$self->{host}:$self->{port} is busy.\n";
     }

      
     my $socket = IO::Socket::INET->new( PeerAddr => $self->{host},
					 PeerPort => $self->{port},
					 Proto    => "tcp",
					 Type     => SOCK_STREAM )
           or die "Couldn't connect to $self->{host}:$self->{port} : $@\n";
 

     print "Socket created.\n";
     $connected{$self->{host}} = PORT;

     # add socket to self hash
     $self->{socket} = $socket;

     bless $self;
     return $self;
}


sub read
{
     my $self = shift;
     my $socket = $self->{socket};

     print $socket "read";
     
     my $response;
     my $byte_read;

     $byte_read = read( $socket, $response, RESP_SZ->[0] );
     if( $response !~ $empty_sign )
     {
	  $byte_read = read( $socket, $response, RESP_SZ->[1], RESP_SZ->[0]);
     }

     return "$response";
}


sub delete
{
    my $self = shift;
    my $socket = $self->{socket};
    close($socket);

    delete( $connected{$self->{host}} );
}


sub DESTROY
{
    my $self = shift;
    my $socket = $self->{socket};
    close($socket);

    delete( $connected{$self->{host}} );
}

1; # Keep perl happy
