#!/usr/bin/env perl
#=======================================================================
# name - token_resolve
# purpose - wrapper for token_resolve() in Manipulate_time.pm package
#=======================================================================
use strict;
use warnings;
my @SEARCH_PATH;

# pre-process to define $SEARCH_PATH
#-----------------------------------
BEGIN {
    use File::Basename;
    use FindBin;
    my ($GEOSDAS_PATH, $BIN_DIR, $PROGRAM_PATH);

    $GEOSDAS_PATH = dirname( $FindBin::Bin );
    $BIN_DIR = "$GEOSDAS_PATH/bin";
    $PROGRAM_PATH = $FindBin::Bin;

    if ($PROGRAM_PATH ne $BIN_DIR) { @SEARCH_PATH = ($PROGRAM_PATH, $BIN_DIR) }
    else                           { @SEARCH_PATH = ($BIN_DIR) }
}

# global variables
#----------------- 
my ($pattern, $yyyymmdd, $hhmmss);

# main program
#-------------
{
    use lib @SEARCH_PATH;
    use Manipulate_time "token_resolve";
    my $filename;

    init();
    $filename = token_resolve($pattern, $yyyymmdd, $hhmmss);

    print "$filename\n";
    exit 1;
}

#=======================================================================
# name - init
# purpose - initialize
#=======================================================================
sub init {
   use FindBin;
   use File::Basename "dirname";

   usage() unless @ARGV;
   usage() if $ARGV[0] eq "help";

   $pattern  = shift @ARGV;
   $yyyymmdd = shift @ARGV;
   $hhmmss   = shift @ARGV;
}

#=======================================================================
# name - usage
# purpose - print usage information
#=======================================================================
sub usage {
    use File::Basename;
    my $script = basename $0;

    print STDERR <<"EOF";

  Usage: $script token_pattern [yyyymmdd hhmmss]

  Description:
  $script takes a tokenized filename, and optionally an eight-digit date
  and a six-digit time and replaces the tokens with the correct values.

  Notes:
  1. If no date and time are supplied, the replacement is done with Unix wildcards.
  2. If only a time is needed you must supply a zero for the date as a placeholder.
 
  Examples:
  $script efake.prog.t%y4%m2%d2.%h2Z 20100228 120000
  $script efake.prog.t19990415.%h2z 0 210000

  Legal tokens are based on the GrADS tokens:
      %y2   2 digit year
      %y4   4 digit year
      %m2   2 digit month (leading zero if needed)
      %mc   3 character month abbreviation (jan, feb etc.)
      %d2   2 digit day (leading zero if needed)
      %j3   3 digit Julian day of year (001-366)
      %h2   2 digit hour
      %n2   2 digit minute (leading zero if needed)
      %s2   2 digit second
      %s    any string - returns "*"
      %c    any single character - returns "?"
      %n    any single digit - returns "[0-9]"
 

EOF
exit 1;
}
