#!/bin/bash

roms=ucsc2.nc
# time=ocean_time
time=time

# tst file with just u, v, angle and the coordinates
ncks --overwrite -v u,v $roms tst.nc

# eta_rho and eta_u match (308), but xi_rho (443) and xi_u (442) do not
# extract two files shifted in xi, and clip the first and last eta
# don't get the coordinates because they will be specified later from the reduced subset
# of rho points lon/lat
ncks --overwrite -C -v u,$time -d xi_u,0,-3 -d eta_u,1,-2 tst.nc tstuL.nc  # lower bound
ncks --overwrite -C -v u,$time -d xi_u,1,-1 -d eta_u,1,-1 tst.nc tstuU.nc  # upper

# average these two to get u on the rho points 
ncra --overwrite tstuL.nc tstuU.nc u.nc 
ncrename --dimension xi_u,xi_red u.nc 
ncrename --dimension eta_u,eta_red u.nc 

# xi_rho and xi_v match (443), but eta_rho (308) and eta_v (307) do not
# extract two files shifted in eta, and clip the first and last xi
ncks --overwrite -C -v v,$time -d xi_v,1,-1 -d eta_v,0,-1 tst.nc tstvL.nc # lower
ncks --overwrite -C -v v,$time -d xi_v,1,-2 -d eta_v,1,-2 tst.nc tstvU.nc # upper

# average these two to get v on the rho points 
ncra --overwrite tstvL.nc tstvU.nc v.nc
ncrename --dimension xi_v,xi_red v.nc 
ncrename --dimension eta_v,eta_red v.nc 

# get angle for this subset of rho points
ncks --overwrite -v angle,lon_rho,lat_rho -d xi_rho,1,-2 -d eta_rho,1,-2 $roms uvangle.nc
ncrename --dimension xi_rho,xi_red uvangle.nc 
ncrename --dimension eta_rho,eta_red uvangle.nc 

# combine all into one file
ncks -A u.nc v.nc 
ncks -A v.nc uvangle.nc

# Now the file uvangle.nc has the u and v components averaged to the same rho points, and 
# the angle centered at those same rho points.

# Next apply rotation with ncap2 ... 
#
# I believe the appropriate equation is
# ueast=Real((Uroms+i*Vroms)*exp(i*angle))   ue  =u*cos(angle)-v*sin(angle)       
# vnorth=Imag((Uroms+i*Vroms)*exp(i*angle))  vn = u*sin(angle)+v*cos(angle)
ncap2 -O -s 'ue=u*cos(angle)-v*sin(angle)' -s 'vn=u*sin(angle)+v*cos(angle)' uvangle.nc final.nc

# make the coordinate names and attributes consistent 
ncrename -v lon_rho,lon_red final.nc
ncrename -v lat_rho,lat_red final.nc
ncatted -a coordinates,ue,m,c,"lon_red lat_red s_rho $time" final.nc
ncatted -a standard_name,ue,a,c,"eastward_sea_water_velocity" final.nc
ncatted -a coordinates,vn,m,c,"lon_red lat_red s_rho $time" final.nc
ncatted -a standard_name,vn,a,c,"northward_sea_water_velocity" final.nc

cp $roms new_$roms
ncks -A final.nc new_$roms
