#!/usr/bin/perl

# This variable will be most of the command we execute
$stub = "wrf2vdf";

# This is a switch to say how much output to make
$quietScript = 0;

# This variable holds the entire help screen
$helpScreen = "
Usage: wrf2vdfbatch [options] metafile wrfFiles
wrfFiles may be a single WRF netCDF output file, a list of such files, or a
    file name containing wildcards.
Options are:
    -varnames arg    Colon delimited list of variable names in metadata to
                         convert
    -atypvars arg    Colon delimited list of atypical names for variables
                         U:V:W:PH:PHB:P:PB:T that appear in WRF file(s)
    -dervars  arg    Colon delimited list of derived variables to convert.
                         Choices are:
                         phnorm: normalized geopotential (PH+PHB)/PHB
                         wind3d: 3D wind speed (U^2+V^2+W^2)^1/2
                         wind2d: 2D wind speed (U^2+V^2)^1/2
                         pfull: full pressure P+PB
                         pnorm: normalized pressure (P+PB)/PB
                         theta: potential temperature T+300
                         tk: temperature in Kelvin 0.037(T+300)(P+PB)^0.29
    -tsincr   arg    Increment between Vapor time steps to convert (e.g.,
                         3=every third), from Vapor time step 0
    -tsstart  arg    Starting time stamp for conversion, in format
                         yyyy-mm-dd_hh:mm:ss
    -tsend    arg    Last time stamp to convert, in format
                         yyyy-mm-dd_hh:mm:ss
    -level    arg    Refinement levels saved.  0=coarsest, 1=next refinement,
                         etc.  -1=finest (full resolution).
    -quiet           Only output suggested vertical extents at end of
                         conversion
    -help            Print this help screen and exit

";

