#!/usr/bin/ruby

#require "narray"
require "numru/ggraph"
require 'numru/gphys'
include NumRu

#-- help
if ARGV.size == 0 then
   puts '[usage] : dcl2dplot [options] [filename]'
   puts '[options] : '
#   puts '--title="string" : draw the title.'
   puts '--save-mode="string" : save file format'
   puts '                       "string" : "PS" => post script, "PNG" => png'
   puts '                                  default = "PNG"'
   puts '--undef="string" : set the undefined value.'
#   puts '--set-viewx=[min:max] : set the x axis viewport.'
#   puts '                    default = [0.2:0.8]'
#   puts '--set-viewy=[min:max] : set the y axis viewport.'
#   puts '                        default = [0.2:0.8]'
   puts '--set-xrange=[min:max] : set the x axis range.'
   puts '--set-yrange=[min:max] : set the y axis range.'
   puts '--set-axises=[colum number(x):colum number(y)] :'
   puts '             set the x coordinate value.'
   puts '             ex. --set-axises=[1:2].'
   puts '--contour=[colum number] : set the contour value.'
   puts '                               ex. --contour=[3].'
   puts '--shade=[colum number] : set the color shade value.'
   puts '                               ex. --shade=[4].'
   puts '--set-cphys=[string:string] : set the contour [value name:unit].'
   puts '                               ex. --set-cunit=[Temperature:K].'
   puts '--set-sphys=[string:string] : set the shade [value name:unit].'
   puts '                               ex. --set-sunit=[heat flux:W m-2].'
#   puts '--set-xlog, --set-ylog : set logalithm coordinate.'
#   puts '--with-clip : clipping the value out of window.'
   puts '--set-xtitle="string" : x axis title.'
   puts '--set-ytitle="string" : y axis title.'
   puts '--set-xsub="string" : x axis unit.'
   puts '--set-ysub="string" : y axis unit.'
   puts '--skip=number : line skip number.'
   puts '--split=type : split type.'
   puts '               ex. if you split by comma, --split=",".'
   puts '               except : if you split by [tab], --split="tab".'
   puts '[example] : dcl2dplot --set-axises=[1:2] --contour=[3] test.dat'
   puts '[NOTE] : --contour or --shade, and --set-axises is neccesary.'
   exit
end

#-- default value set
vxmin = 0.2
vxmax = 0.8
vymin = 0.2
vymax = 0.8
iws = 4
undeflag = false
autoscalew = true
autoscalev = true
undefc = '999.0'
title = ''
xlflag = false
ylflag = false
xpflag = false
ypflag = false
itr = 1
xtitle = ''
ytitle = ''
xsub = ''
ysub = ''
xa = ''
ya = ''
xaflag = false
yaflag = false
xsubflag = false
ysubflag = false
lskip = 0
splitype = "nil"
cphys_flag = false
sphys_flag = false

