
package DAFS_MakeList;

use Exporter;
@ISA = (Exporter);
@EXPORT = qw(makeList);

sub new{

    my $this = shift;
    my (
	$infile,
	$CovThreshold,
	$LenThreshold,
	$cut
	) = @_;

    my $DAFS_MakeList = {
	"in" => $infile,
        "CovThreshold" => $CovThreshold,
	"LenThreshold" => $LenThreshold,
	"cut" => $cut
    };

    bless $DAFS_MakeList, $this;
    return $DAFS_MakeList;
}

sub makeList
{
    my $this = shift;
    my $rList = shift;
    my $count=0;

    open(IN,"$this->{in}") || die "Can't open : $this->{in} $!";
    while(<IN>)
    {
	my $geneName=$_; chomp($geneName);
	my $ExonInfo=<IN>; chomp($ExonInfo);
	my $Seq=<IN>; chomp($Seq);
	my $Cov=<IN>; chomp($Cov);
	<IN>; # end postion parse

	if($this->{cut} > 0)
	{ 
	    ($Seq,$Cov) = $this->Trimming($Seq,$Cov); 
	    if($Seq eq "" || $Cov eq ""){next;}
	}
	my $LenFlag=$this->CheckExonsLength($ExonInfo);
	my $CovFlag=$this->CheckMaxCov($Cov);
	if($LenFlag == 0  || $CovFlag == 0){next;}

    	$$rList[$count][0]=$geneName;
	$$rList[$count][1]=$Seq;
	$$rList[$count][2]=$Cov;
	$$rList[$count][3]=$ExonInfo;
	$count++;
    }
}

sub Trimming
{
    my $this = shift;
    my ($Seq,$Cov) = @_;
    my @Seqs = split(//,$Seq);
    my @Covs = split(/,/,$Cov);

    @Seqs=@Seqs[($this->{cut})..($#Seqs-$this->{cut})];
    @Covs=@Covs[($this->{cut})..($#Covs-$this->{cut})];

    if($#Seqs < 0 || $#Covs < 0){return ("","");}
    else
    {
	$Seq=join("",@Seqs);
	$Cov=join(",",@Covs); $Cov.=",";
	return ($Seq,$Cov);
    }
}

sub CheckExonsLength
{
    my $this = shift;
    my $ExonInfo = $_[0];   
    my @ExonInfos = split(/;/,$ExonInfo); 

    my $ExonsLength=0;
    for(my $i=1; $i<=$#ExonInfos; $i++)
    {
	my @ExonPos = split(/,/,$ExonInfos[$i]); #$ExonPos[1]:ExonEndPos, $ExonPos[2]:ExonStartPos
	$ExonsLength+=$ExonPos[1]-$ExonPos[0]+1;
    }
    if($ExonsLength > $this->{LenThreshold} && $this->{LenThreshold} > 0){return 0;}
    else{return 1;}
}

sub CheckMaxCov
{
    my $this = shift;
    my $Cov = $_[0];
    my @Covs = split(/,/,$Cov);

    my $MaxCoverage = $this->returnMaxCoverage(\@Covs);
    if($MaxCoverage < $this->{CovThreshold}){return 0;}
    else{return 1;}
}

sub returnMaxCoverage
{
    my $this = shift;
    my $rCov = $_[0];
    my $tempMaxCov=0;
    for(my $i=0; $i<=$#{$rCov}; $i++)
    {
	if($tempMaxCov < $$rCov[$i]){$tempMaxCov = $$rCov[$i];}
    }
    return $tempMaxCov;
}

1;
