#!/usr/bin/perl
#
# Written by Jean-Philippe.Vert@mines.org , november 4, 2002
#
# Reference:
# Jean-Philippe Vert, "A tree kernel to analyze phylogenetic profiles", Bioinformatics, vol. 18, p. S276-S284, 2002.

if ($#ARGV !=3) {
  die "This script splits a file into two files, by randomly copying each line into one of the output files. 'ratio' is a number between 0 and 1 which is the number of lines in the file 'outfile1' compared to the number of lines in the input file.\n
Usage: randsplit.pl <infile> <outfile1> <outfile2> ratio\n";
}

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


# Randomly mix the order of the lines
randmix(@line);


my $l = $#line + 1;    # number of lines
my $t = $l * $ARGV[3]; # number of lines to put in the first output file
my $i;

# Open and fill the first output file
open (INFILE , ">".$ARGV[1])
  or die  "Can't open '$ARGV[1]': $!";
for ($i = 0; $i < $t ; $i++) {
  print INFILE $line[$i];
}
close INFILE;

# Open and fill the second output file
open INFILE , ">".$ARGV[2]
  or die  "Can't open '$ARGV[2]': $!";
for ( ; $i < $l ; $i++) {
  print INFILE $line[$i];
}
close INFILE;



# Procedure to randomly mix the objects of an array
sub randmix {
  my $s = $#_ + 1;      # number of objects in the array
  my $i,$j,$x;
  for ($i=0 ; $i<$s ; $i++){
    $j = rand $s;
    $x = $_[$i];
    $_[$i] = $_[$j];
    $_[$j] = $x;
  }
}
