#! /usr/bin/perl

use POSIX;
use strict;
use File::Basename;
use Getopt::Std;

my %opts=( k=>undef, s=>undef, r=>undef, l=>100, f=>".", u=>undef, q=>undef, i=>400, c=>25);
getopts('l:k:r:g:f:n:sc:i:',\%opts);

if (@ARGV <1)  {
    print "usage: sim_imrdenom.pl [-k -c -l -f] <ref>", "\n";
    print " -c coverage [25]\n  -l read length [100]\n  -f ouput prefix [./]\n ";
    exit;
}

my $oprefix =$opts{f};  # set the upper folder. final folder will be $ofolder/$key_id
my $readlen=$opts{l};
my $cov=$opts{c};
my $issingle=$opts{s};
my $isize=$opts{i};

my $setref=$ARGV[0];

if ( ! $setref ) {
	print "please set the reference file\n";
}

my @paired;
my @single;
my @paired_uneq;

my $pz=`which wgsim`;
if ( $pz eq '') {
   die 'wgsim (from SAMTOOLS) is not installed! Please install it into your system directory';
}

if ( ! -e "$setref.fai" ) {
	die "Please index the reference first\n"
}

open my $fh, "<$setref.fai" or die "cannot open the reference index file, please index the reference first\n";
my $chrlen;
while (<$fh>)  {
   	my $gp=$_;
	my @s=split;
	$chrlen += $s[1];
}
#print STDERR "reference genome size is $chrlen\n";

my $nread= ceil($chrlen* $cov / 2 / $readlen);

my $outread1=$oprefix."_1.fq";
my $outread2=$oprefix."_2.fq";
if (defined $issingle) {
    $nread = $nread*2;
    $outread2="/dev/null";
}

my $cmd="wgsim -d $isize -N $nread -1 $readlen -2 $readlen -r 0 -R 0 -e 0 -h $setref $outread1 $outread2";
print $cmd, "\n";
system($cmd);


my $tfile=$oprefix.".t";
open my $tfh, ">$tfile" or die "cannot write to file $tfile\n";
print $tfh "outputfolder $oprefix\n";
print $tfh "reference $setref\n";
print $tfh "iterations 1\nthreads 4\nmaxreads 2000000\n";
if (defined $issingle) {
    print $tfh "loaddata $outread1\n";
} else {
    print $tfh "loaddata $outread1 $outread2\n";
}


