#!/usr/bin/perl -w
use strict;
my$tline="";
my@tlist=();
my$tempi=0;
my$tempj=0;
my$tempk=0;
my$pline="";
my@plist=();
my$tid=0;
my%tidx=();
my$egDirScript="/home/xynlab/zhouff/work/script_app";
my$egDirGenomes="/db/ncbi-genomes-bacteria/Bacteria112007";
my$egDate=`date \"+%F %T\"`;
$egDate=~s/[\r\n]//g;
my@egFlag=();
my@egStart=();
my@egEnd=();
my@egLength=();
my@egTIR=();
my@egDR=();
my@egData=();
my$egNum=0;
my$tFlag=1;
my$tData="";
my$tStart=0;
my$tEnd=0;
my$tLength=0;
my$tTIR=0;
my$tDR=0;
$|=1;
@ARGV==2 or die""."Error in syntax!\n"."    ./filterRedundancy.pl <input.dat> <output.dat>\n";
my$egFileDat=$ARGV[0];
my$egFileOut=$ARGV[1];
$tempj=0;
print"Loading the data ... ";
open(efIn,"$egFileDat")or die"Error when loading the data!\n";
while(<efIn>){$tline=$_;
$tline=~s/[\r\n]//g;
$tData=$tData."$tline\n";
if($tline=~/^\/\/$/){$tFlag=1;
for($tempi=$egNum-1;$tempi>=0;$tempi--){if($egEnd[$tempi]<$tStart){last;}if(($egFlag[$tempi]==1)and($tFlag==1)and(&efIsOverlap($egStart[$tempi],$egEnd[$tempi],$tStart,$tEnd)==1)){if($egTIR[$tempi]>$tTIR){}elsif($egTIR[$tempi]<$tTIR){$egFlag[$tempi]=1;
$egStart[$tempi]=$tStart;
$egEnd[$tempi]=$tEnd;
$egLength[$tempi]=$tLength;
$egTIR[$tempi]=$tTIR;
$egDR[$tempi]=$tDR;
$egData[$tempi]=$tData;}else{if($egDR[$tempi]>$tDR){}elsif($egDR[$tempi]<$tDR){$egFlag[$tempi]=1;
$egStart[$tempi]=$tStart;
$egEnd[$tempi]=$tEnd;
$egLength[$tempi]=$tLength;
$egTIR[$tempi]=$tTIR;
$egDR[$tempi]=$tDR;
$egData[$tempi]=$tData;}else{}}$tFlag=0;
last;}}if($tFlag==1){$egFlag[$egNum]=1;
$egStart[$egNum]=$tStart;
$egEnd[$egNum]=$tEnd;
$egLength[$egNum]=$tLength;
$egTIR[$egNum]=$tTIR;
$egDR[$egNum]=$tDR;
$egData[$egNum]=$tData;
$egNum++;}$tempj++;
$tData="";
($tStart,$tEnd,$tLength,$tTIR,$tDR)=(0,0,0,0,0);}elsif($tline=~/^POSITION\t(\d+)-(\d+)$/){($tStart,$tEnd)=($1,$2);}elsif($tline=~/^LENGTH\t(\d+)$/){$tLength=$1;}elsif($tline=~/^TIR\t(\d+)$/){$tTIR=$1;}elsif($tline=~/^DR\t(\d+)$/){$tDR=$1;}}close(efIn);
print" [done] [Overall:$tempj] [RR:$egNum]\n";
print"Removing redundancy ... ";
$tempk=0;
for($tempi=0;$tempi<$egNum;$tempi++){if($egFlag[$tempi]==1){for($tempj=$tempi+1;$tempj<$egNum;$tempj++){if(($egFlag[$tempj]==1)and(&efIsOverlap($egStart[$tempi],$egEnd[$tempi],$egStart[$tempj],$egEnd[$tempj])==1)){if($egTIR[$tempi]>$egTIR[$tempj]){$egFlag[$tempj]=0;}elsif($egTIR[$tempi]<$egTIR[$tempj]){$egFlag[$tempi]=0;
last;}else{if($egDR[$tempi]>$egDR[$tempj]){$egFlag[$tempj]=0;}elsif($egDR[$tempi]<$egDR[$tempj]){$egFlag[$tempi]=0;
last;}else{$egFlag[$tempj]=0;}}}}}}open(efOut,">$egFileOut")or die"Error when saving data!\n";
for($tempi=0;$tempi<$egNum;$tempi++){if($egFlag[$tempi]==1){print efOut "$egData[$tempi]";
$tempk++;}}close(efOut);
print" [done] [Number:$tempk]\n";
$|=0;
sub efIsOverlap{my($s1,$e1,$s2,$e2)=@_;
my$t=0;
if($s1>$e1){$t=$s1;
$s1=$e1;
$e1=$t;}if($s2>$e2){$t=$s2;
$s2=$e2;
$e2=$t;}if((($s2>=$s1)and($s2<=$e1))or(($s1>=$s2)and($s1<=$e2))){return 1;}else{return 0;}}
