# Usage
#
#   $ ruby merge.rb AAA.nc BBB.nc ...
#
#   Note that the name of NetCDF files to be merged is AAA_rank??????.nc.
#   But, file name given as arguments should not include _rank??????.

require "numru/ggraph"
include NumRu

if ARGV.size < 1 then
  print "Usage : ruby merge.rb AAA.nc BBB.nc ...\n" 
  print "        Note that the name of NetCDF files to be merged is AAA_rank??????.nc.\n"
  print "        But, file name given as arguments should not include _rank??????.\n"
  exit
end

ARGV.each_with_index do |arg, ivar|
  ncfn = arg
  unless ncfn[-3..-1] == '.nc' then
    print "ERROR : Unexpected extention of file name: ", ncfn, "\n"
    exit
  end
  is = ncfn.rindex("/") != nil ? ncfn.rindex("/") : 1
  is += 1
  ie = -4
  vname = ncfn[is..ie]
  outncfn = vname + ".nc"
  print ivar+1, "\n"
  print "   Input  : ", ncfn, "\n"
  print "   Output : ", outncfn, "\n"

  url = ncfn[0..-4] + "_rank??????.nc@" + vname
  gp = GPhys::IO.open_gturl( url )
  outfile = NetCDF.create(outncfn)
  GPhys::NetCDF_IO.each_along_dims_write(gp, outfile, -1) do |sub|
    [sub]
  end
  outfile.close
end



