#!/usr/bin/env ruby
=begin
= mkfig.rb -- make figure for 25 years mean epflx(epflux and its divergence)
=end

## -- method definition --
def make_mean_gphys(season,year,varname,physname)
  ary = []
  y1 = year[0]; y2 = year[1]
  path = "../../#{physname}.NCEP/"
  season.each do |m|
    y1.upto(y2) do |y|
      fn = path + "#{physname}.#{y}.NCEP/#{physname}_#{y}-#{m}_NCEP.nc"
      ary << fn
    end
  end
  return mean_gphys(ary, varname)
end

module NumRu
  module GGraph

    module_function

    def vector_for_dcchart(fx, fy, newframe=true, options=nil)  
      if ! defined?(@@vector_for_dcchart_options)
        @@vector_for_dcchart_options = Misc::KeywordOptAutoHelp.new(
          ['newfig', true, 'if false, do not cleared before figure setting.'],
          ['title', nil, 'Title of the figure(if nil, internally determined)'],
          ['annotate', true, 'if false, do not put texts on the right margin even when newframe==true'],
          ['transpose', false, 'if true, exchange x and y axes'],
          ['xintv', 1, '(Effective only if flow_vect) interval of data sampling in x'],
          ['yintv', 1, '(Effective only if flow_vect) interval of data sampling in y'],
          ['xfact', 1, 'scale factor for x'],
          ['yfact', 1, 'scale factor for y'],
          ['itr',   1, 'log or linear'],
          ['unit_vect', false, 'Show the unit vector'],
          ['max_unit_vect', false, '(Effective only if flow_vect && unit_vect) 
            If true, use the maximum arrows to scale the unit vector; otherwise, normalize in V coordinate.']
        )
      end
      opts = @@vector_for_dcchart_options.interpret(options)
      fx = fx.first2D.copy
      fy = fy.first2D.copy
      sh = fx.shape
      if sh != fy.shape
        raise ArgumentError, "shapes of fx and fy do not agree with each other"
      end
      fx = fx.transpose(1,0) if opts['transpose']
      fy = fy.transpose(1,0) if opts['transpose']
      if ((xi=opts['xintv']) >= 2)
        idx = NArray.int(sh[0]/xi).indgen!*xi     # [0,xi,2*xi,..]
        fx = fx[idx, true]
        fy = fy[idx, true]
      end
      if ((yi=opts['xintv']) >= 2)
        idx = NArray.int(sh[1]/yi).indgen!*yi     # [0,yi,2*yi,..]
        fx = fx[true, idx]
        fy = fy[true, idx]
      end
      xax = fx.coord(0)
      yax = fy.coord(1)
      if newframe
	nextfig = @@next_fig.dup  if ( @@next_fig != nil ) # backup next_fig
        fig(xax, yax, {'itr'=>itr}) 
        axes(xax, yax)
        if opts['title']
          ttl = opts['title']
        else
          fxnm = fx.data.get_att('long_name') || fx.name
          fynm = fy.data.get_att('long_name') || fy.name
          ttl =   '('+fxnm+','+fynm+')'
        end
        title( ttl )
        annotate(fx.lost_axes) if opts['annotate']
	@@next_fig = nextfig      if ( @@next_fig != nil )
      end
      fig(xax, yax, {'new_frame'=>false, 'itr'=>1, 'yreverse'=>false}) \
                                                          if (opts['newfig'])
      DCL.uwsgxa(xax.val) 
      DCL.uwsgya(yax.val)
      xfact = opts["xfact"]; yfact = opts["yfact"]
      before2=DCLExt.ug_set_params( {'LNRMAL'=>false, 'LMSG'=>false,
					 'XFACT1'=>xfact, 'YFACT1'=>yfact} )
#      before=DCLExt.ug_set_params({'lunit'=>true}) if opts['unit_vect']
      DCL.ugvect(fx[true, -1..0].val, fy[true, -1..0].val)
      DCLExt.unit_vect(xfact, yfact, nil, nil, "vxuoff"=>0.01) if opts['unit_vect']
#      DCLExt.ug_set_params(before) if opts['unit_vect']
      nil
    end
  end
end


## -- require libraries -- 
require "getopts"        
require "numru/netcdf_miss"
require "numru/ggraph"
require "colorbar"            # def colorbar
require "libgphys-n"
include NumRu

## -- file config -- 
physname = "EPFLX"
var2 =  "epflx_phi"
var3 =  "epflx_p"
var1 =  "epflx_div"

year = [1979, 2003]
winter = ["12", "01", "02"];  spring = ["03", "04", "05"]
summer = ["06", "07", "08"];  fall = ["09", "10", "11"]

## -- figure config -- 
level = NArray[-1.0e8, -5.0e1, -1.0e1, 0, 1.0e1, 5.0e1, 1.0e8]*1.0e-6
pattern = NArray[30999, 35999, 40999, 55999, 75999, 85999]
vect_ratio = NArray[1.0, 100.0]*8e-12
vect_fact = 1.0

## other figure factor
# xfact = 1e-11; yfact=2.5e-8 
# xfact = 4e-11; yfact=1.5e-8 

djf = make_mean_gphys(winter,year,var1,physname)
mam = make_mean_gphys(spring,year,var1,physname)
jja = make_mean_gphys(summer,year,var1,physname)
son = make_mean_gphys(fall,year,var1,physname)

djf1 = make_mean_gphys(winter,year,var2,physname)
mam1 = make_mean_gphys(spring,year,var2,physname)
jja1 = make_mean_gphys(summer,year,var2,physname)
son1 = make_mean_gphys(fall,year,var2,physname)

djf2 = - make_mean_gphys(winter,year,var3,physname)
mam2 = - make_mean_gphys(spring,year,var3,physname)
jja2 = - make_mean_gphys(summer,year,var3,physname)
son2 = - make_mean_gphys(fall,year,var3,physname)


# set User Path for dcldatabase
DCL.glcset('DUPATH','/home/daktu32/.dcldir/')     


DCL.gropn(2)
DCL.sgpset('lcntl', false)   # 
DCL.sgpset('lfull',true)     # 
DCL.sgpset('lcorner',false)  # 
DCL.uzfact(0.35)             # 
DCL.sgpset('lfprop',true)    # 
DCL.udpset('lmsg',false)     # 

vpt = NArray[0.05, 0.45, 0.05, 0.25]             # 
vpt00 = ( vpt + ([0.050]*2 + [0.32]*2) ).to_a    # 
vpt01 = ( vpt + ([0.474]*2 + [0.32]*2) ).to_a    # 
vpt10 = ( vpt + ([0.050]*2 + [0.10]*2) ).to_a    # 
vpt11 = ( vpt + ([0.474]*2 + [0.10]*2) ).to_a    # 

before = DCLExt.gl_set_params('lmiss'=>true,'rmiss'=>djf.data.get_att("missing_value")[0])

GGraph.set_fig('viewport'=>vpt00, 'itr'=>2)
GGraph.set_axes('xunits'=>'','yunits'=>'','xtitle'=>'') 
DCL.uzpset('labelxb',false)
GGraph.tone( mam, true , 'annot'=>false, 'titl'=>'', 'pat'=>pattern, 'lev'=>level )
GGraph::vector_for_dcchart(mam1, mam2, false,
			   'xfact'=>vect_ratio[0]*vect_fact, 'yfact'=>vect_ratio[-1]*vect_fact, 
                                  'unit'=>false, 'annot'=>false, 'itr'=>2
				    )
DCL.uzpset('pad1',0.2) ; DCL.uxsttl('t','Spring(MAM)', -1) ; DCL.uzpset('pad1',0.7)

GGraph.set_fig('viewport'=>vpt01, 'new_frame'=>false, 'itr'=>2)
GGraph.set_axes('ytitle'=>'')
DCL.uzpset('labelyl',false)
GGraph.tone( jja, true , 'annot'=>false, 'titl'=>'', 'pat'=>pattern, 'lev'=>level )
DCL.uzpset('pad1',0.2) ; DCL.uxsttl('t','Summer(JJA)',-1) ; DCL.uzpset('pad1',0.7)
GGraph::vector_for_dcchart(jja1, jja2, false,
			   'xfact'=>vect_ratio[0]*vect_fact, 'yfact'=>vect_ratio[-1]*vect_fact, 
                                  'unit'=>false, 'annot'=>false, 'itr'=>2
				    )

GGraph.set_fig('viewport'=>vpt10, 'new_frame'=>false, 'itr'=>2)
GGraph.set_axes('ytitle'=>nil,'xtitle'=>nil)
DCL.uzpset('labelyl',true); DCL.uzpset('labelxb',true)
GGraph.tone( son, true , 'annot'=>false, 'titl'=>'', 'pat'=>pattern, 'lev'=>level )
GGraph::vector_for_dcchart(son1, son2, false,
			   'xfact'=>vect_ratio[0]*vect_fact, 'yfact'=>vect_ratio[-1]*vect_fact, 
                                  'unit'=>false, 'annot'=>false, 'itr'=>2
				    )
DCL.uzpset('pad1',0.2) ; DCL.uxsttl('t','Autumn(SON)',-1) ; DCL.uzpset('pad1',0.7)

GGraph.set_fig('viewport'=>vpt11, 'new_frame'=>false,  'itr'=>2)
GGraph.set_axes('ytitle'=>'')
DCL.uzpset('labelyl',false)
GGraph.tone( djf, true , 'annot'=>false, 'titl'=>'', 'pat'=>pattern, 'lev'=>level )
GGraph::vector_for_dcchart(djf1, djf2, false,
			   'xfact'=>vect_ratio[0]*vect_fact, 'yfact'=>vect_ratio[-1]*vect_fact, 
                                  'unit'=>true, 'annot'=>false, 'itr'=>2
				    )
DCL.uzpset('pad1',0.2) ; DCL.uxsttl('t','Winter(DJF)',-1) ; DCL.uzpset('pad1',0.7)

## -- colorbar --
DCL::Util::color_bar({
		       "levels"=>level, 
		       "colors"=>pattern,
		       "eqlev"=>true,
		       "nobound"=>0,
		       "tick1"=>10,"tick2"=>1,
		       "vx0"=>0.3,
		       "vxlength"=>0.4,
		       "vy0"=>0.08,
		       "vylength"=>0.02 
		     })

## -- extra information --
DCL::sgtxzv(0.5,vpt00[3]+0.028,"25 years mean EP flux (1979-2003)",
	        1.15*DCL.uzpget('rsizec2'),0,0,3)
DCL::sgtxzv(0.85,vpt00[3]+0.01,"(divF units:#{djf.data.units.to_s})",
	        0.9*DCL.uzpget('rsizec2'),0,0,3)


DCL.grcls