#-- argv analysis
counter = 0
for i in 0..ARGV.size-1
   tmp = ARGV[i]

   if tmp[0..6] == '--title' then
      tmpval = tmp.split("=")
      title = tmpval[1].gsub("'","")
      counter = counter + 1
   end

   if tmp[0..10] == '--save-mode' then
      tmpval = tmp.split("=")
      if tmpval[1].gsub("'","").gsub('"','') == 'PS' then
         iws = 2
      end
      counter = counter + 1
   end

   if tmp[0..6] == '--undef' then
      undeflag = true
      tmpval = tmp.split("=")
      undefc = tmpval[1]
      counter = counter + 1
   end

   if tmp[0..10] == '--set-viewx' then
      autoscalev = false
      tmpval = tmp.split("=")
      view_range = tmpval[1].split(":")
      vxmin = view_range[0].gsub("[","").to_f
      vxmax = view_range[1].gsub("]","").to_f
      counter = counter + 1
   end

   if tmp[0..10] == '--set-viewy' then
      autoscalev = false
      tmpval = tmp.split("=")
      view_range = tmpval[1].split(":")
      vymin = view_range[0].gsub("[","").to_f
      vymax = view_range[1].gsub("]","").to_f
      counter = counter + 1
   end

   if tmp[0..11] == '--set-xrange' then
      autoscalew = false
      tmpval = tmp.split("=")
      view_range = tmpval[1].split(":")
      xmin = view_range[0].gsub("[","").to_f
      xmax = view_range[1].gsub("]","").to_f
      counter = counter + 1
   end

   if tmp[0..11] == '--set-yrange' then
      autoscalew = false
      tmpval = tmp.split("=")
      view_range = tmpval[1].split(":")
      ymin = view_range[0].gsub("[","").to_f
      ymax = view_range[1].gsub("]","").to_f
      counter = counter + 1
   end

   if tmp[0..11] == '--set-axises' then
      xlflag = true
      tmpval = tmp.split("=")
      xline = tmpval[1].split(":")
      for i in 0..xline.size-1
         xline[i] = xline[i].gsub("[","").gsub("]","")
      end
      counter = counter + 1
   end

   if tmp[0..8] == '--contour' then
      cflag = true
      tmpval = tmp.split("=")
      cont_num = tmpval[1].gsub("[","").gsub("]","")
      counter = counter + 1
   end

   if tmp[0..6] == '--shade' then
      sflag = true
      tmpval = tmp.split("=")
      shade_num = tmpval[1].gsub("[","").gsub("]","")
      counter = counter + 1
   end

   if tmp[0..10] == '--set-cphys' then
      cphys_flag = true
      tmpval = tmp.split("=")
      cline = tmpval[1].split(":")
      ca = cline[0].gsub("[","").gsub("]","")
      csub = cline[1].gsub("[","").gsub("]","")
      counter = counter + 1
   end

   if tmp[0..10] == '--set-sphys' then
      sphys_flag = true
      tmpval = tmp.split("=")
      sline = tmpval[1].split(":")
      sa = sline[0].gsub("[","").gsub("]","")
      ssub = sline[1].gsub("[","").gsub("]","")
      counter = counter + 1
   end

   if tmp[0..11] == '--set-xtitle' then
      xaflag = true
      tmpval = tmp.split("=")
      xa = tmpval[1].gsub("'","")
      counter = counter + 1
   end

   if tmp[0..11] == '--set-ytitle' then
      yaflag = true
      tmpval = tmp.split("=")
      ya = tmpval[1].gsub("'","")
      counter = counter + 1
   end

   if tmp[0..9] == '--set-xsub' then
      xsubflag = true
      tmpval = tmp.split("=")
      xsub = tmpval[1].gsub("'","")
      counter = counter + 1
   end

   if tmp[0..9] == '--set-ysub' then
      ysubflag = true
      tmpval = tmp.split("=")
      ysub = tmpval[1].gsub("'","")
      counter = counter + 1
   end

   if tmp[0..5] == '--skip' then
      tmpval = tmp.split("=")
      lskip = tmpval[1].gsub("'","").to_i
      counter = counter + 1
   end

   if tmp[0..6] == '--split' then
      tmpval = tmp.split("=")
      splitype = tmpval[1].gsub("'","").gsub('"','')
      if splitype == "tab" then
         splitype = "	"
      end
      counter = counter + 1
   end

end

fname = ARGV[counter]

#-- file reading part

f = open( fname, 'r' )

f_content = f.read

#-- Array separate

f_col = f_content.split("\n")
f_col_size = f_col.size

if splitype == "nil" then
   for i in lskip..f_col_size-1
      f_col[i] = f_col[i].split(nil)
   end
else
   for i in lskip..f_col_size-1
      f_col[i] = f_col[i].split(splitype)
   end
end

#-- gsub

for i in lskip..f_col[lskip].size-1
   f_col[lskip][i]=f_col[lskip][i].gsub("'","").gsub("  ","")
   f_col[lskip+1][i]=f_col[lskip+1][i].gsub("'","").gsub("  ","")
end

#-- undef convert

if undeflag == true then
   rmiss = DCL.glrget( 'RMISS' )
   DCL.gllset( 'LMISS', true )

   for j in 0..f_col[lskip].size-1
      for i in lskip..f_col_size-1
         if f_col[i][j]==undefc then
            f_col[i][j] = rmiss.to_s
         end
      end
   end
end

#-- convert Array to NArray
for j in 0..f_col[lskip].size-1
   for i in lskip..f_col_size-1
      f_col[i][j] = f_col[i][j].gsub("'","").gsub('"','').gsub(" ","").gsub('/','').gsub(':','')
   end
end

nval = NArray.to_na(f_col)
dimen = nval.shape
tate = dimen[1]  # Ԥο
yoko = dimen[0]  # ο
val = NArray.sfloat(yoko,tate)

for j in lskip..tate-1
   for i in 0..yoko-1
      val[i,j] = nval[i,j].to_f
   end
end

