#!/usr/bin/env ruby
# ----------------------------------------------
# local load path

 $local_path = '/home/yukiko/work/ape/yukiko/lib'
# $local_path = '/home/yukiko/tmp/ape-data/lib'
$: << $local_path

# ----------------------------------------------
# 必要なライブラリ, モジュールの読み込み

load "#{$local_path}/ape-view.rb"

# ----------------------------------------------


END{

  mknc_file_marge

}

# ----------------------------------------------


def mknc_file_marge

  $gr2ncfile_path = "./work/"
  file =  
    NetCDF.create("CSIRO_control_nofilt-horizontal.nc")
  puts "ECMWF_control_wk_40smooth_qtuz.nc create start"

#  file_name = Array.new
#  Dir.foreach($gr2ncfile_path) { |item|
#    file_name.push("#{$gr2ncfile_path}/#{item}") if item =~ /ECMWF_/
#    file_name.push("#{$gr2ncfile_path}/#{item}") if item =~ /filt.nc/
#  }

  file_name = ("#{$gr2ncfile_path}/CSIRO_control_nofilt-horizontal.nc") 
    
    $t = Ape.new(file_name)

    $t.netcdf_open.var_names.each { |name| 
      if name =~ /tr_/
        unless name =~ /tr_t600/

          puts name
        gphys = $t.go(name) 
          gphys_tmp = 
            GPhys.new( gphys.grid_copy , 
                       VArray.new( gphys.data.val.to_na).rename(gphys.name) )
          gphys_tmp = gphys_tmp.
            set_att("ape_name",gphys.get_att("ape_name")).
            set_att("units",gphys.get_att("units"))
          unless gphys.name =~ /mslp/ || gphys.name =~ /tppn/
            gphys_tmp = gphys_tmp.
              set_att("lost_axis",gphys.get_att("lost_axis"))
          end

        # netCDF 初期化
        GPhys::NetCDF_IO.write(file, gphys_tmp )
        end
      end
    } 


  file_name = ("#{$gr2ncfile_path}/CSIRO_control_nofilt-horizontal_tr_t600.nc") 

    $t = Ape.new(file_name)
    $t.netcdf_open.var_names.each { |name| 
      if name =~ /tr_/
        puts name
        gphys = $t.go(name) 
          gphys_tmp = 
            GPhys.new( gphys.grid_copy , 
                       VArray.new( gphys.data.val.to_na).rename(gphys.name) )
          gphys_tmp = gphys_tmp.
            set_att("ape_name",gphys.get_att("ape_name")).
            set_att("units",gphys.get_att("units")).
            set_att("lost_axis",gphys.get_att("lost_axis"))
        # netCDF 初期化
        GPhys::NetCDF_IO.write(file, gphys_tmp )
      end
    }      
  


  # 大域属性
  file.put_att("Conventions", "CF-1.0")
#  file.put_att("title","Aqua Planet: ECMWF_control Experiment, Wheeler and Kiladis, 1999 Plot")
  file.put_att("title","Aqua Planet: CSIRO_control Experiment")
  file.put_att("history", "Original data produced: #{Time.now} from TR netCDF by Yukiko YAMADA (AGU for APE)")
#  file.put_att("institution", "ECMWF")
  file.put_att("institution", "CSIRO")
  file.close
  
end
