#!/usr/bin/perl -I/nwprod/lib/incmod/perl

# $Id: sub_global.pl,v 1.4 2004/06/02 23:18:41 smo Exp $

#------------------------------------------------------------------------------
# Filename:  sub_global.pl
#
# Purpose:  This script contains global utility subroutines for bluesky.
#
# Subroutines:
#    array_stat
#    convert_date_to_seconds
#    convert_datehr_to_seconds
#    create_working_dir
#    debug
#    default_fill
#    make_date_string
#    print_cwd
#    run_command
#    ToDo
#    zero_zulu
#    get_timezone
#    convert_datetime_to_seconds
#
# By:  sim, smo
#
#  USDA Forest Service - Pacific Northwest Wildland Fire Labratory
#  Copyright (C) 2003-2004
#------------------------------------------------------------------------------

use Time::Local;

$cwd = `pwd`;
# $cwd = system(pwd);
print ("luke- in smoke_sub_global.pl the cwd is $cwd \n");

sub array_stat
{
    my ($max, $min, $sum);
    $sum = 0;
    $count = 0;
    foreach $value (@_)
    {
	$max = $value unless $value < $max;
	$min = $value unless $value > $min;
	$sum += $value;
        $count++;
    }
    $avg = $sum/$count;
    return ($sum, $min, $max, $avg);
};


sub convert_date_to_seconds
{
    # assumes string of YYYYMMDD
    # uses gmt time
    # gets seconds at midnight (zero zulu)
    my $date_str = shift;
    my $year = substr($date_str, 0, 4) - 1900;
    my $month = substr($date_str, 4, 2) - 1;
    my $day = substr($date_str, 6, 2);
    return timegm(0,0,0,$day,$month,$year);
};


sub convert_datehr_to_seconds
{
    # assumes string of YYYYMMDDHH
    # uses gmt time
    # gets seconds at midnight (zero zulu)
    my $date_str = shift;
    my $year = substr($date_str, 0, 4) - 1900;
    my $month = substr($date_str, 4, 2) - 1;
    my $day = substr($date_str, 6, 2);
    my $hr = substr($date_str, 8, 2);
    return timegm(0,0,$hr,$day,$month,$year);
};


sub create_working_dir
{
    # local variables
    my ($field1, $one, $user, $group, $size, $month, $day, $time_or_year, $filename);
 
    # Get a recursive list of everything under $FRAMEWORK_DIR, excluding:
    #    - src and CVS directories and their contents (this is the main reason this sub was created)
    #    - the total byte count for each directory
    #    - the directory names from the list of parent directory contents (only want filenames)
    # The list of directories to create and files to copy are then in lsr.out.
 
#            run_command ( "cp -rp $FRAMEWORK_DIR/$filename $WORKING_DIR",
#                          "cp -rp $FRAMEWORK_DIR/$filename $WORKING_DIR" );
             run_command ( "cp $USHsmoke/$filename $WORKING_DIR",
                           "cp $USHsmoke/$filename $WORKING_DIR" );

};


sub debug
{
    my $level = shift(@_);
    my $message = shift(@_);
    if ($DEBUG_MAX_LEVEL >= $level) {
	if ($level >= 0) {
	    print ("DEBUG $level: ");
	}
	print ("$message\n");
    }
};

sub default_fill
{
    my ($ref_var_hash, $ref_default_hash) = (shift,shift);
#   debug(100, "ref_var_hash, ref_default_hash are $ref_var_hash, $ref_default_hash");
    my $key;
    foreach $key (keys %{$ref_default_hash}) {
	if ($$ref_var_hash{$key} eq "") {
	    debug(100, "key is $key, filling with $$ref_default_hash{$key}");
	    $$ref_var_hash{$key} = $$ref_default_hash{$key};
	}
    }
}

sub make_date_string
{
    my $seconds = shift;
    my $format = shift;
    my $time_zone = shift;
    # recognized time zones are "gmt", "zulu" and "local"

    my @date;
    if ($time_zone eq "gmt" || $time_zone eq "zulu") {
	@date = gmtime($seconds);
    } elsif ($time_zone eq "local") {
	@date = localtime($seconds);
    } else {
	die ("make_date_string called inappropriately with time_zone = $time_zone");
    }

    return sprintf($format, $date[5]+1900, $date[4]+1, $date[3], $date[2], $date[1], $date[0]);
};


sub print_cwd
{
    my $level;
    if ($#_ < 0) {
	$level = -999;
    } else {
	$level = shift(@_);
    }
    use Cwd;
    my $current_dir = cwd;
    debug($level, "current directory is $current_dir");
};

sub run_command
{
    my $text = shift(@_);
    my $command = shift(@_);
    my $cwd = cwd;
    system($command) == 0 
	    or die("FATAL ERROR: $! $text\nfailed on command: $command\ncwd is $cwd\n");
};

sub ToDo
{
    my $message = shift;
    print("WARNING! : TODO ITEM : $message\n");
};


sub zero_zulu
{
    # strip off any hours to get back to zero zulu on this date
    my $starting_time = shift;
    my @gmt = gmtime($starting_time);
    return timegm(0,0,0,@gmt[3],@gmt[4],@gmt[5]);
};


sub get_timezone
{
    # smo 8/2/2002 - TODO - add more smarts here (ideally, want to be able to discern timezone from lat/lon)
    #              - currently TIMEZONE is a variable in params
    # smo 3/18/2003 - add logic to do timezone based on state

    my $state = shift;
    my $tz = "";

    my %tz_hash = qw( WA 8
                      OR 8
                      CA 8
                      NV 8
                      CN 8
                      AZ 7
                      NM 7
                      CO 7
                      WY 7
                      UT 7
                      MT 7
                      ID 7 );

    my %tz_hash_fullname =   ( 'Washington', '8',
                               'Oregon', '8',
                               'California', '8',
                               'Nevada', '8',
                               'Canada', '8',
                               'Arizona', '7',
                               'New Mexico','7',
                               'Colorado', '7',
                               'Wyoming', '7',
                               'Utah', '7',
                               'Montana', '7',
                               'Idaho', '7' );

    $tz1 = $tz_hash{$state};
    $tz2 = $tz_hash_fullname{$state};
    $tz = $tz1;
    if ( $tz eq "" ) { $tz = $tz2; }

    if ( $tz eq "" ) {
        debug(5, "Possible ERROR:  timezone undefined for state = $state");
    }

    return $tz;
};


sub convert_datetime_to_seconds
{
    # assumes string of YYYYMMDD for first arg
    # assumes string of HHMM for second arg
    # uses gmt time
    # gets seconds at midnight (zero zulu)
    my $date_str = shift;
    my $time_str = shift;
    my $year = substr($date_str, 0, 4) - 1900;
    my $month = substr($date_str, 4, 2) - 1;
    my $day = substr($date_str, 6, 2);
    my $hr = substr($time_str, 0, 2);
    my $min = substr($time_str, 2, 2);
    return timegm(0,$min,$hr,$day,$month,$year);
};


sub replace_str
{        
    ($text, $to_replace, $replace_with) = @_;
             
    substr ($text, index($text, $to_replace), length($to_replace), $replace_with);
             
    return $text;          
};

return 1;
