#!/usr/bin/env ruby

=begin

=gpcat

複数ファイルに対して時刻の最小値・最大値を求め, その値をもとに
ディレクトリを作成する. 

==USAGE

  % arare-mkdir --file filename


==OPTIONS

      --help          : print this message. 
      --file filename : file name (required).

==HISTORY

  2009/06/22  K Sugiyama (created)

=end

require "numru/netcdf"
require "numru/dcl"
require "numru/ggraph"
require "getoptlong"
include NumRu

###
###引数処理
###
parser = GetoptLong.new
parser.set_options(
                   ###    global option   ###
                   ['--file', "-f", GetoptLong::REQUIRED_ARGUMENT],
                   ['--dir',  "-d", GetoptLong::REQUIRED_ARGUMENT],
                   ["--help", "-h", GetoptLong::NO_ARGUMENT ]
                   )
begin
  parser.each_option do |name, arg|
    eval "$OPT_#{name.sub(/^--/, '').gsub(/-/, '_')} = '#{arg}'" 
  end
    rescue
  exit(1)
end

if $OPT_HELP then
  help
  exit(0)
end  

###
### 初期設定
###
coords = ["x", "z", "t", "s"] # 軸の設定
dir = "#{$OPT_dir}"           # トップディレクトリ

if ($OPT_dir)
  maindir = $OPT_dir.to_s
else
  maindir = "."
end

# ファイル置き場
ncfile = $OPT_file.to_s
p ncfile
#/(.*)arare-(.*)([-_]\d+)-rank\d\d\d\d\d\d_(.+).nc/ =~ ncfile
/^([a-z,A-Z,1-9]+)_(\w+)_rank\d\d\d\d\d\d.nc/ =~ ncfile
prefix =  $1
p prefix
###
### 時刻を表す文字列を付けたディレクトリ作成し, 
### ファイルを移動させる. 
###

gturl = "#{ncfile}@t"
gphys = GPhys::IO.open_gturl(gturl)
subdir = "time_#{sprintf("%09d", gphys.val.min)}-#{sprintf("%09d", gphys.val.max)}"
Dir::mkdir("#{maindir}/#{subdir}") unless FileTest.exist?("#{maindir}/#{subdir}")
system("mv #{prefix}* #{maindir}/#{subdir}/")
p "#{maindir}/#{subdir}"
