#!/usr/bin/perl
#
use Getopt::Long;
use File::Basename;
#
&GetOptions(
   "a|args=s" => \$args,
   "o=s"      => \$outfile,
   "h|help"   => \$help,
) or usage();
if ($help) { usage(); }
#
SWITCH: {
  if (! $args) {
    $args = '-c';
    last SWITCH;
  }
  if ($args eq 'select') {
    $args = '-v"lon,lat,lev,mlon,mlat,mlev,time,mtime,year,day,ut,f107a,f107d,ctpoten,hpower,p0"';
    last SWITCH;
  }
  if ($args eq 'selectnew') {
    $args = '-v"time,lon,lat,lev,ilev,mlon,mlat,mlev,imlev,LBC,mtime,year,day,calendar_advance,write_date,iter,ut,timestep,f107d,f107a,hpower,ctpoten,byimf,colfac,dtide,sdtide,ncep_ncfile,gpi_ncfile,see_ncfile,gswm_mi_di_ncfile,gswm_mi_sdi_ncfile,gswm_nm_di_ncfile,gswm_nm_sdi_ncfile,alfa30,e30,alfad2,ed2,mag,p0,grav"';
  }
  $nothing = 1;
} # end switch
#
if ($outfile) {
  if (! open(NCDFILE, "> $outfile")) {
    die "\n>>> Could not open output file $outfile\n";
  } else {
    print "\nOpened output file $outfile\n";
  }
}
@flist = @ARGV;
if ($#flist == -1) { @flist = glob("*.nc"); }
$nfiles = $#flist + 1;
print "\nNumber of nc files = $nfiles\n\n";
#
$ncdcmd = 'ncdump';
FILELOOP: foreach $file (@flist) {
  ($name, $path, $suffix) = fileparse($file,".nc");
  if (! $outfile) {
    $ncdfile = $name . '.ncd';
    if (! open(NCDFILE, "> $ncdfile")) {
      die "\n>>> Could not open ncdump output file $ncdfile\n"; }
  } else {
    $ncdfile = $outfile;
  }
  $command = $ncdcmd . ' ' . $args . ' ' . $file;
  print NCDFILE 
    "\n==============================================================================\n\n";
  print NCDFILE `$command`;
  print "$command > $ncdfile\n\n";
  if (! $outfile) { close NCDFILE; }
} # end FILELOOP
if ($outfile) { close NCDFILE; }
print "\n";
#-------------------------------------------------------------------------
sub usage {
  die <<EOF;

SYNOPSIS
  mkncd [-args "args"] [file1 file2 ...]

PURPOSE:
  Execute ncdump on each file arg.

OPTIONS
  -args "args"	Execute "ncdump args" on each file (default = "-c")
		If args=="select", print a small subset of tgcm variables.
		If args=="selectnew", print subset of vars from "new" histories

ARGS [file1 file2 ...]
  Optional list of netCDF files on which to execute ncdump.
  If no file args are given, execute ncdump on all *.nc files in cwd.

EXAMPLES
  mkncd file1.nc file2.nc
  mkncd TGCM*nc
  mkncd -o all.ncd
  mkncd -args select -o all.ncd
  mkncd -args -v"mtime,time,f107a,f107d"
  mkncd -args "-bf -v"mtime,TN"" -o TN.ncd myfile.nc

CAVEAT
  If a requested variable is not on the input file, ncdump will issue
  an error message and the output file will be empty.

EOF
}
