#!/usr/bin/perl


use strict;
use warnings;
use lib "/home/liuqi/soft/ViennaRNA-2.2.4/interfaces/Perl/";
use RNA;
use Data::Dumper;
my %seqs;
my %loci;
open CHART,$ARGV[0] || die "$!";
     $/=">";<CHART>;$/="\n";
     while(<CHART>){
       chomp;
       my $seqhead = $_;
       my $seqname;
       my $loc;
       if($seqhead=~/^(\S+?)\|(\S+?)\|/) {
          $seqname = $1;
          $loc = $2;
       }
       $/=">";
       my $seq=<CHART>;
       chomp($seq);
       $seq=~s/\s//g;
       $seq=~s/\n//g;
       $seqs{$seqname} = uc($seq);
       $loci{$seqname} = $loc;
       $/="\n";
}
close CHART;

#chr4.trna90 (15207225-15207153) Length: 73 bp
#Type: Ala       Anticodon: AGC at 34-36 (15207192-15207190)     Score: 57.37
#HMM Sc=36.56    Sec struct Sc=20.81
#         *    |    *    |    *    |    *    |    *    |    *    |    *    |  
#Seq: GGGGATGTAGCTCAGATGGTAGAGCGCTCGCTTAGCATGCGAGAGGcACGGTGATCGATACCCCGCATCTCCA
#Str: >>>>>>>..>>>>........<<<<.>>>>>.......<<<<<.....>>>.>.......<.<<<<<<<<<<.


my %idmap;
open CHART, "orySat7-tRNAs_name_map.txt" || die "$!";
<CHART>;
while(<CHART>){
   chomp;
   my @temp = split(/\t/,$_);
   $idmap{$temp[0]} = $temp[1];
}
close CHART;


my $name;
my $startloc;
my $endloc;
my $length;
my $aa;

my $seq;
my $head;
my $priseq;
my $str;
my $stucture;
my $intronStart=0;
my $intronEnd=0;
my $codon;

open IN,$ARGV[1] || die "$!";
if($ARGV[1] =~ /^(\w+)-/){
   $head = $1;
}
#open OUT, ">$head.expand.structure.txt" || die "$!";

while(<IN>){
   chomp;
   next if(/^$/);
   if(/(\S+)\s\((\d+)-(\d+)\)\s+Length/){      
      $name = $1;
      $startloc = $2;
      $endloc = $3;
   } elsif(/Type:\s(\S+)\s+Anticodon:\s+(\S+)\s+at\s+(\d+)-(\d+)\s+\(\d+-\d+\)/){
      $aa=$1;
      $codon=$2;
   } elsif(/Possible intron: (\d+)-(\d+)/){
      $intronStart = $1;
      $intronEnd = $2;
   } elsif(/Seq: (\w+)/){
      $seq = $1;
      $priseq = $seq;
   } elsif(/Str: (\S+)/){
      $str=$1;
      $str =~ s/>/(/g;
      $str =~ s/</)/g;
      if (not exists $idmap{$name}) {
        warn $name;
        #next;
      }
	  $name = $idmap{$name};
      my $in = index($seqs{$name},uc($seq));
      warn $name if($in == -1);
      my $len = length($seq);
      my $loc = $in + $len;
      my $objseq = substr($seqs{$name},$loc);
      #my($struct,$mfe)=RNA::fold($objseq);
      my $struct = "." x length($objseq);
 
      if($intronStart != 0 and $intronEnd != 0) {
        substr($seq, $intronStart,$intronEnd-$intronStart+1) = "";
        substr($str, $intronStart,$intronEnd-$intronStart+1) = "";
        $len = $len-($intronEnd-$intronStart+1);
        $intronStart = 0;
        $intronEnd = 0;
      }
      $seq.=$objseq;
      $str.=$struct;
      print ">".$name."|1-$len\n".$seq."\n".$str."\n";
	   
   }
}
close IN;