#!/usr/local/bin/perl

sub eol { ($elt+1) % $cols == 0; }	# is this the last elt on line?

$maxlen = 1;	# widest string yet seen

$winsize = "\0" x 8;
$TIOCGWINSZ = 0x40087468;  # should be require sys/ioctl.pl

if (ioctl(STDOUT, $TIOCGWINSZ, $winsize)) {
    ($rows, $cols, $xpixel, $ypixel) = unpack('S4', $winsize);
} else {
    $cols = 80;
}


while (<>) { 	# read stdin into $_
    s/\s+$//;
    $maxlen = $mylen if (($mylen = length($_)) > $maxlen);
    push(list, $_);
} 

$maxlen += 1;  # spaces

$cols = int($cols / $maxlen) || 1;
$rows = int(($#list+$cols) / $cols);
$mask = sprintf("%%-%ds ", $maxlen-1);

for ($elt = 0; $elt < $rows * $cols; $elt++) { 
    $target =  ($elt%$cols) * $rows + int(($elt/$cols));
    $piece = sprintf($mask, $target < ($#list+1) ? $list[$target] : "");
    $piece =~ s/\s+$// if do eol();  # don't blank pad to eol of line
    print $piece;
    print "\n" if do eol();
}

print "\n" if do eol();