#!/usr/bin/env perl

# converts chrom names into RefSeq ids within SGA
# usage: ./chr_replace_sga.pl <-a species> <file.sga>

use strict;
use Getopt::Long;
my %opt;
my @options = ("help", "h", "assembly=s", "a=s", "s=s", "db=s", "i=s", "d=s");
if( ! GetOptions( \%opt, @options ) ) { &usage(); }

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;

# -a, -i & -f take arg. 
# Option -d is the deprecated form of -i, and -s is the deprecated form of -a.

usage() if (exists $opt{'help'}) || (exists $opt{'h'});

# Get assembly
if (exists $opt{'s'}) {
    warn "WARNING: option -s is deprecated. Please use option -a instead.\n";
    $opt{'a'} = $opt{'s'};
}

my $DB;
$opt{'i'} = $opt{'db'} if exists $opt{'db'};
if (exists $opt{'i'}) {
  $DB = $opt{'i'};
} else {
    if (exists $opt{'d'}) {
        warn "Option -d is deprecated - please use option -i.";
        $DB = $opt{'d'};
    } else {
        $DB = './';
    }
}

my $nstorage_path = File::Spec->catfile($DB, "chro_idx.nstorage");
if (! (-e $nstorage_path && -r $nstorage_path) ) {
    print STDERR "Could not open $nstorage_path: file not found or not readable. Please see option -i.\n";
    usage();
}
my $chr2SV = retrieve($nstorage_path);

while(<>) {
    chomp;
    if (/(\S+)\t(.*)/) {
        print "$chr2SV->{$opt{'a'}}->{$1}\t$2\n";
    }
}

sub usage {
    print STDERR <<"_USAGE_";

Usage: chr_replace_sga.pl [-i|--db <dir>] -a <species> <SGA file>

        Options
        -------

        --db <dir>  directory where chro_idx.nstorage is to be found.
        -i <dir>    short form of --db.

_USAGE_
    exit(1);
}

1;

