#!/usr/bin/perl -w
use strict;

my $family = $ARGV[0] or die $!;
my $namefile = $family.".blastout.names";
my $clusterfile = $family.".blastout.cluster";
my $alnfile = $family.".blastout.stk";
my $fastafile = $family.".blastout.fa";
my $blastfile = $family.".blastout";

open(N,$namefile);

open(C,">",$clusterfile);
my $line;
while($line = <N>)
{

    chomp($line);

    if($line eq "")
    {
	next;
    }
    # Name einlesen
    my $outline="";
    my $mirna = `echo '$line'| gawk '{print \$2;}'`;
    chomp($mirna);
    my $myname=  `echo '$line'| gawk '{print \$1;}'`;
    chomp($myname);
    # Laenge besorgen
    
    my $temptext = `cat $alnfile | grep '$myname' | gawk '{print \$2;}'`;
    chomp($temptext);
    $temptext =~ s/\.//g;
    
    my $length= length($temptext);


    # Chromosom besorgen
    my $chromo = `cat $fastafile | grep '$myname' | gawk '{print \$2;}'`;
    chomp($chromo);
   

    # Start und Ende besorgen
    $temptext =  `cat $fastafile | grep '$myname' | gawk '{print \$1;}'`;
    chomp($temptext);
    
    my @values = split(/\|/,$temptext); 
    my $sizeV = @values;
    my $start = (split(/-/,$values[($sizeV-1)]))[0];
    my $end = (split(/-/,$values[($sizeV-1)]))[1];
    

    # Strang berechnen
    my $strand = "+";
    my $creg=$chromo;
    $creg =~ s/\|/\\\|/g;
    my $command =  "cat $blastfile | gawk '/".$creg."/ {print \$9; print \$10;}'";
    print "Command für Ausschnitt-Suche:".$command."\n";
    
    $temptext =  `$command`;
    
    # print $temptext."\n";
    @values = split(/\n/,$temptext);
    
    my $counter = 0;
    while($counter <= (@values -1))
    {
	
	chomp($values[$counter]);
	chomp($values[$counter+1]);
	
	my $startO=$values[$counter];
	my $endO =$values[$counter +1];
	
	if($startO eq "")
	{
	    $counter +=2;
	    next;
	}
	if($startO > $start && $endO < $end)
	{
	    if($endO < $startO)
	    {
		$strand="-";
	    }
	    print "Used: start:$startO end: $endO\n";
	    last;
	    
	}

	$counter +=2;
    }
   
    
    #if($temptext eq $end)
    #{
#	$strand = "-";
#    }
    $outline = $mirna."\t".$length."\t".$chromo."\t".$start."\t".$end."\t".$strand."\t".$chromo."\n";
    print C $outline;


}
