#! /s/perl/bin/perl


# Need a splitter function to chunk up a uuencoded file into multiple
# pieces, suitable for mailing, and mailing them.
#
# Usage is:
#   uumerge <filename to extract> <mail folder>
#
# extract the filename requested from a mail folder, saving it to the
# current directory.
# Maybe if no mail folder is specified, search for files in the
# current directory that match the "split" names and merge them.


($bigfile, $folder) = @ARGV;

# Quick Error Checks
die "Usage: uumerge <filename> <email folder>\n" if (!$folder);
die "Error, file $bigfile already exists.\n" if (-f $bigfile);

$uufile = "${bigfile}.uu";
open(FOLDER, $folder) || die "Could not open mail folder $folder.\n";
open(BIG, "| uudecode") || die "Could not run uudecode.\n";

$piece = 1;
$in_piece = 0;

$total = 0;
$tot = 1;
$last = 0;

while (<FOLDER>) {

    if ($in_piece) {
      
      if ( /^---- END (\S+) piece (\d+) of (\d+) ----/ )
        {
        $in_piece = 0;
        }
      else
        {
        print BIG;
        }
    } else {
      if ( /^---- BEGIN (\S+) piece (\d+) of (\d+) ----/ )
        {
        $fname = $1;
        $pce = $2;
        $tot = $3;

        if ($fname eq $bigfile) 
          {
          print "Found piece $pce out of $tot from $fname\n";
          $in_piece = $pce;
          $total++;
          $last++;
          if ($last != $in_piece)
            {
            print "Error: pieces are out of order.\n";
            last;
            }
          }
        }
    }
}

close BIG;
close FOLDER;

if ($in_piece || ($total != $tot))
  {
  print "Error while extracting $bigfile.\n";
  unlink($bigfile);
  }
else
  {
  print "Successfully extracted $bigfile.\n";
  }

exit 0;

