=begin
= netcdf_cutter.rb
== $B35MW(B
:ORG_data $B$K3JG<$5$l$k(B CMAP $B%*%j%8%J%k%G!<%?$r(B 1 $B%u7nKh$KJ,3d$9$k%9%/%j%W%H(B.

== USAGE
  $ netcdf_cutter.rb $B%U%!%$%kL>(B $BJQ?t(B

=end
var_attr= {"units"=>"hours since 1979-1-1 00:00:00"}

dtype = "CMAP"
phys = "time"

# exchange time units "hours" => "date&time" 
def time2date(jd)
  dates = jd/24
  jd_ext = Date.jd(dates)
  seireki_gannen = Date.valid_date?(1979,1,1)
  date = jd_ext + seireki_gannen 
  return date
end

#############  $B0J2<%a%$%s%k!<%A%s(B  ##############
require "numru/netcdf"
module NumRu
  class NetCDFVar
    alias put scaled_put
    alias get scaled_get
  end
end

require "numru/ggraph"
include NumRu

require "getopts"

#======= ruby 1.6 $B$G(B Date::parse $B$r$D$+$&$?$a$N$*$^$8$J$$(B
class Hash
  alias values_at indices # values_at $B$O(B ruby-1.6 $B$K$OL5$$%a%=%C%I$J$N$G(B
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[0], "r").var_names[-1]  
else 
  var = ARGV[ARGV.size-1]
end

pname = var.to_s.upcase #=> $BJ*M}NL$r(B get.

#--------------------------------------
# title $B$rF@$k(B. $B$b$7$J$1$l$P(B, longname $B$r$=$l$H$9$k(B.
nc = NetCDF.open(file[0])
p  longname = nc.var(var).att("long_name").get
#  title = nc.att("title").get
   title = nil
nc.close

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

#  gphys $B%*!<%W%s(B
#
gphys = GPhys::NetCDF_IO.open(file[0], var)

start_time = gphys.coord(gphys.axnames.index(phys)).val[0]

date = time2date(start_time)
startyear = date.year

# $B@_DjItJ,(B
## $BDI2C%a%=%C%IDj5A%U%!%$%k(B
require "libgphys-n.rb"
## $BB0@-@_Dj%U%!%$%k(B
require "CMAP-ncattr.conf.rb"


time_coord = gphys.coord(gphys.axnames.index(phys))
num = time_coord.val

0.upto(num.size-1) do |i|
  year = startyear + (i+1)/12
  amari = (i+1)%12
  if amari < 10 && amari > 0 
    output = "#{pname}_#{year}-0#{amari}_#{dtype}.nc"
  elsif amari == 0
    output = "#{pname}_#{year}-12_#{dtype}.nc"
  else
    output = "#{pname}_#{year}-#{amari}_#{dtype}.nc"
  end
  p "now making "+output
  gphys.cut(phys=>num[i]).save(output, $global_attr, nil, nil, $history)
  p "done"
end
