#!/usr/bin/ruby

require "numru/ggraph"
require 'getoptlong'
include NumRu

def print_usage
  <<~USAGE
  Usage : 
    $ ruby merge.rb IN.nc (OUT.nc)

    Note that the name of NetCDF files to be merged is IN_rank??????.nc.
    But, file name given as arguments should not include _rank??????.
    It is assumed that a variable named 'IN' is included in the input file.
    If OUT.nc is not given, a output file name is IN.nc.
  USAGE
end

parser = GetoptLong.new

parser.set_options(
  ['--time_index_s', '-s',     GetoptLong::OPTIONAL_ARGUMENT],
  ['--time_index_e', '-e',     GetoptLong::OPTIONAL_ARGUMENT],
#  ['--plev', '-p',               GetoptLong::REQUIRED_ARGUMENT],
)

$OPT_time_index_s = 0
$OPT_time_index_e = -1
begin
  parser.each_option do |name, arg|
    eval "$OPT_#{name.sub(/^--/, '').gsub(/-/, '_')} = '#{arg}'"
#    print name, ":", arg, "\n"
  end
rescue
  exit(1)
end


if ARGV.size < 1 then
#  puts <<~USAGE
  puts print_usage
  exit
end

ncfn_in  = ARGV[0]
if ARGV.size >= 2 then
  ncfn_out = ARGV[1]
else
  ncfn_out = nil
end

unless ncfn_in[-3..-1] == '.nc' then
  print "ERROR : Unexpected extention of file name: ", ncfn_in, "\n"
  exit
end
is = ncfn_in.rindex("/") != nil ? ncfn_in.rindex("/") : -1
is += 1
ie = -4
vname = ncfn_in[is..ie]

if ncfn_out == nil then
  ncfn_out = vname + ".nc"
end

print "   Input  : ", ncfn_in, "\n"
print "   Output : ", ncfn_out, "\n"

if File.exist?(ncfn_out) then
  print "File, ", ncfn_out, " exists.\n"
  print "Overwrite the file? (yes/no)\n"
  input = $stdin.gets
  if input.chomp != 'yes' then
    print "STOP\n"
    exit
  end
end


url = ncfn_in[0..-4] + "_rank??????.nc@" + vname
gp = GPhys::IO.open_gturl( url )
#
na_time = gp.coord('time').val
times = na_time[$OPT_time_index_s]
timee = na_time[$OPT_time_index_e]
gp = gp.cut('time'=>times..timee)

itime = 0
itimes = $OPT_time_index_s
if $OPT_time_index_e < 0 then
  itimee = $OPT_time_index_e + na_time.size
else
  itimee = $OPT_time_index_e
end
ntime = (itimee-itimes+1)

# Output
outfile = NetCDF.create(ncfn_out)
GPhys::NetCDF_IO.each_along_dims_write(gp, outfile, -1) do |sub|
  # https://qiita.com/hokaccha/items/3abd55aa23894b57ffd1#comment-00bb23380f8b3b7cc489
  progress = ((itime+1).to_f/ntime.to_f*100).round(3)
  print "working... "+progress.round(3).to_s+"%\r"
  STDOUT.flush
  if (itime+1) == ntime then
    print "\n"
  end
  itime += 1
  [sub]
end
outfile.close
