#!/usr/bin/perl -i.bak

use English;

## get input
undef $INPUT_RECORD_SEPARATOR;
$file = <>;

#print STDERR $file;

## transform it

my $openingSquareBracketsRE = '(?<!\\\\)\\[{3}'; 
# in other words, we want '[[[', not preceded by a '\'

my $closingSquareBracketsRE = '(?<!\\\\)\\]{3}';

my $not3ClosingSquareBracketsRE = '((?!\\]3).)*?';

$file =~ s/$openingSquareBracketsRE($not3ClosingSquareBracketsRE)$closingSquareBracketsRE/scriptedMatrixReplace($1)/egs; 

## print output
print $file;
#print "\n";
#print STDERR $file;


######################
# subroutines
######################

sub scriptedMatrixReplace {
    my ($expr) = @_;

#    print STDERR "******** here: $expr\n";

    my @rows;
    my $out;

    @rows = createScriptedMatrix($expr);
    $out = matrixToLatex(@rows);

    return $out;
}

sub createScriptedMatrix {
    my ($expr) = @_;

    $expr =~ /(\d+),(\d+),(.*)/s;
    my $numRows = $1;
    my $numCols = $2;
    my $script = $3;

#    print STDERR "$numRows, $numCols, S: $script\n";

    my @rows;
    my $cols;

    for ($rowIndex = 0; $rowIndex < $numRows; $rowIndex++) {
	$cols = []; 
	for ($colIndex = 0; $colIndex < $numCols; $colIndex++) {
	    local $i = $rowIndex + 1;
	    local $j = $colIndex + 1;
	    $cols->[$colIndex] = eval $script;
#	    print STDERR "On $i,$j\n";
	}
	$rows[$rowIndex] = $cols;
    }
	    
#    use Data::Dumper;
#    print STDERR Dumper(@rows);

    return @rows;
} 

sub matrixToLatex {
    my @rows = @_;

    my @cols;
    my ($row, $out);
    my $colCount;
    my $colSpecifier;
    my $i;
    my $out;

    foreach $row (@rows) {
	@cols = @$row;
	$colCount = $#cols + 1; 
           # yeah, okay, so we do this for every row
	   # and we only need to do it once!
	foreach $col (@cols) {
	    $out .= "$col & ";
              
	}
	$out = substr($out,0,-3); 
           ## STRIP OFF THE EXTRA & THAT WE PUT AFTER THE LAST COLUMN
	$out .= "\n".'\\\\ ';
    }
    
    ## STRIP OFF THE \\  THAT WE PUT AFTER THE LAST LINE OF THE MATRIX
    $out = substr($out,0,-3);

    for ($i = 0; $i < $colCount; $i++) {
	$colSpecifier .= 'l';
    }

    $out = '\left[ \begin{array}{'.$colSpecifier.'}'."\n".'   ' . $out . '\end{array} \right]';

#    print STDERR "**************$out\n";

    return $out;
}


