#!/usr/bin/perl

require "../oscpl/osc.pl";
require "./osc_screen.pl";

osc_connect("infocalypse.al.cl.cam.ac.uk", 4500, "GPIB0::7::INSTR");

$num_worms = 5;
$worm_change_probability = 20;
$worm_length = 80;




print "saving screen...\n";
# $data = save_screen();
print "done               \n";

sub handler {
	local($sig) = @_;
	print "Caught a SIG$sig--shutting down\n";
#	restore_screen($data);
	exit(0);
}
$SIG{'INT'} = 'handler';

# worm


for ($count = 0; $count < $num_worms; $count++) {
	print "initializing worm $count\n";
	$wormtrail[$count] = [];
	for ($i = 0; $i < $worm_length; $i++) {
		$coordref = [100, $i];
		@coords = @{$coordref};
		osc_write(":display:pixel 100, $i, 1");
		push(@{$wormtrail[$count]}, $coordref);
	}
	# preserve head
	$worm_x_head[$count] = 100;
	$worm_y_head[$count] = $i;
	# first delta
	$worm_x_delta[$count] = 1;
	$worm_y_delta[$count] = 1;
}


$x = 0;
$y = 0;

while(1) {
	for ($count = 0; $count < $num_worms; $count++) {
		# draw a black dot on the end of the tail
		@coords = @{shift(@{$wormtrail[$count]})};
		osc_write(":display:pixel ".$coords[0].", ".$coords[1].", 0");

		# draw a white dot where the head of the worm will now be
		if (int(rand($worm_change_probability)) == 0) {
			$worm_x_delta[$count] = rand(5) - 2;
			$worm_y_delta[$count] = rand(5) - 2;
		}
		$x = $worm_x_head[$count];
		$y = $worm_y_head[$count];
		$x += $worm_x_delta[$count];
		$y += $worm_y_delta[$count];
		$x %= $x_pixels;
		$y %= $y_pixels;
		$coordref = [$x, $y];
		@coords = @{$coordref};

		$worm_x_head[$count] = $x;
		$worm_y_head[$count] = $y;
		push(@{$wormtrail[$count]}, $coordref);
		osc_write(":display:pixel ".$coords[0].", ".$coords[1].", 1");

		# little bit of decay on the whole display
#		if (int(rand(15)) == 0) {
#			osc_write(":display:pixel $x, $y, 0");
#			$x++;
#			if ($x >= $x_pixels) {
#				$x = 0;
#				$y++;
#				$y %= $y_pixels;
#			}
#		}
	}
}

#while (1) {
#	$x = int(rand(512));
#	$y = int(rand(304));
#	$color = int(rand(3));
#	osc_write(":display:pixel $x, $y, $color");
#	print ":display:pixel $x, $y, $color\n";
#	select(undef, undef, undef, 0.05);
#}


