#! /usr/bin/ruby
# -*- coding: utf-8 -*-

# 陸惑星実験用描画スクリプト
# == 説明
# * このスクリプトは水平分布を描くものである.
#
# == オプション
# --lon_start   経度の開始点
# --lon_end   経度の開始点
# --range      プロットする値の範囲. min:max という形式で指定する.
# --inclination      雲の消滅時間
# --wsn        出力先. pdf だったら --wsn=2
#
# == USAGE
#   % fig_lonmean_timeseries.rb --var SoilMoist --range=0:1000 --wsn 2
#
# == 履歴
# * 2018-01-01 石渡正樹 作成

require "./script/load_config.rb"

require "getoptlong"        # for option_parse
require "numru/ggraph"
include NumRu

script_dir = "/GFD_Dennou_Work3/momoko/SyncRotEarthRad/script"

DATA_HOME = "./"

TMPFILE = "dcl.pdf"

latent_heat = 2.5e6


## オプション解析
parser = GetoptLong.new
parser.set_options(
   ###    global option   ###
   ['--var',                    GetoptLong::REQUIRED_ARGUMENT],
   ['--time_start',               GetoptLong::REQUIRED_ARGUMENT],
   ['--time_end',                 GetoptLong::REQUIRED_ARGUMENT],
   ['--clrmap',                 GetoptLong::REQUIRED_ARGUMENT],
   ['--nlev',                 GetoptLong::REQUIRED_ARGUMENT],
   ['--time_interval',                 GetoptLong::REQUIRED_ARGUMENT],
   ['--int',                 GetoptLong::REQUIRED_ARGUMENT],
   ['--lon_start',                   GetoptLong::REQUIRED_ARGUMENT],
   ['--lon_end',                   GetoptLong::REQUIRED_ARGUMENT],
   ['--lat_start',                   GetoptLong::REQUIRED_ARGUMENT],
   ['--lat_end',                   GetoptLong::REQUIRED_ARGUMENT],
   ['--range',                    GetoptLong::REQUIRED_ARGUMENT],
   ['--exp_header',                    GetoptLong::REQUIRED_ARGUMENT],
   ['--image_header',                    GetoptLong::REQUIRED_ARGUMENT],
   ['--wsn',                      GetoptLong::REQUIRED_ARGUMENT]
)
parser.each_option do |name, arg|
  eval "$OPT_#{name.sub(/^--/, '').gsub(/-/, '_')} = '#{arg}'"  # strage option value to $OPT_val
end

wsn = ($OPT_wsn||1)

exp_header = ($OPT_exp_header||'LP_16p_Omg1.0_I23.5_S1800_W20cm')
image_header = ($OPT_image_header||'LP_16p_Omg1.0_I23.5_S1800_W20cm')

var = ($OPT_var||'Temp')

time_start = ($OPT_time_start||0).to_f
time_end = ($OPT_time_end||800).to_f

time_interval = ($OPT_time_interval||1).to_f

contour_interval = ($OPT_int||10).to_f


lon_start = ($OPT_lon_start||0).to_f
lon_end = ($OPT_lon_end||364).to_f

clrmap = ($OPT_clrmap||9).to_f
nlev = ($OPT_nlev||30).to_f

title = ''

range = ($OPT_range||'0:10000')
VAL_MIN =  range.split(':')[0].to_f
VAL_MAX =  range.split(':')[1].to_f

lux_all = Hash.new

# 出力ファイル名
#epsfn = "#{image_header}_#{var}_yz_timemean#{time_start}-#{time_end}.eps"
#pngfn = "#{image_header}_#{var}_yz_timemean#{time_start}-#{time_end}.png"
pdffn = "#{image_header}_#{var}_anim_yz_time#{time_start}-#{time_end}.pdf"
gifanimfn = "#{image_header}_#{var}_anim_yz_time#{time_start}-#{time_end}.gif"

file = var + '.nc'

gturls=[]

nexpnum = EXPNUMS.size

for i in 0..EXPNUMS.size-1
  p i
  gturls.push( GPhys::IO.open_gturl("#{exp_header}_#{EXPNUMS[i]}/#{var}.nc@#{var},time=#{DATA_TIME_RANGE[i]}:#{time_interval}") )
  p gturls
end

gp_result = GPhys.join(gturls)

p gp_result

#if var == 'EvapU' then
#  gphys = gphys / latent_heat
#end

# データの切り出し
gphys = gp_result.cut('time'=>time_start..time_end)
all = gphys

#p all

# トーンのカラーマップ
DCL.sgscmn(clrmap)   # colormap

#DCL.swpset("lwait",false)   # 次の描画の前にマウスクリックを待つ
#DCL.swpset("lalt",true)    # 裏で描画（パラパラアニメ用）

# 描画
DCL.gropn(wsn)
    
DCL.sgpset('lcntl', false) ; DCL.uzfact(0.7)

GGraph.set_axes('xtickint'=>730, 'xlabelint'=>3650)
GGraph.set_axes('ytickint'=>10, 'ylabelint'=>30)
vx0,vx1,vy0,vy1 = 0.15,0.85,0.2,0.55
GGraph.set_fig 'viewport'=>[vx0,vx1,vy0,vy1]
DCL.uscset('cyspos', 'B' )              # move unit y axis
DCL.udlset('LMSG', false)
#DCL::uxmttl('T', '', 0.0)  # title (large character)
#DCL.ugpset('LUMSG', false)   # no message

opt_tone = {
   'min'=>VAL_MIN, 'max'=>VAL_MAX,  
   'title'=>'',
   'nlev'=>nlev,
   'annotate'=>false,
   'exchange'=>false,
   'title'=>title,
   'interval'=>contour_interval
#   'xintv'=>200,
#   'yintv'=>1
}


p all.coord('time').val

DCL::sgstxs(0.03)
DCL::sgstxc(-1)

data_time=all.coord('time').val

draw_first=true
for t in data_time
  if draw_first==true
    GGraph.tone_and_contour(all.cut('time'=>t), true, opt_tone)
    draw_first==false
  else
    GGraph.tone_and_contour(all.cut('time'=>t), false, opt_tone)
  end
  
  DCL::sgtxv(0.50, 0.58, 'time='+t.to_s+'day')
end

GGraph.color_bar('landscape'=>true)

DCL.grcls

# 画像ファイルの変換
if wsn == '2' then
  if File.exist?(TMPFILE) then
    puts("MESSAGE: post processing ... #{pdffn} will be generate.")
    `convert -rotate 90 dcl.pdf #{pdffn}`
  end
end

if File.exist?(pdffn) then
  system("convert -delay 50 -loop 0 #{pdffn} #{gifanimfn}")
end

if File.exist?(TMPFILE) then
  system("rm #{TMPFILE}")
end

