#!/usr/bin/perl

use strict;use warnings;
use List::MoreUtils qw(any); #import of any-function

use feature qw(say);
use Data::Dumper;
use Benchmark;

############################################
#SUBs

sub file_create {
    my$name = $_[0].".pattern";
    if (-f $name) {}#print "File ".$_[0]." already existing! No Action!\n"}
    else {
	open my $fh, '>>', $name;
	print $fh "#mir\tpxy\tbmo\tmse\tmci\thme\tdpl3\ttca\tdpo\tnvi\tame\taga\tdme\trpr\tapi\tpattern\tother_names\n";
    }
}

sub file_write {
    my$name = $_[0].".pattern";
    my$text = $_[1];
    if (-f $name) {
	open my $fh, '>>', $name;
	print $fh $text;
    }
}

###############################################
#MAIN

my$start = new Benchmark;

open (FILE, 'mir_orthodata');
my $j=0;
my $temp;
my $temp2;
my $temp3;
my @A;
my @B;
my $sub;

while (<FILE>) {
    chomp;
# Species	Genes	Alg.-Conn.	tca	bmo	dme	ame	pxy	api	mci	mse	(lmi)	dpo	hme	rpr	nvi	aga	dpl3	(dpl)
(my $spec,my $genes,my $conn,$A[$j][6],$A[$j][1],$A[$j][11],$A[$j][9],$A[$j][0], $A[$j][13],$A[$j][3],$A[$j][2],my $lmi,$A[$j][7],$A[$j][4],$A[$j][12], $A[$j][8], $A[$j][10],$A[$j][5],my $dpl1) = split("\t");
#Erzeugen der Pattern, Speichern in $A[][16], mir-string in $A[][17],  mir-xxx in $A[][20], output-str in $A[][21]
$A[$j][16]=""; #pattern
$A[$j][17]=""; #mir-string

$A[$j][20]=""; #mir-xxx
$A[$j][21]=""; #output-str
#aka
$A[$j][22]=""; #aka

#Durchlauf der Species
for (my $n=0;$n<=13;$n++) {
	#Anfuegen an mir-string
	$A[$j][17] .= $A[$j][$n]."\t";


	#Pattern auslesen
	if ($A[$j][$n] eq "*") {$A[$j][16].="0";}
	else {$A[$j][16].="1";


#Eintraege nach Komma separieren, in Arr(@mir) stecken, den nach anderen mir-Unterarten durchsuchen, Ausgabe in aka-Spalte ([22])
		my @mir = split(',',$A[$j][$n]);
		#falls mir-xxx_1 -> entfernen des underscore
		if ($A[$j][20] eq "") {
			my@T;
			if (index($mir[0],"dpl3") != -1) {@T = split('_',substr $mir[0],5)}
			else {@T = split('_',substr $mir[0],4)}
			$A[$j][20] = $T[0];
		}
		
		foreach my $z (@mir) {
			my@T;
			if (index($z,"dpl3") != -1) {@T = split('_',substr $z,5)}
			else {@T = split('_',(substr $z,4))}
			if ($A[$j][20] ne $T[0] && index($A[$j][22],$T[0]) == -1) {
				$A[$j][22].=$T[0]."\t"}
		}
	}
}


if ($A[$j][20] eq "") {$A[$j][20] = "N/A"}
#Erzeugen des Ausgabestring
$A[$j][21].=$A[$j][20]."\t".$A[$j][17]."".$A[$j][16]."\t".$A[$j][22]."\n";


#Ausgabestring >> .pattern
my $filename = $A[$j][16];

file_create($filename); 
file_write($filename, $A[$j][21]);

$j++;
}


#each file: generate entry for other_names if not already in list

my@FILES = glob("*.pattern");
foreach my $file (@FILES) {
    my @Data;my @Index;

    open (PATTERN, "<", $file);
#discard first line (header)
    <PATTERN>; 
    my @all = <PATTERN>;

foreach my$line (@all) {
    chomp $line;
    my @Fields = split(/\t/, $line);
    push (@Index, $Fields[0]);
    
    #print @Index;
    }


foreach my$line (@all) {
    chomp $line;
    my @Fields = split(/\t/, $line);

    if (scalar(@Fields) > 16) {
    for(my$z=16;$z<scalar(@Fields);$z++) {
	if (any { $Fields[$z] eq $_ } @Index) {}
	else { open (OUTFILE, ">>$file");
	       my$outstring = $Fields[$z]."\t";
	       for (my$k=1;$k<=15;$k++) {
		   $outstring .= $Fields[$k]."\t";
	       }
	       $outstring .= "\n";
	       print OUTFILE $outstring;
	       close (OUTFILE);
	}
	
    }
}

    close (PATTERN);}

}

#create index.pattern
#system(q(for i in *.pattern; do grep -v '#' \$i | awk '{print"\$1\t\$10\t\$11\n"}' ; done | sort > index.pattern));

system(`touch index`);
open (INDEX, ">", "index");
foreach my $file (@FILES) {
     open (PATTERN, "<", $file);
#discard first line (header)
    <PATTERN>; 
    my @all = <PATTERN>;

foreach my$line (@all) {
    chomp $line;
    my @Fields = split(/\t/, $line);
    my$out = $Fields[0]."\t".$Fields[15]."\n";
    print INDEX $out;
}
}
close (INDEX);
system(`sort index > index.pattern`);
system(`rm -r index`);
=cut


my$end =  new Benchmark;
my$diff = timediff($end, $start);

# report
print "Time taken was ", timestr($diff, 'all'), " seconds\n"; 

