#!/usr/bin/env ruby

##################################################
=begin
= NAME

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

= DESCRIPTION

((*gpprint*)) is a command-line tool 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 [options] url
 
where the format of the url is 

     path[@|/]varname[,dimname=pos1[:pos2[:thinning_intv]][,dimname=...]]

= OPTIONS

:-h, --help
   print this message.
:-l, --long
   print with "%f".
:-e, --exp
   print with "%e".
:-f format, --fmt format
   set print format. 

= EXAMPLES

    % gpprint data.nc@temp
    % gpprint -l data.nc@temp,lon=135.0
    % gpprint -e data.nc@temp,lon=130:150,lat=0
    % gpprint -f " %10.3f," 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)
  2005/06/15  S Takehiro (set first_dim_length 1 when gp.shape[0] returns nil)
  2005/08/10  S Takehiro (utilize internal function for printing help message)
  2005/08/23  S Takehiro (common methods to gp* command moved to gpcommon.rb)
  2010/03/10  Y SASAKI (change help block into RD format)
  2012/02/19  S Takehiro (description for gturl format updated)
  2017/04/02  S Takehiro (options added)

=end
##################################################

require "numru/gphys"
require "numru/gphys/gpcommon"
include NumRu

require "getoptlong"

#---------------------- Option Configuration ----------------------
parser = GetoptLong.new(
  ["--exp",      "-e", GetoptLong::NO_ARGUMENT      ],
  ["--long",     "-l", GetoptLong::NO_ARGUMENT      ],
  ["--fmt",      "-f", GetoptLong::REQUIRED_ARGUMENT],
  ["--help",     "-h", GetoptLong::NO_ARGUMENT      ])
begin
  parser.each{|opt, arg|
    case opt
    when "--exp"  then eval "$OPT_exp=true"
    when "--long" then eval "$OPT_long=true"
    when "--fmt"  then eval "$OPT_fmt='#{arg}'"
    when "--help" then eval "$OPT_help=true"
    else
      raise "must not happen"
    end
  }
  rescue GetoptLong::AmbigousOption, GetoptLong::InvalidOption,
          GetoptLong::MissingArgument, 
          GetoptLong::NeedlessArgument => err
    help
    $srderr.puts err.message
    exit 1
end

#------------------------ Help message ------------------------
if $OPT_help then
  help
  exit(0)
end

#------------------------ Help message ------------------------
gturl = ARGV[0]
gp = GPhys::IO.open_gturl(gturl)

new_line_int = 5

first_dim_len = (gp.shape[0]||1)
if $OPT_fmt then
  fmt=$OPT_fmt
elsif $OPT_exp then
  fmt=" %e,"
elsif $OPT_long then
  fmt=" %f,"
else
  fmt=" %g,"
end

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