#-- gphys object making
#---- grid data inserting
xaxe_counter=0
yaxe_counter=0
if val[xline[0].to_i-1,lskip] == val[xline[0].to_i-1,lskip+1] then
   axe_flag = 'y'
   for i in lskip..tate-1
      if val[xline[0].to_i-1,i] == val[xline[0].to_i-1,i+1] then
         yaxe_counter=yaxe_counter+1
      else
         yaxe_counter=yaxe_counter+1
         break
      end
   end
else
   axe_flag = 'x'
   for i in lskip..tate-1
      if val[xline[1].to_i-1,i] == val[xline[1].to_i-1,i+1] then
         xaxe_counter=xaxe_counter+1
      else
         xaxe_counter=xaxe_counter+1
         break
      end
   end
end

if xaxe_counter == 0 then
   xaxe_counter = (tate-1-lskip) / yaxe_counter
else
   yaxe_counter = (tate-1-lskip) / xaxe_counter
end
xaxe = NArray.sfloat(xaxe_counter)
yaxe = NArray.sfloat(yaxe_counter)
contour = NArray.sfloat(xaxe_counter,yaxe_counter)
shade = NArray.sfloat(xaxe_counter,yaxe_counter)

if axe_flag == 'y' then
   for i in lskip..lskip+yaxe_counter-1
      yaxe[i-lskip] = val[xline[1].to_i-1,i]
   end
   for i in 0..xaxe_counter-1
      xaxe[i] = val[xline[0].to_i-1,lskip+i*yaxe_counter]
   end
else
   for i in lskip..lskip+xaxe_counter-1
      xaxe[i-lskip] = val[xline[0].to_i-1,i]
   end
   for i in 0..yaxe_counter-1
      yaxe[i] = val[xline[1].to_i-1,lskip+i*xaxe_counter]
   end
end

#---- contour and shade data inserting
if axe_flag == 'y' then
   for j in 0..yaxe_counter-1
      for i in 0..xaxe_counter-1
         if cflag == true then
            contour[i,j] = val[cont_num.to_i-1,lskip+i*yaxe_counter+j]
         end
         if sflag == true then
            shade[i,j] = val[shade_num.to_i-1,lskip+i*yaxe_counter+j]
         end
      end
   end
else
   for j in 0..yaxe_counter-1
      for i in 0..xaxe_counter-1
         if cflag == true then
            contour[i,j] = val[cont_num.to_i-1,lskip+j*xaxe_counter+i]
         end
         if sflag == true then
            shade[i,j] = val[shade_num.to_i-1,lskip+j*xaxe_counter+i]
         end
      end
   end
end

#---- gphys making
lon_a = VArray.new( xaxe, {"long_name"=>xa, "units"=>xsub}, "xaxe" )
lon = Axis.new.set_pos(lon_a)
lat_a = VArray.new( yaxe, {"long_name"=>ya, "units"=>ysub}, "yaxe" )
lat = Axis.new.set_pos(lat_a)

if cflag == true then
   if cphys_flag == false then
      ca = 'contour'
      csub = '1'
   end
   cont_a = VArray.new( contour, {"long_name"=>ca, "units"=>csub}, "contour" )
   contphys = GPhys.new( Grid.new(lon,lat), cont_a )
end

if sflag == true then
   if sphys_flag == false then
      sa = 'shade'
      ssub = '1'
   end
   shade_a = VArray.new( shade, {"long_name"=>sa, "units"=>ssub}, "shade" )
   shadephys = GPhys.new( Grid.new(lon,lat), shade_a )
end

#-- dcl part

DCL.sgiset('IFONT', 2)
DCL.uzfact(0.6)
DCL.sgpset('lcntl',false)
DCL.gropn( iws )
#DCL.grfrm

#if autoscalev == false then
#   DCL.grsvpt( vxmin, vxmax, vymin, vymax )
#end

if autoscalew == false then
   if sflag == true then
      GGraph.tone shadephys.cut( 'xaxe'=>xmin..xmax, 'yaxe'=>ymin..ymax )
      GGraph.color_bar
   end
   if cflag == true then
      if sflag == true then
         GGraph.contour contphys.cut( 'xaxe'=>xmin..xmax, 'yaxe'=>ymin..ymax ), false
      else
         GGraph.contour contphys.cut( 'xaxe'=>xmin..xmax, 'yaxe'=>ymin..ymax )
      end
   end
else
   if sflag == true then
      GGraph.tone shadephys
      GGraph.color_bar
   end
   if cflag == true then
      if sflag == true then
         GGraph.contour contphys, false
      else
         GGraph.contour contphys
      end
   end
end


DCL.grcls
