% interpolating onto Calus River grid and generating the tidal forcing file

Cfname = 'calus_tide.nc'
% create new file
create = 1;
if(create)
    cmd=['! ncgen -o ' Cfname ' ./calus_tide.cdl'];
    eval(cmd);    
end

fname = 'interp_tide.nc'
fname2 = '../../FORCING/calus_grid.nc'

llm
rlon2 = nc_varget(fname2,'lon_rho');
rlat2 = nc_varget(fname2,'lat_rho');
mask2 = nc_varget(fname2,'mask_rho');

disp('Getting Variables')
tp = nc_varget(fname,'tide_period');
t_ep = nc_varget(fname,'tide_Ephase');
t_ea = nc_varget(fname,'tide_Eamp');
t_cp = nc_varget(fname,'tide_Cphase');
t_ca = nc_varget(fname,'tide_Cangle');
cmin = nc_varget(fname,'tide_Cmin');
cmax = nc_varget(fname,'tide_Cmin');
t_const = nc_varget(fname,'tidal_constituents');

for i=1:length(t_const)
    disp(i)
    p = find(isnan(squeeze(t_ep(i,:,:)))==0);
    t_ep(i,:,:) = griddata(rlon(p),rlat(p),squeeze(t_ep(i,p)),rlon,rlat);
    p = find(isnan(squeeze(t_ea(i,:,:)))==0);
    t_ea(i,:,:) = griddata(rlon(p),rlat(p),squeeze(t_ea(i,p)),rlon,rlat);
    p = find(isnan(squeeze(t_cp(i,:,:)))==0);
    t_cp(i,:,:) = griddata(rlon(p),rlat(p),squeeze(t_cp(i,p)),rlon,rlat);
    p = find(isnan(squeeze(t_ca(i,:,:)))==0);
    t_ca(i,:,:) = griddata(rlon(p),rlat(p),squeeze(t_ca(i,p)),rlon,rlat);
    p = find(isnan(squeeze(cmin(i,:,:)))==0);
    cmin(i,:,:) = griddata(rlon(p),rlat(p),squeeze(cmin(i,p)),rlon,rlat);
    p = find(isnan(squeeze(cmax(i,:,:)))==0);
    cmax(i,:,:) = griddata(rlon(p),rlat(p),squeeze(cmax(i,p)),rlon,rlat);
end

for i=1:length(t_const)
    disp(i)

    t_ep2(i,:,:) = griddata(rlon,rlat,squeeze(t_ep(i,:,:)),rlon2,rlat2);
    t_ea2(i,:,:) = griddata(rlon,rlat,squeeze(t_ea(i,:,:)),rlon2,rlat2);
    t_cp2(i,:,:) = griddata(rlon,rlat,squeeze(t_cp(i,:,:)),rlon2,rlat2);
    t_ca2(i,:,:) = griddata(rlon,rlat,squeeze(t_ca(i,:,:)),rlon2,rlat2);
    cmin2(i,:,:) = griddata(rlon,rlat,squeeze(cmin(i,:,:)),rlon2,rlat2);
    cmax2(i,:,:) = griddata(rlon,rlat,squeeze(cmax(i,:,:)),rlon2,rlat2);
end

nc_varput(Cfname,'lon_rho',rlon2);
nc_varput(Cfname,'lat_rho',rlat2);
nc_varput(Cfname,'mask_rho',mask2);
nc_varput(Cfname,'tide_period',tp);
nc_varput(Cfname,'tide_Ephase',t_ep2);
nc_varput(Cfname,'tide_Eamp',t_ea2);
nc_varput(Cfname,'tide_Cphase',t_cp2);
nc_varput(Cfname,'tide_Cangle',t_ca2);
nc_varput(Cfname,'tide_Cmin',cmin2);
nc_varput(Cfname,'tide_Cmax',cmax2);
nc_varput(Cfname,'tidal_constituents',t_const);
 
