#!/usr/bin/env ruby
# 設定部分
## 変数名
$new_vname = "tp"
## RUBYLIB に追加
$: << '/GFD_Dennou_Club/dc-arch/dcchart/daktu32/ERA40'
$: << '/GFD_Dennou_Club/dc-arch/dcchart/daktu32/ERA40/bin'
$: << '/work31/daktu32/ERA40'
$: << '/work31/daktu32/ERA40/bin'
## 追加メソッド定義ファイル
require "libgphys-e.rb"
## 属性設定ファイル
require "ERA40-ncattr.conf.rb"


require "getopts"
require "numru/netcdf"
require "numru/gphys"
include NumRu


def gtadd(file)
  gphys_file = Array.new
  
  file.each {|f|  
      var = NetCDF.open(f, "r").var_names[-1]
    temp = GPhys::NetCDF_IO.open(f, var)
    gphys_file << temp
  }
  
  sum = gphys_file[0]
  
  1.upto(gphys_file.size-1) do |i|
    sum += gphys_file[i]
  end
  
  gphys = sum
  
  return gphys
end


def print_help

  print <<HELP

====================================================
                #{File.basename($0)} ver.0.1
====================================================

Describe:

  任意数のデータの積を作成する.

  * データフォーマットは netCDF に限る. 

  * 出力は, 与えられたデータと同様の格子構造をもつ netCDF フ
    ァイルである.

  * 格子構造が異なると エラー を返す.

USAGE: #{File.basename($0)} <opt> [ncfile [ncfile ..] ] [var]
  
  * 引数解説

    [ncfile] : 対象とする netCDF ファイル名を指定. 
               (ex. mean-V_2001_01.nc)
               複数指定可能. その場合, 変数値を各格子毎に平均
               したものを出力する.

    [var]    : 足したい変数名.

  * オプション

    -h, -H, --help : このメッセージを表示.
    -o, --output   : 出力する netCDF ファイル名を指定. 
                     デフォルトは, "gtadd.nc"

HISTORY:

  2003/12/06  created  by daktu32@ep.sci.hokudai.ac.jp

====================================================

HELP

end


# オプション解析 ----------------------------------------------------
unless getopts("hH", "help", "o:", "output:")
  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_help
exit 1
end

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

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


# 保存ファイル名が与えられたら, その名前で保存. デフォルトは "gtadd.nc".
if ($OPT_o) then
  output = ($OPT_o).to_s
elsif ($OPT_output) then
  output = ($OPT_output).to_s
else 
  output = "gtadd.nc"
end


# オプション解析 終了----------------------------------------------------



# メインルーチン

p file

p $var_attr

ask_overwrite(output)

gphys = gtadd(file)
#global_attr = global_attr(file[0])
vname = NetCDF.open(file[0], "r").var_names[-1]
gphys.save(output, $global_attr, vname, $var_attr, $history, $new_vname)          # nc ファイルに保存 

exit
