#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;

# This code is part of the MOCAT analysis pipeline
# Code is (c) Copyright EMBL and BGI, 2012-2013
# This code is released under GNU GPL v3.

my $prev_insert = "";
my $prev_read   = "";
my $INSERTS     = 0;
my $BASES       = 0;
my $READS       = 0;
my $MAX         = 0;
my $insert;
my $format;
my $identity;
my $length;
my $screened;
my $extracted;
my $stats;
my $prev_length;
my $read;

GetOptions(
	'format:s'    => \$format,
	'identity:s'  => \$identity,
	'length:s'    => \$length,
	'screened:s'  => \$screened,
	'extracted:s' => \$extracted,
	'stats:s'     => \$stats
);

while (<STDIN>) {
	chomp( my $line = $_ );
	my @line = split "\t", $_;
	my $length;

	if ( $format eq 'SAM' ) {
		$line[0] =~ m/(.+)\/([12])$/;
		$read       = $line[0];
		$insert     = $1;
		# $direction  = $2;
		# $ref_id     = $line[2];
		# $first_base = $line[3];
		$length     = length $line[9];
		# $last_base  = $first_base + $length - 1;
	}
	elsif ( $format eq 'SOAP' ) {
		$line[0] =~ m/(.+)\/([12])$/;
		$read       = $line[0];
		$insert     = $1;
        # $direction  = $2;
		# $ref_id     = $line[7];
		# $first_base = $line[8];
		$length     = $line[5];
		# $last_base  = $first_base + $length - 1;
	}

	if ( $insert ne $prev_insert && $prev_insert ne '' ) {
		$INSERTS++;
	}
	if ( $read ne $prev_read && $prev_read ne '' ) {
		$READS++;
		$BASES += $prev_length;
	}
	if ( $length > $MAX ) {
		$MAX = $length;
	}
	$prev_read   = $read;
	$prev_insert = $insert;
	$prev_length = $length;
	print STDOUT "$line\n";
}
$INSERTS++;
$READS++;
$BASES += $prev_length;


open IN, "<$stats" or die "ERROR & EXIT: Cannot open file $stats (error was $!)";
chomp( my $S1 = <IN> );
chomp( my $S2 = <IN> );
close IN;
my @S2 = split "\t", $S2;
if (!$S2[6]) {
  $S2[6] = '';
  $S2[7] = '';
  $S2[8] = '';
}

my $ostats = $stats;
$ostats =~ s/.stats$//;
$ostats = "$ostats.filtered.l$length.p$identity.stats";
open STATS, ">$ostats" or die("Could not open output stats file ($ostats): $!");
print STATS "Reads\tBases\tMax\tAvg\tKmer\tInserts\tMin % identity\tMin length\tSOAP max mismatches\n";
print STATS "$READS\t$BASES\t$MAX\t" . $BASES / $READS . "\t$S2[4]\t$INSERTS\t$S2[6]\t$S2[7]\t$S2[8]\n";
close STATS;

exit 0;
