#!/usr/bin/perl
# Assume we already have two 10,000-base DNA sequences who are reverse
# complement to each other, generate random 100-base reads from these two
# sequences. The two sequences are expected to be in file "rando.seq" and
# "random_revcom.seq", as generated by the "gen_randome_sequence.pl" script.
# The created reads will be saved in file "random.fa" in the FASTA format.
# "random_revcom.seq" respectively.
use strict;
use warnings;

my $sequence_length = 100000;
my $read_length = 100;
my $seq_file = "random.seq";
my $seq_revcom_file = "random_revcom.seq";
my $fasta_file = "random.fa";

my $random_number;
my $char;
my $i;
my $seq;
my $seq_revcom;
my $kmer;
my $num_of_reads;

# Check sequence_length argument
my $numArgs;
$numArgs = $#ARGV+1;
if ($numArgs == 1) {
	$sequence_length = $ARGV[0];
}

open SEQFILE, "$seq_file" or die $!;
$seq = <SEQFILE>;
print length($seq) . " bases are read from $seq_file.\n";
close(SEQFILE);

open SEQFILE, "$seq_revcom_file" or die $!;
$seq_revcom = <SEQFILE>;
print length($seq_revcom) . " bases are read from $seq_revcom_file.\n";
close(SEQFILE);


open FASTAFILE, ">$fasta_file" or die $!;
$num_of_reads = ($sequence_length / $read_length) * 10;
for($i = 0; $i < $num_of_reads; $i++) {
	$random_number = int(rand($sequence_length - $read_length + 1));
	$kmer = substr($seq, $random_number, $read_length);
	print FASTAFILE ">$random_number\n$kmer\n";
}

for($i = 0; $i < $num_of_reads; $i++) {
	$random_number = int(rand($sequence_length - $read_length + 1));
	$kmer = substr($seq_revcom, $random_number, $read_length);
	print FASTAFILE ">rc$random_number\n$kmer\n";
}
close(FASTAFILE);

$num_of_reads = $num_of_reads * 2;
print "$num_of_reads random reads are generated successfully!\n";
exit(0);
