#!/usr/bin/perl 

# converts sga format to fps format 
# usage: ./sga2fps.pl [<-s 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]

#my %opts;
#getopt('sf:', \%opts);  # -s, & -f take arg. Values in %opts, Hash keys will be the switch names

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

my $file = "";
my $species = "";
my $feature = "";
my $ft_flag = 0;
my $set0flag = 0;
#my $DB = "/home/local/db/genome/";
my $DB = "/db/genome/";

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

&Usage() if defined($opt{'help'}) || defined($opt{'h'});

#&Usage() if $#ARGV < 0;

if ($opt{'db'} ne '') {
    $DB = $opt{'db'};
}
open FH, $DB."chro_idx.nstorage" or die "Wrong Chrom Id Storable file $DB.\"chro_idx.nstorage\": $!";
my $chr2SV = retrieve($DB."chro_idx.nstorage");

if ($opt{'s'} ne '') {
    $species = $opt{'s'};
}
if ($opt{'species'} ne '') {
    $species = $opt{'species'};
}
if ($opt{'f'} ne '') {
    $feature = $opt{'f'};
    $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(/\t/,$firstline);
chomp $f[0];
chomp $f[4];
chomp $f[5];
if ($f[0] =~ /[NA][CT]_\S+\.\d+/ && 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. -s 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(/\t/,$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];
          }
        }
        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(/\t/,$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
	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
	    --db <path>              Use <path> to locate Chrom Id Storable File 'chro_idx.nstorage'
            -f <feature>             Set <feature> field
            -s|--species <species>   Assembly <species> (i.e hg18)
            --set0flag               Set 0 flag at postion 29 of the FP line, forcing unoriented output 
                                     (default : blank)

_USAGE_
    exit(1);
}

1;