if ( $#ARGV == -1 ) # Print help and exit if no arguments are given
{
	print( "$helpScreen" );
	exit 0;
}

# Parse command line arguments
$i = 0;
for ( ; $i <= $#ARGV ; $i++ )
{
	if ( $ARGV[$i] eq "-varnames" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ )
		{
			print( "wrf2vdfbatch: -varnames option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -varnames $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-atypvars" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ )
		{
			print( "wrf2vdfbatch: -atypvars option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -atypvars $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-dervars" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ )
		{
			print( "wrf2vdfbatch: -dervars option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -dervars $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-tsincr" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ )
		{
			print( "wrf2vdfbatch: -tsincr option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -tsincr $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-tsstart" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ )
		{
			print( "wrf2vdfbatch: -tsstart option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -tsstart $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-tsend" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ )
		{
			print( "wrf2vdfbatch: -tsend option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -tsend $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-level" )
	{
		$i++;
		if ( $ARGV[$i] =~ /^-/ && $ARGV[$i] ne "-1" )
		{
			print( "wrf2vdfbatch: -level option requires argument\n" );
			exit 1;
		}
		$stub = $stub . " -level $ARGV[$i]";
		next;
	}
	if ( $ARGV[$i] eq "-quiet" )
	{
		$quietScript = 1;
		$stub = $stub . " -quiet";
		next;
	}
	if ( $ARGV[$i] eq "-help" || $ARGV[$i] eq "-h" || $ARGV[$i] eq "--h"
		 || $ARGV[$i] eq "--help" )
	{
		print( "$helpScreen" );
		exit 0;
	}
	if ( $ARGV[$i] =~ /^-/ )
	{
		print( "wrf2vdfbatch: Unrecognized option $ARGV[$i]\n" );
		exit 1;
	}
	last; # If we get down here, we're done with options and we've moved on
		  # to files
}

# Get the metafile name
$stub = $stub . " $ARGV[$i]";

# These are the bottom of the bottom and top layers.  Start with high values
# so that they are sure to change.
$bottomBottom = 400000.0;
$bottomTop = 400000.0;

# These are the total number of time steps actually converted and the total
# number of time steps in the WRF files.
$tsConverted = 0;
$tsInFiles = 0;

# The starting index of the WRF file list
$i++;
$firstWrfIndex = $i;

# Loop over WRF files
for ( ; $i <= $#ARGV ; $i++ )
{
	$command = $stub . " $ARGV[$i]";

	# Normal output
	if ( $quietScript != 1 )
	{
		print( "For WRF output file $ARGV[$i]:\n" );
	}

	$result = `$command`;
	$exitStat = `echo $?`;
	
	# Handle errors
	if ( $exitStat != 0 )
	{
		print( "wrf2vdfbatch: wrf2vdf exited with non-zero exit status\n" );
		print( "Command executed was: $command\n" );
		exit 1;
	}

	# Normal output
	if ( $quietScript != 1 )
	{
		print( "$result\n" );
	}

	# Extract the most restrictive vertical extents and maybe the number of
	# time steps converted. Two different formats to deal with, depending on the
	# -quiet option
	if ( $quietScript == 1 ) # What to do if quiet option is on
	{
		@newExts = split( / /, $result );
	}
	else # What to do if quiet option is off
	{
		# This gathers the extents

		# Index where a key phrase begins
		$mostIndex = index( $result, "Most restrictive vertical extents: " );
		if ( $mostIndex < 0 ) # Handle errors
		{
			print( "wrf2vdfbatch: Problem finding most restrictive vertical " );
			print( "extents\nin wrf2vdf output\n" );
			exit 1;
		}
		
		# Index of the first newline found after that index
		$nIndex = index( $result, "\n", $mostIndex );
		if ( $nIndex < $mostIndex ) # Handle errors
		{
			print( "wrf2vdfbatch: Problem finding newline after most ");
			print( "restrictive\nvertical extents\n" );
			exit 1;
		}

		# Length of substring to take
		$strLength = $nIndex - $mostIndex - 35;
		
		# Take the extents
		$extsStr = substr( $result, $mostIndex + 35, $strLength );

		# Split them up
		@newExts = split( / to /, $extsStr );


		# Done getting extents.  Now get time step info.

		# Index where a key phrase begins
		$timeIndex = index( $result, "Time steps converted: " );
		if ( $timeIndex < 0 ) # Handle errors
		{
			print( "wrf2vdfbatch: Problem finding time step information in\n" );
			print( "wrf2vdf output\n" );
			exit 1;
		}
	
		# Index of the first newline found after that index
		$nIndex = index( $result, "\n", $timeIndex );
		if ( $nIndex < $timeIndex ) # Handle errors
		{
			print( "wrf2vdfbatch: Problem finding newline after time steps " );
			print( "converted\n" );
			exit 1;
		}

		# Length of the substring to take
		$strLength = $nIndex - $timeIndex - 22;

		# Take the time step info
		$tsInfoStr = substr( $result, $timeIndex + 22, $strLength );

		# Split up it up and add to the tally
		@tsInfo = split( / of /, $tsInfoStr );	
		$tsConverted += $tsInfo[0];
		$tsInFiles += $tsInfo[1];
	}

	# Compare old and new extents
	if ( $newExts[0] < $bottomBottom )
	{
		$bottomBottom = $newExts[0];
	}
	if ( $newExts[1] < $bottomTop )
	{
		$bottomTop = $newExts[1];
	}




}

# Report how many time steps were converted and number of files, if desired
if ( $quietScript != 1 )
{
	print( "Time steps converted: $tsConverted\n" );
	print( "Total time steps in files: $tsInFiles\n" );
	print( "Total number of WRF files \(converted or not\): " );
	$totalFiles = $#ARGV + 1 - $firstWrfIndex;
	print( "$totalFiles\n" );
}

# Report most restrictive extents
print( "Bottom of bottom layer: $bottomBottom\n" );
print( "Bottom of top layer: $bottomTop\n" );
print( "You may want to change the vertical extents in your .vdf file.\n" );
