#!/usr/bin/env ruby
=begin

= gtderiv.rb : netCDF 変数の任意の次元の微分を取る.
  
= USAGE :

  $ gtbin.rb -[hHo] <--output=[outputname]> [ncfile]

= note

=end

#############  以下メインルーチン  ##############

require "getopts"
require "numru/ggraph"
require "numru/gphys/gphys_deriv"
include NumRu


# オプション解析 ----------------------------------------------------
unless getopts("hH", "help", "each", "o:", "output:", "c", "dim:")
  print "#{$0}:illegal options. please exec this program with -h/--help. \n"
  exit 1
end


if ($OPT_h) || ($OPT_H) || ($OPT_help) || ARGV.size == 0 then
  print <<EOF

EOF
exit 0
end



# 引数に与えた nc ファイルを格納する 配列.
file = Array.new

# 引数中の nc ファイルのみ格納
ARGV.each do |i| 
  if i =~ /.nc$/ then
    p i
    file << i
  end
end

# 変数 : デフォルトはヘッダ の一番最後の変数を自動的に選択
if ARGV[ARGV.size-1] =~ /.nc$/ then
  var = NetCDF.open(file[0], "r").var_names[-1]
else # 陽に指定も可能. その場合, 一番最後に与える.
  var = ARGV[ARGV.size-1]
end


if file.size == 1 then  # 単体の nc ファイルの場合
  gphys = GPhys::NetCDF_IO.open(file[0].to_s, var)
elsif ($OPT_c) 
  gphys = GPhys::NetCDF_IO.open(file, var)
else         
  vgarray = Array.new
  file.each do |f|
    vgarray << GPhys::NetCDF_IO.open(f.to_s, var)
  end
  vgphys = vgarray[0]
  1.upto(vgarray.length-1) {|n|
    vgphys += vgarray[n]
  }
  gphys = vgphys/file.length
end

# title
$title = ($OPT_title) if ($OPT_title)


#--------------------------------------
# title を得る. なければ変数の long_name をそれとする
nc = NetCDF.open(file[0])
p  longname = nc.var(var).att("long_name").get
p  title = nc.att("title")
nc.close

if title 
 $title = title
else 
 $title = longname
end


## 追加メソッド定義ファイル
require "libgphys-n.rb"
## 属性設定ファイル
require "NCEP-ncattr.conf.rb"


# 保存ファイル名が与えられたら, その名前で保存. 
if ($OPT_o) then
  output = ($OPT_o).to_s
elsif ($OPT_output) then
  output = ($OPT_output).to_s
else 
  output = "new_"+file[0].to_s
end

dim = $OPT_dim
dim = 0 if $OPT_dim

p dgp = NumRu::GPhys::Derivative::cderiv(gphys, dim)

vname = NetCDF.open(file[0], "r").var_names[-1]
globalattr = global_attr(file[0])
dgp.save("output.nc", globalattr, vname)


