#!/usr/bin/env perl

# converts sga format to fps format
# usage: ./sga2fps.pl [<-a species>] file.sga

use strict;
use Getopt::Long;
use Storable qw (retrieve nstore);         # package to store persistently variables in files [http://search.cpan.org/author/AMS/Storable-2.07/Storable.pm]
use File::Spec; # To avoid the "dangling /" problem - see l. 35

# getopt('asf:', \%opts);  # -a, & -f take arg. Values in %opts, Hash keys will
# be the switch names. Note: -s is the deprecated form of -a.

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

my $file     = '';
my $species  = '';
my $feature  = '';
my $ft_flag  = 0;
my $set0flag = 0;
my $DB = './';

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

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

if ($opt{'i'} ne '') {   # See gff2sga, ll. 34-44
    $DB = $opt{'i'};
}
if ($opt{'db'} ne '') {
    $DB = $opt{'db'};
}
# NOTE: the following line only works if a slash is supplied after the argument to -i/--db,
# e.g. "-i data/". This is NOT mentioned in the help.
#              ^
# open FH, $DB."chro_idx.nstorage" or die "Wrong Chrom Id Storable file $DB.\"chro_idx.nstorage\": $!";
#
# This, OTOH, will work with or without the slash, and would work on non-UNIX
# OSes, should we really insist. This introduces a dependency to File::Spec,
# however.
my $nstorage_path = File::Spec->catfile($DB, "chro_idx.nstorage");
my $chr2SV = retrieve($nstorage_path) or die "Wrong Chrom Id Storable file \"$nstorage_path\": $!";

# Last of -a, --species and -s takes precedence, if >1 supplied.
if ($opt{'s'} ne '') {
    warn "WARNING: option -s is deprecated, please use -a.\n";
    $species = $opt{'s'};
}
if ($opt{'species'} ne '') {
    $species = $opt{'species'};
}
if ($opt{'a'} ne '') {
    $species = $opt{'a'};
}
if ($opt{'f'} ne '') {
    $feature = substr($opt{'f'}, 0, 19);
    $ft_flag = 1;
}
if ($opt{'set0flag'} ne '') {
    $set0flag = 1;
}

$file = $ARGV[0];
#print "SGA file : $file\n";
#print "Options: Species $species\n";


my $char29 = " ";
my $count = 1;
# open the SGA file
my $SGA;
if ($file ne "") {
    open ($SGA, "$file") || die "can't open $file : $!";
} else {
    $SGA = "STDIN";
}

my $firstline = <$SGA>;
my @f = split(/\s+/,$firstline);
chomp $f[0];
chomp $f[4];
chomp $f[5];
if (exists($chr2SV->{$f[0]})) {
    if ($f[3] eq "0") {
        $f[3] = "+";
        if ($set0flag) {
            $char29 = "0";
        }
    }
    if (!$ft_flag) {
        if ($f[5] ne "") {
            $feature=substr($f[5], 0, 19);
        } else {
            $feature=substr($f[1], 0, 19-length($f[4])).'_'.$f[4];
        }
    }
    printf("FP   %-20s:+U%1s EU:%-18s1%1s%10s;%6d.\n", $feature, $char29, $f[0], $f[3], $f[2], $count);
    print_fps_1($SGA);
} elsif ($f[0] =~ /^chr/) {
    if ($species && exists($chr2SV->{$species}->{$f[0]})) {
        if ($f[3] eq "0") {
            $f[3] = "+";
            if ($set0flag) {
                $char29 = "0";
            }
        }
        if (!$ft_flag) {
            if ($f[5] ne "") {
                $feature=substr($f[5], 0, 19);
            } else {
                $feature=substr($f[1], 0, 19-length($f[4])).'_'.$f[4];
            }
        }
        printf("FP   %-20s:+U%1s EU:%-18s1%1s%10s;%6d.\n", $feature, $char29, $chr2SV->{$species}->{$f[0]}, $f[3], $f[2], $count);
        print_fps_2($SGA, $species);
    } else {
        print STDERR "Please, provide a valid genome assembly (e.g. -a hg18) for chrom name to RefSeq id conversion!\n";
        exit(1);
    }
} else {
    print STDERR "Unrecognized sequence version $f[0] : please, check the chromosome identifier (only valid RefSeq ids are accepted)!\n";
    exit(1);
}
close ($SGA);

sub print_fps_1 {
    my ($fh) = @_;
    while(<$fh>){
        my $lin=$_;
        $count++;
        chomp $lin;
        my @ar=split(/\s+/,$lin);
        if ($ar[3] eq "0") {
            $ar[3] = '+';
#            if ($set0flag) {
#           $char29 = '0';
#            }
        }
# truncate description to fit field length
        if (!$ft_flag) {
            if ($ar[5] ne "") {
                $feature=substr($ar[5], 0, 19);
            } else {
                $feature=substr($ar[1], 0, 19-length($ar[4])).'_'.$ar[4];
            }
        }
        if (exists($chr2SV->{$ar[0]})) {
            printf("FP   %-20s:+U%1s EU:%-18s1%1s%10s;%6d.\n", $feature, $char29, $ar[0], $ar[3], $ar[2], $count);
        }
    }
}

sub print_fps_2 {
    my ($fh, $species) = @_;
    while(<$fh>){
        my $lin=$_;
        $count++;
        chomp $lin;
        my @ar=split(/\s+/,$lin);
        if ($ar[3] eq "0") {
            $ar[3] = '+';
#            if ($set0flag) {
#           $char29 = '0';
#            }
        }
# truncate description to fit field length
        if (!$ft_flag) {
            if ($ar[5] ne "") {
                $feature=substr($ar[5], 0, 19);
            } else {
                $feature=substr($ar[1], 0, 19-length($ar[4])).'_'.$ar[4];
            }
        }
# convert chr to chromosome SV
        if ($species && exists($chr2SV->{$species}->{$ar[0]})) {
            printf("FP   %-20s:+U%1s EU:%-18s1%1s%10s;%6d.\n", $feature, $char29, $chr2SV->{$species}->{$ar[0]}, $ar[3], $ar[2], $count);
        }
    }
}

sub Usage {
    print STDERR <<"_USAGE_";

    sga2fps.pl [options] <SGA file|stdin>

        where options are:
        -h|--help                Show this stuff
        -i|--db <path>           Use <path> to locate Chrom Id Storable File 'chro_idx.nstorage'
        -f <feature>             Set <feature> field
        -a|--species <species>   Assembly <species> (i.e. hg18)
        -s|--species <species>   deprecated, use -a
        --set0flag               Set 0 flag at position 29 of the FP line, forcing unoriented output (default: blank)

_USAGE_
    exit(1);
}

1;

