#!/usr/bin/env perl

# transform variableStep WIG files to SGA
# usage: wigVS2sga.pl -f "feature" -a species  <WIG file|sdtin>

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;

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

my $file = "";
my $species = "hg19";
my $feature = "WIG";
my $span = 1;
my $norm = 1;

my $DB = "./";
# my $DB = "/db/genome/";
#
if( ! GetOptions( \%opt, @options ) ) { &Usage(); }
&Usage()  if defined($opt{'help'}) || defined($opt{'h'});

#define options
if ($opt{'i'} ne '') {
    $DB = $opt{i};
} elsif ($opt{'db'} ne '') {
    $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;

if ($opt{'f'} ne '') {
    $feature = $opt{'f'};
}
if ($opt{'feature'} ne '') {
    $feature = $opt{'feature'};
}
# 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{'a'} ne '') {
    $species = $opt{'a'};
}
if ($opt{'species'} ne '') {
    $species = $opt{'species'};
}
if ($opt{'n'} ne '') {
    $norm = $opt{'n'};
}

$file = $ARGV[0];
my $WIG;
if ($file ne "") {
    open ($WIG, "$file") || die "can't open $file : $!";
} else {
    $WIG = "STDIN";
}

# Skip WIG header (if present)
my $firstline = "";
while (<$WIG>) {
    next if (/^track/ or /^browser/ or /^#/);
    if (/^variableStep/) {
        $firstline = $_;
        last;
    }
}
my $chro = "";
if ($firstline =~ /variableStep\s+chrom=(chr[0-9XYLG]+)\s+span=(\d+)/) {
    $chro = $1;
    $span = $2;
} elsif ($firstline =~ /variableStep chrom=(chr[0-9XYLG]+)/) {
    $chro = $1;
}
my $pos = 0;
while(<$WIG>){
    if (/variableStep\s+chrom=(chr[0-9XYLG]+)/){
        $chro=$1;
    } elsif (/^(\d+)\s+(\S+)/) {
        $pos = $1;
        my $val = $2 * $norm;
            print $chr2SV->{$species}->{$chro},"\t$feature\t$pos\t0\t$val\n";
    }
}

sub Usage {
    print STDERR <<"_USAGE_";

    wigVS2sga.pl [options] <WIG 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 <feature>   Set Feature name <feature> [def=WIG]
        -a|--species <species>   Assembly <species> [def=hg19]
        -s                       Deprecated, please use -a.
        -n <int>                 Normalization factor for data value: it needs to be converted to INTEGER [def=1]

        Convert variableStep WIG files to SGA.

_USAGE_
    exit(1);
}

1;

