use strict;
use Data::Dumper;

my %seqs;
my %chromsize;
open CHART,$ARGV[0] || die "$!";
     $/=">";<CHART>;$/="\n";
     while(<CHART>){
       chomp;
       my $seqhead = $_;
       my $seqname;
       if($seqhead=~/^(\S+)/) {
          $seqname = $1;
       }
       $/=">";
       my $seq=<CHART>;
       chomp($seq);
       $seq=~s/\s+//g;
       $seq=~s/\n+//g;
       $seqs{$seqname} = $seq;
       $chromsize{$seqname} = length($seq);
       $/="\n";
}
close CHART;

=pod
my %idmap;
open CHART,$ARGV[2] || die "$!";
     $/=">";<CHART>;$/="\n";
     while(<CHART>){
       chomp;
       my $seqhead = $_;
       if($seqhead=~/Arabidopsis_thaliana_TAIR10_Feb_2011_(\S+) \((\S+)\)/) {
          $idmap{$1} = $2;
       }
       $/=">";
       my $seq=<CHART>;
       $/="\n";
     }
close CHART;
=cut

open IN,$ARGV[1] || die "$!";
while(<IN>){
   chomp;
   next if(/^$/);
   my @tem = split(/\t/);
   my $minLoc;
   my $maxLoc;
   my $strand = $tem[5];
   if($strand eq "+") {
       #if($tem[1]>99){
       #    $minLoc = $tem[1]-100;
       #} else {
       #    $minLoc = 0;
       #}
       $minLoc=$tem[1]+1;
       if($tem[2]+100 > $chromsize{$tem[0]}){
           $maxLoc = $chromsize{$tem[0]};
       } else {
           $maxLoc = $tem[2]+100;
       }
   } else {
       #if($tem[2]>99){
       #    $minLoc = $tem[2]-100;
       #} else {
       #    $minLoc = 0;
       #}
       #if($tem[1]+100 > $chromsize{$tem[0]}){
       #    $maxLoc = $chromsize{$tem[0]};
       #} else {
       #    $maxLoc = $tem[1]+100;
       #}

       if($tem[1]>99){
           $minLoc = $tem[1]-100+1;
       } else {
           $minLoc = 1;
       }
       $maxLoc = $tem[2];
   }
   my $objseq .= substr($seqs{$tem[0]},$minLoc-1,$maxLoc-$minLoc+1);
   $objseq = &revdnacomp($objseq) if $strand eq "-";
   my $start = 1;
   my $end = $tem[2]-$tem[1];
   print ">".$tem[3]."|".$tem[0].":".$minLoc."-".$maxLoc.":".$strand."|".$start."-".$end."\n".$objseq."\n";
   #print ">".$idmap{$tem[3]}."|".$start."-".$end."\n".$objseq."\n";
}
close IN;


sub revdnacomp {
  my $dna = shift;
  my $revcomp = reverse($dna);
  $revcomp =~ tr/ACGTacgt/TGCAtgca/;
  return $revcomp;
}
