#!/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{

  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/work/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)


  $exp_hash = {
    "con" => "con", 
    "a" => "mradlAa", 
    "b" => "mradlAb", 
    "c" => "mradlAc", 
    "d" => "mradlAd"
  }


  $cum = "adj"
  $exp = "con"
  $timestep = "2hour"

  numnum = 0
  num = ARGV[numnum+1].to_i  if numnum = ARGV.index("-num")
  $timestep = "1hour"           if numnum = ARGV.index("-1hour")
  $cum = "kuo"                 if numnum = ARGV.index("-kuo")
  $exp = ARGV[numnum+1]           if numnum = ARGV.index("-exp")

  $fig_path = "/home/yukiko/work/aqua3d/yukiko/mradl/20051213/fig/anim/"
  $dir_path = "/home/yukiko/work/aqua3d/yukiko/mradl/20051213/#{$cum}700#{$exp_hash[$exp]}/"

  ## へんすうじょうほう
  set_varinfo

  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

  if $timestep == "2hour"
    $gifname = 
      "#{$cum}_#{$exp}_#{varlist}_y0510"
  else
    $gifname = 
      "#{$cum}_#{$exp}_#{varlist}_y0510_#{$timestep}"
  end

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

end

def set_varinfo

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

  # 凝結加熱 (cumulus + largescale)
  $qcnd_hash = {
    "variable" => "qcnd", 
    "filename" => ["#{$dir_path}qcnd_sum_10.nc","#{$dir_path}qcnd_sum_20.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" => ["#{$dir_path}qcndc_sum_10.nc","#{$dir_path}qcndc_sum_20.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" => ["#{$dir_path}qcndl_sum_10.nc","#{$dir_path}qcndl_sum_20.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" => ["#{$dir_path}t_out_10.nc", "#{$dir_path}t_out_20.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" => ["#{$dir_path}q_out_10.nc", "#{$dir_path}q_out_20.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" => ["#{$dir_path}tv_out_10.nc","#{$dir_path}tv_out_20.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" => ["#{$dir_path}theta_out_10.nc","#{$dir_path}theta_out_20.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" => ["#{$dir_path}thetae_out_10.nc","#{$dir_path}thetae_out_20.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" => ["#{$dir_path}thetaesat_out_10.nc","#{$dir_path}thetaesat_out_20.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" => ["#{$dir_path}brunt_out_10.nc","#{$dir_path}brunt_out_20.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" => ["#{$dir_path}relh_out_10.nc","#{$dir_path}relh_out_20.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" => ["#{$dir_path}div_out_10.nc","#{$dir_path}div_out_20.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" => ["#{$dir_path}vor_out_10.nc","#{$dir_path}vor_out_20.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" => ["#{$dir_path}sigdot_out_10.nc","#{$dir_path}sigdot_out_20.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" => ["#{$dir_path}gph_out_10.nc","#{$dir_path}gph_out_20.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" => ["#{$dir_path}u_out_10.nc","#{$dir_path}u_out_20.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" => ["#{$dir_path}v_out_10.nc","#{$dir_path}v_out_20.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" => ["#{$dir_path}qradl_sum_10.nc","#{$dir_path}qradl_sum_20.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" => ["#{$dir_path}qrads_sum_10.nc","#{$dir_path}qrads_sum_20.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" => ["#{$dir_path}qvdf_sum_10.nc","#{$dir_path}qvdf_sum_20.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" => ["#{$dir_path}thetae_out_10.nc","#{$dir_path}thetae_out_20.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" => ["#{$dir_path}thetaesat_out_10.nc","#{$dir_path}thetaesat_out_20.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" => ["#{$dir_path}brunt_out_10.nc","#{$dir_path}brunt_out_20.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"])
 
  # ------------------------------------------------------------
  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|

    $file_label = "day=#{format("%.1f",(num*1.0*timestep/24) )}"
    print "  #{$file_label} #{Time.now}\n"

# 1 枚目: 凝結加熱
    DCL.uzpset('labelxb',false)
    GGraph.set_fig('viewport'=>[0.10,0.80,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(true,1.4,true,true)[true,true,num*timestep]
    g = g.set_att("long_name","").set_att("unit","").set_lost_axes("")
    g_tmp = gphys_1.cut(true,1.4,true,true).mean(0)[true,num*timestep].
      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, "lat=1.4, #{$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.10,0.80,0.34,0.47], 'new_frame'=>false )

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

    g = gphys_1.cut(true,4.2,true,true)[true,true,num*timestep].
      set_lost_axes("").set_att("long_name","").set_att("unit","")
    g_tmp = gphys_1.cut(true,4.2,true,true).mean(0)[true,num*timestep].
      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, "lat=4.2, #{$var_array[0]["lost_axis"]}", 1.0)
    GGraph.color_bar( colorbar_hash )
    DCL::uzinit 

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

    g = gphys_1.cut(true,9.8,true,true)[true,true,num*timestep].
      set_lost_axes("").set_att("long_name","").set_att("unit","")
    g_tmp = gphys_1.cut(true,9.8,true,true).mean(0)[true,num*timestep].
    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, "lat=9.8, #{$var_array[0]["lost_axis"]}", 1.0)
    GGraph.color_bar( colorbar_hash )

    
  }
  
  DCL::grcls 

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 > #{$fig_path}#{$gifname}_anim.gif`
  `mv dcl_001.xwd.gif #{$fig_path}#{$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
