#!/usr/bin/perl
#
# Copies stdin to stdout appending sums of columns
# Example:
#  ls -ls | total
# |  50 -r-xr-xr-x  1 root  wheel      50316 21 ΟΛΤ 15:36 chio
# |  58 -r-xr-xr-x  1 root  wheel      58136 21 ΟΛΤ 15:37 chmod
# |  60 -r-xr-xr-x  1 root  wheel      60700 21 ΟΛΤ 15:37 cp
# | 264 -r-xr-xr-x  1 root  wheel     258248 21 ΟΛΤ 15:37 csh
# | 152 -r-xr-xr-x  1 root  wheel     144584 21 ΟΛΤ 15:37 date
# | -----------------------------------------------------------
# | 584             5                 571984 105 
#
# Copyright (c) 1997 Andrew Maltsev <am@amsoft.ru>
#

# @p - average positions of columns
# @n - sum
# @d - digital or no?

$lines=0;
while(<>)
{ print;
  $lines++;
  chop;
  $ml=length if $ml<length;
  split;
  shift @_ if $_[0] eq "";
  $n=-1;
  $p=0;
  while(@_)
   { $str=shift @_;
     $n++;
     $p=index($_,$str,$p);		# not very accurate, but simple
#     print "str=`$str' pp=$p l=", length($str), "\n";
     $p[$n]+=$p+length($str);
     next unless ($str =~ /^[0-9]+$/);
     $n[$n]+=$str;
     $d[$n]++;
   }
}

# Nothing to print
exit(0) unless $lines;

# Footer
print "-" x $ml . "\n";
$footer="";
while(@n)
{ $n=shift @n;
  $p=int((shift @p)/$lines+0.5);
  $d=(shift @d)/$lines;
#  print "n=$n p=$p d=$d i(p)=",int($p),"\n";
  $_="";
  $_=$n if $d > .6;
#  print "`$_'",$p-length($_)-length($footer),"\n";
  $footer.=" " x ($p-length($_)-length($footer));
  $footer.="$_ ";
#  print "`$footer'\n";
}
print "$footer\n";

