#! /usr/bin/perl -w
# Hack to munge life.table for bedbugs.

my %vars = ();
my $done_vars = 0;

while(<>) {
    if (m/^#/) {
        print $_;
    } elsif (m/^(n_states|neighborhood|symmetries):/) {
        print $_;
    } elsif (m/^var /) {
        die "Complicated variable" unless m/^var (.)=\{0,1\}$/;
        $vars{$1} = 1;
    } else {
        chomp;
        my @cells = split /,/;
        my %myvars = ();
        die "Unexpected number of comma-separated items" unless @cells == 10;
        my @dirs = qw/c n ne e se s sw w nw/;
        if (!$done_vars) {
            print "var zz={0," . join(",", 2..17) . "}\n";
            print "var aa={" . join(",", 18..33) . "}\n";
            foreach my $d (@dirs) {
                print "var z$d={zz}\n";
                print "var a$d={aa}\n";
                print "var q$d={z$d,a$d}\n";
            }
            $done_vars = 1;
        }
        my $i = 0;
        while (my $dir = pop @dirs) {
            die "Duplicate var" if exists($myvars{$cells[$i]});
            if (exists($vars{$cells[$i]})) {
                $myvars{$cells[$i]} = 1;
                $cells[$i] = "q".$dir;
            } elsif ($cells[$i] eq "0") {
                $cells[$i] = "z".$dir;
            } elsif ($cells[$i] eq "1") {
                $cells[$i] = "a".$dir;
            } else {
                die "Unexpected cell $cells[$i]";
            }
            $i++;
        }
        print join(",", @cells), "\n";
    }
}
