#!/usr/bin/python3
import xarray as xr
import argparse
import os

parser = argparse.ArgumentParser()
parser.add_argument('ifile')
parser.add_argument('odir')
args = parser.parse_args()

ifile = args.ifile
fname = os.path.basename(ifile).split('_')
gcm = fname[1]
odir = "{}/{}/".format(args.odir, gcm)
os.makedirs(odir, exist_ok=True)

ds = xr.open_dataset(ifile)
tmax = ds[['T2']].resample(times='D').max() # Celsius
tmin = ds[['T2']].resample(times='D').min()
prec = ds[['PREC']] # mm
prec = prec.where(prec > 0.025, 0).resample(times='D').sum()
wspd = ds[['WND']].resample(times='D').mean() # m/s

ds = prec.copy()
ds['TMAX'] = tmax.T2
ds['TMIN'] = tmin.T2
ds['WSPD'] = wspd.WND

out = "{}/{}_{}".format(odir, gcm, fname[2])
ds.to_netcdf(out)
