#! /usr/bin/env ruby

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

module NumRu
  class NetCDFVar

    def get_with_miss_and_scaling2(*args) # make mask before scaling
      __interpret_missing_params if !defined?(@missval)
      packed_data = simple_get(*args)
      scaled_data = scaled_get(*args)
      sf = att('scale_factor')
      ao = att('add_offset')
      if @vmin || @vmax
	if sf && ao
	  csf = sf.get
	  cao = ao.get
	  vmin = (@vmin-cao)/csf if @vmin
	  vmax = (@vmax-cao)/csf if @vmax
	elsif
	  vmin = @vmin; vmax = @vmax
	end
	if vmin
	  mask = (packed_data >= vmin) 
	mask = mask.and(packed_data <= vmax) if vmax
	else
	  mask = (packed_data <= vmax)
	end
	data = NArrayMiss.to_nam(scaled_data, mask)
      elsif @missval	# only missing_value is present.
	eps = 1e-6
	missval = @missval[0].to_f
	vmin = missval - eps
	vmax = missval + eps
	mask = (packed_data <= vmin) 
	mask = mask.or(packed_data >= vmax)
	data = NArrayMiss.to_nam(scaled_data, mask)
      else
	data = scaled_data
      end
      data
    end
  end
end


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

var_epy = 'epflx_phi'
var_epz = 'epflx_p'
var_epdiv = 'epflx_div'
var_epmask = 'sfc_mask'

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

  mask_fnm = f.gsub('\.daily', '').gsub('EPFLX','MASK').gsub('daily\_', '')

  epy = GPhys::NetCDF_IO.open(f, var_epy)
  epz = GPhys::NetCDF_IO.open(f, var_epz)
  epdiv = GPhys::NetCDF_IO.open(f, var_epdiv)
  epmask = GPhys::NetCDF_IO.open(mask_fnm, var_epmask)

  epy = epy.mean($OPT_mean)
  epz = epz.mean($OPT_mean)
  epdiv = epdiv.mean($OPT_mean)
  epmask = epmask.cut('level'=>100..1000).mean('lon')

  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')
  [epy, epz, epdiv].each do |gp|
    gphys = gp + epmask
    GPhys::IO.write(nc, gphys)
  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
  ## $B%X%C%@$r(B Monthly-Mean $BMQ$K=q$-49$((B ----------------------
  nc = NetCDF.open(newfile, mode="a+")
  nc.redef # into define mode

  [var_epy, var_epz, var_epdiv].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}"
  
}

