#!/usr/bin/perl
#
# Multiplication of two matrices (or vectors, etc.); we collect expressions
# of the form __e[...] in both operands, and apply the rule
# __e[foo,i].__e[j,bar] = __e[foo,bar] if i=j and 0 otherwise.

die "Usage: $0 matrix1 matrix2\n" unless $#ARGV == 1;
$m1 = $ARGV[0];
$m2 = $ARGV[1];

open(STDOUT, "|samuel --batch");
print "M1=$m1; M2=$m2; 0";

foreach $_ (split(/[+-]/,$m1)) {
	if (/\b__e\[(\d+,)*(\d+)\]/) {
		$tsr1{$2} .= "$&;" unless $ok1{$&}++;
		++$found{$2};
	}
}
foreach $_ (split(/[+-]/,$m2)) {
	if (/\b__e\[(\d+)(,\d+)*\]/) {
		$tsr2{$1} .= "$&;" unless $ok2{$&}++;
		++$found{$1};
	}
}
foreach $i (sort keys(%found)) {
	chop($a1 = $tsr1{$i});
	chop($a2 = $tsr2{$i});
	foreach $e1 (split(/;/,$a1)) {
		foreach $e2 (split(/;/,$a2)) {
			$foo = $1 if $e1 =~ /\b__e\[((\d+,)*)(\d+)\]/ ;
			$bar = $2 if $e2 =~ /\b__e\[(\d+)((,\d+)*)\]/ ;
			if ($foo) {
				chop $foo;
				$foo .= $bar;
				$e3 = "__e[$foo]";
			} elsif ($bar) {
				$bar =~ s/^,//;
				$e3 = "__e[$bar]";
			} else {
				$e3 = "1";
			}
			print "+(?M1:$e1).(?M2:$e2).$e3\n";
		}
	}
}
print ";\n";
close STDOUT;	# Wait for samuel(1) to terminate
exit 0;
