#!/usr/local/bin/perl

if ($ARGV[0] eq "-s")	# grab subject, if any
{
  $sub = $ARGV[1];
  shift; shift;
}

if ($#ARGV<1) {die "usage: splitmail [-s subject] size-in-k user [user2...]\n";}

$size = $ARGV[0];	# max size for pieces, in K

if ($size<=0) {die "usage: splitmail [-s subject] size-in-k user [user2...]\n";}

shift;
$size *= 1024;		
$partnum = 1;		# current part number
$got = 0;		# number of bytes we've read

$recips = join(' ',@ARGV); $#ARGV = -1;
open(STDOUT,qq/|Mail -s "$sub part 1" $recips/) || die;

while (<>)
{
  $len = length($_);
  if ($got + $len > $size)
  {
    print "-- end of part $partnum --\n";
    $partnum++;
    close(STDOUT);
    open(STDOUT,qq/|Mail -s "$sub part $partnum" $recips/) || die;
    $got = 0;
  }
  print;
  $got += $len;
}

print "-- end of file --\n";
close(STDOUT);
exit 0;
