#!/usr/bin/env perl

# converts sga format from partitioning to gff format
# usage: ./partit2gff file.sga

use strict;
use Getopt::Long;
use File::Spec;

my %opt;
my @options = ("help", "h", "db=s", "i=s");

if( ! GetOptions( \%opt, @options ) ) { &Usage(); }

&Usage()  if defined($opt{'help'}) || defined($opt{'h'});
&Usage() if $#ARGV < 0;

use Storable qw (retrieve nstore);         # package to store persistently variables in files [http://search.cpan.org/author/AMS/Storable-2.07/Storable.pm]

# hash defining chromosome from SV of chromosomes in current genome assemblies
my $DB = './';
if (exists $opt{'i'}) {
  $DB = $opt{'i'};
} elsif (exists $opt{'db'}) {
  $DB = $opt{'db'};
}

my $nstorage_path = File::Spec->catfile($DB, "chro_idx.nstorage");
open FH, $nstorage_path or die "Wrong Chrom Id Storable file \"$nstorage_path\": $!";
my $chr2SV = retrieve($nstorage_path);
close FH;

my @pos = ();
my $count = 0;
print "##gff-version   3\n";
while(<>){
#print $chr2AC{$chro},"\t$exp\t$pos\t+\t",$score_ref->{$chr2AC{$chro}}->{'+'}->{$pos},"\n";
# Partitioning algorithm reports positions of start and end of tag,
#NC_000001.9    CTCF    227595  +       1  Start Line
#NC_000001.9    CTCF    227633  -       1  End Line

    my $lin=$_;
    chomp $lin;
    my @ar=split(/\t/,$lin);
# eventually escape offending characters?

    if ($ar[3] eq '+') {
        $pos[0] = $ar[2];
    } elsif ($ar[3] eq '-') {
        $pos[1] = $ar[2];
        $count++;
        if (exists($chr2SV->{$ar[0]})){
# ChrX  . gene XXXX YYYY  .  +  . ID=gene01;name=resA
            print $chr2SV->{$ar[0]},"\tChIPSeq\t$ar[1]\t$pos[0]\t$pos[1]\t$ar[4]\t+\t.\t$count\n";
        }
        else {
            print $ar[0],"\tChIPSeq\t$ar[1]\t$pos[0]\t$pos[1]\t$ar[4]\t+\t.\t$count\n";
#print STDERR "Sequence version $ar[0] not in current genome assembly!\n";
        }
        @pos = ();
    }
}

sub Usage {
    print STDERR <<"_USAGE_";

    partit2gff.pl <SGA file>

    Options:

      -h | --help   show this help
      -i | --db <dir> which dir to look for chro_idx.nstorage in

_USAGE_
    exit(1);
}

1;

