#!/usr/bin/perl -w

use strict;
no warnings 'portable';

my %mem;

my ($floatm, $orm);
while (<>) {
	chomp;
	if (/mask = (\S+)/) {
		($orm, $floatm) = ($1, $1);
		$floatm =~ s/1/0/g;
		$orm  =~ s/X/0/g; $orm  = oct "0b$orm";
		next;
	}
	if (/mem\[(\d+)\] = (\d+)/) {
		my $data = $2;
		for my $addr (addr2list($1|$orm, $floatm)) {
			$mem{$addr} = $data;
			# print "mem[$addr=", pack("b*", $addr),"] = $2\n";
		}
	}
}

my $sum;
for (keys %mem) { $sum += $mem{$_} };
print "Sum=$sum\n";

sub addr2list {
	my ($addr, $mask) = @_;
	if ($mask =~ s/X/0/) {
		my $off = length $';
		return (addr2list($addr | (1 << $off), $mask),
			addr2list($addr & ~(1 << $off), $mask));
	} else {
		return ($addr);
	}
}
