#!/usr/local/bin/perl 

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

use strict;

&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 $chr2SV = retrieve("/db/genome/chro_idx.nstorage");

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>

_USAGE_
    exit(1);
}

1;
