#! /usr/local/bin/perl

print "Content-type: text/html\r\n\r\n";

%F = &formdata();
$data = $F{'data'};
$data = &fakeData() unless $data;
@color = ("black", "red", "blue", "green", "magenta", "darkcyan", "gold");

print "<form method=POST action=match.cgi>\n";
print "<div><textarea name=data rows=10 cols=60 wrap=virtual>$data</textarea></div>\n";
print "<input type=submit accesskey=s value=Submit>\n";
print "</form>\n";

print "<pre>";
print &showMatch($data);
print "</pre>";

sub style { # c depth
	local ($c, $depth) = (@_);
	local ($result);
	local ($background) = ($c =~ /[{}]/) ? "#CCCCCC" : "#FFFFFF";
	$depth += 3 if $c =~ /[\[\]]/;
	$depth = $depth % @color;
	$result = "<span style=\"color: $color[$depth]; font-weight: bold; background: $background\">";
	$result .= $c;
	$result .= "</span>";
	return $result;
}

sub showMatch { # s
	local ($s) = (@_);
	local (@s) = split //, $s;
	local ($pdepth, $bdepth, $sdepth) = 0;
	local ($colored) = "";
	for $s (@s) {
		if ($s eq '(') {
			$pdepth++;
			$colored .= style($s, $pdepth);
		} elsif ($s eq ')') {
			$colored .= style($s, $pdepth);
			$pdepth--;
		} elsif ($s eq '{') {
			$bdepth++;
			$colored .= style($s, $bdepth);
		} elsif ($s eq '}') {
			$colored .= style($s, $bdepth);
			$bdepth--;
		} elsif ($s eq '[') {
			$sdepth++;
			$colored .= style($s, $sdepth);
		} elsif ($s eq ']') {
			$colored .= style($s, $sdepth);
			$sdepth--;
		} else {
			$colored .= $s;
		}
	}
	return $colored;
}

sub formdata { # nil -> %F
    local (*formdata);
    if ($ENV{'REQUEST_METHOD'} eq 'POST') {
        read (STDIN, $F, $ENV{'CONTENT_LENGTH'});
    } else {
        $F = $ENV{'QUERY_STRING'};
    }
    @formdata = split (/&/, $F);
    for (@formdata) {
        local ($name, $value) = split (/=/, $_, 2);
        $value =~ s/\+/ /g;
        $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        $F{$name} = $value;
    }
    return (%F);
}

sub fakeData {
return 'roots (a, b, c) {
	y         = (((a * (x ^ 2)) + (b * x)) + c)
	radical   = sqrt(((b * b) - ((4 * a) * c)))
	root1     = ((-b - radical) / (2 * a))
	root2     = ((-b + radical) / (2 * a))
}

/* bubble sort */
for (i=0; i&lt;n-1; i++) {
  for (j=0; j&lt;n-1-i; j++)
    if (a[j+1] &lt; a[j]) {  /* compare the two neighbors */
      tmp = a[j];         /* swap a[j] and a[j+1]      */
      a[j] = a[j+1];
      a[j+1] = tmp;
  }
}
';
}
