#!/usr/bin/perl
#
# A pretty-printer for polynomials. Identifiers, coefficients, exponents
# and indices are written in different colours, and the output is formatted.
# Written by Thierry Bousch, and released into the Public Domain.

# Here is my choice of colours:
$color_normal		= '00';		# Normal mode
$color_identifiers	= '01';		# Bright
$color_coefficients	= '01;31';	# Bright red
$color_exponents	= '01;34';	# Bright blue
$color_indices		= '01;32';	# Bright green

$en = "\033[${color_normal}m";
$ei = "\033[${color_identifiers}m";
$ec = "\033[${color_coefficients}m";
$ee = "\033[${color_exponents}m";
$et = "\033[${color_indices}m";

if (open(PIPE, "-|") == 0) {
	# This is the child. Add space before + and - but not after a
	# comma or opening parenthesis. Then reformat the text.
	$columns = 0;
	$notfirst = 0;
	while (<STDIN>) {
		s/([\+\-])/ \1/g;
		s/([\(,]) /\1/g;
		s,\)/,\) /,g;
		s,/\(,/ \(,g;
		@line = split(" ");
		foreach $word (@line) {
			$columns += $notfirst + length($word);
			if ($notfirst) {
				if ($columns > 76) {
					print "\n";
					$columns = length($word);
				}
				else { print " "; }
			}
			print $word;
			$notfirst = 1;
		}
	}
	print "\n";
	exit(0);
}

# The parent only needs to do the colorizing
while (<PIPE>) {
	# Identifiers
	s/((\[[^\]]+\])|([a-zA-Z_]\w*))/$ei\1$en/g;
	# Coefficients
	s/([+\-\/\(,])(\d+)/\1$ec\2$en/g;
	s/^(\d+)/$ec\1$en/g;
	# Exponents
	s/\^(\d+)/\^$ee\1$en/g;
	# Tensor indices
	s/\!(\d+)/\!$et\1$en/g;
	print;
}
