#!/usr/bin/perl

use strict;
use warnings;

my $MAXLEVEL = 7;

sub makeLevel($);

our @bsllines;
open(my $ifh, "<", "levelX.bsl") or die($!);
@bsllines = <$ifh>;
close $ifh;

for(my $i = 1; $i <= $MAXLEVEL; $i++) {
   makeLevel($i);
}

sub makeLevel($) {
	my $num = shift;

	my @autolines;
	
	open(my $ifh, "<", "level" . $num . ".dat") or die($!);
	my @llines = <$ifh>;
	close($ifh);

	my $yoffs = 0;
	foreach my $line (@llines) {
		my $xoffs = 0;
		my @parts = split//,$line;
		while((my $part = shift @parts)) {
			if($part eq "#") {
				#print "$xoffs / $yoffs\n";
				push @autolines, "-- GESCHENK\n";
				push @autolines, "FLOCKS.maxobjcount = FLOCKS.maxobjcount + 1;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount] = {};\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].x = $xoffs;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].y = $yoffs;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].gfxnum = math.random(0, 59);\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].speed = 0;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].wind = 0;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].type = math.random(FLOCKS.minpixelnum,FLOCKS.maxpixelnum);\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].obj = \n" .
								 "    AddGFXPixel(FLOCKS.gfxs[FLOCKS.obj[FLOCKS.maxobjcount].type][FLOCKS.obj[FLOCKS.maxobjcount].gfxnum],\n" .
								 "           0,0, 1);\n";
								 
			} elsif($part eq "X" || $part eq "Y" || $part eq "Z") {
				#print "$xoffs / $yoffs\n";
				push @autolines, "-- BAUM\n";
				push @autolines, "FLOCKS.maxobjcount = FLOCKS.maxobjcount + 1;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount] = {};\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].x = $xoffs;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].y = $yoffs;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].gfxnum = math.random(0, 59);\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].speed = 0;\n",
								 "FLOCKS.obj[FLOCKS.maxobjcount].wind = 0;\n";
				if($part eq "X") {
					push @autolines, "FLOCKS.obj[FLOCKS.maxobjcount].type = FLOCKS.minbaumnum;\n";
				} elsif($part eq "Y") {
					push @autolines, "FLOCKS.obj[FLOCKS.maxobjcount].type = FLOCKS.minbaumnum + 1;\n";
				} else {
					push @autolines, "FLOCKS.obj[FLOCKS.maxobjcount].type = FLOCKS.minbaumnum + 2;\n";
				}
				push @autolines, "FLOCKS.obj[FLOCKS.maxobjcount].obj = AddObject(FLOCKS.gfxs[FLOCKS.obj[FLOCKS.maxobjcount].type][FLOCKS.obj[FLOCKS.maxobjcount].gfxnum], " ,
											"0,0, 0, 1, 0, 0);\n";						 
			}
			$xoffs += 32;
		}
		$yoffs += 32;
	}

	open(my $bofh, ">", "../level" . $num . ".bsl") or die($!);
	foreach my $line (@bsllines) {
		print $bofh $line;
		if($line =~ /AUTOPIXELINSERTHERE/) {
			foreach my $aline (@autolines) {
				print $bofh $aline;
			}
			print $bofh $line;
		}
	}
	close($bofh);

	open(my $lofh, ">", "../level" . $num . ".dat") or die($!);
	foreach my $line (@llines) {
		$line =~ s/\#/ /g;
		$line =~ s/X/ /g;
		print $lofh $line;
	}
	close($bofh);

}
