#!/usr/bin/perl -w
use Getopt::Long;
use vars qw/$opt_help $opt_seed/;
GetOptions("help","seed:i");
if (defined $opt_help){
  print "
 usage example: splitfile.pl data.dat 3 1 1
 That will make data.dat.1 with 3/5 of the data,
 data.dat.2 with 1/5 of the data, and data.dat.3 with 1/5.
 The first argument is the file to split, following is
 arbitrary amount of numbers, separated by spaces.
 Use -seed <number> to make reproducible random numbers.

";
exit(0);  
}
if (defined $opt_seed){
#  print "seed $opt_seed\n";
  srand($opt_seed);
}   
$infile=shift @ARGV;
$nfiles=@ARGV;
$sum=0;
for $i (@ARGV) {$sum+=$i}

open IN,"<$infile" or die "no file $infile";
while ($line=<IN>){
  if ($line=~m/^\s*\#/){
	push @header,$line;
    next;
  };
  next if $line=~m/^\s*$/;
  push @all,$line;
}

&shuffle(\@all);

$nrec=@all;
$m=0;
for $i (1..$nfiles) {
  $n=$m+ int($ARGV[$i-1]*$nrec/$sum);
  $n=$nrec if $n>$nrec or $i==$nfiles;
  @sub=@all[$m..$n-1];
  $outfile=$infile.".$i";
  open OUT,">$outfile";
  print OUT @header,@sub;     
  close OUT;
  print "wrote $outfile with array index $m to ",$n-1,"\n";
  $m=$n;
}

sub shuffle{
  my $array= shift;
  my $i;
  for ($i=@$array; --$i;){
    my $j = int rand ($i+1);
    next if $i == $j;
    @$array[$i,$j]=@$array[$j,$i];
  }
}
