require "numru/gphys"
require "numru/dcl"
include NumRu

ARGV.length<2 && raise("Usage: ruby #$0 var Omega")

var = ARGV.shift
aomega = ARGV.shift
randoms = (101..125).to_a
nrandom = randoms.length

path = "../data/"

for n in 0...nrandom
  random = randoms[n]
  p fname = "#{path}Omega#{aomega}/baro_rn4expcs_freedecay_cpg100_Omega#{aomega}-#{random}.nc"
  file = NetCDF.open(fname)


  gux = GPhys::IO.open(file,"mvlon")
  if n==0
    nlat,ntim = gux.shape
    lat = gux.coord("lat").val
    tim = gux.coord("t").val
    nm = file.dim("n").length
    omega = file.att("Omega").get[0]
    a = file.att("Radius").get[0]
    ux = NArray.sfloat(tim.length,lat.length,nrandom)
  end
  ux[true,true,n] = gux.val.transpose(1,0)

  file.close
end

ux = ux.mean(2)


case var
when "u-xm"
  umax = 5.0
when "ucos-xm"
  coslat = NMath::cos(lat*Math::PI/180).reshape!(1,nlat)
  ux *= coslat
  umax = 2.0
end


iws = ARGV.delete("-ps") ? 2 : 4
if ARGV.delete("-png")
  DCL::swlset("lwnd",false)
  DCL::swlset("ldump",true)
  DCL::swlset("lwait",false)
end
DCL::sglset("lfull",true)
DCL::udlset("lmsg",false)
DCL::swiset("iclrmap",14)
DCL::gropn(iws)

DCL::grfrm
DCL::grsvpt(0.09,0.98,0.08,0.67)
DCL::grswnd(0,tim[-1],-90,90)
DCL::grstrn(1)
DCL::grstrf
DCL::uzfact(0.7)

DCL::uwsgxa(tim)
DCL::uwsgya(lat)

ntone = 10
ci = umax/ntone
for i in 1...ntone
  DCL::uestlv(-umax*(i+1)/ntone,-umax*i/ntone,(57-5*i)*1000+999)
  DCL::uestlv(umax*(i)/ntone,umax*(i+1)/ntone,(52+5*i)*1000+999)
end
DCL::uestlv(-999,-umax,10999)
DCL::uestlv(umax,999,99999)
DCL::uetonf(ux)
#DCL::uetone(ux)

DCL::udsfmt("(f4.1)")
DCL::udgcla(-ci*20,ci*20,ci)
DCL::udcntz(ux)

#DCL::usdaxs
DCL::uxaxdv("b",0.2,1)
DCL::uxaxdv("t",0.2,1)
DCL::uyaxdv("l",10,30)
DCL::uyaxdv("r",10,30)
#DCL::uxsttl("t","zonal-mean uhcos#{DCL::csgi(172)}",0)
DCL::uxsttl("b","time [s]",0)
DCL::uysttl("l","latitude",0)

vname = {"u-xm"=>"U","ucos-xm"=>"Ucos#{DCL::csgi(172)}"}[var]
DCL::sgtxzr(0.02,0.70,"zonal-mean #{vname}",0.02,0,-1,2)
DCL::sgtxzr(0.98,0.035,"Omega=#{omega.to_i}, U=sqrt2, a=#{a.to_i}, Random=#{random}",0.012,0,1,1)
DCL::sgtxzr(0.98,0.015,"Contour interval=#{ci}",0.012,0,1,1)

DCL::grcls
