#!/usr/bin/env ruby

##################################################
=begin
=gpprint

A command to print the values of a variable specified by
a gtool4-type URL. 

Outputs are comma-separated ascii texts with line feeding
to avoid long lines and are made to stdout.

==USAGE

     % gpprint url
 
where the format of the url is
 
     path@varname[,dimname=pos1[:pos2[:thinning_intv]][,dimname=...]]

==EXAMPLES

    % gpprint data.nc@temp
    % gpprint data.nc@temp,lon=135.0
    % gpprint data.nc@temp,lon=130:150,lat=0
    % gpprint data.nc@temp,lon=130:150,lat=0:90:2

==HISTORY

  2004/12/14  T Horinouchi, created
  2005/01/12  T Horinouchi, document -> in rd
=end
##################################################

require "numru/gphys"
include NumRu

#####################################################
URLfmt = "path@varname[,dimname=pos1[:pos2[:thinning_intv]][,dimname=...]]"

def parse_gturl(gturl)
  if /(.*)@(.*)/ =~ gturl
    file = $1
    var = $2
  else
    raise "invalid URL: '@' between path & variable is not found\n\n" + 
           "URL format: " + URLfmt
  end
  if /,/ =~ var
    slice = Hash.new
    thinning = Hash.new
    var_descr = var.split(/,/)
    var = var_descr.shift
    var_descr.each do |s|
      if /(.*)=(.*)/ =~ s
	dimname = $1
	subset = $2
	case subset
	when /(.*):(.*):(.*)/
	  slice[dimname] = ($1.to_f)..($2.to_f)
	  thinning[dimname] = {0..-1,$3.to_i}
	when /(.*):(.*)/
	  slice[dimname] = ($1.to_f)..($2.to_f)
	else
	  slice[dimname] = subset.to_f
	end
      else
	raise "invalid URL: variable subset specification error\n\n" + 
           "URL format: " + URLfmt
      end
    end
    thinning = nil if thinning.length == 0
  else
    slice = nil
    thinning = nil
  end
  [file, var, slice, thinning]
end
#####################################################

usage = "\n\nUSAGE:\n\n % " + $0 + " " + URLfmt + "\n"

raise usage if ARGV.length != 1 or /^-+h/ =~ ARGV[0]
gturl = ARGV[0]
file, var, slice, thinning = parse_gturl(gturl)
gp = GPhys::IO.open(file,var)
gp = gp.cut(slice) if slice
gp = gp[thinning] if thinning

new_line_int = 6
first_dim_len = gp.shape[0]
fmt = " %g,"
i = 1
gp.val.each do |v| 
  printf(fmt,v)
  print "\n" if (i % new_line_int) == 0 or (i % first_dim_len) == 0
  i += 1
end
