#!/usr/bin/env perl
use warnings;
use strict;

my $usage = "
	Filter for TIRvish produced gff files. Control distance between TSD and TIR.
		Usage: perl filter_gff_TIR.pl -gff TIRvish.gff [options]
			-gff	[file] The screen output (gff format) produced by TIRvish
			-maxdist	[int] max allowed coordinate distance between TIR and TSD (both left and right). Default: 1 (bp)
			-ext	[int] extend x bp to flanking regions and output coordinate to List. Default: 0 (bp)
\n";

my $gff = $ARGV[0]; #gff of TIR candidates generated by TIRvish
my $max_dist = 1; #max allowed coordinate distance between TIR and TSD (both left and right).
my $extend = 0; #extend x bp to flanking regions and output coordinate to List.

my $k=0;
foreach (@ARGV){
	$gff = $ARGV[$k+1] if /^-gff$/i and $ARGV[$k+1] !~ /^-/;
	$max_dist = $ARGV[$k+1] if /^-maxdist$/i and $ARGV[$k+1] !~ /^-/;
	$extend = $ARGV[$k+1] if /^-ext$/i and $ARGV[$k+1] !~ /^-/;
	die $usage if /^-help$|^-h$/i;
	$k++;
	}


open GFFout, ">$gff.filtered" or die $!;
open List, ">$gff.list" or die $!;

open GFF, "<$gff" or die $usage;
my ($candidate, $chr, $ltir_s, $rtir_e, $ltsd_e, $rtsd_s, $keep) = ('', '', '', '', '', '', 1);
while (<GFF>){
	chomp;
	(print GFFout "$_\n" and next) if /^#/ and !/^###/;

	if (/^###/){
		if ($keep eq 1){
			print GFFout "###\n$candidate";
			my ($ext_s, $ext_e) = ($ltir_s-$extend, $rtir_e+$extend);
			print List "$chr:$ltir_s..$rtir_e\t$chr:$ext_s..$ext_e\n";
			}
		($candidate, $chr, $ltir_s, $rtir_e, $ltsd_e, $rtsd_s, $keep) = ('', '', '', '', '', '', 1);
		next;
		}

	$candidate .= "$_\n";
	my ($type, $start, $end);
	($chr, $type, $start, $end) = (split)[0,2,3,4];
	next unless defined $type;
	($ltir_s, $rtir_e) = ($start, $end) if $type eq "terminal_inverted_repeat_element";
	if ($type eq "target_site_duplication"){
		($ltsd_e = $end and next) if $ltsd_e eq '';
		$rtsd_s = $start if $rtsd_s eq '';
		}
	if ($rtsd_s ne ''){
#print "$ltir_s - $ltsd_e > $max_dist or $rtsd_s - $rtir_e > $max_dist\n";
		$keep = 0 if $ltir_s - $ltsd_e > $max_dist or $rtsd_s - $rtir_e > $max_dist;
		}
	}

