require "gtk2"
require "numru/gphys"
require "numru/dcl"
require "spml"
include NumRu
include SPML

ARGV.length==2 || raise("Usage: ruby #$0 omega random")

omega = ARGV.shift
random = ARGV.shift

path = "../data/"
p fname = "#{path}Omega#{omega}/baro_rn4expcs_freedecay_cpg100_Omega#{omega}-#{random}.nc"
file = NetCDF.open(fname) 

var_u = GPhys::IO.open(file,"mvlon")
var_vor = GPhys::IO.open(file,"vor")
t = GPhys::IO.open(file,"t").val
lon = file.var("lon").get
lat = file.var("lat").get
omega = file.att("Omega").get[0]
a = file.att("Radius").get[0]
nm = file.dim("n").length

w_Initial(nm,lon.length,lat.length)

f = 2*omega*NMath::sin(lat*Math::PI/180)
f.reshape!(1,lat.length)
cosphi = NMath::cos(lat*Math::PI/180)

ntim = t.length

DCL::sglset("lfull",true)
DCL::udlset("lmsg",false)
DCL::swiset("iclrmap",14)
#DCL::swiset("iwidth",450)
#DCL::swiset("iheight",325)
DCL::swlset("lwnd",false)
DCL::gropn(4)

DCL::uzfact(0.7)

title = ["u", "ucos#{DCL::csgi(172)}", "PV", 'PV_y"']


lonw = NArray.sfloat(lon.length).fill(1)
lonw /= lonw.sum

DCL::uzrset("uxuser",0)
for i in 0...ntim
  ux = var_u[true,i].val
  vor = var_vor[true,true,i].val
  ucos = ux*cosphi
  tmp = vor+f
  potvor = tmp.mul_add(lonw,0)
  potvor_y = (xy_GradLat_w(w_xy(tmp))/a).mul_add(lonw,0)

  data = [ux, ucos, potvor, potvor_y]

  vymin = 0.13
  vymax = 0.66
  for n in 0...title.length
    n==0 ? DCL::grfrm : DCL::grfig
    vxmin = 0.02+0.245*n
    vxmax = vxmin+0.16
    case n
    when 0
      xmax = 10
    when 1
      xmax = 5
    when 2
      if omega==0
        xmax = 20
      else
        xmax = 2*omega
      end
    when 3
      if omega==0
        xmax = 1000
      else
        xmax = 2*omega
      end
    end
    DCL::grsvpt(vxmin,vxmax,vymin,vymax)
    DCL::grswnd(-xmax,xmax,-90,90)
    DCL::grstrn(1)
    DCL::grstrf

    DCL::usxaxs("b")
    DCL::uyaxdv("u",10,30)
    DCL::uxsttl("b",title[n],0)

    DCL::sgplzu(data[n],lat,1,2)
  end
  DCL::sgtxzr(0.02,0.71,"t=#{"%3.1f"%t[i]}sec",0.02,0,-1,2)
  DCL::sgtxzr(0.98,0.007,"Omega=#{omega.to_i}, U=sqrt2, a=#{a.to_i}, random=#{random}",0.012,0,1,1)

end

DCL::grcls
