#!/usr/bin/perl

use strict;
use Bio::Index::Fasta;
use Getopt::Long;
use Benchmark;


my $t0 = new Benchmark;
print "starting at " . localtime() . "\n\n";

my $program=$0;
$program=~s/.*\///;
use vars qw( %options);

#
# - validate_options verifes all command-line options are valid, and
#   creates needed ones if they were not given.
# - print_usage informs the user how to run the script
# - die_wrong_parameters tells user how to get usage info
#
use subs qw(
            validate_options
            print_usage
            die_wrong_parameters
            );

#
# Hash with all the error messages for each option
#
my %option_error_message =
    (
     "db"      => "No database File defined",
	 "idx"     => "No index file location defined",
	 );


#
# Print usage and exit if no command line parameters
#
unless ($#ARGV >= 0) {
    print_usage;
    exit (1);
}

#
# Gather up the command line parameters
# if additional options are added, update vars statement above
#
&GetOptions(\%options,
            "db=s",   #input file is a type of string
            "idx=s",
			);


############ The code starts here ######################

#indexing fasta file
my $type = $ENV{'BIOPER_INDEX_TYPE'};
if( $type ) {
   $Bio::Index::Abstract::USE_DBM_TYPE = $type;
 }
my $indexFile = Bio::Index::Fasta->new($options{"idx"}, 'WRITE');
$indexFile->make_index($options{"db"});

my $t1 = new Benchmark;
print "\nEnding at " . localtime() . "\n";

my $td = timediff($t1, $t0);
print "\nThe code took:",timestr($td),"\n";


################ And finish here ####################




# validate_options:
# verifies that parameters are valid
#
sub validate_options {

    die_wrong_parameters($option_error_message{'db'}, $option_error_message{'idx'})
        unless ($options{'db'} && $options{'idx'});
}

#
# die_wrong_parameters
#
sub die_wrong_parameters {
    print "\n@_\n";
    die "For usage information, run this script without any parameters.\n";
}

#
# validate the parameters, and set empty ones to defaults
#
&validate_options();

#
#  DO NOT EMACS INDENT BEYOND HERE
#  DOING SO WILL BREAK THE CODE DUE TO HERE STATEMENTS IN print_usage
#
# print_usage
#
sub print_usage {
    print <<"END_OF_USAGE"

     Wrong number of parameters passed, please check again.

           Usage:
 
		         $program -db=database_File  -idx=index_File 

           where:
                
                 <db>   (required) = the database file (in Fasta format) to be indexed for faster access
                                       i.e : my_fasta_file.fasta

                 <idx>  (required) = the file name that you want to give to the index file 
                                       i.e : my_index_file.idx

          Example:

                $program -db=my_fasta_file.fasta -idx=my_index_file.idx


END_OF_USAGE
}
