#!/usr/bin/perl
#use Mooix::Thing;
#use Fcntl q{:flock};
run sub {
	my $this=shift;
	%_=@_;

	return unless $this->spring;
	
	# Set the duck to waddling. Note that this is done while
	# the duck is still (presumably) locked by the caller. Use
	# a unique id in the waddling field since this method might
	# be called twice at the same time.
	return if $this->waddling;
	my $id=$$;
	$this->waddling($id);
		
	# After forking to the background, the duck isn't locked
	# for movement anymore (since the caller holds the lock
	# only until this method returns).
	return $this unless $this->background;
	
	# Waddle around a bit, depending on how tightly the spring
	# is wound.
	my $max=$this->max_spring;
	while ($this->spring - 1 > $max_spring / 2) {
		# Lock the duck for movement, then check to see if
		# it's still supposed to be waddling, or if
		# something stopped it.
		my $lock=$this->getlock(LOCK_EX);
		return unless $this->waddling eq $id;
		
		$this->msg('energetic_waddle');
		$this->spring($this->spring - 1);
		close $lock; # allow someone to intercept it
		sleep 1;     # while it sleeps
	}
	# A final waddle, and stop waddling.
	my $lock=$this->getlock(LOCK_EX);
	return unless $this->waddling eq $id;
	$this->msg('waddle');
	$this->waddling(0);
	# Unwind the spring all the way.
	$this->spring(0);
	close $lock;
}
