#! /usr/bin/env ruby
=begin

= title:

  mkmean-nc-4dim.rb  -- netCDF データの 3, 4 次元目(time 軸, date 軸)についての平均をとったデータを生成するスクリプト.

= usage:

  mkmean-nc-4dim.rb file [file...] (例: $ mkmean-nc-4dim.rb ./*.nc)

= description:
* 引数にとった nc ファイルそれぞれに対して, 3, 4 次元目それぞれに対して平均をとった nc ファイルを新たに生成する.
  * 頭に daily という接頭句がついているファイルのみ対象
  * 生成されるファイル名は daily を除いたものになる.
* 地表面データから月平均データを生成するのに使用.
 
= history:

  2003-12-22 created by daktu32@ep.sci.hokudai.ac.jp

=end


require "getopts"

require "numru/netcdf"

module NumRu
  class NetCDFVar
    def scaled_get(hash=nil)
      sf = att('scale_factor')
      ao = att('add_offset')
      if ( sf == nil && ao == nil ) then
	# no scaling --> just call get
	simple_get(hash)
      else
	if (sf != nil) 
	  csf = sf.get
	       if csf.is_a?(NArray) then  # --> should be a numeric
		 csf = csf[0]
	       elsif csf.is_a?(String)
		 raise NetcdfError, "scale_factor is not a numeric"
	       end
	  if(csf == 0) then; raise NetcdfError, "zero scale_factor"; end
	else
	  csf = 1.0      # assume 1 if not defined
	end
	if (ao != nil) 
	  cao = ao.get
	  if cao.is_a?(NArray) then  # --> should be a numeric
	    cao = cao[0]
	  elsif csf.is_a?(String)
	    raise NetcdfError, "add_offset is not a numeric"
	  end
	    else
	  cao = 0.0      # assume 0 if not defined
	end
	var = simple_get(hash)
	var = var.to_type( NArray::FLOAT )
	csf*var+cao
      end
    end  
    alias put scaled_put
    alias get scaled_get
  end
end

require "numru/ggraph"
include NumRu

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



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


file = Array.new
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.last, "r").var_names[-1]
else
  var = ARGV[ARGV.size-1]
end

if file.size == 1 then
  file = file[0].to_s
end


filename = File.basename($0)

p file
p a = Time.now

file.each {|f|

  p gphys = GPhys::NetCDF_IO.open(f, var)
  p mean = gphys.mean(2, 3)
  
  p newfile = File.basename(f).sub("daily_", "")
  p newfile = ($OPT_output) if ($OPT_output)

  global_attr = global_attr(f)
  mean.save(newfile, global_attr)
  
  p "make #{newfile}"

}

p Time.now - a


