#!/usr/bin/env ruby
=begin
= mkfig.rb -- make figure for energy balance

$B%(%M%k%.!<%P%i%s%94XO"?^(B. $B0J2<$NJ*M}NL$N0^EYJ?6QCM$r%W%m%C%H(B.

* NSWRS : $BCOI=LL%M%C%HC;GH%U%i%C%/%9(B
* NLWRS : $BCOI=LL%M%C%HD9GH%U%i%C%/%9(B
* USWRF : $BBg5$>eC<308~$-C;GH%U%i%C%/%9(B
* ULWRF : $BBg5$>eC<308~$-D9GH%U%i%C%/%9(B
* DSWRF : $BBg5$>eC<Fb8~$-C;GH%U%i%C%/%9(B
* PRATE : $B9_?e6/EY(B($B@xG.$N7A$K=q$-D>$9(B)
* LHTFL : $BCOI=LL$K$*$1$k@xG.%U%i%C%/%9(B
* SHTFL : $BCOI=LL$K$*$1$k82G.%U%i%C%/%9(B

$BIA$1$?$i(B, $B@5L#$N%U%i%C%/%9$rIA$/(B.

=end

require "getopts"        # for option_parse
require "numru/netcdf_miss"
require "numru/ggraph"
require "colorbar"
require "libgphys-n"
require "getopts"
include NumRu
include Misc

## enable to the option min, max 

  def GGraph::line(gphys, newframe=true, options=nil)
    if newframe!=true && newframe!=false
      raise ArgumentError, "2nd arg (newframe) must be true or false"
    end
    if ! defined?(@@line_options)
      @@line_options = Misc::KeywordOptAutoHelp.new(
						    ['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'],
						    ['exchange', false, 'whether to exchange x and y axes'],
						    ['index', 1, 'line/mark index'],
						    ['type', 1, 'line type'],
						    ['label', nil, 'if a String is given, it is shown as the label'],
						    ['max', nil, 'maximam value for draw line'],
						    ['min', nil, 'minimam value for draw line']
						    )
    end
    opts = @@line_options.interpret(options)
    gp = gphys.first1D
    if !opts['exchange']
      x = gp.coord(0)
      y = gp.data
      xax = x
      if opts['min']
	ymin = opts['min'].to_f
      else
	ymin = gp.data.val.min
      end
      if opts['max']
	ymax = opts['max'].to_f
      else
	ymax = gp.data.val.max
      end
      yax = VArray.new(NArray[ymin, ymax], gp.data, gp.data.name)      
    else
      y = gp.coord(0)
      x = gp.data
      yax = y
      if opts['min']
	xmin = opts['min'] 
      else
	xmin = gp.data.val.min
      end
      if opts['max']
	xmax = opts['max'] if opts['max']
      else
	xmax = gp.data.val.max
      end
      xax = VArray.new(NArray[xmin, xmax], gp.data, gp.data.name)
    end
    if newframe
      fig(xax, yax)
      axes(xax, yax)
      title( (opts['title'] || gp.data.get_att('long_name')) )
      annotate(gp.lost_axes) if opts['annotate']
    end
    if opts['label']
      lcharbk = DCL.sgpget('lchar')
      DCL.sgpset('lchar',true)
      DCL.sgsplc(opts['label'])
      end
    DCL.uulinz(x.val, y.val, opts['type'], opts['index'])
    DCL.sgpset('lchar',lcharbk) if opts['label']
    nil
  end


##-----------------------
#  $B%i%$%s%a%=%C%I:FDj5A(B?

def plot_line_main(gphys_array, line_opts={})
  
  line_index_ary = Array.new; name_ary = Array.new

  default_index = 12
  
  line_hash = { "index"=> default_index }.update(line_opts)
  line_index_ary.push(default_index)
  name_ary.push(gphys_array[0].data.get_att("long_name"))
  
  GGraph.line( gphys_array[0], true, line_hash )
  gphys_array.size.times{ |num|
      unless num == 0
	line_hash = { "index"=> (num*10 + default_index)}
	line_index_ary.push(num*10 +default_index)
	name_ary.push(gphys_array[num].data.get_att("long_name"))
	GGraph.line( gphys_array[num], false, line_hash ) 
      end
  }
  
  return name_ary, line_index_ary
  
end



##-----------------------
#  $B%i%$%s%$%s%G%C%/%9$N<oN`$rI=<((B

def __show_line_index(str_ary,line_index_ary) 
    charsize = 1.0 * DCL.uzpget('rsizec1')
    dvx = 0.01
    dvy = charsize*1.5
    raise TypeError,"Array expected" if ! str_ary.is_a?(Array)
    vxmin,vxmax,vymin,vymax = DCL.sgqvpt
    vx = 0.15
    vy = 0.12 - charsize/2
  str_ary.size.times{|num|
    DCL::sgtxzv(vx,vy,"--- #{str_ary[num]}", 
		  charsize, 0, -1, line_index_ary[num])
      vy -= dvy
      if num == 4
	vx = 0.30
	vy = 0.12 - charsize/2
      end
  }
    nil
  end

#################################################################


unless getopts("nlwrs:", "nswrs:", "ulwrf:", "uswrf:", "dswrf:", "output:epflx.nc")
  print "#{$0}:illegal options.\n"
  exit 1
end

nc_nlwrs, var_nlwrs =   ($OPT_nlwrs).split(/\s*@\s*/)
nc_nswrs, var_nswrs =   ($OPT_nswrs).split(/\s*@\s*/)
nc_ulwrf, var_ulwrf =   ($OPT_ulwrf).split(/\s*@\s*/)
nc_uswrf, var_uswrf =   ($OPT_uswrf).split(/\s*@\s*/)
nc_dswrf, var_dswrf =   ($OPT_dswrf).split(/\s*@\s*/)
year_month = nlwrs.scan(/[\d\-]+/)[0]
#year, month = nlwrs.scan(/[\d\-]+/)[0].split(/\s*-\s*/)

gp_ary = []
gp_ary << GPhys::IO.open(nc_nlwrs, var_nlwrs)
gp_ary << GPhys::IO.open(nc_nswrs, var_nswrs)
gp_ary << GPhys::IO.open(nc_ulwrf, var_ulwrf)
gp_ary << GPhys::IO.open(nc_uswrf, var_uswrf)
gp_ary << GPhys::IO.open(nc_dswrf, var_dswrf)

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


## four in one(itr 2)
itr = 1
min = -300
max = +500

## annual mean

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)     # 

# $B%S%e!<%]!<%H@_Dj(B
vpt = NArray[0.15,0.85,0.23,0.58]

# dcl $B$K7gB;CM>pJs$r65$($k(B
before = DCLExt.gl_set_params('lmiss'=>true,'rmiss'=>gp_ary[0].data.get_att("missing_value")[0])

# annual mean
GGraph.set_fig('viewport'=>vpt, 'itr'=>itr)
names, idxs = plot_line_main(gp_ary, 'annot'=>false, 'titl'=>'RADIATION BALANCE(#{year_month})', 'min'=>min, 'max'=>max)
DCL.uzpset('pad1',0.2) ; DCL.uxsttl('t','ANNUAL',-1) ; DCL.uzpset('pad1',0.7)

__show_line_index(names,idxs)

## -- extra information --
DCL::sgtxzv(0.88,vpt[3]+0.01,"(units:#{gp_ary[0].data.units.to_s})",
	        0.9*DCL.uzpget('rsizec2'),0,0,3)

DCL.grcls

