#!@DASPERL
#
# Script to generate GEOS-4/4 dynamics initial condition from a blend
# of NCEP and GEOS analyses.
#
# !REVISION HISTORY:
#
#  28Feb2005  Todling   Initial code (very crude).
#  12Apr2005  Owens     additional error trapping (less crude).
#  20May2006  Todling   Added tracer opt + levels
#  08Aug2006  Todling   Added prec (default prec=32)
#-----------------------------------------------------------------------------

use Env;                 # make env vars readily available
use FindBin;             # so we can find where this script resides
use File::Basename;      # for basename(), dirname()
use File::Copy "cp";     # for cp()
use Getopt::Long;        # command line options
 
# Command line options
# --------------------
  GetOptions( "h", "oldyn", "dynonly", "o=s", "pa=s", "pb=s", "notracer", "prec=s" );

  usage() if $opt_h;

# FVROOT is where the binaries have been installed
# ------------------------------------------------
  $fvroot  = dirname($FindBin::Bin);
  $fvroot  =~ s|/u/.realmounts/share|/share|;   # for portability accros
                                                # NAS machines
  $user = getlogin();

  $init_status=init();

  if (! $init_status ) {

# Blend NCEP and GEOS analyses generating a dyn-vector like file and possible a GEOS-4 dyn restart
# ------------------------------------------------------------------------------------------------
     $cmd = $fvroot . "/bin/ss2fv.x $spc $dyn -ua $dyn -o $newdyn -pick $nymd $nhms -pa $pa -pb $pb $prec $rs $notracer" ;
     print " $cmd\n";
     $blendrc = System($cmd,"rst4ncep.log");

# If GEOS-5, generate GCM dynamics restarts 
# -----------------------------------------
     if ( ( $do_g5 ) && ( $blendrc == 0 ) ) {
       $cmd = $fvroot . "/bin/dyn2rs5.x -dynrst fvcore_internal_rst -moistrst moist_internal_rst -ana $newdyn -nymd $nymd -nhms $nhms" ;
       print " $cmd\n";
       $rc = System($cmd,"rst4ncep.log");
     }else{ $rc = 1; }
   }else{ $rc = 1; }

exit ($rc);
#------------------------------------------------------------------------------------

sub init {


  if ( $#ARGV < 3 ) {
       print STDERR "missing nymd, nhms and/or expid; see usage";
       usage();
  } else {              # required command lile args
       $nymd  = $ARGV[0];
       $nhms  = sprintf("%6.6d",$ARGV[1]);
       $dyn   = $ARGV[2];
       $spc   = $ARGV[3];
       $yyyy  = substr($nymd,0,4);
       $mm    = substr($nymd,4,2);
       $dd    = substr($nymd,6,2);
       $hh    = substr($nhms,0,2);
  }

  if( $opt_o ) {
      $newdyn = $opt_o;
  } else {
      $newdyn = "newdyn.eta.nc4";
  }

  $g5gcm   = 1  if ( -e "$fvroot/bin/GEOSgcm.x" );
  $fvgcm   = 1  if ( -e "$fvroot/bin/fvpsas.x"  );

  $rs = "";
  if ( $fvgcm ) { 
       $rs = "-rs";
       if( $opt_oldyn ) { $oldyn = "-oldyn" };
  }
  $notracer = "";
  if( $opt_notracer ) { $notracer = "-notracer" };

  if( $opt_pa ) {
      $pa = $opt_pa;
  } else {
      $pa = "0.2";
  }

  if( $opt_pb ) {
      $pb = $opt_pb;
  } else {
      $pb = "0.4";
  }

  if( $opt_prec ) {
      $prec = "-prec $opt_prec";
  } else {
      $prec = "-prec 32";
  }

  if( $g5gcm ) {
      if( $opt_dynonly ) {
          $do_g5 = 0;
      } else {
          $do_g5 = 1;
          if (! -e "fvcore_internal_rst" ) { print("Cannot find fvcore_internal_rst\n"); return 1};
          if (! -e "moist_internal_rst"  ) { print("Cannot find moist_internal_rst \n"); return 1};
      }
  }

return 0;
}

#......................................................................
                                                                                                                             
#
# System: This routine saves stdout/stderr, redirects it to a specified file,
#         runs a shell command using this new stdout/stderr, and finally
#         restores the original stdout/stderr.
#
                                                                                                                             
sub System {
                                                                                                                             
    my ( $cmd, $logfile ) = @_;
                                                                                                                             
    print "$myname: $cmd\n" if ( $opt_v );
                                                                                                                             
    open SAVEOUT, ">&STDOUT";  # save stdout
    open SAVEERR, ">&STDERR";  # save stderr
                                                                                                                             
    open STDOUT, ">>$logfile" or die "can't redirect stdout";
    open STDERR, ">>$logfile" or die "can't redirect stderr";
                                                                                                                             
    select STDERR; $| = 1;     # make it unbuffered
    select STDOUT; $| = 1;     # make it unbuffered
                                                                                                                             
    $rc = system ( $cmd );     # run the shell command
                                                                                                                             
    close STDOUT;
    close STDERR;
                                                                                                                             
    open STDOUT, ">&SAVEOUT" ;  # restore stdout
    open STDERR, ">&SAVEERR" ;  # restore stdout
                                                                                                                             
    close SAVEERR;
    close SAVEOUT;
                                                                                                                             
    return $rc;
                                                                                                                             
  }

#------------------------------------------------------------------------------------

sub usage {

   print <<"EOF";

NAME
     rst4ncepf - Generates GEOS-4/5 (fvcore) restarts from NCEP and GEOS analyses.
                 In case of GEOS-4 the file  d_rst                                       is created on output;
                 In case of GEOS-5 the files fvcore_internal_rst and moist_internal_rst are created on output.
          
SYNOPSIS

     rst4ncepf [...options...]  nymd  nhms  dyn spc   
          
DESCRIPTION

     The following parameter are required 

     nymd     Year-month-day, e.g., 19990901  for 01 Sept 1999 
     mhms     Hour-minutes-seconds, e.g., 120000
     dyn      GEOS analysis file (to be used for dyn-template and blending)
     spc      Spectral file (usually, an NCEP-analysis file)

OPTIONS
 
 -h            prints this usage notice

 -o            optinal filename for output dyn-vector

 -oldyn        needed when using old GEOS-4 analysis file not containing nstep

 -dynonly      use when within GEOS-5 context wants dyn vector only

 -prec XX      determines precision of intermediate hdf (eta) file (default: 32)

 -pa PALEV     level above which to use blending field

 -pb PBLEV     level below which to use analysis field

 -notracer     to not output tracer (nq>1) to hdf (eta) intermediate file

ENVIRONMENT

AUTHOR
      R. Todling (todling\@gmao.gsfc.nasa.gov), NASA/GSFC/GMAO

EOF

  exit(1)

	   }
