#!/usr/bin/perl -W
#
# Usage : $pgr_name m n mu scale
# Output : LaTeX code for the m,n,\mu graph. Requires TikZ

# Subroutine gcd
sub gcd {
    my ($a, $b) = @_;
    return &gcd($b,$a) if $a < $b;
    if($b == 0) {
	return $a;
    } else {
	return &gcd($b, $a % $b);
    }
}

$m = shift;
$n = shift;
$mu = shift;
$scale = shift;
$node_counter = 0;

print "\\begin{tikzpicture}[scale=".$scale."]\n";


# Non degenerate
for(my $j = 1 ; $j < $n; ++$j) {
    for(my $i = 1; $i < $m; ++$i) {
	print "\t\\definecolor{colori".$i."j".$j."}{rgb}{".(($i+$j)/($m+$n)).",".($i+$j)/($m+$n).",".($i/$m+$j/$n)."}\n";
	my $color = "colori".$i."j".$j;
	for(my $k = 1; $k < $i+$j+$mu; ++$k) {
	    my $x0, $y0, $x1, $y1;
	    if($k > $j+$mu) {
		$y0 = 1;
		$x0 = ($k-$j-$mu)/$i;
	    } else {
		$x0 = 0;
		$y0 = ($k-$mu)/$j;
	    }
	    if($k < $i+$mu) {
		$y1 = 0;
		$x1 = ($k-$mu)/$i;
	    } else {
		$x1 = 1;
		$y1 =($k-$i-$mu)/$j;
	    }
	    print "\t\\draw [".$color.",thick] (".$x0.",".$y0.") -- (".$x1.",".$y1.");\n";
	}
    }
}

# Degenerate : horizontal
for(my $j = 1; $j < $n; ++$j) {
    print "\t\\definecolor{colori0j".$j."}{rgb}{".$j/($m+$n).",".$j/$n.",".$j/($m+$n)."}\n";
    my $color = "colori0j".$j;
    for(my $k = 1; $k < $j+$mu ; ++$k) {
	print "\t\\draw [".$color.",thick] (0,".(($k-$mu)/$j).") -- (1,".(($k-$mu)/$j).");\n";
    }
}

# Degenerate : vertical
for(my $i = 1; $i < $m; ++$i) {
    print "\t\\definecolor{colori".$i."j0}{rgb}{".$i/$m.",".$i/($m+$n).",".$i/($m+$n)."}\n";
    my $color = "colori".$i."j0";
    for(my $k = 1; $k < $i+$mu ; ++$k) {
	print "\t\\draw [".$color.",thick] (".(($k-$mu)/$i).", 0) -- (".(($k-$mu)/$i).", 1);\n";
    }
}

print "\t\\definecolor{black}{rgb}{0,0,0}\n";
print "\t\\draw [black,thick] (0,0) -- (1,0) -- (1,1) -- (0,1) -- cycle;\n";
	
print "\\end{tikzpicture}\n";
