#!/usr/bin/env ruby

=begin

$  for file in *.xwd ; do xwdtopnm ${file} |  pnmcut 2 2 904 654 > test.pnm; ppmtogif test.pnm > ${file}.gif; done
$ gifsicle --delay=50 --no-loop dcl_*.gif > movie.gif

=end

# ----------------------------------------------
# プログラムメイン

END{

  $latitude = 360
  num = 6
  set_filename(num)           # ファイル名等基本設定
  mradl_anim_main             # gif 作成
  print "gif convert start #{Time.now}\n"
  mkgifanim                   # gif アニメ作成シェルスクリプト

}

# ----------------------------------------------
# 必要なライブラリ, モジュールの読み込み

#$local_path = '/work11/ape/yukiko/lib'
#$local_path = '/home/yukiko/lib'
$local_path = '/home/yukiko/eva01/work11/ape/yukiko/lib'
$: << $local_path

require "getopts"
require "numru/netcdf"
module NumRu
  class NetCDFVar
    alias put scaled_put
    alias get scaled_get
  end
end

require "numru/ggraph"
require "colorbar"
include NumRu
include NMath


#----------------------------------------------
# 設定

def set_filename(num)

  set_varinfo
  numnum = 0
  num = ARGV[numnum+1].to_i  if numnum = ARGV.index("-num")
  $timestep = "1hour"           if numnum = ARGV.index("-1hour")
  $timestep = "2hour"           if numnum = ARGV.index("-2hour")
#  $longitude = ARGV[numnum+1].to_i if numnum = ARGV.index("-lon")
  $latitude = 360

  if num == 1
    varlist = "q"
    $var_array.push($q_hash) 
  elsif num == 2
    varlist = "t"
    $var_array.push($t_hash) 
  elsif num == 3
    varlist = "qcnd"
    $var_array.push($qcnd_hash) 
  end

  $gifname = 
    "AGCM5_kuo_mradlAc_#{varlist}_lat#{$latitude}lon0510-#{$timestep}"

  print "#{$gifname} name start #{Time.now}\n"

end

