#!/usr/local/bin/perl5

use Turtle;

$turtle = Turtle->create();

$turtle->color('none');
$turtle->move(100,100);
$turtle->width(1);

$times = $ARGV[0];
$dir = 270;
$r = 10;
$x = 0;
$y = 0;

sub move {
    my ($x1,$y1) = @_;
    $turtle->color('none');
    $x += $x1;
    $y += $y1;
    $turtle->move($x1,$y1);
}

sub forward {
    $turtle->color('black');
    if ($dir == 0) {
	$x = $x+$r;
	$turtle->move($r,0);
    } elsif ($dir == 90) {
	$y = $y+$r;
	$turtle->move(0,$r);
    } elsif ($dir == 180) {
	$x = $x-$r;
	$turtle->move(-$r,0);
    } elsif ($dir == 270) {
	$y = $y-$r;
	$turtle->move(0,-$r);
    }
}

sub left {
    $dir -= 90;
    $dir %= 360;
}
sub right {
    $dir += 90;
    $dir %= 360;
}

sub dragon {
    my ($level) = @_;
    my ($x1,$y1) = ($x,$y);
    my ($dir1);

    if ($level<=1) {
# print "$x $y ->";
	&forward();
# print "$x $y\n";
    } else {
	# write the first segment
	&dragon($level-1);
	# move to the starting point
	&move($y1-$y,$x-$x1);
	# memorize this position
# print "m $x $y\n";
	$x1 = $x;
	$y1 = $y;
	$dir1 = $dir;
	# Turn Left
	&left();
	# write the second segment
	&dragon($level-1);
	# return the last position and direction
	&move($x1-$x,$y1-$y);
	$dir = $dir1;
# print "r $x $y\n";
    }
}

&dragon($times);
$turtle->MainLoop();

# end
