
$patchsize = 50;
$screenwidth = $patchsize * 2;
$screenheight = $screenwidth;

@design=('.', '#');
@spacing=(" ", "\n");

@xoff = (0, $patchsize, $patchsize, 0);
@yoff = (0, 0, $patchsize, $patchsize);

$patchno = 0;

while ($line = <>) {
    local ($x, $y);
    for $_ (split(/\s+/, $line)) {
	if (/^([0-9]+):/) {
	    &newfile($1) ;
	    next;
	}

	$xoff = $xoff[$patchno];
	$yoff = $yoff[$patchno];
	
	if ($_ eq 'nw') {
	    for $y (0  .. $patchsize - 1 ) {
		for $x (0  .. $patchsize - 1 - $y  ) {
		    &blackpoint($x, $y);
		}
	    }
	} elsif ($_ eq 'ne') {
	    for $y (0  .. $patchsize - 1 ) {
		for $x (0 + $y  .. $patchsize - 1  ) {
		    &blackpoint($x, $y);
		}
	    }
	} elsif ($_ eq 'se') {
	    for $y (0  .. $patchsize - 1 ) {
		for $x ($patchsize - 1 - $y  .. $patchsize - 1 ) {
		    &blackpoint($x, $y);
		}
	    }
	} elsif ($_ eq 'sw') {
	    for $y (0  .. $patchsize - 1 ) {
		for $x (0  .. $y) {
		    &blackpoint($x, $y);
		}
	    }
	} else {
	    print STDERR "Bad patch: $_ in line $line at line $..\n";
	}

	$patchno++;
    }
}


sub newfile {
    local($fn) = @_;

    if ($fileopen) {
	&printscreen;
	close FILE;
    }
    
    unless (open(FILE, "> patch.$fn")) {
	print STDERR "Couldn\'t open file patch.$fn: $!\n";
	$fileopen = 0;
    }

    $fileopen = 1;
    print FILE "P1\n$screenwidth $screenheight\n\n";
    @screen = (); $patchno = 0;

    print STDERR "Opened file patch.$fn.\n";
}

sub blackpoint {
    local($x, $y) = @_;

    $screensize = $#screen;

    $index = ($x + $xoff) + $screenwidth * ($y + $yoff);
    $screen[$index] = 1;
}


sub printscreen {
    for $i (0 .. $screenheight * $screenwidth - 1) {
	$screen[$i] = 0 unless defined($screen[$i]);
	print FILE $screen[$i];
	print FILE ((($i + 1) % $screenwidth) ? $spacing[0] : $spacing[1]);
    }
}
