#!/usr/bin/perl -w

#EOC
#------------------------------------------------------------------------------
#                  GEOS-Chem Global Chemical Transport Model                  !
#------------------------------------------------------------------------------
#BOP
#
# !IROUTINE: levUp.pl
#
# !DESCRIPTION: Adds the 'lev:positive = "up"' attribute to netCDF files
#  that have a vertical dimension, and that do not already have the
#  lev:positive attribute.
#\\
#\\
# !CALLING SEQUENCE: 
# levUp.pl 
#
# !REMARKS:
# Not the most efficient algorithm but since this is a one-off operation
# we can live with it. (bmy, 2/27/17)
#
# !REVISION HISTORY:
#  27 Feb 2017 - R. Yantosca - Initial version
#EOP
#------------------------------------------------------------------------------
#BOC
#
# !LOCAL VARIABLES:
#

# Strings
my $cmd     = "";
my $ncFile  = "";
my $result  = "";

# Arrays
my @ncFiles = qx/ls -1 *.nc*/;

# Loop over all netCDF files
foreach $ncFile ( @ncFiles ) {

  # Strip newline
  chomp( $ncFile );

  # See if the file already has a lev dimensions
  $cmd    = qq/ncdump -c $ncFile | grep "lev(lev)"/;
  $result = qx/$cmd/;

  # See if the file already has a lev:positive attribute
  if ( length( $result ) > 0 ) {
    $cmd    = qq/ncdump -c $ncFile | grep "lev:positive"/;
    $result = qx/$cmd/;

    # If not, then add the lev:positive attribute
    if ( length ( $result ) == 0 ) {
      $cmd    = qq/ncatted -a positive,lev,c,c,up $ncFile/;
      print "EXECUTING: $cmd\n";
      $result = qx/$cmd/;
    }
  }
}

# Exit and pass error code to Unix shell
exit( $? );
#EOC
