#! /usr/bin/env ruby
=begin

= mkmean_dor_dsefl.rb: $B4%Ag@EE*%(%M%k%.!<(B( dsefl, dsefl_bar, dsefl_dash) $B$N(B
                       $BG$0U<!85$NJ?6QCM$r(B netCDF $B%U%!%$%k$KJ]B8$9$k%9%/%j%W%H(B.

== USAGE

  % mkmean_for_dsefl.rb --output hoge.nc --mean time ncfile.nc

=end
require "getopts"
require "numru/ggraph"
require "libgphys-n"
require "NCEP-ncattr.conf"
include NumRu


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

var_dsefl =      'dsefl'
var_dsefl_bar  = 'dsefl_bar'
var_dsefl_dash = 'dsefl_dash'

filename = File.basename($0)
ARGV.each {|f|

  dsefl =      GPhys::NetCDF_IO.open(f, var_dsefl)
  dsefl_bar =  GPhys::NetCDF_IO.open(f, var_dsefl_bar)
  dsefl_dash = GPhys::NetCDF_IO.open(f, var_dsefl_dash)

  dsefl = dsefl.mean($OPT_mean)
  dsefl_bar = dsefl_bar.mean($OPT_mean)
  dsefl_dash = dsefl_dash.mean($OPT_mean)

  p newfile = File.basename(f).sub("daily_", "")
  p newfile = ($OPT_output) if ($OPT_output)

  ym = f.scan(/(\d+)-(\d+)/)
  year = ym[0]
  month = ym[1]

  nc = NetCDF.open(newfile, 'w')
  [dsefl, dsefl_bar, dsefl_dash].each do |gp|
    GPhys::IO.write(nc, gp)
  end
  global_attr = $global_attr
  global_attr.to_a.each {|attr| 
      nc.put_att(attr[0], attr[1]) if attr[1]
  } 
  nc.put_att("history", $history)
  nc.close

  p "make #{newfile}"
}
=begin
  ## $B%X%C%@$r(B Monthly-Mean $BMQ$K=q$-49$((B ----------------------
  nc = NetCDF.open(newfile, mode="a+")
  nc.redef # into define mode

  [var_dsefl, var_dsefl_bar, var_dsefl_dash].each do |var|
    var = nc.var(var)
    var.each_att do |att|
      att_val = att.get
      if att_val.is_a?(String)
	att.put(att_val.sub(/^4x\ *[D|d]aily/, "Monthly Mean"))
      end
    end

  end
  
  nc.each_att do |att|
    att_val = att.get
    if att_val.is_a?(String)
      att.put(att_val.sub(/^4x\ *[D|d]aily/, "Monthly Mean"))
    end
  end

  nc.close
  
  p "make #{newfile}"
  


=end