def set_varinfo

  rmiss = DCL.glpget('rmiss')
  $var_array = []

  # 凝結加熱 (cumulus + largescale)
  $qcnd_hash = {
    "variable" => "qcnd", 
    "filename" => ["qcnd_sum_50.nc","qcnd_sum_60.nc"],
    "diff"     => false, 
    "levels" => NArray[0, 0.4e-4, 0.8e-4, 1.2e-4, 
      1.6e-4, 2.0e-4, 2.4e-4, rmiss],
    "lost_axis" => " ",
    "title" => "condensation heating (K s-1)"
  }

  # 凝結加熱 (cumulus)
  $qcndc_hash = {
    "variable" => "qcndc", 
    "filename" => ["qcndc_sum_50.nc","qcndc_sum_60.nc"],
    "diff"     => false, 
    "levels" => NArray[0, 0.4e-4, 0.8e-4, 1.2e-4, 
      1.6e-4, 2.0e-4, 2.4e-4, rmiss],
    "lost_axis" => " ",
    "title" => "cumulus condensation heating (K s-1)"
  }

  # 凝結加熱 (large scale)
  $qcndl_hash = {
    "variable" => "qcndl", 
    "filename" => ["qcndl_sum_50.nc","qcndl_sum_60.nc"],
    "diff"     => false, 
    "levels" => NArray[0, 0.4e-4, 0.8e-4, 1.2e-4, 
      1.6e-4, 2.0e-4, 2.4e-4, rmiss],
    "lost_axis" => " ",
    "title" => "L.S. condensation heating (K s-1)"
  }

  # 温度偏差
  $t_hash = {
    "variable" => "t", 
    "filename" => ["t_out_50.nc", "t_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-1,-0.5, 0, 0.5, 1, 1.5, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "temperature (K)"
  }
  
  # 比湿偏差
  $q_hash = {
    "variable" => "q", 
    "filename" => ["q_out_50.nc", "q_out_60.nc"], 
    "diff"     => true, 
    "levels" => NArray[rmiss,-2e-3,-1e-3, 0, 1e-3, 2e-3, 3e-3,rmiss], 
    "lost_axis" => "(diff) from (mean) zonal", 
    "title" => "specific humidity (1)"
  }

  # 仮温度偏差
  $tv_hash = {
    "variable" => "tv", 
    "filename" => ["tv_out_50.nc","tv_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss, -1, -0.5, 0, 0.5, 1, 1.5, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "virtual temperature (K)"
  }

  # 温位偏差
  $theta_hash = {
    "variable" => "theta", 
    "filename" => ["theta_out_50.nc","theta_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-1,-0.5, 0, 0.5, 1, 1.5, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "potentital temperature (K)"
  }

  # 相当温位偏差
  $thetae_hash = {
    "variable" => "thetae", 
    "filename" => ["thetae_out_50.nc","thetae_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-5,-2.5, 0, 2.5, 5, 7.5, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "equivalent potentital temperature (K)"
  }

  # 飽和相当温位偏差
  $thetaesat_hash = {
    "variable" => "thetae", 
    "filename" => ["thetaesat_out_50.nc","thetaesat_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-2,-1, 0, 1, 2, 3, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
#    "title" => "saturated equivalent potentital temperature (K)"
    "title" => "saturated equiv. pot. temp. (K)"
  }

  # 安定度 (Brunt-Vaisala frequency)
  $brunt_hash = {
    "variable" => "n_2", 
    "filename" => ["brunt_out_50.nc","brunt_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-2e-4,-1e-4, 0, 1e-4, 2e-4, 3e-4, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "Brunt-Vaisala frequency (s-1)"
  }

  # 相対湿度偏差
  $relh_hash = {
    "variable" => "rh", 
    "filename" => ["relh_out_50.nc","relh_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[0, 1.0/6, 2.0/6, 3.0/6, 4.0/6, 5.0/6, 1, rmiss], 
    "lost_axis" => " ",
    "title" => "relative humidity (1)"
  }

  # 発散
  $div_hash = {
    "variable" => "div", 
    "filename" => ["div_out_50.nc","div_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss,-10e-6,-5e-6, 0, 5e-6, 10e-6, 15e-6, rmiss], 
    "lost_axis" => " ",
    "title" => "divergence (s-1)"
  }

  # 発散
  $vor_hash = {
    "variable" => "vor", 
    "filename" => ["vor_out_50.nc","vor_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss,-10e-6,-5e-6, 0, 5e-6, 10e-6, 15e-6, rmiss], 
    "lost_axis" => " ",
    "title" => "vorticity (s-1)"
  }

  # 鉛直流
  $sigdot_hash = {
    "variable" => "sigdot", 
    "filename" => ["sigdot_out_50.nc","sigdot_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss,-10e-7,-5e-7, 0, 5e-7, 10e-7, 15e-7, rmiss], 
    "lost_axis" => " ",
    "title" => "sigma-vertical velocity (s-1)"
  }

  # ジオポテンシャル
  $gph_hash = {
    "variable" => "z", 
    "filename" => ["gph_out_50.nc","gph_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-10,-5, 0, 5, 10, 15, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "geopotential height (m)"
  }

  # 東西風
  $u_hash = {
    "variable" => "u", 
    "filename" => ["u_out_50.nc","u_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-5,-2.5, 0, 2.5, 5, 7.5, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "eastward wind (m s-1)"
  }

  # 南北風
  $v_hash = {
    "variable" => "v", 
    "filename" => ["v_out_50.nc","v_out_60.nc"],
    "diff"     => true, 
    "levels" => NArray[rmiss,-4,-2, 0, 2, 4, 6, rmiss], 
    "lost_axis" => "(diff) from (mean) zonal",
    "title" => "northward wind (m s-1)"
  }

  # 長波放射加熱
  $qradl_hash = {
    "variable" => "qradl", 
    "filename" => ["qradl_sum_50.nc","qradl_sum_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss,-1.5e-5,-1.2e-5,-0.9e-5,-0.6e-5,-0.3e-5, 0, rmiss], 
    "lost_axis" => " ",
    "title" => "longwave heating (K s-1)"
  }

  # 短波放射加熱
  $qrads_hash = {
    "variable" => "qrads", 
    "filename" => ["qrads_sum_50.nc","qrads_sum_60.nc"],
    "diff"     => false, 
    "levels" => NArray[0, 2e-6, 4e-6, 6e-6, 8e-6, 10e-6, 12e-6, rmiss], 
    "lost_axis" => " ",
    "title" => "shortwave heating (K s-1)"
  }

  # 鉛直拡散加熱
  $qvdf_hash = {
    "variable" => "qvdf", 
    "filename" => ["qvdf_sum_50.nc","qvdf_sum_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss, 1e-6, 2e-6, 3e-6, 4e-6, 5e-6, 6e-6, rmiss], 
    "lost_axis" => " ",
    "title" => "diffusive heating (K s-1)"
  }

  # 相当温位
  $thetae_nodiff_hash = {
    "variable" => "thetae", 
    "filename" => ["thetae_out_50.nc","thetae_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss, 320, 325, 330, 335, 340, 345, rmiss], 
    "lost_axis" => " ",
    "title" => "equivalent potentital temperature (K)"
  }

  # 飽和相当温位
  $thetaesat_nodiff_hash = {
    "variable" => "thetae", 
    "filename" => ["thetaesat_out_50.nc","thetaesat_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss, 320, 325, 330, 335, 340, 345, rmiss], 
    "lost_axis" => " ",
    "title" => "saturated equiv. pot. temp. (K)"
  }

  # 安定度 (Brunt-Vaisala frequency)
  $brunt_nodiff_hash = {
    "variable" => "n_2", 
    "filename" => ["brunt_out_50.nc","brunt_out_60.nc"],
    "diff"     => false, 
    "levels" => NArray[rmiss,0, 4e-4, 8e-4, 12e-4, 16e-4, 20e-4, rmiss], 
    "lost_axis" => " ",
    "title" => "Brunt-Vaisala frequency (s-1)"
  }

end


# ----------------------------------------------
# お絵描きメイン

def mradl_anim_main

  # ------------------------------------------------------------
  # 温度
  gphys_1 = GPhys::NetCDF_IO.open($var_array[0]["filename"], 
                                  $var_array[0]["variable"])

  # 東西風
#  gphys_u = GPhys::NetCDF_IO.open("u_out.nc", "u")
  # 鉛直風
#  gphys_sig = GPhys::NetCDF_IO.open("sigdot_out.nc", "sigdot")
 
  # ------------------------------------------------------------
  DCL.swpset('LDUMP', true) 
  DCL.swpset('LWAIT',false) ; DCL.swpset('LWAIT0',false) 
  DCL.swpset('LWAIT1',false)
  DCL.swpset('IPOSX', 50) ; DCL.swpset('IPOSY',50)  

  DCL.gropn(1)

  DCL.uzfact(0.6)                # 文字の大きさ倍
  DCL.sgpset('lcorner',false)    # コーナーマークはつけない
  DCL.slmgn(0.0, 0.0, 0.0, 0.0)  # 描画マージン指定
  DCL.sgpset('lfprop',true)      # プロポーショナルフォントを使う
  DCL.sgpset('lfull',true)       # 全画面表示
  DCL.sgpset('lcntl', false)     # アンダーバーは普通に表示
  DCL.uscset('cyspos', 'B' )      # y 軸単位を書く位置

  ipara = NumRu::DCL.uzpget('RSIZEC1')
  DCL.uzpset('RSIZEC0',0.012)    # 小タイトル 文字大きさ
  DCL.uzpset('INDEXL0',1)       # 小タイトル 文字ラインインデックス
  rmiss = DCL.glpget('rmiss')
  colorbar_hash = {
    'vlength'=>0.13,
    "vwidth"=>0.01,
    'labelintv'=>1, 
    'voff'=>0.02,
    "constwidth" => true
  }
  patterns = NArray[30999, 35999, 45999, 55999, 70999, 75999, 85999]

  if $timestep == "1hour"
    timeall = 15*24
    timestep = 1
  elsif $timestep == "2hour"
    timeall = 15*12
    timestep = 2
  end

#  (15*12).times{ |num|
#     (1).times{ |num|
  timeall.times{ |num|

    numnum= num * 10/ 24 * timestep

#    $file_label = "lon=#{$longitude}, day=#{numnum*1.0/10+5+40}"
    $file_label = "day=#{numnum*1.0/10+5+40}"
    print "  #{$file_label} #{Time.now}\n"

# 1 枚目: 凝結加熱
    DCL.uzpset('labelxb',false)
    GGraph.set_fig('viewport'=>[0.13,0.78,0.52,0.65],'new_frame'=>true) 
    GGraph.next_axes('xunits'=>'','yunits'=>'','xtitle'=>'') 

    tone_hash = { 'patterns'=> patterns, 'levels'=>$var_array[0]["levels"] }

    g = gphys_1.cut(0..$latitude,0,true,true)[true,true,num*timestep+119]
    g = g.set_att("long_name","").set_att("unit","").set_lost_axes("")
    g_tmp = gphys_1.cut(0..$latitude,0,true,true).mean(0)[true,num*timestep+119].
      set_lost_axes("")

    if $var_array[0]["diff"] 
      GGraph.tone( g-g_tmp, true , tone_hash ) 
#      GGraph.tone( g-g_tmp ) 
    else 
      g = - g if $var_array[0]["variable"] == "sigdot"
      GGraph.tone( g, true , tone_hash ) 
#      GGraph.tone( g ) 
    end

#    vect_plot(gphys_u,gphys_sig,num,timestep)
    DCL::uxsttl("t", $var_array[0]["title"], -1.0 ) 
    DCL::uzinit 
    DCL.uxpttl("t", 0, "lon=0, #{$var_array[0]["lost_axis"]}", 1.0)
    DCL::uxsttl("t", "#{$file_label}" , 1.0 )
    GGraph.color_bar( colorbar_hash )
    DCL::uzinit 

# 2 枚目: 温度偏差
    DCL.uzpset('labelxb',false)
    GGraph.next_axes('xunits'=>'','yunits'=>'','xtitle'=>nil) 
    GGraph.set_fig('viewport'=>[0.13,0.78,0.34,0.47], 'new_frame'=>false )

    tone_hash = { 'patterns'=> patterns, 'levels'=>$var_array[0]["levels"] }

    g = gphys_1.cut(0..$latitude,5,true,true)[true,true,num*timestep+119].
      set_lost_axes("").set_att("long_name","").set_att("unit","")
    g_tmp = gphys_1.cut(0..$latitude,5,true,true).mean(0)[true,num*timestep+119].
      set_lost_axes("")

    if $var_array[0]["diff"] 
      GGraph.tone( g-g_tmp, true , tone_hash ) 
#      GGraph.tone( g-g_tmp ) 
    else 
      g = - g if $var_array[0]["variable"] == "sigdot"
      GGraph.tone( g, true , tone_hash ) 
#      GGraph.tone( g ) 
    end

    DCL::uxsttl("t", $var_array[0]["title"], -1.0 ) 
    DCL::uzinit 
    DCL.uxpttl("t", 0, "lon=5, #{$var_array[0]["lost_axis"]}", 1.0)
    GGraph.color_bar( colorbar_hash )
    DCL::uzinit 

# 3 枚目: 比湿偏差
    DCL.uzpset('labelxb',true)
    GGraph.set_fig('viewport'=>[0.13,0.78,0.16,0.29], 'new_frame'=>false )
    tone_hash = { 'patterns'=> patterns, 'levels'=>$var_array[0]["levels"] }

    g = gphys_1.cut(0..$latitude,10,true,true)[true,true,num*timestep+119].
      set_lost_axes("").set_att("long_name","").set_att("unit","")
    g_tmp = gphys_1.cut(0..$latitude,10,true,true).mean(0)[true,num*timestep+119].
    set_lost_axes("")

    if $var_array[0]["diff"] 
      GGraph.tone( g-g_tmp, true , tone_hash ) 
#      GGraph.tone( g-g_tmp ) 
    else 
      g = - g if $var_array[0]["variable"] == "sigdot"
      GGraph.tone( g, true , tone_hash ) 
#      GGraph.tone( g ) 
    end

    DCL::uzinit 
    DCL::uxsttl("t", $var_array[0]["title"], -1.0 ) 
    DCL::uzinit 
    DCL.uxpttl("t", 0, "lon=10, #{$var_array[0]["lost_axis"]}", 1.0)
    GGraph.color_bar( colorbar_hash )

    
  }
  
  DCL::grcls 

end


def vect_plot(gphys_u,gphys_sig,num,timestep)

    g_u =  gphys_u.cut(0..$latitude,0,true,true)[true,true,num*timestep+119].
      set_lost_axes($lost_axis)
    g_sig = gphys_sig.cut(0..$latitude,0,true,true)[true,true,num*timestep+119].
      set_lost_axes($lost_axis)

    # ベクトルの間引
    u_data  = NArrayMiss.sfloat( g_u.axis(0).pos.val.size , 
			   g_u.axis(1).pos.val.size ).fill!(0.0)
 
    sig_data = NArrayMiss.sfloat( g_sig.axis(0).pos.val.size , 
			    g_sig.axis(1).pos.val.size ).fill!(0.0)

    num_l = 3
    num_z = 1

    g_u.axis(0).pos.val.size.times{ |num|
      if (num % num_l) == 0
	u_data[num,true] =  g_u.data.val[num,true]
	sig_data[num,true] =  g_sig.data.val[num,true]
      elsif
	u_data[num,true]  = 0.0
	sig_data[num,true]  =  0.0
      end
    }
    
    g_u.axis(1).pos.val.size.times{ |num|
      if (num % num_z) == 0
	u_data[true,num] = u_data[true,num]
	sig_data[true,num] = sig_data[true,num]
      elsif
	u_data[true,num] = 0.0
	sig_data[true,num] = 0.0
      end
    }

    #  (u,-sigdot) 
    DCL::uglset('LMSG', false)
    DCL::uglset('LNRMAL', false)
    DCL::ugrset('XFACT1', 2*10E-6*100)
    DCL::ugrset('YFACT1', 30.0*1000)
    DCL::uglset('LUNIT', false)
    DCL::ugrset('VXUNIT', 0.06)
    DCL::ugrset('VYUNIT', 0.06)
    DCL::ugrset('VXUOFF', 0.01)

    DCL::ugvect( u_data, -sig_data[true,1..-1] ) 

end


# gif アニメ作成シェルスクリプト
def mkgifanim

  `for file in *.xwd ; do xwdtopnm ${file} |  pnmcut 2 2 904 654 > tmp.pnm; ppmtogif tmp.pnm > ${file}.gif; done >& /dev/null `
#  `gifsicle --delay=50 --loopcount=100 dcl_*.gif > #{$gifname}-anim.gif`
  `gifsicle --loopcount=100 dcl_*.gif > #{$gifname}-anim.gif`
  `mv dcl_001.xwd.gif #{$gifname}-t0.gif`
  `rm dcl_* tmp.pnm`
#  `rm dcl_*.xwd tmp.pnm`

end



# ----------------------------------------------
# GPhys メソッド追加定義

def GGraph.annotate(str_ary) # GGraph の annotate メソッド再定義

  charsize = 0.7 * 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.66 
#  vy = 0.12 - charsize/2
#  vy = 0.10 - charsize/2
  vy = 0.11 - charsize/2
  str_ary.each{|str|
    DCL::sgtxzv(vx,vy,"[ #{str} ]",charsize,0,-1,1)
    vy -= dvy
  }
  nil
end

class GPhys

  # 座標, データ操作ログ記録関数の定義 (Grid.lost_axes 参照)
  def add_lost_axes( lost )
    GPhys.new( @grid.copy.add_lost_axes( lost.to_a ), @data)
  end
  def set_lost_axes( lost )
    GPhys.new( @grid.copy.set_lost_axes( lost.to_a ), @data)
  end

  # rename 再定義 (gphys class の値を返す)
  def rename(name)
    GPhys.new(@grid,@data.copy.rename(name))
  end

  # attribute 変更再定義 (gphys class の値を返す)
  def set_att(name,val)
    GPhys.new(@grid,@data.copy.set_att(name,val))
  end

end
