package sim;

use Data::Dumper;
require 'ebpacket.pm';

# this loads in the same place as the ebhw module
# and performs a similar task, only 
# it does packet IO to a file
# permits testing other sections of the code. Mostly for testbedding


sub new {

	$self = {};
	
	$packet_path = "/home/sheer/mk3eb/packets";
	$self->{packet_file} = "$packet_path/packets.eb2pl";
	$self->{packet_out_file} = "$packet_path/packets.pl2eb";
	$self->{packet_offset} = 0;

	bless ($self);
	return($self);
}

sub set_packet_file {
	my $self = shift;
	$self->{packet_file} = shift;
}

sub set_packet_output_FILE {
	my $self = shift;
	$self->{packet_out_file} = shift;
}


sub set_packet_offset {
	my $self = shift;
	$self->{packet_offset} = shift || 0;
}

sub get_packet {
	my $self = shift;
	my $FH;
	my $file = $self->{packet_file};
	my $packet = new ebpacket;
	my $current_packet;
	my $packet_number = 0;

	open($FH,"<$file");

	if($self->{packet_offset} == 0) {
		$current_packet = 1;
	} else {
		$current_packet = 0;
	}

	while($in = <$FH>) {
		chop($in);
		if($in eq "!") {
			# handle next packet
			$packet_number++;

			if($current_packet) {
				$current_packet = 0;
				return($packet);
			}

			if($packet_number == $self->{packet_offset}) {
				$current_packet = 1;
				$packet->{sequence_number} = $packet_number;
			}

		} elsif($current_packet) {
			$value = hex $in;
			push(@{$packet->{pbuf}},$value);
			$packet->{size}++;
		}
	}

	close($FH);

	$self->{packet_offset}++;

	return(undef);
}

sub put_packet {
	my $self = shift;
	my $packet = shift;
	my $count = 0;
	my $len = $packet->{size};
	my $file = $self->{packet_out_file};

	open($FH,">$file"); # todo: append

	for($count=0;$count<$len;$count++) {
		$data = $packet->{pbuf}[$count];
		printf $FH ("%x\n",$data);
	}
	print $FH "!\n";
	close($FH);
}

1;
