#!/usr/bin/perl
#
# Written by Jean-Philippe Vert

if ($#ARGV != 3) {
  die "Usage: ./split.pl <intputfile> <output1> <output2> <ratio>\nThis scripts randomly shuffles the lines of <inputfile> and split them to create to files with relative size <ratio>";
}




# Read the input file
open (INFILE , $ARGV[0]) || die "Can't open $ARGV[0]: $!";
my @line = <INFILE>;
close (INFILE);


# shuffle the lines
fisher_yates_shuffle(\@line);

my $s = scalar(@line);
my $r = int ($s * $ARGV[3]);
my $t = $s -$r;
print "The initial file has $s lines\nI randomly split it into $r and $t lines\n";

open (OUTFILE , ">".$ARGV[1]) || die "Can't open $ARGV[1]: $!";
my $i;
for ($i = 0 ; $i < $r ; $i++) {
  my $u = pop @line;
  print OUTFILE $u;
}
close OUTFILE;

open (OUTFILE , ">".$ARGV[2]) || die "Can't open $ARGV[2]: $!";
for ($i = $r ; $i < $s ; $i++) {
  my $u = pop @line;
  print OUTFILE $u;
}
close OUTFILE;




# fisher_yates_shuffle( \@array ) : 
# generate a random permutation of @array in place
sub fisher_yates_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];
  }
}

