#!/usr/athena/bin/perl

do "lib.pl";

$parts = 1;

$oldselect = select(STDOUT); $| = 1; select($oldselect);

while ($_ = $ARGV[0], /^-/) {
    shift;
    if (/^-in$/) {
	die "Missing argument to \"-in\".\n" if (! @ARGV);
	$infile = shift;
	next;
    }
    if (/^-out$/) {
	die "Missing argument to \"-out\".\n" if (! @ARGV);
	$outfile = shift;
	next;
    }
    if (/^-parts$/) {
	die "Missing argument to \"-parts\".\n" if (! @ARGV);
	$parts = shift;
	next;
    }
    die "Unknown argument \"$_\".\n";
}

if (! $infile) {
    die "No input file specified.\n";
}

if (! $outfile) {
    $outfile = $infile;
}

print "Reading... ";

@records = &lopip'read_data($infile);

print @records + 0, " records.\n";

print "Saving...";

$chunksize = int(@records / $parts);
$chunksize++ if ($parts * $chunksize != @records);

foreach $part (1..$parts) {
    open(OUT, ">$outfile.part$part") || 
	die "Opening \"$outfile.part$part: $!.\n";
    $chunkstart = ($part - 1) * $chunksize;
    $chunkend = ($part * $chunksize) - 1;
    $chunkend = $#records if ($chunkend > $#records);
    print " ", $chunkstart, "-", $chunkend;
    @chunk = @records[$chunkstart..$chunkend];
    &lopip'posting_write("main'OUT", *chunk);
    close(OUT);
}

print "\n";
