#!/usr/bin/env perl

use strict;
use Storable qw (retrieve nstore); # package to store persistently variables in files [http://search.cpan.org/author/AMS/Storable-2.07/Storable.pm]

Usage()  unless (@ARGV == 3);

my $chr_NC_gi         = $ARGV[0];
my $chr_size          = $ARGV[1];
my $chro_idx_nstorage = $ARGV[2];

my $chr2SV;
my $assembly;

open(FH, "<$chr_NC_gi")  or die "Couldn't open file $chr_NC_gi: $!";
while(<FH>) {
    if ( /^#(\S+)/ ){
        $assembly = $1;
    }
    elsif( /^(\S+)\s+(\S+)/ ){
        my $chr = $1;
        my $ac  = $2;
        $chr2SV->{$ac}                    = "chr$chr";
        $chr2SV->{$assembly}->{"chr$chr"} = $ac;
        $chr2SV->{$assembly}->{"$chr"}    = $ac;
        $chr2SV->{$assembly}->{$ac}       = $ac;
        $chr2SV->{'assembly'}->{$ac}      = $assembly;
    }
}

open(FH, "<$chr_size")  or die "Couldn't open file $chr_size: $!";
while(<FH>) {
    if( /^(\S+)\s+(\S+)/ ){
        my $ac     = $1;
        my $length = $2;
        $chr2SV->{'length'}->{$ac} = $length;
    }
}

nstore ($chr2SV, "$chro_idx_nstorage");
exit 0;

sub Usage {
    print {*STDERR} "
        Usage:

        make_chro_idx.nstorage.pl <chr_NC_gi> <chr_size> <chro_idx.nstorage>

        Combines text files <chr_NC_gi> and <chr_size> in a single binary file named chro_idx.nstorage.
        chr_NC_gi maps sequence identifiers to chromosome names whereas chr_size informs programs
        about the size of the chromosomes. C programs of the ChIP-Seq tools use the text files
        chr_NC_gi and chr_size whereas Perl scripts the binary file chro_idx.nstorage. Note that the
        filenames are hard-coded in the programs, which read these file. However, this script takes the
        names of these files from the command line. The filenames are thus free.
        \n";

    exit(1);
}

