#!/usr/bin/perl

use strict;
use warnings;

#
# usage:
#
# bed-2-fasta.pl GENOME BED
#

if (!defined ($ARGV[1])) {
  printf (STDERR "Usage:\n    bed-2-fasta.pl GENOME BED\n");
  exit (1);
}

my $genome = $ARGV[0];
my $bed = $ARGV[1];

my $name;
my $seq = "";
my %chrs;
printf (STDERR "Reading genome...");
open (my $ifs, $genome) or die ($!);
while (my $line = <$ifs>) {
  chomp($line);
  $line =~ s/\r//;
  if (substr ($line, 0, 1) eq ">") {
    if ($seq ne "") {
      #printf (stderr "name %s\n", $name);
      $chrs{$name} = $seq;
      $seq = "";
    }
    $name = substr ($line, 1);
    my @t = split (" ", $name);
    $name = $t[0];
  } else {
    $seq .= $line;
  }
}
if ($seq ne "") {
  $chrs{$name} = $seq;
  $seq = "";
}
close ($ifs);
printf (STDERR "done\n");

my $idx = 1;
open ($ifs, $bed) or die ($!);
while (my $line = <$ifs>) {
  chomp($line);
  $line =~ s/\r//;
  my @t = split ("\t", $line);
  my $chr = $t[0];
  my $p_s = $t[1];
  my $p_e = $t[2];
  #my $name = $t[3];
  #my $p_c = $t[4];
  my $name = "lc_${chr}_${p_s}_$idx";
  if (exists ($chrs{$chr})) {
    printf (STDOUT ">%s\n", $name);
    printf (STDOUT "%s\n", substr ($chrs{$chr}, $p_s, $p_e - $p_s + 1));
  } else {
    printf (STDERR "No such chromosome: %s\n", $chr);
  }
  $idx += 1;
}
