#!/usr/bin/perl -w

# ----------------------------------------------------------------
# John Kerl
# kerl.john.r@gmail.com
# 2004/07/01
#
# This script aligns tabular ASCII data nicely.
# Sample input:
#
# 2 4 8 16 32 64 27 54 7 14 28 56 11 22 44 88 75 49 98
# 3 9 27 81 41 22 66 97 89 65 94 80 38 13 39 16 48 43 28
# 4 16 64 54 14 56 22 88 49 95 77 5 20 80 17 68 70 78 9
# 5 25 24 19 95 71 52 58 88 36 79 92 56 78 87 31 54 68 37
# 7 49 40 78 41 85 90 24 67 65 51 54 75 20 39 71 93 45 12
# 8 64 7 56 44 49 89 5 40 17 35 78 18 43 41 25 99 85 74
# 9 81 22 97 65 80 13 16 43 84 49 37 30 68 6 54 82 31 77
# 11 20 18 97 57 21 29 16 75 17 86 37 3 33 60 54 89 70 63
# 12 43 11 31 69 20 38 52 18 14 67 97 53 30 57 78 27 21 50
# 13 68 76 79 17 19 45 80 30 87 20 58 47 5 65 37 77 92 100
#
# Corresponding output:
#
#   2   4   8  16  32  64  27  54   7  14  28  56  11  22  44  88  75  49  98
#   3   9  27  81  41  22  66  97  89  65  94  80  38  13  39  16  48  43  28
#   4  16  64  54  14  56  22  88  49  95  77   5  20  80  17  68  70  78   9
#   5  25  24  19  95  71  52  58  88  36  79  92  56  78  87  31  54  68  37
#   7  49  40  78  41  85  90  24  67  65  51  54  75  20  39  71  93  45  12
#   8  64   7  56  44  49  89   5  40  17  35  78  18  43  41  25  99  85  74
#   9  81  22  97  65  80  13  16  43  84  49  37  30  68   6  54  82  31  77
#  11  20  18  97  57  21  29  16  75  17  86  37   3  33  60  54  89  70  63
#  12  43  11  31  69  20  38  52  18  14  67  97  53  30  57  78  27  21  50
#  13  68  76  79  17  19  45  80  30  87  20  58  47   5  65  37  77  92 100
#
# Each element is printed with a field width equal to the maximum width in the
# matrix.
#
# Options:
# -l for left  alignment
# -r for right alignment
# ----------------------------------------------------------------


$left = 0;
$width = -1;

while ((@ARGV >= 1) && ($ARGV[0] =~ m/^-/)) {
	if ($ARGV[0] eq "-l") {
		$left = 1;
	}
	elsif ($ARGV[0] eq "-r") {
		$left = 0;
	}
	elsif ($ARGV[0] eq "-w") {
		shift @ARGV;
		die "$0:  Missing argument to -w.\n" unless @ARGV;
		$width = $ARGV[0];
	}
	else {
		die "$0:  Unrecognized option \"$ARGV[0]\".\n";
	}
	shift @ARGV;
}

@lines=<>;

if ($width == -1) {
	$maxwidth = 0;
	for my $line (@lines) {
		chomp $line;
		$line =~ s/^\s+//;
		my @fields = split /\s+/, $line;
		for my $field (@fields) {
			$len = length($field);
			$maxwidth = $len if $len > $maxwidth;
		}
	}
	$width = $maxwidth;
}

for my $line (@lines) {
	chomp $line;
	$line =~ s/^\s+//;
	my @fields = split /\s+/, $line;
	$i = 0;
	for my $field (@fields) {
		if ($i > 0) {
			print " ";
		}
		if ($left) {
			if ($i == (@fields - 1)) {
				# Avoid trailing spaces
				print $field;
			}
			else {
				printf "%-*s", $width, $field;
			}
		}
		else {
			printf "%*s", $width, $field;
		}
		$i++;
	}
	print "\n";
}
