#! /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 folder for ouput [./]\n  -k filename\n";
    exit;
}

my $key_id=$opts{k};   #
my $ofolder=$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;


if (!defined $key_id) {
	#my $BATCHW="sim_";
	#my ($BATCHI)= split(/\./, basename($setref));
	#$key_id=$BATCHW.$BATCHI;
	$key_id="sim";
}

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="./outread_1.fa";
my $outread2="./outread_2.fa";
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=$ofolder."/$key_id.t";
open my $tfh, ">$tfile" or die "cannot write to file $tfile\n";
print $tfh "outputfolder $ofolder/$key_id\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";
}


